-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
319 lines (265 loc) · 8.28 KB
/
main.go
File metadata and controls
319 lines (265 loc) · 8.28 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
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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"golang.design/x/hotkey"
)
type APIRequest struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
}
type HotkeyInfo struct {
Hotkey *hotkey.Hotkey `json:"-"`
Request APIRequest `json:"request"`
}
type AddRequest struct {
Hotkey string `json:"hotkey"`
Request APIRequest `json:"request"`
}
type HotkeyManager struct {
mu sync.RWMutex
registered map[string]HotkeyInfo
httpClient http.Client
apiToken string
}
func NewHotkeyManager(token string) *HotkeyManager {
return &HotkeyManager{
registered: make(map[string]HotkeyInfo),
httpClient: http.Client{Timeout: 3 * time.Second},
apiToken: token,
}
}
func (h *HotkeyManager) isAuthenticated(r *http.Request) bool {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return false
}
token := strings.TrimPrefix(authHeader, "Bearer ")
return token == h.apiToken
}
func (h *HotkeyManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/hotkeys" {
http.NotFound(w, r)
return
}
if !h.isAuthenticated(r) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
log.Printf("⚠️ Unauthorized access attempt from %s", r.RemoteAddr)
return
}
switch r.URL.Path {
case "/hotkeys":
switch r.Method {
case http.MethodGet:
h.handleGet(w, r)
case http.MethodPost:
h.handleAdd(w, r)
case http.MethodDelete:
h.handleDelete(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
}
func (h *HotkeyManager) handleGet(w http.ResponseWriter, r *http.Request) {
h.mu.RLock()
defer h.mu.RUnlock()
responseMap := make(map[string]APIRequest)
for key, info := range h.registered {
responseMap[key] = info.Request
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(responseMap); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
}
}
func (h *HotkeyManager) handleAdd(w http.ResponseWriter, r *http.Request) {
var requests []AddRequest
if err := json.NewDecoder(r.Body).Decode(&requests); err != nil {
http.Error(w, "Invalid request body: expected a JSON array", http.StatusBadRequest)
return
}
type BatchResult struct {
Hotkey string `json:"hotkey"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
}
var results []BatchResult
var successfulCount int
h.mu.Lock()
defer h.mu.Unlock()
for _, req := range requests {
keyStr := req.Hotkey
req.Request.Method = strings.ToUpper(req.Request.Method)
if req.Hotkey == "" || req.Request.URL == "" {
results = append(results, BatchResult{keyStr, "failed", "Missing 'hotkey' or 'request.url' field"})
continue
}
if _, err := url.ParseRequestURI(req.Request.URL); err != nil {
results = append(results, BatchResult{keyStr, "failed", "Invalid request.url"})
continue
}
if req.Request.Method == "" {
req.Request.Method = http.MethodGet
}
if _, ok := h.registered[keyStr]; ok {
results = append(results, BatchResult{keyStr, "failed", "Hotkey already registered"})
continue
}
mods, key, err := parseHotkey(keyStr)
if err != nil {
results = append(results, BatchResult{keyStr, "failed", fmt.Sprintf("Invalid hotkey format: %v", err)})
continue
}
hk := hotkey.New(mods, key)
if err := hk.Register(); err != nil {
results = append(results, BatchResult{keyStr, "failed", fmt.Sprintf("Error registering hotkey with OS: %v", err)})
continue
}
h.registered[keyStr] = HotkeyInfo{
Hotkey: hk,
Request: req.Request,
}
go h.listenForKeypress(keyStr, req.Request, hk)
log.Printf("✅ Hotkey registered (batch): %s -> %s %s", keyStr, req.Request.Method, req.Request.URL)
results = append(results, BatchResult{keyStr, "success", "Hotkey registered successfully"})
successfulCount++
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusMultiStatus)
if err := json.NewEncoder(w).Encode(results); err != nil {
log.Printf("Error encoding batch response: %v", err)
}
}
func (h *HotkeyManager) handleDelete(w http.ResponseWriter, r *http.Request) {
h.mu.Lock()
defer h.mu.Unlock()
count := len(h.registered)
for key, info := range h.registered {
if err := info.Hotkey.Unregister(); err != nil {
log.Printf("❌ Failed to unregister hotkey '%s' with OS, but removing from list anyway: %v", key, err)
}
}
h.registered = make(map[string]HotkeyInfo)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "All %d hotkeys unregistered successfully.", count)
}
func parseHotkey(s string) ([]hotkey.Modifier, hotkey.Key, error) {
parts := strings.Split(s, "+")
if len(parts) == 0 {
return nil, 0, fmt.Errorf("empty hotkey string")
}
var mods []hotkey.Modifier
keyStr := parts[len(parts)-1]
for i := 0; i < len(parts)-1; i++ {
switch strings.ToLower(parts[i]) {
case "ctrl", "control":
mods = append(mods, hotkey.ModCtrl)
case "alt", "option":
mods = append(mods, hotkey.ModAlt)
case "shift":
mods = append(mods, hotkey.ModShift)
default:
return nil, 0, fmt.Errorf("unknown or unsupported modifier: %s (only Ctrl, Alt, Shift are supported)", parts[i])
}
}
specialKeyMap := map[string]hotkey.Key{
"f1": hotkey.KeyF1,
"f2": hotkey.KeyF2,
"f3": hotkey.KeyF3,
"f4": hotkey.KeyF4,
"f5": hotkey.KeyF5,
"f6": hotkey.KeyF6,
"f7": hotkey.KeyF7,
"f8": hotkey.KeyF8,
"f9": hotkey.KeyF9,
"f10": hotkey.KeyF10,
"f11": hotkey.KeyF11,
"f12": hotkey.KeyF12,
"arrowup": hotkey.KeyUp,
"arrowdown": hotkey.KeyDown,
"arrowleft": hotkey.KeyLeft,
"arrowright": hotkey.KeyRight,
" ": hotkey.KeySpace,
"spacebar": hotkey.KeySpace,
"space": hotkey.KeySpace,
"return": hotkey.KeyReturn,
"tab": hotkey.KeyTab,
"escape": hotkey.KeyEscape,
"delete": hotkey.KeyDelete,
}
lowerKeyStr := strings.ToLower(keyStr)
if k, ok := specialKeyMap[lowerKeyStr]; ok {
return mods, k, nil
}
if len(keyStr) == 1 {
char := keyStr[0]
if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') {
k := hotkey.Key(strings.ToUpper(keyStr)[0])
return mods, k, nil
}
}
return nil, 0, fmt.Errorf("unsupported key: %s (only single characters A-Z/0-9 are supported in this example)", keyStr)
}
func (h *HotkeyManager) listenForKeypress(keyStr string, requestDetails APIRequest, hk *hotkey.Hotkey) {
for range hk.Keydown() {
log.Printf("🔥 Hotkey pressed: %s. Triggering API call to %s %s", keyStr, requestDetails.Method, requestDetails.URL)
go func(details APIRequest) {
var bodyReader io.Reader
if details.Body != "" {
bodyReader = strings.NewReader(details.Body)
}
req, err := http.NewRequest(details.Method, details.URL, bodyReader)
if err != nil {
log.Printf("❌ [Hotkey: %s] Failed to create request: %v", keyStr, err)
return
}
for key, value := range details.Headers {
req.Header.Set(key, value)
}
if bodyReader != nil && req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := h.httpClient.Do(req)
if err != nil {
log.Printf("❌ [Hotkey: %s] Error calling API: %v", keyStr, err)
return
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
log.Printf("📞 [Hotkey: %s] API call completed. Status: %s, Response: %s", keyStr, resp.Status, string(respBody))
}(requestDetails)
}
log.Printf("🛑 Listener for hotkey %s has stopped.", keyStr)
}
func main() {
var listenAddr string
flag.StringVar(&listenAddr, "address", "127.0.0.1:32325", "The address and port to listen on")
flag.Parse()
apiToken := os.Getenv("HOTKEY_API_TOKEN")
if apiToken == "" {
log.Fatal("FATAL: Environment variable HOTKEY_API_TOKEN must be set.")
}
log.Println("✅ API Token loaded from environment variable.")
manager := NewHotkeyManager(apiToken)
go func() {
log.Printf("🚀 HTTP server listening on %s", listenAddr)
if err := http.ListenAndServe(listenAddr, manager); err != nil {
log.Fatalf("HTTP server failed: %v", err)
}
}()
log.Println("🎧 Hotkey manager is ready. Add hotkeys via the API.")
log.Println("➡️ Press Ctrl+C to exit.")
select {}
}