-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1931 lines (1681 loc) · 54.9 KB
/
app.go
File metadata and controls
1931 lines (1681 loc) · 54.9 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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"strconv"
"strings"
"sync"
"time"
core "github.com/kushiemoon-dev/flacidal-core"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct - main Wails application
type App struct {
ctx context.Context
config *core.Config
db *core.Database
tidalClient *core.TidalClient
spotifySearch *core.SpotifyClient // For search/matching (Client Credentials, no login)
matcher *core.Matcher
downloader *core.TidalHifiService // FLAC downloader
downloadManager *core.DownloadManager // Concurrent download manager
logBuffer *core.LogBuffer // Log buffer for Terminal page
sourceManager *core.SourceManager // Multi-source manager
tidalSource *core.TidalSource // Tidal source
qobuzSource *core.QobuzSource // Qobuz source
trackContentMap sync.Map // maps trackID (int) → contentID (string) for history tracking
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{}
}
// startup is called when the app starts
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
// Initialize log buffer
a.logBuffer = core.NewLogBuffer(500)
a.logBuffer.Info("FLACidal starting...")
// Load config
config, err := core.LoadConfig()
if err != nil {
a.logBuffer.Warn("Could not load config: " + err.Error())
config = &core.Config{}
}
a.config = config
a.logBuffer.Success("Configuration loaded")
// Initialize database
db, err := core.NewDatabase()
if err != nil {
a.logBuffer.Error("Database initialization failed: " + err.Error())
} else {
a.logBuffer.Success("Database initialized")
}
a.db = db
// Initialize Tidal client (uses internal credentials, no user config needed)
a.tidalClient = core.NewTidalClientDefault()
a.tidalClient.SetCountryCode(config.CountryCode)
if config.ProxyURL != "" {
if err := a.tidalClient.SetProxy(config.ProxyURL); err != nil {
a.logBuffer.Warn("Proxy config error (Tidal API): " + err.Error())
} else {
a.logBuffer.Info("Tidal API proxy: " + config.ProxyURL)
}
}
a.logBuffer.Info("Tidal client ready")
// Initialize Spotify search client (Client Credentials, no login needed)
a.spotifySearch = core.NewSpotifyClientForSearch()
// Initialize matcher
a.matcher = core.NewMatcher(a.spotifySearch, a.db)
// Initialize FLAC downloader
a.downloader = core.NewTidalHifiService()
// Attach logger so endpoint rotation events appear in Terminal page
a.downloader.SetLogger(a.logBuffer)
if config.ProxyURL != "" {
if err := a.downloader.SetProxy(config.ProxyURL); err != nil {
a.logBuffer.Warn("Proxy config error (downloader): " + err.Error())
}
}
// Apply custom endpoints if configured
if len(config.TidalHifiEndpoints) > 0 {
a.downloader.SetEndpoints(config.TidalHifiEndpoints)
a.logBuffer.Info(fmt.Sprintf("Tidal HiFi endpoint pool: %d endpoints configured", len(config.TidalHifiEndpoints)))
}
// Set download options from config
quality := config.DownloadQuality
if quality == "" {
quality = "LOSSLESS"
}
fileNameFormat := config.FileNameFormat
if fileNameFormat == "" {
fileNameFormat = "{artist} - {title}"
}
a.downloader.SetOptions(core.DownloadOptions{
Quality: quality,
FileNameFormat: fileNameFormat,
OrganizeFolders: config.OrganizeFolders,
FolderTemplate: config.FolderTemplate,
EmbedCover: config.EmbedCover,
SaveCoverFile: config.SaveCoverFile,
AutoAnalyze: config.AutoAnalyze,
AutoQualityFallback: config.AutoQualityFallback,
QualityFallbackOrder: config.QualityOrder,
FirstArtistOnly: config.FirstArtistOnly,
SkipExisting: config.SkipExisting,
ArtistSeparator: config.ArtistSeparator,
PlaylistSubfolder: config.PlaylistSubfolder,
SaveLyricsFile: config.SaveLyricsFile,
SaveFolderCover: config.SaveFolderCover,
})
a.logBuffer.Info("FLAC downloader service ready")
// Initialize download manager with 4 concurrent workers
a.downloadManager = core.NewDownloadManager(a.downloader, 4)
// Serialized event channel to avoid concurrent ExecuteJS calls that crash WebKit on Linux.
// Events are queued and emitted one at a time from a dedicated goroutine.
type progressEvent struct {
trackID int
status string
result *core.DownloadResult
}
eventCh := make(chan progressEvent, 64)
go func() {
for ev := range eventCh {
runtime.EventsEmit(ctx, "download-progress", map[string]interface{}{
"trackId": ev.trackID,
"status": ev.status,
"result": ev.result,
})
// Small delay between events to let WebKit/GTK process JS
time.Sleep(50 * time.Millisecond)
}
}()
a.downloadManager.SetProgressCallback(func(trackID int, status string, result *core.DownloadResult) {
// Log download events
if a.logBuffer != nil {
switch status {
case "queued":
a.logBuffer.Info(fmt.Sprintf("Track %d added to queue", trackID))
case "downloading":
a.logBuffer.Info(fmt.Sprintf("Downloading track %d...", trackID))
case "completed":
if result != nil {
a.logBuffer.Success(fmt.Sprintf("Downloaded: %s (quality: %s)", result.FilePath, result.Quality))
if result.QualityMismatch {
a.logBuffer.Warn(fmt.Sprintf("Quality mismatch: requested %s but got %s",
result.RequestedQuality, result.Quality))
}
if result.Analysis != nil {
if result.Analysis.IsTrueLossless {
a.logBuffer.Info(fmt.Sprintf("Analysis: %s - True lossless", result.Analysis.VerdictLabel))
} else {
a.logBuffer.Warn(fmt.Sprintf("Analysis: %s - May be upscaled from lossy source", result.Analysis.VerdictLabel))
}
}
}
case "error":
if result != nil && result.Error != "" {
a.logBuffer.Error(fmt.Sprintf("Download failed: %s", result.Error))
}
case "cancelled":
a.logBuffer.Warn(fmt.Sprintf("Track %d cancelled", trackID))
}
}
// Update download history counts
if a.db != nil {
switch status {
case "completed":
if cid, ok := a.trackContentMap.Load(trackID); ok {
_ = a.db.IncrementDownloadCounts(cid.(string), true)
a.trackContentMap.Delete(trackID)
}
case "error":
if cid, ok := a.trackContentMap.Load(trackID); ok {
_ = a.db.IncrementDownloadCounts(cid.(string), false)
a.trackContentMap.Delete(trackID)
}
}
}
// Queue event for serialized emission (blocking — workers wait
// briefly if buffer is full, which is negligible vs download time)
eventCh <- progressEvent{trackID, status, result}
})
a.downloadManager.Start()
a.logBuffer.Success("Download manager started (4 workers)")
// Initialize source manager
a.sourceManager = core.NewSourceManager()
// Initialize Tidal source
a.tidalSource = core.NewTidalSource()
a.tidalSource.SetAvailable(config.TidalEnabled)
a.sourceManager.RegisterSource(a.tidalSource)
a.logBuffer.Info("Tidal source registered")
// Initialize Qobuz source
a.qobuzSource = core.NewQobuzSource(config.QobuzAppID, config.QobuzAppSecret)
a.qobuzSource.SetLogger(a.logBuffer)
if config.ProxyURL != "" {
if err := a.qobuzSource.SetProxy(config.ProxyURL); err != nil {
a.logBuffer.Warn("Proxy config error (Qobuz): " + err.Error())
}
}
if len(config.QobuzEndpoints) > 0 {
a.qobuzSource.SetEndpoints(config.QobuzEndpoints)
a.logBuffer.Info(fmt.Sprintf("Qobuz endpoint pool: %d endpoints configured", len(config.QobuzEndpoints)))
}
if config.QobuzAuthToken != "" {
a.qobuzSource.SetCredentials(config.QobuzAppID, config.QobuzAppSecret, config.QobuzAuthToken)
}
a.sourceManager.RegisterSource(a.qobuzSource)
if config.QobuzEnabled && config.QobuzAppID != "" {
a.logBuffer.Info("Qobuz source registered")
}
// Set preferred source
if config.PreferredSource != "" {
a.sourceManager.SetPreferredSource(config.PreferredSource)
}
// Configure inter-source fallback for download manager
if config.QobuzEnabled && a.qobuzSource.IsAvailable() {
a.downloadManager.SetFallbackQobuzSource(a.qobuzSource)
}
sourceOrder := config.SourceOrder
if len(sourceOrder) == 0 {
// Default: prefer Tidal, fall back to Qobuz if enabled
if config.QobuzEnabled {
sourceOrder = []string{"tidal", "qobuz"}
} else {
sourceOrder = []string{"tidal"}
}
}
a.downloadManager.SetSourceOrder(sourceOrder)
a.downloadManager.SetGenerateM3U8(config.GenerateM3U8)
a.downloadManager.SetSkipUnavailable(config.SkipUnavailableTracks)
a.logBuffer.Success("FLACidal ready!")
}
// shutdown is called when the app is closing
func (a *App) shutdown(ctx context.Context) {
// Stop download manager
if a.downloadManager != nil {
a.downloadManager.Stop()
}
// Save config
if a.config != nil {
core.SaveConfig(a.config)
}
// Close database
if a.db != nil {
a.db.Close()
}
}
// =============================================================================
// Config Methods (exposed to frontend)
// =============================================================================
// GetConfig returns current configuration
func (a *App) GetConfig() *core.Config {
return a.config
}
// SaveConfig saves configuration
func (a *App) SaveConfig(config core.Config) error {
a.config = &config
if a.downloadManager != nil {
a.downloadManager.SetGenerateM3U8(config.GenerateM3U8)
a.downloadManager.SetSkipUnavailable(config.SkipUnavailableTracks)
}
if a.downloader != nil {
opts := a.downloader.GetOptions()
opts.AutoQualityFallback = config.AutoQualityFallback
opts.QualityFallbackOrder = config.QualityOrder
opts.FirstArtistOnly = config.FirstArtistOnly
opts.SkipExisting = config.SkipExisting
opts.ArtistSeparator = config.ArtistSeparator
opts.PlaylistSubfolder = config.PlaylistSubfolder
if config.DownloadQuality != "" {
opts.Quality = config.DownloadQuality
}
if config.FileNameFormat != "" {
opts.FileNameFormat = config.FileNameFormat
}
opts.OrganizeFolders = config.OrganizeFolders
opts.FolderTemplate = config.FolderTemplate
opts.EmbedCover = config.EmbedCover
opts.SaveCoverFile = config.SaveCoverFile
opts.AutoAnalyze = config.AutoAnalyze
opts.SaveLyricsFile = config.SaveLyricsFile
opts.SaveFolderCover = config.SaveFolderCover
a.downloader.SetOptions(opts)
}
if a.downloadManager != nil {
a.downloadManager.SetSourceOrder(config.SourceOrder)
}
// Apply proxy changes immediately (no restart needed)
if a.tidalClient != nil {
if err := a.tidalClient.SetProxy(config.ProxyURL); err != nil {
a.logBuffer.Warn("Proxy config error (Tidal API): " + err.Error())
}
}
if a.downloader != nil {
if err := a.downloader.SetProxy(config.ProxyURL); err != nil {
a.logBuffer.Warn("Proxy config error (downloader): " + err.Error())
}
}
if a.qobuzSource != nil {
if err := a.qobuzSource.SetProxy(config.ProxyURL); err != nil {
a.logBuffer.Warn("Proxy config error (Qobuz): " + err.Error())
}
}
return core.SaveConfig(&config)
}
// ResetToDefaults resets configuration to default values
func (a *App) ResetToDefaults() (*core.Config, error) {
defaultCfg := core.GetDefaultConfig()
// Preserve download folder if set
if a.config != nil && a.config.DownloadFolder != "" {
defaultCfg.DownloadFolder = a.config.DownloadFolder
}
a.config = defaultCfg
if err := core.SaveConfig(defaultCfg); err != nil {
return nil, err
}
if a.logBuffer != nil {
a.logBuffer.Info("Configuration reset to defaults")
runtime.EventsEmit(a.ctx, "log", a.logBuffer.Info("Settings restored to defaults"))
}
return defaultCfg, nil
}
// GetConnectionStatus returns service status
func (a *App) GetConnectionStatus() map[string]interface{} {
return map[string]interface{}{
"tidalReady": true, // Always ready (uses internal credentials)
"spotifySearch": a.spotifySearch != nil,
}
}
// EndpointStatus represents the status of an API endpoint
type EndpointStatus struct {
Name string `json:"name"`
URL string `json:"url"`
Status string `json:"status"` // "online", "offline", "slow"
LatencyMs int64 `json:"latencyMs"` // Response time in milliseconds
}
// CheckAPIStatus checks the status of all configured API endpoints
func (a *App) CheckAPIStatus() []EndpointStatus {
endpoints := []struct {
name string
url string
}{
{"Tidal HiFi Proxy", "https://vogel.qqdl.site"},
{"Metadata (hifi-one)", "https://hifi-one.spotisaver.net"},
{"Metadata (hifi-two)", "https://hifi-two.spotisaver.net"},
{"Metadata (triton)", "https://triton.squid.wtf"},
{"Tidal API", "https://api.tidalhifi.com"},
}
// Add Qobuz if enabled
if a.config != nil && a.config.QobuzEnabled {
endpoints = append(endpoints, struct {
name string
url string
}{"Qobuz API", "https://www.qobuz.com/api.json/0.2"})
}
results := make([]EndpointStatus, len(endpoints))
var wg sync.WaitGroup
client := &http.Client{Timeout: 10 * time.Second}
for i, ep := range endpoints {
wg.Add(1)
go func(idx int, name, url string) {
defer wg.Done()
status := EndpointStatus{Name: name, URL: url}
start := time.Now()
resp, err := client.Head(url)
latency := time.Since(start)
status.LatencyMs = latency.Milliseconds()
if err != nil {
status.Status = "offline"
} else {
resp.Body.Close()
if resp.StatusCode >= 500 {
status.Status = "offline"
} else if latency > 3*time.Second {
status.Status = "slow"
} else {
status.Status = "online"
}
}
results[idx] = status
}(i, ep.name, ep.url)
}
wg.Wait()
return results
}
// OpenConfigFolder opens the app config directory in the system file manager
func (a *App) OpenConfigFolder() error {
configDir := core.GetDataDir()
return openFolder(configDir)
}
// openFolder opens a folder in the system file manager
func openFolder(path string) error {
switch goruntime.GOOS {
case "darwin":
return exec.Command("open", path).Start()
case "windows":
return exec.Command("explorer", path).Start()
default:
return exec.Command("xdg-open", path).Start()
}
}
// =============================================================================
// Tidal Methods (exposed to frontend)
// =============================================================================
// SetTidalCredentials saves Tidal client credentials
func (a *App) SetTidalCredentials(clientID, clientSecret string) error {
a.config.TidalClientID = clientID
a.config.TidalClientSecret = clientSecret
// Initialize client with new credentials
a.tidalClient = core.NewTidalClient(clientID, clientSecret)
return core.SaveConfig(a.config)
}
// FetchTidalPlaylist fetches a public playlist from Tidal URL
func (a *App) FetchTidalPlaylist(url string) (*core.TidalPlaylist, error) {
// Parse URL to get playlist UUID
id, contentType, err := core.ParseTidalURL(url)
if err != nil {
return nil, err
}
if contentType != "playlist" {
return nil, fmt.Errorf("URL is not a playlist (got %s)", contentType)
}
return a.downloader.GetPlaylistFromProxy(id)
}
// FetchTidalContent fetches playlist, album, or single track from any Tidal URL
func (a *App) FetchTidalContent(url string) (map[string]interface{}, error) {
id, contentType, err := core.ParseTidalURL(url)
if err != nil {
return nil, err
}
result := map[string]interface{}{
"type": contentType,
"id": id,
}
switch contentType {
case "playlist":
playlist, err := a.downloader.GetPlaylistFromProxy(id)
if err != nil {
return nil, err
}
result["title"] = playlist.Title
result["creator"] = playlist.Creator
result["coverUrl"] = playlist.CoverURL
result["tracks"] = playlist.Tracks
result["trackCount"] = len(playlist.Tracks)
case "album":
album, err := a.downloader.GetAlbumFromProxy(id)
if err != nil {
return nil, err
}
result["title"] = album.Title
result["creator"] = album.Artist
result["coverUrl"] = album.CoverURL
result["tracks"] = album.Tracks
result["trackCount"] = len(album.Tracks)
result["albumType"] = album.AlbumType
case "track":
trackIDInt, convErr := strconv.Atoi(id)
if convErr != nil {
return nil, fmt.Errorf("invalid track ID: %s", id)
}
track, err := a.downloader.GetTrackAsTidalTrack(trackIDInt)
if err != nil {
return nil, err
}
result["title"] = track.Title
result["creator"] = track.Artist
result["coverUrl"] = track.CoverURL
result["tracks"] = []core.TidalTrack{*track}
result["trackCount"] = 1
case "mix":
mix, err := a.downloader.GetMixFromProxy(id)
if err != nil {
return nil, err
}
result["title"] = mix.Title
result["creator"] = mix.Creator
result["coverUrl"] = mix.CoverURL
result["tracks"] = mix.Tracks
result["trackCount"] = len(mix.Tracks)
case "artist":
artist, err := a.tidalClient.GetArtistDiscography(id)
if err != nil {
return nil, err
}
result["title"] = artist.Name
result["creator"] = artist.Name
result["coverUrl"] = artist.PictureURL
result["albums"] = artist.Albums
result["albumCount"] = len(artist.Albums)
result["artistId"] = artist.ID
result["tracks"] = []core.TidalTrack{} // empty — tracks loaded per album
default:
return nil, fmt.Errorf("unsupported content type: %s", contentType)
}
return result, nil
}
// ValidateTidalURL checks if a URL is a valid Tidal URL
func (a *App) ValidateTidalURL(url string) map[string]interface{} {
id, contentType, err := core.ParseTidalURL(url)
if err != nil {
return map[string]interface{}{
"valid": false,
"error": err.Error(),
}
}
return map[string]interface{}{
"valid": true,
"id": id,
"type": contentType,
}
}
// =============================================================================
// Database Methods (exposed to frontend)
// =============================================================================
// GetCacheStats returns track cache statistics
func (a *App) GetCacheStats() map[string]interface{} {
if a.db == nil {
return map[string]interface{}{"error": "database not initialized"}
}
total, byMethod, err := a.db.GetCacheStats()
if err != nil {
return map[string]interface{}{"error": err.Error()}
}
return map[string]interface{}{
"total": total,
"byMethod": byMethod,
}
}
// GetDownloadHistory returns all download history
func (a *App) GetDownloadHistory() ([]core.DownloadRecord, error) {
if a.db == nil {
return nil, nil
}
return a.db.GetAllDownloadRecords()
}
// GetDownloadHistoryFiltered returns filtered download history with pagination
func (a *App) GetDownloadHistoryFiltered(filter map[string]interface{}) (map[string]interface{}, error) {
if a.db == nil {
return nil, fmt.Errorf("database not initialized")
}
// Parse filter options
dbFilter := core.HistoryFilter{}
if ct, ok := filter["contentType"].(string); ok {
dbFilter.ContentType = ct
}
if search, ok := filter["search"].(string); ok {
dbFilter.Search = search
}
if limit, ok := filter["limit"].(float64); ok {
dbFilter.Limit = int(limit)
}
if offset, ok := filter["offset"].(float64); ok {
dbFilter.Offset = int(offset)
}
records, total, err := a.db.GetDownloadRecordsFiltered(dbFilter)
if err != nil {
return nil, err
}
return map[string]interface{}{
"records": records,
"total": total,
}, nil
}
// DeleteHistoryRecord deletes a single download history record
func (a *App) DeleteHistoryRecord(id int64) error {
if a.db == nil {
return fmt.Errorf("database not initialized")
}
return a.db.DeleteDownloadRecord(id)
}
// ClearDownloadHistory removes all download history
func (a *App) ClearDownloadHistory() error {
if a.db == nil {
return fmt.Errorf("database not initialized")
}
err := a.db.ClearAllHistory()
if err == nil && a.logBuffer != nil {
a.logBuffer.Info("Download history cleared")
}
return err
}
// RefetchFromHistory re-downloads content from history
func (a *App) RefetchFromHistory(tidalContentID string) (map[string]interface{}, error) {
if a.db == nil {
return nil, fmt.Errorf("database not initialized")
}
// Get the record to find the content type
record, err := a.db.GetDownloadRecord(tidalContentID)
if err != nil {
return nil, err
}
if record == nil {
return nil, fmt.Errorf("history record not found")
}
// Reconstruct the Tidal URL
var url string
switch record.ContentType {
case "playlist":
url = fmt.Sprintf("https://tidal.com/browse/playlist/%s", tidalContentID)
case "album":
url = fmt.Sprintf("https://tidal.com/browse/album/%s", tidalContentID)
case "track":
url = fmt.Sprintf("https://tidal.com/browse/track/%s", tidalContentID)
default:
return nil, fmt.Errorf("unknown content type: %s", record.ContentType)
}
// Fetch the content
return a.FetchTidalContent(url)
}
// GetMatchFailures returns all match failures
func (a *App) GetMatchFailures() ([]core.MatchFailure, error) {
if a.db == nil {
return nil, nil
}
return a.db.GetMatchFailures()
}
// =============================================================================
// App Info
// =============================================================================
// GetAppVersion returns application version
func (a *App) GetAppVersion() string {
return "4.0.5"
}
// UpdateInfo represents available update information
type UpdateInfo struct {
HasUpdate bool `json:"hasUpdate"`
Version string `json:"version"`
URL string `json:"url"`
ReleaseURL string `json:"releaseUrl"`
}
// CheckForUpdate checks GitHub for a newer release
func (a *App) CheckForUpdate() (*UpdateInfo, error) {
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", "https://api.github.com/repos/kushiemoon-dev/flacidal/releases/latest", nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "FLACidal/"+a.GetAppVersion())
resp, err := client.Do(req)
if err != nil {
return &UpdateInfo{HasUpdate: false}, nil
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return &UpdateInfo{HasUpdate: false}, nil
}
var release struct {
TagName string `json:"tag_name"`
HTMLURL string `json:"html_url"`
Assets []struct {
BrowserDownloadURL string `json:"browser_download_url"`
} `json:"assets"`
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return &UpdateInfo{HasUpdate: false}, nil
}
if err := json.Unmarshal(body, &release); err != nil {
return &UpdateInfo{HasUpdate: false}, nil
}
latestVersion := strings.TrimPrefix(release.TagName, "v")
currentVersion := a.GetAppVersion()
hasUpdate := latestVersion != currentVersion && latestVersion > currentVersion
downloadURL := release.HTMLURL
if len(release.Assets) > 0 {
downloadURL = release.Assets[0].BrowserDownloadURL
}
return &UpdateInfo{
HasUpdate: hasUpdate,
Version: latestVersion,
URL: downloadURL,
ReleaseURL: release.HTMLURL,
}, nil
}
// =============================================================================
// Logging Methods (exposed to frontend)
// =============================================================================
// GetLogs returns all log entries
func (a *App) GetLogs() []core.LogEntry {
if a.logBuffer == nil {
return []core.LogEntry{}
}
return a.logBuffer.GetAll()
}
// ClearLogs clears all log entries
func (a *App) ClearLogs() {
if a.logBuffer != nil {
a.logBuffer.Clear()
}
}
// AddLog adds a log entry (for testing/debug)
func (a *App) AddLog(level, message string) {
if a.logBuffer != nil {
entry := a.logBuffer.Add(level, message)
// Emit log event to frontend
runtime.EventsEmit(a.ctx, "log", entry)
}
}
// =============================================================================
// Matcher Methods (exposed to frontend)
// =============================================================================
// MatchPlaylistTracks matches all tracks from a Tidal playlist to Spotify
func (a *App) MatchPlaylistTracks(tracks []core.TidalTrack) []core.MatchResult {
if a.matcher == nil {
return nil
}
return a.matcher.MatchPlaylist(tracks)
}
// MatchSingleTrack matches a single track
func (a *App) MatchSingleTrack(track core.TidalTrack) core.MatchResult {
if a.matcher == nil {
return core.MatchResult{TidalTrack: track, Matched: false, MatchMethod: "none"}
}
return a.matcher.MatchTrack(track)
}
// =============================================================================
// Download Methods (exposed to frontend)
// =============================================================================
// OpenFLACFilesDialog opens a multi-file picker filtered to FLAC files.
func (a *App) OpenFLACFilesDialog() ([]string, error) {
paths, err := runtime.OpenMultipleFilesDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select FLAC Files to Analyze",
Filters: []runtime.FileFilter{
{DisplayName: "FLAC Audio (*.flac)", Pattern: "*.flac"},
},
})
if err != nil {
return nil, err
}
return paths, nil
}
// SelectDownloadFolder opens a folder picker dialog
func (a *App) SelectDownloadFolder() (string, error) {
folder, err := runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
Title: "Select Download Folder",
})
if err != nil {
return "", err
}
return folder, nil
}
// GetDownloadFolder returns the configured download folder
func (a *App) GetDownloadFolder() string {
if a.config != nil && a.config.DownloadFolder != "" {
return a.config.DownloadFolder
}
return ""
}
// SetDownloadFolder saves the download folder to config
func (a *App) SetDownloadFolder(folder string) error {
if a.config == nil {
a.config = &core.Config{}
}
a.config.DownloadFolder = folder
return core.SaveConfig(a.config)
}
// IsDownloaderAvailable checks if the download service is reachable
func (a *App) IsDownloaderAvailable() bool {
if a.downloader == nil {
return false
}
return a.downloader.IsAvailable()
}
// DownloadTrack downloads a single track by its Tidal ID
func (a *App) DownloadTrack(trackID int, outputDir string) (*core.DownloadResult, error) {
if a.downloader == nil {
return nil, fmt.Errorf("downloader not initialized")
}
if outputDir == "" {
return nil, fmt.Errorf("no output directory specified")
}
return a.downloader.DownloadTrack(trackID, outputDir, "", "")
}
// DownloadTrackFromTidal downloads using TidalTrack data (for UI convenience)
func (a *App) DownloadTrackFromTidal(track core.TidalTrack, outputDir string) (*core.DownloadResult, error) {
if a.downloader == nil {
return nil, fmt.Errorf("downloader not initialized")
}
if outputDir == "" {
return nil, fmt.Errorf("no output directory specified")
}
return a.downloader.DownloadTrack(track.ID, outputDir, track.Copyright, track.Label)
}
// QueueDownloads queues multiple tracks for concurrent download
func (a *App) QueueDownloads(tracks []core.TidalTrack, outputDir string, contentName string, contentID string, contentType string) (int, error) {
if a.downloadManager == nil {
return 0, fmt.Errorf("download manager not initialized")
}
if outputDir == "" {
return 0, fmt.Errorf("no output directory specified")
}
// Create subfolder with content name (playlist/album/track title)
if contentName != "" {
outputDir = filepath.Join(outputDir, core.SanitizeFileName(contentName))
if err := os.MkdirAll(outputDir, 0755); err != nil {
return 0, fmt.Errorf("failed to create folder: %w", err)
}
}
queued := a.downloadManager.QueueMultiple(tracks, outputDir)
// Save initial history record
if a.db != nil && contentID != "" {
_ = a.db.SaveDownloadRecord(&core.DownloadRecord{
TidalContentID: contentID,
TidalContentName: contentName,
ContentType: contentType,
TracksTotal: queued,
})
}
// Map each trackID → contentID for progress callback
for _, t := range tracks {
a.trackContentMap.Store(t.ID, contentID)
}
return queued, nil
}
// QueueQobuzDownloads queues Qobuz-sourced tracks for concurrent download
func (a *App) QueueQobuzDownloads(tracks []core.SourceTrack, outputDir string, contentName string) (int, error) {
if a.downloadManager == nil {
return 0, fmt.Errorf("download manager not initialized")
}
if outputDir == "" {
return 0, fmt.Errorf("no output directory specified")
}
if contentName != "" {
outputDir = filepath.Join(outputDir, core.SanitizeFileName(contentName))
if err := os.MkdirAll(outputDir, 0755); err != nil {
return 0, fmt.Errorf("failed to create folder: %w", err)
}
}
return a.downloadManager.QueueQobuzTracks(tracks, outputDir), nil
}
// QueueArtistAlbum fetches a Tidal album's tracks and queues them all for download.
// outputDir should be the artist folder; an album subfolder is created automatically.
func (a *App) QueueArtistAlbum(albumID string, artistName string, outputDir string) (int, error) {
if a.downloadManager == nil {
return 0, fmt.Errorf("download manager not initialized")
}
if outputDir == "" {
return 0, fmt.Errorf("no output directory specified")
}
album, err := a.downloader.GetAlbumFromProxy(albumID)
if err != nil {
return 0, fmt.Errorf("failed to fetch album: %w", err)
}
// Create {Artist}/{Album} folder structure
artistFolder := core.SanitizeFileName(artistName)
if artistFolder == "" {
artistFolder = core.SanitizeFileName(album.Artist)
}
albumFolder := core.SanitizeFileName(album.Title)
albumDir := filepath.Join(outputDir, artistFolder, albumFolder)
if err := os.MkdirAll(albumDir, 0755); err != nil {
return 0, fmt.Errorf("failed to create album folder: %w", err)
}
queued := a.downloadManager.QueueMultiple(album.Tracks, albumDir)
return queued, nil
}
// DownloadArtistAssets downloads the artist's profile picture and banner image.
// Files are saved to {outputDir}/{artistName}/ as profile.jpg, profile_hires.jpg, banner.jpg.
// Returns the number of files successfully downloaded.
func (a *App) DownloadArtistAssets(artistID string, artistName string, outputDir string) (int, error) {
if outputDir == "" {
return 0, fmt.Errorf("no output directory specified")
}
name, pictureID, err := a.tidalClient.GetArtistPictureID(artistID)
if err != nil {
return 0, fmt.Errorf("failed to fetch artist info: %w", err)
}
if pictureID == "" {
return 0, fmt.Errorf("artist has no picture available")
}
// Use fetched name if caller didn't provide one
if artistName == "" {