Repository navigation
Expand file tree
/
Copy pathbeeep.go
More file actions
93 lines (76 loc) · 1.77 KB
/
Copy pathbeeep.go
File metadata and controls
93 lines (76 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Package beeep provides a cross-platform library for sending desktop notifications and beeps.
package beeep
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"runtime"
"time"
)
var (
// ErrUnsupported is returned when an operating system is not supported.
ErrUnsupported = fmt.Errorf("beeep: unsupported operating system: %s", runtime.GOOS)
)
// AppName is the name of app.
// This should be the application's formal name, rather than some sort of ID.
var AppName = "DefaultAppName"
// timeout is notification duration (where applicable).
var timeout = time.Second * 5
func pathAbs(path string) string {
var err error
var abs string
if path != "" {
abs, err = filepath.Abs(path)
if err != nil {
abs = path
}
}
return abs
}
func bytesToFilename(data []byte) (string, error) {
sum := sha256.Sum256(data)
name := hex.EncodeToString(sum[:]) + ".png"
var dirs []string
if dir, err := os.UserCacheDir(); err == nil {
dirs = append(dirs, dir)
}
dirs = append(dirs, os.TempDir())
var err error
for _, dir := range dirs {
var out string
if out, err = writeIcon(filepath.Join(dir, "beeep"), name, data); err == nil {
return out, nil
}
}
return "", err
}
func writeIcon(dir, name string, data []byte) (string, error) {
out := filepath.Join(dir, name)
if _, err := os.Stat(out); err == nil {
return out, nil
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
tmp, err := os.CreateTemp(dir, "*.tmp")
if err != nil {
return "", err
}
_, err = tmp.Write(data)
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(tmp.Name(), out)
}
if err != nil {
os.Remove(tmp.Name())
if _, serr := os.Stat(out); serr == nil {
return out, nil
}
return "", err
}
return out, nil
}