-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrolify.go
322 lines (273 loc) · 6.52 KB
/
controlify.go
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
_ "controlify/assets"
"controlify/keymap"
_ "embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"fyne.io/systray"
"github.com/gen2brain/beeep"
"github.com/gorilla/websocket"
"golang.design/x/hotkey"
"golang.design/x/hotkey/mainthread"
)
//go:embed assets/icon.ico
var windowsIconData []byte
//go:embed assets/icon.png
var linuxIconData []byte
var (
clients = make(map[*websocket.Conn]string)
mu sync.Mutex
clientsByID = make(map[string]*websocket.Conn)
exePath = filepath.Dir(func() string { p, _ := os.Executable(); return p }())
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
imgPath string
isCLI string
iconData []byte
beeepIconName string
)
const (
beeepTitle = "Controlify"
)
func createTempImage() (string, error) {
// Get the temporary directory
tmpDir := os.TempDir()
// Construct the path for the temporary file
tmpFilePath := filepath.Join(tmpDir, beeepIconName)
// Write embedded image data to the temporary file
err := os.WriteFile(tmpFilePath, iconData, 0644)
if err != nil {
return "", fmt.Errorf("error writing to temporary file: %v", err)
}
// Return the path to the temporary file
return tmpFilePath, nil
}
func runWebSocketServer() {
mux := http.NewServeMux()
mux.HandleFunc("/", handleConnections)
server := &http.Server{
Addr: "localhost:8999",
Handler: mux,
}
go sendHeartbeats()
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal("ListenAndServe: ", err)
}
}
func sendHeartbeats() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for client := range clients {
err := client.WriteMessage(websocket.TextMessage, []byte("heartbeat"))
if err != nil {
removeClient(client)
}
}
mu.Unlock()
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("error upgrading to WebSocket: %v", err)
return
}
defer func() {
mu.Lock()
defer mu.Unlock()
delete(clients, ws)
ws.Close()
}()
var initialMsg map[string]interface{}
err = ws.ReadJSON(&initialMsg)
if err != nil {
log.Printf("error reading initial message: %v", err)
return
}
log.Print(initialMsg)
clientID, ok := initialMsg["clientID"].(string)
if !ok || clientID == "" {
log.Printf("clientID missing or invalid")
return
}
if isCLI != "true" {
if clientID == "spicetify-client" {
beeep.Notify(beeepTitle, "Spotify client hooked!", imgPath)
} else if clientID == "deej-client" {
beeep.Notify(beeepTitle, "Deej connected!", imgPath)
} else {
beeep.Alert(beeepTitle, fmt.Sprintf("Unknown client connected with ID %v!", clientID), imgPath)
}
}
clientsByID[clientID] = ws
mu.Lock()
clients[ws] = clientID
mu.Unlock()
for {
var msg map[string]interface{}
err := ws.ReadJSON(&msg)
if err != nil {
break
}
log.Printf("received message: %v %v", msg, clientID)
forwardMessage(msg)
}
}
func forwardMessage(msg map[string]interface{}) {
targetClientID := "spicetify-client"
mu.Lock()
targetClient, ok := clientsByID[targetClientID]
mu.Unlock()
if !ok {
log.Printf("target client not found: %s", targetClientID)
return
}
err := targetClient.WriteJSON(msg)
if err != nil {
log.Printf("error sending message to client %s: %v", targetClientID, err)
}
}
func removeClient(client *websocket.Conn) {
mu.Lock()
defer mu.Unlock()
client.Close()
delete(clients, client)
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "--cli" {
isCLI = "true"
}
if runtime.GOOS == "windows" {
iconData = windowsIconData
beeepIconName = "icon.ico"
} else {
iconData = linuxIconData
beeepIconName = "icon.png"
}
imgPath, _ = createTempImage()
config, err := loadConfig(filepath.Join(exePath, "config.json"))
if err != nil {
errMsg := "Config not found, hotkey function is disabled"
if isCLI != "true" {
beeep.Alert(beeepTitle, errMsg, imgPath)
} else {
log.Print(errMsg)
}
} else {
initHotkeys(config)
}
// Connect to WebSocket server
go runWebSocketServer()
if len(os.Args) > 1 && os.Args[1] == "--cli" || isCLI == "true" {
select {}
} else if len(os.Args) > 1 && os.Args[1] != "" {
log.Printf("Run executable with --cli to run without system tray and in console.")
} else {
// Initialize system tray
systray.Run(onReady, onExit)
}
}
func initHotkeys(config map[string]string) {
// Set up hotkey
mainthread.Init(func() {
for event, shortcut := range config {
if shortcut == "" {
continue
} else {
go func(event, shortcut string) {
if err := registerHotkey(event, shortcut); err != nil {
log.Printf("Error registering hotkey for %s: %v", event, err)
}
}(event, shortcut)
}
}
})
}
func registerHotkey(event, shortcut string) error {
// Parse shortcut string
modifiers, key, err := parseShortcut(shortcut)
if err != nil {
return err
}
// Register hotkey
hk := hotkey.New(modifiers, key)
err = hk.Register()
if err != nil {
return err
}
log.Printf("Registered hotkey for %s: %s\n", event, shortcut)
for {
<-hk.Keyup()
msg := map[string]interface{}{event: ""}
forwardMessage(msg)
}
}
func parseShortcut(shortcut string) ([]hotkey.Modifier, hotkey.Key, error) {
parts := strings.Split(shortcut, "+")
if len(parts) == 0 {
return nil, 0, fmt.Errorf("invalid shortcut: %s", shortcut)
}
var modifiers []hotkey.Modifier
for _, part := range parts[:len(parts)-1] {
mod, err := keymap.ParseModifier(part)
if err != nil {
return nil, 0, err
}
modifiers = append(modifiers, mod)
}
key, err := keymap.ParseKey(parts[len(parts)-1])
if err != nil {
return nil, 0, err
}
return modifiers, key, nil
}
func loadConfig(filename string) (map[string]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
var shortcuts map[string]string
err = json.NewDecoder(file).Decode(&shortcuts)
if err != nil {
return nil, err
}
return shortcuts, nil
}
func onReady() {
err := beeep.Notify(beeepTitle, "Controlify running as a tray app", imgPath)
if err != nil {
panic(err)
}
// Set up system tray
systray.SetIcon(iconData)
systray.SetTitle(beeepTitle)
systray.SetTooltip(beeepTitle)
// Add menu items
systray.AddMenuItem("Controlify", "")
systray.AddSeparator()
mQuit := systray.AddMenuItemCheckbox("Quit", "", false)
go func() {
for range mQuit.ClickedCh {
systray.Quit()
}
}()
}
func onExit() {
os.Exit(0)
}