Commit 96d2aa9af9

96d2aa9af97851329b9eee6286c8ae216ebd6589

parent: 07c1ff74db

Unsigned

Wraient <wraient.911@gmail.com> · 2024-11-15 13:36 UTC

stashing

Layout: unified · split

Build/curd-windows-build.iss +2 −2
@@ -1,6 +1,6 @@
1[Setup] 1[Setup]
2AppName=Curd Installer 2AppName=Curd Installer
3AppVersion=0.0.10 3AppVersion=1.0.1
4DefaultDirName={pf}\Curd 4DefaultDirName={pf}\Curd
5DefaultGroupName=Curd 5DefaultGroupName=Curd
6AllowNoIcons=yes 6AllowNoIcons=yes
@@ -15,7 +15,7 @@ Name: "desktopicon"; Description: "Create a &desktop shortcut"; GroupDescription
15 15
16[Files] 16[Files]
17; Copy the Curd executable to the install directory 17; Copy the Curd executable to the install directory
18Source: "Z:releases/curd-0.0.10/windows/curd.exe"; DestDir: "{app}"; Flags: ignoreversion 18Source: "Z:releases/curd-1.0.1/windows/curd.exe"; DestDir: "{app}"; Flags: ignoreversion
19Source: "Z:/home/wraient/Projects/curd/Build/mpv.exe"; DestDir: "{app}\bin"; Flags: ignoreversion 19Source: "Z:/home/wraient/Projects/curd/Build/mpv.exe"; DestDir: "{app}\bin"; Flags: ignoreversion
20 20
21[Icons] 21[Icons]
cmd/curd/main.go +79 −1
@@ -3,12 +3,17 @@ package main
3import ( 3import (
4 "flag" 4 "flag"
5 "fmt" 5 "fmt"
6 "log"
6 "os" 7 "os"
8 "os/exec"
7 "path/filepath" 9 "path/filepath"
8 "strconv"
9 "runtime" 10 "runtime"
11 "strconv"
12 "strings"
10 "sync" 13 "sync"
14 "syscall"
11 "time" 15 "time"
16
12 "github.com/wraient/curd/internal" 17 "github.com/wraient/curd/internal"
13) 18)
14 19
@@ -70,6 +75,8 @@ func main() {
70 editConfig := flag.Bool("e", false, "Edit config") 75 editConfig := flag.Bool("e", false, "Edit config")
71 subFlag := flag.Bool("sub", false, "Watch sub version") 76 subFlag := flag.Bool("sub", false, "Watch sub version")
72 dubFlag := flag.Bool("dub", false, "Watch dub version") 77 dubFlag := flag.Bool("dub", false, "Watch dub version")
78 daemonFlag := flag.Bool("d", false, "Run as daemon for anilist notifications")
79 closeDaemonFlag := flag.Bool("close-daemon", false, "Close the running daemon")
73 80
74 // Custom help/usage function 81 // Custom help/usage function
75 flag.Usage = func() { 82 flag.Usage = func() {
@@ -101,6 +108,77 @@ func main() {
101 return 108 return
102 } 109 }
103 110
111 // Add this after flag.Parse() around line 86
112 if *closeDaemonFlag {
113 pidFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd-daemon.pid")
114
115 // Read PID from file
116 pidBytes, err := os.ReadFile(pidFile)
117 if err != nil {
118 if os.IsNotExist(err) {
119 internal.CurdOut("No daemon is running")
120 internal.ExitCurd(nil)
121 }
122 log.Fatalf("Error reading PID file: %v", err)
123 }
124
125 // Parse PID
126 pid, err := strconv.Atoi(strings.TrimSpace(string(pidBytes)))
127 if err != nil {
128 log.Fatalf("Error parsing PID: %v", err)
129 }
130
131 // Find process
132 process, err := os.FindProcess(pid)
133 if err != nil {
134 log.Fatalf("Error finding process: %v", err)
135 }
136
137 // Send SIGTERM signal
138 if err := process.Signal(syscall.SIGTERM); err != nil {
139 log.Fatalf("Error terminating daemon: %v", err)
140 }
141
142 // Remove PID file
143 if err := os.Remove(pidFile); err != nil {
144 log.Printf("Warning: Failed to remove PID file: %v", err)
145 }
146
147 internal.CurdOut("Daemon stopped successfully")
148 internal.ExitCurd(nil)
149 }
150
151 if *daemonFlag {
152 // Check if daemon is already running
153 pidFile := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd-daemon.pid")
154 if _, err := os.Stat(pidFile); err == nil {
155 internal.CurdOut("Daemon is already running")
156 internal.ExitCurd(nil)
157 }
158
159 // Fork the process
160 if os.Getenv("CURD_DAEMON") != "1" {
161 cmd := exec.Command(os.Args[0], "-d")
162 cmd.Env = append(os.Environ(), "CURD_DAEMON=1")
163 cmd.Start()
164
165 internal.CurdOut("Daemon started in background")
166 internal.ExitCurd(nil)
167 }
168
169 // Write PID file
170 pid := os.Getpid()
171 if err := os.WriteFile(pidFile, []byte(strconv.Itoa(pid)), 0644); err != nil {
172 log.Fatalf("Failed to write PID file: %v", err)
173 }
174 defer os.Remove(pidFile)
175
176 // Start daemon
177 if err := internal.StartDaemon(user.Token); err != nil {
178 log.Fatalf("Daemon error: %v", err)
179 }
180 }
181
104 if *currentCategory { 182 if *currentCategory {
105 userCurdConfig.CurrentCategory = true 183 userCurdConfig.CurrentCategory = true
106 } 184 }
go.mod +1 −1
@@ -3,8 +3,8 @@ module github.com/wraient/curd
3go 1.23.2 3go 1.23.2
4 4
5require ( 5require (
6 github.com/Microsoft/go-winio v0.6.2
7 github.com/charmbracelet/bubbletea v1.1.1 6 github.com/charmbracelet/bubbletea v1.1.1
7 github.com/coder/websocket v1.8.12
8 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 8 github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4
9 github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2 9 github.com/hugolgst/rich-go v0.0.0-20240715122152-74618cc1ace2
10) 10)
go.sum +2 −2
@@ -1,5 +1,3 @@
1github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
2github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
3github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= 1github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
4github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= 2github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
5github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY= 3github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY=
@@ -10,6 +8,8 @@ github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqo
10github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= 8github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
11github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= 9github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0=
12github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= 10github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0=
11github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
12github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
13github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= 13github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= 14github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
15github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI= 15github.com/gen2brain/beeep v0.0.0-20240516210008-9c006672e7f4 h1:ygs9POGDQpQGLJPlq4+0LBUmMBNox1N4JSpw+OETcvI=
internal/daemon.go added +336
@@ -0,0 +1,336 @@
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}
internal/player.go +2 −14
@@ -10,7 +10,7 @@ import (
10 "os/exec" 10 "os/exec"
11 "path/filepath" 11 "path/filepath"
12 "runtime" 12 "runtime"
13 "github.com/Microsoft/go-winio" 13 // "github.com/Microsoft/go-winio"
14) 14)
15var logFile = "debug.log" 15var logFile = "debug.log"
16 16
@@ -77,25 +77,13 @@ func StartVideo(link string, args []string) (string, error) {
77 return mpvSocketPath, nil 77 return mpvSocketPath, nil
78} 78}
79 79
80// Helper function to join args with a space
81func joinArgs(args []string) string {
82 result := ""
83 for i, arg := range args {
84 if i > 0 {
85 result += " "
86 }
87 result += arg
88 }
89 return result
90}
91
92func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) { 80func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) {
93 var conn net.Conn 81 var conn net.Conn
94 var err error 82 var err error
95 83
96 if runtime.GOOS == "windows" { 84 if runtime.GOOS == "windows" {
97 // Use named pipe for Windows 85 // Use named pipe for Windows
98 conn, err = winio.DialPipe(ipcSocketPath, nil) 86 // conn, err = winio.DialPipe(ipcSocketPath, nil)
99 } else { 87 } else {
100 conn, err = net.Dial("unix", ipcSocketPath) 88 conn, err = net.Dial("unix", ipcSocketPath)
101 } 89 }