-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttpserver.go
More file actions
837 lines (722 loc) · 28.8 KB
/
httpserver.go
File metadata and controls
837 lines (722 loc) · 28.8 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
// httpserver.go
package main
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
//go:embed frontend/src/assets/images/hc-512.png
var logo []byte
const relativeAudioFolderName = "tmp" // User-defined relative folder
var (
serverListenAddress string // Stores "localhost:PORT" for display or "IP:PORT" from listener.Addr()
actualPort int // port for audio server + messages from python backend to go
isServerInitialized bool // Flag to indicate if server init (port assignment) was successful
)
type PythonMessage struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload"` // Delay parsing payload until type is known
}
type TaskUpdatePayload struct {
Message string `json:"message"`
TaskType string `json:"tasktype,omitempty"`
Progress float64 `json:"progress,omitempty"` // Optional progress percentage (0.0 to 1.0)
}
type ToastPayload struct {
Message string `json:"message"`
ToastType string `json:"toastType,omitempty"` // e.g., "info", "success", "warning", "error"
}
type AlertPayload struct {
Title string `json:"title"`
Message string `json:"message"`
Severity string `json:"severity"` // e.g., "info", "warning", "error"
}
type ClipInfo struct {
Name string `json:"name"`
FilePath string `json:"filePath"` // Absolute path to the audio file for Go to serve
TimelineIn float64 `json:"timelineIn"`
TimelineOut float64 `json:"timelineOut"`
SourceIn float64 `json:"sourceIn"`
SourceOut float64 `json:"sourceOut"`
}
type PythonCommandResponse struct {
Status string `json:"status"`
TaskID string `json:"taskID"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
// Alert
ShouldShowAlert bool `json:"shouldShowAlert,omitempty"`
AlertTitle string `json:"alertTitle,omitempty"`
AlertMessage string `json:"alertMessage,omitempty"`
AlertSeverity string `json:"alertSeverity,omitempty"` // "info", "warning", "error"
AlertIssued bool `json:"alertIssued,omitempty"`
}
func (a *App) sendRequestToPython(ctx context.Context, method, path string, payload interface{}) ([]byte, error) {
if !a.pythonReady || a.pythonCommandPort == 0 {
return nil, fmt.Errorf("python backend is not ready")
}
url := fmt.Sprintf("http://localhost:%d%s", a.pythonCommandPort, path)
var reqBody io.Reader
// Marshal payload to JSON if it exists
if payload != nil {
jsonBody, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("error marshalling payload for %s: %w", path, err)
}
reqBody = bytes.NewBuffer(jsonBody)
// Optional: Log payload for debugging. Be careful with sensitive data.
// log.Printf("Go -> Python [%s %s]: %s", method, path, string(jsonBody))
} else {
log.Printf("Go -> Python [%s %s]", method, path)
}
// Create request with context, which allows for per-request timeouts
req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
if err != nil {
return nil, fmt.Errorf("error creating request for %s: %w", path, err)
}
// --- CENTRALIZED HEADER LOGIC ---
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
if a.authToken != "" {
req.Header.Set("Authorization", "Bearer "+a.authToken)
}
// Use the single, shared httpClient from the App struct
resp, err := a.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("http client error for %s: %w", path, err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body from %s: %w", path, err)
}
// Check for non-successful status codes
if resp.StatusCode != http.StatusOK {
log.Printf("Python responded to %s with status %s. Body: %s", path, resp.Status, string(responseBody))
// Return the body along with the error, as it might contain a structured error message
return responseBody, fmt.Errorf("python server responded with non-200 status: %s", resp.Status)
}
return responseBody, nil
}
func (a *App) SendCommandToPython(commandName string, taskID string, params map[string]interface{}) (*PythonCommandResponse, error) {
commandPayload := map[string]interface{}{
"command": commandName,
"params": params,
}
if params == nil {
commandPayload["params"] = make(map[string]interface{})
}
ackCh := make(chan struct{}, 1)
a.ackMutex.Lock()
a.ackTasks[taskID] = ackWaiter{ch: ackCh}
a.ackMutex.Unlock()
// Create a context. The shared client's timeout will apply unless this context has a shorter one.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // timeout for ACK response
defer cancel()
_, err := a.sendRequestToPython(ctx, "POST", "/command", commandPayload)
if err != nil {
a.ackMutex.Lock()
delete(a.ackTasks, taskID)
a.ackMutex.Unlock()
return nil, err
}
select {
case <-ackCh:
log.Printf("Go: Task %s acknowledged by backend", taskID)
case <-ctx.Done():
return nil, fmt.Errorf(
"timeout waiting for ack for task %s",
taskID,
)
}
return &PythonCommandResponse{
Status: "acknowledged",
Message: "Task started",
}, nil
}
func (a *App) commonMiddleware(next http.HandlerFunc, endpointRequiresAuth bool) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
// 1. Set CORS Headers
// 'actualPort' is assumed to be the globally available port of this server
// If 'actualPort' is 0 (server not fully initialized), this might not be ideal,
// but typically middleware runs after port is known.
origin := fmt.Sprintf("http://localhost:%d", actualPort)
writer.Header().Set("Access-Control-Allow-Origin", origin)
writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") // Common methods
writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Auth-Token") // Common headers + future auth
// 2. Handle OPTIONS (pre-flight) requests
if request.Method == http.MethodOptions {
log.Printf("Middleware: Responding to OPTIONS request for %s", request.URL.Path)
writer.WriteHeader(http.StatusOK)
return
}
// 3. Token Authorization (Placeholder - globally disabled for now)
// When 'globalAuthEnabled' is true, and 'endpointRequiresAuth' is true, token check will be performed.
const globalAuthEnabled = true // MASTER SWITCH: Keep false to disable actual token checking logic.
// Set to true when you're ready to implement and test token auth.
if endpointRequiresAuth {
//log.Printf("Middleware: Endpoint %s requires auth.", request.URL.Path)
if globalAuthEnabled {
//log.Printf("Middleware: Global auth is ENABLED. Performing token check for %s.", request.URL.Path)
if a.authToken == "" { // Assuming App struct has 'authToken string'
log.Printf("Auth Error: Auth token not configured on server for %s", request.URL.Path)
http.Error(writer, "Internal Server Error - Auth not configured", http.StatusInternalServerError)
return
}
clientToken := ""
authHeader := request.Header.Get("Authorization")
if authHeader != "" {
parts := strings.Split(authHeader, " ")
if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" {
clientToken = parts[1]
}
}
// Optionally, check for a custom token header if Authorization is empty
if clientToken == "" {
clientToken = request.Header.Get("X-Auth-Token")
}
if clientToken == "" {
query := request.URL.Query()
clientToken = query.Get("token")
}
if clientToken == "" {
log.Printf("Auth Warning: No token provided by client for protected endpoint %s", request.URL.Path)
http.Error(writer, "Unauthorized - Token required", http.StatusUnauthorized)
return
}
if clientToken != a.authToken {
log.Printf("Auth Warning: Invalid token provided for %s. Client: [%s...], Expected: [%s...]",
request.URL.Path,
clientToken,
a.authToken,
)
//truncateTokenForLog(clientToken),
//truncateTokenForLog(a.authToken))
http.Error(writer, "Unauthorized - Invalid token", http.StatusUnauthorized)
return
}
// log.Printf("Auth: Token validated successfully for %s", request.URL.Path)
} else {
log.Printf("Middleware: Global auth is DISABLED. Token check skipped for %s (even though endpoint requires it).", request.URL.Path)
}
}
// } else {
// log.Printf("Middleware: Endpoint %s does not require auth.", request.URL.Path)
// }
// 4. Call the actual handler if all checks passed (or were skipped)
next.ServeHTTP(writer, request)
}
}
func findFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
func (a *App) GetToken() string {
return a.authToken
}
// initializes and starts the HTTP server in a goroutine.
// It sets the global actualPort and serverListenAddress if successful.
// Returns an error if listener setup fails.
func (a *App) LaunchHttpServer() error {
if a.authToken == "" {
a.authToken = "HushCut-" + uuid.NewString()
}
log.Println("Auth: Generated server auth token.")
log.Printf("Audio Server: Attempting to serve .wav files from: %s", a.tmpPath)
if _, err := os.Stat(a.tmpPath); os.IsNotExist(err) {
log.Printf("Audio Server Warning: The audio folder '%s' does not exist. Please ensure it's created next to the executable.", a.tmpPath)
}
mux := http.NewServeMux()
// --- ENDPOINTS --- //
// Logo endpoint
mux.HandleFunc("/logo", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
w.Write(logo)
})
// Audio files
coreAudioHandler := http.HandlerFunc(a.audioFileEndpoint)
mux.Handle("/", a.commonMiddleware(coreAudioHandler, true))
// Ready signal
readyHandler := func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodPost { // Allow GET or POST
http.Error(w, "Method not allowed for ready signal", http.StatusMethodNotAllowed)
log.Printf("PythonReadyHandler: Method %s blocked", r.Method)
return
}
log.Println("HTTP Server: Received ready signal from Python backend.")
a.pythonReadyChan <- true
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "Go server acknowledges Python backend readiness.")
}
mux.Handle("/ready", a.commonMiddleware(http.HandlerFunc(readyHandler), false)) // false: no auth
// Main communication endpoint
pythonMsgHandlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { a.msgEndpoint(w, r) })
mux.Handle("/msg", a.commonMiddleware(pythonMsgHandlerFunc, true))
// Clip rendering endpoint
mux.HandleFunc("/render_clip", a.commonMiddleware(http.HandlerFunc(a.handleRenderClip), true))
// Server
port, err := findFreePort()
if err != nil {
return fmt.Errorf("could not find free port: %w", err)
}
actualPort = port
serverListenAddress = fmt.Sprintf("localhost:%d", actualPort)
isServerInitialized = true
log.Printf("🎵 Audio Server: Starting on http://%s", serverListenAddress)
log.Printf("Audio Server: Serving .wav files from: %s", a.tmpPath)
listener, err := net.Listen("tcp", serverListenAddress)
if err != nil {
return fmt.Errorf("could not start HTTP server listener: %w", err)
}
// Start the HTTP server in a new goroutine so it doesn't block
go func() {
if errServe := http.Serve(listener, mux); errServe != nil && errServe != http.ErrServerClosed {
log.Printf("ERROR: Audio Server failed: %v", errServe)
isServerInitialized = false
// You might want to signal this failure to the main Wails app
// if user interaction or state change is needed.
}
log.Println("Audio Server: Goroutine finished.")
}()
return nil // Listener setup and goroutine launch successful
}
func (a *App) audioFileEndpoint(writer http.ResponseWriter, request *http.Request) {
origin := fmt.Sprintf("http://localhost:%d", actualPort)
writer.Header().Set("Access-Control-Allow-Origin", origin)
writer.Header().Set("Access-Control-Allow-Methods", "GET")
if request.Method == http.MethodOptions {
writer.WriteHeader(http.StatusOK)
return
}
if request.Method != http.MethodGet {
http.Error(writer, "Method not allowed", http.StatusMethodNotAllowed)
log.Printf("Audio Server Warning: Non-GET request (%s) blocked for: %s", request.Method, request.URL.Path)
return
}
requestedPath := filepath.Clean(request.URL.Path)
if strings.Contains(requestedPath, "..") {
http.Error(writer, "Invalid path", http.StatusBadRequest)
log.Printf("Audio Server Warning: Path traversal attempt blocked for: %s", request.URL.Path)
return
}
if !strings.HasSuffix(strings.ToLower(requestedPath), ".wav") {
if requestedPath == "/" || requestedPath == "" {
welcomeMsg := "Welcome to the internal WAV audio server."
if isServerInitialized && serverListenAddress != "" {
welcomeMsg += fmt.Sprintf(" Serving from http://%s (folder: %s)", serverListenAddress, a.tmpPath)
} else {
welcomeMsg += " (Server initializing or encountered an issue)."
}
fmt.Fprint(writer, welcomeMsg)
return
}
http.Error(writer, "File type not allowed. Only .wav files are served.", http.StatusForbidden)
log.Printf("Audio Server Warning: Non-WAV file request blocked: %s", requestedPath)
return
}
fullPath := filepath.Join(a.tmpPath, requestedPath)
absEffectiveAudioFolderPath, err := filepath.Abs(a.tmpPath)
if err != nil {
http.Error(writer, "Internal server error", http.StatusInternalServerError)
log.Printf("Audio Server Error: getting absolute path for effectiveAudioFolderPath: %v", err)
return
}
absFullPath, err := filepath.Abs(fullPath)
if err != nil {
http.Error(writer, "Internal server error", http.StatusInternalServerError)
log.Printf("Audio Server Error: getting absolute path for fullPath: %v", err)
return
}
if !strings.HasPrefix(absFullPath, absEffectiveAudioFolderPath) {
http.Error(writer, "Invalid path (escapes base directory)", http.StatusBadRequest)
log.Printf("Audio Server Warning: Attempt to access file outside base directory: %s (resolved from %s) vs base %s", requestedPath, absFullPath, absEffectiveAudioFolderPath)
return
}
fileInfo, err := os.Stat(fullPath)
if os.IsNotExist(err) {
if _, statErr := os.Stat(a.tmpPath); os.IsNotExist(statErr) {
errMsg := fmt.Sprintf("Audio folder '%s' not found. Please ensure it exists next to the executable and is named '%s'.", a.tmpPath, relativeAudioFolderName)
http.Error(writer, errMsg, http.StatusInternalServerError)
log.Printf("Base audio folder not found: %s", a.tmpPath)
return
}
http.NotFound(writer, request)
log.Printf("Audio Server Info: File not found: %s", fullPath)
return
}
if err != nil {
http.Error(writer, "Internal server error", http.StatusInternalServerError)
log.Printf("Audio Server Error: accessing file stats for %s: %v", fullPath, err)
return
}
if fileInfo.IsDir() {
http.Error(writer, "Cannot serve directories", http.StatusForbidden)
log.Printf("Audio Server Warning: Attempt to access directory: %s", fullPath)
return
}
writer.Header().Set("Content-Type", "audio/wav")
writer.Header().Set("Accept-Ranges", "bytes") // Good for media seeking
http.ServeFile(writer, request, fullPath)
log.Printf("Audio Server Served: %s (Client: %s)", fullPath, request.RemoteAddr)
}
// (Assuming a.effectiveAudioFolderPath is correctly set up as in your original code)
func (a *App) handleRenderClip(w http.ResponseWriter, r *http.Request) {
// --- Parameter validation (same as your original code) ---
query := r.URL.Query()
fileName := query.Get("file")
startStr := query.Get("start")
endStr := query.Get("end")
if fileName == "" || startStr == "" || endStr == "" {
http.Error(w, "Missing required query parameters", http.StatusBadRequest)
return
}
startSeconds, errStart := strconv.ParseFloat(startStr, 64)
endSeconds, errEnd := strconv.ParseFloat(endStr, 64)
if errStart != nil || errEnd != nil || startSeconds < 0 || endSeconds <= startSeconds {
http.Error(w, "Invalid start or end time parameters", http.StatusBadRequest)
return
}
cleanFileName := filepath.Base(fileName)
if cleanFileName != fileName || strings.Contains(fileName, "..") || strings.ContainsAny(fileName, "/\\") {
http.Error(w, "Invalid file name parameter", http.StatusBadRequest)
return
}
originalFilePath := filepath.Join(a.tmpPath, cleanFileName)
if _, err := os.Stat(originalFilePath); os.IsNotExist(err) {
http.NotFound(w, r)
return
}
runtime.LogDebugf(a.ctx, "RenderClip: BUFFERING request for %s, segment %f to %f", originalFilePath, startSeconds, endSeconds)
// --- FFMPEG Command Setup ---
cmd := ExecCommand(a.ffmpegBinaryPath,
"-i", originalFilePath,
"-af", fmt.Sprintf("atrim=start=%.6f:end=%.6f", startSeconds, endSeconds),
"-f", "wav",
"-vn",
"-hide_banner",
"-loglevel", "error",
"pipe:1",
)
// --- 1. THE SAFETY NET: Guaranteed Process Cleanup ---
// This defer block is the most important part. It ensures that no matter what happens,
// the ffmpeg process is killed and its resources are released.
defer func() {
if cmd.Process != nil {
cmd.Process.Kill() // Ensure the process is terminated.
}
// Wait is still required to release the process resources from Go's perspective.
cmd.Wait()
//log.Printf("RenderClip Cleanup: Successfully cleaned up ffmpeg process for %s", originalFilePath)
}()
// --- Pipe Setup ---
ffmpegOutput, err := cmd.StdoutPipe()
if err != nil {
http.Error(w, "Internal server error (stdout pipe)", http.StatusInternalServerError)
return // defer will run
}
if err := cmd.Start(); err != nil {
http.Error(w, "Internal server error (ffmpeg start)", http.StatusInternalServerError)
return // defer will run
}
// --- 2. THE BUFFERING LOGIC ---
var audioData bytes.Buffer
doneCh := make(chan error, 1) // A channel to signal when copying is complete.
go func() {
// Perform the copy in a separate goroutine.
_, err := io.Copy(&audioData, ffmpegOutput)
doneCh <- err
}()
// --- 3. THE STABILITY ADDITION: Handle Client Disconnects ---
// We wait for one of two things to happen:
// - The copying to the buffer finishes (doneCh receives a value).
// - The client disconnects (r.Context().Done() is closed).
select {
case err := <-doneCh:
// Copying finished. Check for errors.
if err != nil {
log.Printf("RenderClip: Failed to buffer ffmpeg output: %v", err)
http.Error(w, "Failed to generate audio segment", http.StatusInternalServerError)
return // defer will run
}
case <-r.Context().Done():
// Client disconnected before we finished buffering.
log.Printf("RenderClip: Client disconnected during buffering. Aborting.")
// We don't need to write an error to the response, as the client is gone.
// We simply return, and the defer block will kill ffmpeg and clean up.
return
}
// If we get here, the audioData buffer is successfully filled.
runtime.LogDebugf(a.ctx, "RenderClip: Successfully buffered %d bytes. Now serving content.", audioData.Len())
audioDataReader := bytes.NewReader(audioData.Bytes())
serveName := fmt.Sprintf("rendered_clip_%s_%.2f_%.2f.wav", cleanFileName, startSeconds, endSeconds)
modTime := time.Now()
// http.ServeContent is perfect for serving data from an in-memory buffer (via io.ReadSeeker).
// It will correctly set Content-Length, Content-Type, and handle range requests.
http.ServeContent(w, r, serveName, modTime, audioDataReader)
}
// Python/Lua helper send stuff here
func (a *App) msgEndpoint(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
for decoder.More() {
var msg PythonMessage
if err := decoder.Decode(&msg); err != nil {
log.Printf("msgEndpoint: Error decoding PythonMessage: %v", err)
http.Error(w, "Invalid JSON format", http.StatusBadRequest)
return
}
taskID := r.URL.Query().Get("task_id")
switch msg.Type {
case "taskAck":
a.ackMutex.Lock()
waiter, ok := a.ackTasks[taskID]
if ok {
delete(a.ackTasks, taskID)
}
a.ackMutex.Unlock()
if ok {
select {
case waiter.ch <- struct{}{}:
default:
}
}
w.WriteHeader(http.StatusOK)
case "taskUpdate":
var updateData TaskUpdatePayload
if err := json.Unmarshal(msg.Payload, &updateData); err != nil {
http.Error(w, "Invalid payload for 'taskUpdate'", http.StatusBadRequest)
log.Printf("msgEndpoint: Error unmarshalling taskUpdate payload: %v", err)
return
}
// Emit an event to the frontend with the progress update.
// The frontend will listen for "taskProgressUpdate".
runtime.EventsEmit(a.ctx, "taskProgressUpdate", map[string]interface{}{
"taskID": taskID,
"message": updateData.Message,
"progress": updateData.Progress,
})
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Task update received.")
return // IMPORTANT: We are done. We do not touch the pendingTasks channel.
case "taskResult":
var taskData PythonCommandResponse
if err := json.Unmarshal(msg.Payload, &taskData); err != nil {
log.Printf("msgEndpoint: Error unmarshalling taskResult: %v", err)
}
w.WriteHeader(http.StatusOK)
a.pendingMu.Lock()
respCh, ok := a.pendingTasks[taskID]
delete(a.pendingTasks, taskID)
a.pendingMu.Unlock()
if ok {
// Send the entire taskData (which includes Python's alert *request*) to SyncWithDavinci
select {
case respCh <- taskData:
log.Printf("msgEndpoint: Successfully sent taskData to go channel for task %s", taskID)
default:
log.Printf("msgEndpoint: WARNING - Could not send to respCh for task %s. Channel full/listener gone.", taskID)
// If SyncWithDavinci is gone but Python wanted an alert, we *could* emit it here as a fallback.
// However, this implies SyncWithDavinci might have timed out or errored earlier.
if taskData.ShouldShowAlert && a.licenseValid {
log.Printf("msgEndpoint: SyncWithDavinci listener gone for task %s, but Python requested alert. Emitting globally.", taskID)
runtime.EventsEmit(a.ctx, "showAlert", map[string]interface{}{
"title": taskData.AlertTitle,
"message": taskData.AlertMessage,
"severity": taskData.AlertSeverity,
})
}
}
} else {
log.Printf("msgEndpoint: Warning - Received 'taskResult' for taskID '%s', but no pending task found.", taskID)
// Similar to above, if no pending task, but Python wanted an alert for this orphaned task_id.
if taskData.ShouldShowAlert && a.licenseValid {
log.Printf("msgEndpoint: No pending task for %s, but Python requested alert. Emitting globally.", taskID)
runtime.EventsEmit(a.ctx, "showAlert", map[string]interface{}{
"title": taskData.AlertTitle,
"message": taskData.AlertMessage,
"severity": taskData.AlertSeverity,
})
}
}
}
}
fmt.Fprintln(w, "All messages processed.")
}
func (a *App) GetProjectDataPayloadType() ProjectDataPayload {
return ProjectDataPayload{
ProjectName: "",
Timeline: Timeline{
Name: "",
FPS: 0,
VideoTrackItems: nil,
AudioTrackItems: nil,
},
Files: nil,
}
}
func (a *App) SyncWithDavinci() (*PythonCommandResponse, error) { // Use your actual PythonCommandResponse type
if !a.pythonReady {
// This error will be caught by JS, and a toast will be shown. No AlertIssued flag needed.
return nil, fmt.Errorf("python backend not ready")
}
taskID := uuid.NewString()
// Use the correct type for PythonCommandResponse, e.g., main.PythonCommandResponse
respCh := make(chan PythonCommandResponse, 1)
a.pendingMu.Lock()
a.pendingTasks[taskID] = respCh
a.pendingMu.Unlock()
// Cleanup deferred to ensure it runs
defer func() {
a.pendingMu.Lock()
delete(a.pendingTasks, taskID)
a.pendingMu.Unlock()
log.Printf("Go: Cleaned up sync task %s", taskID)
}()
params := map[string]interface{}{
"taskId": taskID,
}
pyAckResp, err := a.SendCommandToPython("sync", taskID, params) // This is the initial ACK from Python
if err != nil {
return nil, fmt.Errorf("failed to send command to python: %w", err)
}
if pyAckResp.Status != "acknowledged" {
return nil, fmt.Errorf("python command acknowledgement error: %s", pyAckResp.Message)
}
log.Printf("Go: Waiting for final Python response for task %s...", taskID)
finalResponse := <-respCh // Wait for Python's actual processing response
log.Printf("Go: Received final Python response for task %s", taskID)
if finalResponse.ShouldShowAlert {
log.Printf("Go: Python requested an alert. Title: '%s', Message: '%s', Severity: '%s'",
finalResponse.AlertTitle, finalResponse.AlertMessage, finalResponse.AlertSeverity)
runtime.EventsEmit(a.ctx, "showAlert", map[string]interface{}{
"title": finalResponse.AlertTitle,
"message": finalResponse.AlertMessage,
"severity": finalResponse.AlertSeverity,
})
finalResponse.AlertIssued = true
if finalResponse.Status == "" || finalResponse.Status == "success" { // If Python didn't explicitly set status to error
finalResponse.Status = "error" // Default to error if an alert is flagged
}
if finalResponse.Message == "" && finalResponse.AlertMessage != "" {
finalResponse.Message = finalResponse.AlertMessage
}
}
if finalResponse.Status != "success" {
log.Printf("Go: Python task %s reported status '%s'. AlertIssued: %t. Message: %s",
taskID, finalResponse.Status, finalResponse.AlertIssued, finalResponse.Message)
return &finalResponse, nil
}
// Python reported success, and no alert was needed (or it was handled)
log.Printf("Go: Python task %s reported success. Message: %s", taskID, finalResponse.Message)
return &finalResponse, nil // finalResponse.AlertIssued will be false if no alert was processed
}
func (a *App) MakeFinalTimeline(projectData *ProjectDataPayload, makeNewTimeline bool) (*PythonCommandResponse, error) {
if !a.pythonReady {
return nil, fmt.Errorf("python backend not ready")
}
// kind of working measure to make sure only one request is sent to Python at a time.
if a.isApplyingEdits {
return nil, fmt.Errorf("makeFinalTimeline already running")
}
a.isApplyingEdits = true
defer func() {
a.isApplyingEdits = false
}()
runtime.EventsEmit(a.ctx, "showFinalTimelineProgress")
// Adopt the async task pattern
taskID := uuid.NewString()
respCh := make(chan PythonCommandResponse, 1)
a.pendingMu.Lock()
a.pendingTasks[taskID] = respCh
a.pendingMu.Unlock()
log.Printf("Go: Starting task 'makeFinalTimeline' with ID: %s", taskID)
// Add taskId to the parameters sent to Python
params := map[string]interface{}{
"taskId": taskID,
"projectData": projectData,
"makeNewTimeline": makeNewTimeline,
}
pyAckResp, err := a.SendCommandToPython("makeFinalTimeline", taskID, params)
if err != nil {
return nil, fmt.Errorf("failed to send 'makeFinalTimeline' command: %w", err)
}
if pyAckResp.Status != "acknowledged" {
return nil, fmt.Errorf("python 'makeFinalTimeline' ack error: %s", pyAckResp.Message)
}
log.Printf("Go: Waiting for final timeline result for task %s...", taskID)
// Wait for the final result from the channel
finalResponse := <-respCh
log.Printf("Go: Received final timeline result for task %s: %v", taskID, finalResponse)
// Process the final response (handle alerts, errors, etc.)
if finalResponse.ShouldShowAlert {
runtime.EventsEmit(a.ctx, "showAlert", map[string]interface{}{
"title": finalResponse.AlertTitle, "message": finalResponse.AlertMessage, "severity": finalResponse.AlertSeverity,
})
finalResponse.AlertIssued = true
if finalResponse.Status != "error" {
finalResponse.Status = "error"
}
if finalResponse.Message == "" {
finalResponse.Message = finalResponse.AlertMessage
}
}
// Return the full response object, which is more flexible than just a string
if finalResponse.Status != "success" {
// We return the response object so the frontend can see the message, even on error.
// The second return value (error) is nil because the *communication* was successful.
// The frontend should check the Status field of the returned object.
log.Printf("Final response status is not success. TaskID: %s", taskID)
return &finalResponse, nil
}
runtime.EventsEmit(a.ctx, "finished")
log.Print("finished making final timeline.")
return &finalResponse, nil
}
func (a *App) SetDavinciPlayhead(timecode string) (bool, error) {
if !a.pythonReady {
return false, fmt.Errorf("python backend not ready")
}
taskID := uuid.NewString()
params := map[string]interface{}{
"taskId": taskID,
"time": timecode,
}
// 3. Send the command and just check the acknowledgement
pyResponse, err := a.SendCommandToPython("setPlayhead", taskID, params)
if err != nil {
return false, fmt.Errorf("failed to send 'SetDavinciPlayhead' command: %w", err)
}
if pyResponse.Status != "acknowledged" {
return false, fmt.Errorf("python 'SetDavinciPlayhead' ack error: %s", pyResponse.Message)
}
if pyResponse.Status != "acknowledged" {
return false, nil
}
return true, nil
}