internal/daemon.go

336 lines · 6937 bytes

  1package internal
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"log"
  8	"net/http"
  9	"os"
 10	"os/exec"
 11	"path/filepath"
 12	"os/signal"
 13	"strconv"
 14	"syscall"
 15
 16	"github.com/coder/websocket"
 17)
 18
 19func StartDaemon(token string) error {
 20	ctx, cancel := context.WithCancel(context.Background())
 21	defer cancel()
 22
 23	// Setup signal handling
 24	sigChan := make(chan os.Signal, 1)
 25	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
 26
 27	// Create a done channel for cleanup
 28	done := make(chan struct{})
 29
 30	// Start signal handler
 31	go func() {
 32		sig := <-sigChan
 33		log.Printf("Received signal: %v", sig)
 34		cancel()
 35		close(done)
 36	}()
 37
 38	// Setup logging
 39	userCurdConfig := GetGlobalConfig()
 40	logFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "daemon.log")
 41	
 42	f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
 43	if err != nil {
 44		return fmt.Errorf("failed to open log file: %v", err)
 45	}
 46	defer f.Close()
 47	
 48	log.SetOutput(f)
 49	log.Printf("Starting Curd daemon...")
 50
 51	// Connect to AniList WebSocket
 52	wsURL := "wss://graphql.anilist.co/websocket"
 53	c, _, err := websocket.Dial(ctx, wsURL, &websocket.DialOptions{
 54		HTTPHeader: http.Header{
 55			"Authorization": []string{"Bearer " + token},
 56			"Content-Type": []string{"application/json"},
 57		},
 58	})
 59	if err != nil {
 60		return fmt.Errorf("websocket connection failed: %v", err)
 61	}
 62	defer c.Close(websocket.StatusNormalClosure, "")
 63
 64	// Updated subscription message with notifications
 65	initMsg := map[string]interface{}{
 66		"type": "start",
 67		"id":   "1",
 68		"payload": map[string]interface{}{
 69			"query": `
 70				subscription {
 71					Notification {
 72						... on ActivityLikeNotification {
 73							id
 74							type
 75							userId
 76							activityId
 77							context
 78							createdAt
 79							user {
 80								name
 81							}
 82						}
 83						... on ActivityReplyNotification {
 84							id
 85							type
 86							userId
 87							activityId
 88							context
 89							createdAt
 90							user {
 91								name
 92							}
 93						}
 94						... on ActivityMentionNotification {
 95							id
 96							type
 97							userId
 98							activityId
 99							context
100							createdAt
101							user {
102								name
103							}
104						}
105						... on ActivityReplySubscribedNotification {
106							id
107							type
108							userId
109							activityId
110							context
111							createdAt
112							user {
113								name
114							}
115						}
116						... on ThreadCommentMentionNotification {
117							id
118							type
119							userId
120							commentId
121							context
122							createdAt
123							user {
124								name
125							}
126						}
127						... on ThreadCommentReplyNotification {
128							id
129							type
130							userId
131							commentId
132							context
133							createdAt
134							user {
135								name
136							}
137						}
138						... on ThreadCommentSubscribedNotification {
139							id
140							type
141							userId
142							commentId
143							context
144							createdAt
145							user {
146								name
147							}
148						}
149						... on ThreadLikeNotification {
150							id
151							type
152							userId
153							threadId
154							context
155							createdAt
156							user {
157								name
158							}
159						}
160						... on RelatedMediaAdditionNotification {
161							id
162							type
163							mediaId
164							context
165							createdAt
166							media {
167								title {
168									userPreferred
169								}
170							}
171						}
172						... on MediaDataChangeNotification {
173							id
174							type
175							mediaId
176							context
177							createdAt
178							media {
179								title {
180									userPreferred
181								}
182							}
183						}
184						... on MediaMergeNotification {
185							id
186							type
187							mediaId
188							context
189							createdAt
190							media {
191								title {
192									userPreferred
193								}
194							}
195						}
196						... on MediaDeletionNotification {
197							id
198							type
199							context
200							createdAt
201						}
202					}
203				}
204			`,
205		},
206	}
207
208	if err := c.Write(ctx, websocket.MessageText, mustJSON(initMsg)); err != nil {
209		return fmt.Errorf("failed to send subscription: %v", err)
210	}
211
212	// Listen for updates
213	go func() {
214		for {
215			select {
216			case <-ctx.Done():
217				log.Printf("Shutting down daemon...")
218				c.Close(websocket.StatusNormalClosure, "")
219				return
220			default:
221				_, message, err := c.Read(ctx)
222				if err != nil {
223					if websocket.CloseStatus(err) != websocket.StatusNormalClosure {
224						log.Printf("WebSocket read error: %v", err)
225					}
226					continue
227				}
228
229				// Parse the notification
230				var response struct {
231					Type    string `json:"type"`
232					Payload struct {
233						Data struct {
234							Notification map[string]interface{} `json:"Notification"`
235						} `json:"data"`
236					} `json:"payload"`
237				}
238
239				if err := json.Unmarshal(message, &response); err != nil {
240					log.Printf("Failed to parse message: %v", err)
241					continue
242				}
243
244				// Only process data messages
245				if response.Type != "data" {
246					continue
247				}
248
249				notification := response.Payload.Data.Notification
250				if notification == nil {
251					continue
252				}
253
254				// Log the notification
255				log.Printf("Received notification: %s", string(message))
256
257				// Send desktop notification
258				notifType := notification["type"].(string)
259				context := notification["context"].(string)
260				
261				var title, body string
262				switch notifType {
263				case "ACTIVITY_LIKE":
264					username := notification["user"].(map[string]interface{})["name"].(string)
265					title = "New Like"
266					body = fmt.Sprintf("%s liked your activity", username)
267				case "ACTIVITY_REPLY":
268					username := notification["user"].(map[string]interface{})["name"].(string)
269					title = "New Reply"
270					body = fmt.Sprintf("%s replied to your activity: %s", username, context)
271				// Add more cases as needed
272				default:
273					title = "AniList Notification"
274					body = context
275				}
276
277				if err := SendNotification(title, body); err != nil {
278					log.Printf("Failed to send notification: %v", err)
279				}
280			}
281		}
282	}()
283
284	// Wait for shutdown signal
285	<-done
286	return nil
287}
288
289func mustJSON(v interface{}) []byte {
290	b, err := json.Marshal(v)
291	if err != nil {
292		panic(err)
293	}
294	return b
295}
296
297// Add this new function to handle desktop notifications
298func SendNotification(title, message string) error {
299	cmd := exec.Command("notify-send", "--app-name=Curd", title, message)
300	return cmd.Run()
301}
302
303func KillDaemon() error {
304	userCurdConfig := GetGlobalConfig()
305	pidFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd-daemon.pid")
306	
307	// Read PID file
308	pidBytes, err := os.ReadFile(pidFile)
309	if err != nil {
310		return fmt.Errorf("daemon not running or PID file not found")
311	}
312	
313	// Parse PID
314	pid, err := strconv.Atoi(string(pidBytes))
315	if err != nil {
316		return fmt.Errorf("invalid PID in file: %v", err)
317	}
318	
319	// Kill process
320	process, err := os.FindProcess(pid)
321	if err != nil {
322		return fmt.Errorf("process not found: %v", err)
323	}
324	
325	// Send SIGTERM signal
326	if err := process.Signal(syscall.SIGTERM); err != nil {
327		return fmt.Errorf("failed to kill daemon: %v", err)
328	}
329	
330	// Remove PID file
331	if err := os.Remove(pidFile); err != nil {
332		log.Printf("Warning: failed to remove PID file: %v", err)
333	}
334	
335	return nil
336}