energy/pkgs/notice/notice_linux.go

58 lines
1.3 KiB
Go
Raw Normal View History

2023-01-26 12:42:54 +08:00
//----------------------------------------
//
// Copyright © yanghy. All Rights Reserved.
//
// Licensed under Apache License Version 2.0, January 2004
//
// https://www.apache.org/licenses/LICENSE-2.0
2023-01-26 12:42:54 +08:00
//
//----------------------------------------
2023-01-25 21:02:18 +08:00
//go:build linux
// +build linux
2023-01-25 22:26:08 +08:00
package notice
2023-01-25 21:02:18 +08:00
import (
2023-01-25 22:26:08 +08:00
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path/filepath"
2023-01-25 21:02:18 +08:00
"sync"
"github.com/godbus/dbus/v5"
)
var once sync.Once
2023-01-25 22:26:08 +08:00
var scriptNum int
2023-01-25 21:02:18 +08:00
func SendNotification(n *Notification) {
conn, err := dbus.SessionBus() // shared connection, don't close
if err != nil {
println("Failed to send message to bus", err)
return
}
2023-01-25 22:26:08 +08:00
var appIcon string
var appName = UniqueID()
if n.Icon != nil && len(n.Icon) > 0 {
bh := md5.Sum(n.Icon)
dataHash := hex.EncodeToString(bh[:])
2023-01-25 22:33:24 +08:00
fileName := fmt.Sprintf("notice-%s-%s", dataHash, n.iconExt)
2023-01-25 22:26:08 +08:00
appIcon = filepath.Join(os.TempDir(), fileName)
if _, err := os.Stat(appIcon); os.IsNotExist(err) {
err = ioutil.WriteFile(appIcon, n.Icon, 0600)
if err != nil {
return
}
}
}
2023-01-25 21:02:18 +08:00
obj := conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
2023-01-25 22:26:08 +08:00
call := obj.Call("org.freedesktop.Notifications.Notify", 0, appName, uint32(0), appIcon, n.Title, n.Content, []string{}, map[string]dbus.Variant{}, n.Timeout)
2023-01-25 21:02:18 +08:00
if call.Err != nil {
println("Failed to send message to bus", call.Err)
}
}