-
-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathapp.go
More file actions
2008 lines (1698 loc) · 57.7 KB
/
app.go
File metadata and controls
2008 lines (1698 loc) · 57.7 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/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"net/http"
"strings"
"sync"
"time"
"github.com/afkarxyz/SpotiFLAC/backend"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
type App struct {
ctx context.Context
}
type CurrentIPInfo struct {
IP string `json:"ip"`
Country string `json:"country"`
CountryCode string `json:"country_code,omitempty"`
Source string `json:"source,omitempty"`
}
const checkOperationTimeout = 10 * time.Second
func NewApp() *App {
return &App{}
}
type timedResult[T any] struct {
value T
err error
}
func runWithTimeout[T any](timeout time.Duration, fn func() (T, error)) (T, error) {
resultCh := make(chan timedResult[T], 1)
go func() {
value, err := fn()
resultCh <- timedResult[T]{value: value, err: err}
}()
select {
case result := <-resultCh:
return result.value, result.err
case <-time.After(timeout):
var zero T
return zero, fmt.Errorf("operation timed out after %s", timeout)
}
}
func containsStreamingURL(body []byte) bool {
trimmedBody := strings.TrimSpace(string(body))
if trimmedBody == "" {
return false
}
var directResp struct {
URL string `json:"url"`
}
if err := json.Unmarshal(body, &directResp); err == nil && isStreamingURL(directResp.URL) {
return true
}
var nestedResp struct {
Data struct {
URL string `json:"url"`
} `json:"data"`
}
if err := json.Unmarshal(body, &nestedResp); err == nil && isStreamingURL(nestedResp.Data.URL) {
return true
}
return isStreamingURL(trimmedBody)
}
func containsLRCLIBResults(body []byte) bool {
trimmedBody := strings.TrimSpace(string(body))
if trimmedBody == "" {
return false
}
var searchResults []map[string]interface{}
if err := json.Unmarshal(body, &searchResults); err == nil {
return len(searchResults) > 0
}
var exactResult map[string]interface{}
if err := json.Unmarshal(body, &exactResult); err == nil {
return len(exactResult) > 0
}
return false
}
func containsMusicBrainzResults(body []byte) bool {
trimmedBody := strings.TrimSpace(string(body))
if trimmedBody == "" {
return false
}
var payload struct {
Count int `json:"count"`
Recordings []json.RawMessage `json:"recordings"`
}
if err := json.Unmarshal(body, &payload); err != nil {
return false
}
return payload.Count > 0 || len(payload.Recordings) > 0
}
func isStreamingURL(raw string) bool {
candidate := strings.TrimSpace(raw)
if candidate == "" {
return false
}
parsed, err := url.Parse(candidate)
if err != nil {
return false
}
return (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != ""
}
func previewResponseBody(body []byte, maxLen int) string {
preview := strings.TrimSpace(string(body))
if maxLen > 0 && len(preview) > maxLen {
return preview[:maxLen] + "..."
}
return preview
}
func fetchCurrentIPInfo() (CurrentIPInfo, error) {
type ipwhoisResponse struct {
Success bool `json:"success"`
IP string `json:"ip"`
Country string `json:"country"`
CountryCode string `json:"country_code"`
Message string `json:"message"`
}
type ipapiResponse struct {
IP string `json:"ip"`
Country string `json:"country_name"`
CountryCode string `json:"country_code"`
Error bool `json:"error"`
Reason string `json:"reason"`
}
client := &http.Client{Timeout: 8 * time.Second}
tryFetch := func(source, reqURL string, parse func(body []byte) (CurrentIPInfo, error)) (CurrentIPInfo, error) {
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return CurrentIPInfo{}, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36")
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return CurrentIPInfo{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return CurrentIPInfo{}, err
}
if resp.StatusCode != http.StatusOK {
return CurrentIPInfo{}, fmt.Errorf("%s returned status %d: %s", source, resp.StatusCode, previewResponseBody(body, 200))
}
info, err := parse(body)
if err != nil {
return CurrentIPInfo{}, err
}
info.Source = source
return info, nil
}
info, err := tryFetch("ipwho.is", "https://ipwho.is/", func(body []byte) (CurrentIPInfo, error) {
var payload ipwhoisResponse
if err := json.Unmarshal(body, &payload); err != nil {
return CurrentIPInfo{}, err
}
if !payload.Success {
return CurrentIPInfo{}, fmt.Errorf("ipwho.is lookup failed: %s", strings.TrimSpace(payload.Message))
}
if strings.TrimSpace(payload.IP) == "" || strings.TrimSpace(payload.Country) == "" {
return CurrentIPInfo{}, fmt.Errorf("ipwho.is returned incomplete IP data")
}
return CurrentIPInfo{
IP: strings.TrimSpace(payload.IP),
Country: strings.TrimSpace(payload.Country),
CountryCode: strings.TrimSpace(payload.CountryCode),
}, nil
})
if err == nil {
return info, nil
}
firstErr := err
info, err = tryFetch("ipapi.co", "https://ipapi.co/json/", func(body []byte) (CurrentIPInfo, error) {
var payload ipapiResponse
if err := json.Unmarshal(body, &payload); err != nil {
return CurrentIPInfo{}, err
}
if payload.Error {
return CurrentIPInfo{}, fmt.Errorf("ipapi.co lookup failed: %s", strings.TrimSpace(payload.Reason))
}
if strings.TrimSpace(payload.IP) == "" || strings.TrimSpace(payload.Country) == "" {
return CurrentIPInfo{}, fmt.Errorf("ipapi.co returned incomplete IP data")
}
return CurrentIPInfo{
IP: strings.TrimSpace(payload.IP),
Country: strings.TrimSpace(payload.Country),
CountryCode: strings.TrimSpace(payload.CountryCode),
}, nil
})
if err == nil {
return info, nil
}
return CurrentIPInfo{}, fmt.Errorf("failed to detect public IP: %v; fallback failed: %v", firstErr, err)
}
func (a *App) GetCurrentIPInfo() (string, error) {
info, err := fetchCurrentIPInfo()
if err != nil {
return "", err
}
payload, err := json.Marshal(info)
if err != nil {
return "", err
}
return string(payload), nil
}
func (a *App) getFirstArtist(artistString string) string {
if artistString == "" {
return ""
}
delimiters := []string{", ", " & ", " feat. ", " ft. ", " featuring "}
for _, d := range delimiters {
if idx := strings.Index(strings.ToLower(artistString), d); idx != -1 {
return strings.TrimSpace(artistString[:idx])
}
}
return artistString
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
if err := backend.InitHistoryDB("SpotiFLAC"); err != nil {
fmt.Printf("Failed to init history DB: %v\n", err)
}
if err := backend.InitISRCCacheDB(); err != nil {
fmt.Printf("Failed to init ISRC cache DB: %v\n", err)
}
if err := backend.InitProviderPriorityDB(); err != nil {
fmt.Printf("Failed to init provider priority DB: %v\n", err)
}
go func() {
if err := backend.PrimeTidalAPIList(); err != nil {
fmt.Printf("Failed to prime Tidal API list: %v\n", err)
}
}()
}
func (a *App) shutdown(ctx context.Context) {
backend.CloseHistoryDB()
backend.CloseISRCCacheDB()
backend.CloseProviderPriorityDB()
}
type SpotifyMetadataRequest struct {
URL string `json:"url"`
Batch bool `json:"batch"`
Delay float64 `json:"delay"`
Timeout float64 `json:"timeout"`
Separator string `json:"separator,omitempty"`
}
type DownloadRequest struct {
Service string `json:"service"`
Query string `json:"query,omitempty"`
TrackName string `json:"track_name,omitempty"`
ArtistName string `json:"artist_name,omitempty"`
AlbumName string `json:"album_name,omitempty"`
AlbumArtist string `json:"album_artist,omitempty"`
ReleaseDate string `json:"release_date,omitempty"`
CoverURL string `json:"cover_url,omitempty"`
TidalAPIURL string `json:"tidal_api_url,omitempty"`
TidalVariant string `json:"tidal_variant,omitempty"`
OutputDir string `json:"output_dir,omitempty"`
AudioFormat string `json:"audio_format,omitempty"`
FilenameFormat string `json:"filename_format,omitempty"`
TrackNumber bool `json:"track_number,omitempty"`
Position int `json:"position,omitempty"`
UseAlbumTrackNumber bool `json:"use_album_track_number,omitempty"`
SpotifyID string `json:"spotify_id,omitempty"`
EmbedLyrics bool `json:"embed_lyrics,omitempty"`
EmbedMaxQualityCover bool `json:"embed_max_quality_cover,omitempty"`
ServiceURL string `json:"service_url,omitempty"`
Duration int `json:"duration,omitempty"`
ItemID string `json:"item_id,omitempty"`
SpotifyTrackNumber int `json:"spotify_track_number,omitempty"`
SpotifyDiscNumber int `json:"spotify_disc_number,omitempty"`
SpotifyTotalTracks int `json:"spotify_total_tracks,omitempty"`
SpotifyTotalDiscs int `json:"spotify_total_discs,omitempty"`
ISRC string `json:"isrc,omitempty"`
Copyright string `json:"copyright,omitempty"`
Publisher string `json:"publisher,omitempty"`
Composer string `json:"composer,omitempty"`
PlaylistName string `json:"playlist_name,omitempty"`
PlaylistOwner string `json:"playlist_owner,omitempty"`
AllowFallback bool `json:"allow_fallback"`
UseFirstArtistOnly bool `json:"use_first_artist_only,omitempty"`
UseSingleGenre bool `json:"use_single_genre,omitempty"`
EmbedGenre bool `json:"embed_genre,omitempty"`
Separator string `json:"separator,omitempty"`
}
type DownloadResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
File string `json:"file,omitempty"`
Error string `json:"error,omitempty"`
AlreadyExists bool `json:"already_exists,omitempty"`
ItemID string `json:"item_id,omitempty"`
}
func cleanupInvalidDownloadArtifacts(paths ...string) {
seen := make(map[string]struct{}, len(paths))
for _, path := range paths {
if path == "" {
continue
}
if _, ok := seen[path]; ok {
continue
}
seen[path] = struct{}{}
if err := os.Remove(path); err == nil {
fmt.Printf("Removed invalid download artifact: %s\n", path)
}
}
}
func (a *App) GetStreamingURLs(spotifyTrackID string, region string) (string, error) {
if spotifyTrackID == "" {
return "", fmt.Errorf("spotify track ID is required")
}
fmt.Printf("[GetStreamingURLs] Called for track ID: %s, Region: %s\n", spotifyTrackID, region)
client := backend.NewSongLinkClient()
urls, err := client.GetAllURLsFromSpotify(spotifyTrackID, region)
if err != nil {
return "", err
}
jsonData, err := json.Marshal(urls)
if err != nil {
return "", fmt.Errorf("failed to encode response: %v", err)
}
return string(jsonData), nil
}
func (a *App) GetSpotifyMetadata(req SpotifyMetadataRequest) (string, error) {
if req.URL == "" {
return "", fmt.Errorf("URL parameter is required")
}
if req.Delay == 0 {
req.Delay = 1.0
}
if req.Timeout == 0 {
req.Timeout = 300.0
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(req.Timeout*float64(time.Second)))
defer cancel()
settings, err := a.LoadSettings()
separator := req.Separator
if separator == "" {
separator = ", "
if err == nil && settings != nil {
if sep, ok := settings["separator"].(string); ok {
if sep == "semicolon" {
separator = "; "
} else if sep == "comma" {
separator = ", "
}
}
}
}
data, err := backend.GetFilteredSpotifyData(ctx, req.URL, req.Batch, time.Duration(req.Delay*float64(time.Second)), separator, func(tracks interface{}) {
runtime.EventsEmit(a.ctx, "metadata-stream", tracks)
})
if err != nil {
return "", fmt.Errorf("failed to fetch metadata: %v", err)
}
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil {
return "", fmt.Errorf("failed to encode response: %v", err)
}
return string(jsonData), nil
}
type SpotifySearchRequest struct {
Query string `json:"query"`
Limit int `json:"limit"`
}
func (a *App) SearchSpotify(req SpotifySearchRequest) (*backend.SearchResponse, error) {
if req.Query == "" {
return nil, fmt.Errorf("search query is required")
}
if req.Limit <= 0 {
req.Limit = 10
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return backend.SearchSpotify(ctx, req.Query, req.Limit)
}
type SpotifySearchByTypeRequest struct {
Query string `json:"query"`
SearchType string `json:"search_type"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
func (a *App) SearchSpotifyByType(req SpotifySearchByTypeRequest) ([]backend.SearchResult, error) {
if req.Query == "" {
return nil, fmt.Errorf("search query is required")
}
if req.SearchType == "" {
return nil, fmt.Errorf("search type is required")
}
if req.Limit <= 0 {
req.Limit = 50
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
return backend.SearchSpotifyByType(ctx, req.Query, req.SearchType, req.Limit, req.Offset)
}
func (a *App) DownloadTrack(req DownloadRequest) (DownloadResponse, error) {
if req.Service == "qobuz" && req.SpotifyID == "" {
return DownloadResponse{
Success: false,
Error: "Spotify ID is required for Qobuz",
}, fmt.Errorf("spotify ID is required for Qobuz")
}
if req.Service == "" {
req.Service = "tidal"
}
if req.OutputDir == "" {
req.OutputDir = "."
} else {
if req.PlaylistName != "" {
sanitizedPlaylist := backend.SanitizeFilename(req.PlaylistName)
req.OutputDir = filepath.Join(req.OutputDir, sanitizedPlaylist)
}
req.OutputDir = backend.SanitizeFolderPath(req.OutputDir)
}
if req.AudioFormat == "" {
req.AudioFormat = "LOSSLESS"
}
var err error
var filename string
if req.FilenameFormat == "" {
req.FilenameFormat = "title-artist"
}
if req.ISRC == "" && strings.Contains(req.FilenameFormat, "{isrc}") && req.SpotifyID != "" {
req.ISRC = backend.ResolveTrackISRC(req.SpotifyID)
}
itemID := req.ItemID
if itemID == "" {
if req.SpotifyID != "" {
itemID = fmt.Sprintf("%s-%d", req.SpotifyID, time.Now().UnixNano())
} else {
itemID = fmt.Sprintf("%s-%s-%d", req.TrackName, req.ArtistName, time.Now().UnixNano())
}
backend.AddToQueue(itemID, req.TrackName, req.ArtistName, req.AlbumName, req.SpotifyID)
}
backend.SetDownloading(true)
backend.StartDownloadItem(itemID)
defer backend.SetDownloading(false)
spotifyURL := ""
if req.SpotifyID != "" {
spotifyURL = fmt.Sprintf("https://open.spotify.com/track/%s", req.SpotifyID)
}
metadataSeparator := req.Separator
if metadataSeparator == "" {
metadataSeparator = ", "
metadataSettings, _ := a.LoadSettings()
if metadataSettings != nil {
if sep, ok := metadataSettings["separator"].(string); ok {
if sep == "semicolon" {
metadataSeparator = "; "
} else if sep == "comma" {
metadataSeparator = ", "
}
}
}
}
if req.SpotifyID != "" && (req.Copyright == "" || req.Publisher == "" || req.Composer == "" || req.SpotifyTotalDiscs == 0 || req.ReleaseDate == "" || req.SpotifyTotalTracks == 0 || req.SpotifyTrackNumber == 0) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
trackURL := fmt.Sprintf("https://open.spotify.com/track/%s", req.SpotifyID)
trackData, err := backend.GetFilteredSpotifyData(ctx, trackURL, false, 0, metadataSeparator, nil)
if err == nil {
var trackResp struct {
Track struct {
Copyright string `json:"copyright"`
Publisher string `json:"publisher"`
Composer string `json:"composer"`
TotalDiscs int `json:"total_discs"`
TotalTracks int `json:"total_tracks"`
TrackNumber int `json:"track_number"`
ReleaseDate string `json:"release_date"`
} `json:"track"`
}
if jsonData, jsonErr := json.Marshal(trackData); jsonErr == nil {
if json.Unmarshal(jsonData, &trackResp) == nil {
if req.Copyright == "" && trackResp.Track.Copyright != "" {
req.Copyright = trackResp.Track.Copyright
}
if req.Publisher == "" && trackResp.Track.Publisher != "" {
req.Publisher = trackResp.Track.Publisher
}
if req.Composer == "" && trackResp.Track.Composer != "" {
req.Composer = trackResp.Track.Composer
}
if req.SpotifyTotalDiscs == 0 && trackResp.Track.TotalDiscs > 0 {
req.SpotifyTotalDiscs = trackResp.Track.TotalDiscs
}
if req.SpotifyTotalTracks == 0 && trackResp.Track.TotalTracks > 0 {
req.SpotifyTotalTracks = trackResp.Track.TotalTracks
}
if req.SpotifyTrackNumber == 0 && trackResp.Track.TrackNumber > 0 {
req.SpotifyTrackNumber = trackResp.Track.TrackNumber
}
if req.ReleaseDate == "" && trackResp.Track.ReleaseDate != "" {
req.ReleaseDate = trackResp.Track.ReleaseDate
}
}
}
}
}
if req.TrackName != "" && req.ArtistName != "" {
expectedFilename := backend.BuildExpectedFilename(req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.FilenameFormat, req.PlaylistName, req.PlaylistOwner, req.TrackNumber, req.Position, req.SpotifyDiscNumber, req.UseAlbumTrackNumber, req.ISRC)
expectedPath := filepath.Join(req.OutputDir, expectedFilename)
if !backend.GetRedownloadWithSuffixSetting() {
if fileInfo, err := os.Stat(expectedPath); err == nil && fileInfo.Size() > 100*1024 {
backend.SkipDownloadItem(itemID, expectedPath)
return DownloadResponse{
Success: true,
Message: "File already exists",
File: expectedPath,
AlreadyExists: true,
ItemID: itemID,
}, nil
}
}
}
lyricsChan := make(chan string, 1)
isrcChan := make(chan string, 1)
if req.SpotifyID != "" {
if req.EmbedLyrics {
go func() {
client := backend.NewLyricsClient()
resp, _, err := client.FetchLyricsAllSources(req.SpotifyID, req.TrackName, req.ArtistName, req.AlbumName, req.Duration)
if err == nil && resp != nil && len(resp.Lines) > 0 {
lrc := client.ConvertToLRC(resp, req.TrackName, req.ArtistName)
lyricsChan <- lrc
} else {
lyricsChan <- ""
}
}()
} else {
close(lyricsChan)
}
if req.Service == "qobuz" {
go func() {
client := backend.NewSongLinkClient()
isrc, err := client.GetISRCDirect(req.SpotifyID)
if err != nil {
fmt.Printf("Warning: failed to resolve ISRC for Qobuz: %v\n", err)
}
isrcChan <- isrc
}()
} else {
close(isrcChan)
}
} else {
close(lyricsChan)
close(isrcChan)
}
switch req.Service {
case "amazon":
downloader := backend.NewAmazonDownloader()
if req.ServiceURL != "" {
filename, err = downloader.DownloadByURL(req.ServiceURL, req.OutputDir, req.AudioFormat, req.FilenameFormat, req.PlaylistName, req.PlaylistOwner, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.CoverURL, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.EmbedMaxQualityCover, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
} else {
filename, err = downloader.DownloadBySpotifyID(req.SpotifyID, req.OutputDir, req.AudioFormat, req.FilenameFormat, req.PlaylistName, req.PlaylistOwner, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.CoverURL, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.EmbedMaxQualityCover, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
}
case "tidal":
tidalVariant := strings.ToLower(strings.TrimSpace(req.TidalVariant))
if tidalVariant == "alt" {
downloader := backend.NewTidalDownloader("")
filename, err = downloader.DownloadAlt(req.SpotifyID, req.OutputDir, req.FilenameFormat, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.UseAlbumTrackNumber, req.CoverURL, req.EmbedMaxQualityCover, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
} else if req.TidalAPIURL == "" || req.TidalAPIURL == "auto" {
downloader := backend.NewTidalDownloader("")
if req.ServiceURL != "" {
filename, err = downloader.DownloadByURLWithFallback(req.ServiceURL, req.OutputDir, req.AudioFormat, req.FilenameFormat, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.UseAlbumTrackNumber, req.CoverURL, req.EmbedMaxQualityCover, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.AllowFallback, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
} else {
filename, err = downloader.Download(req.SpotifyID, req.OutputDir, req.AudioFormat, req.FilenameFormat, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.UseAlbumTrackNumber, req.CoverURL, req.EmbedMaxQualityCover, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.AllowFallback, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
}
} else {
downloader := backend.NewTidalDownloader(req.TidalAPIURL)
if req.ServiceURL != "" {
filename, err = downloader.DownloadByURL(req.ServiceURL, req.OutputDir, req.AudioFormat, req.FilenameFormat, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.UseAlbumTrackNumber, req.CoverURL, req.EmbedMaxQualityCover, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.AllowFallback, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
} else {
filename, err = downloader.Download(req.SpotifyID, req.OutputDir, req.AudioFormat, req.FilenameFormat, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.UseAlbumTrackNumber, req.CoverURL, req.EmbedMaxQualityCover, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, req.ISRC, spotifyURL, req.AllowFallback, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
}
}
case "qobuz":
isrc := strings.TrimSpace(req.ISRC)
if isrc == "" {
fmt.Println("Waiting for ISRC (Qobuz dependency)...")
isrc = <-isrcChan
}
downloader := backend.NewQobuzDownloader()
quality := req.AudioFormat
if quality == "" {
quality = "6"
}
filename, err = downloader.DownloadTrackWithISRC(isrc, req.OutputDir, quality, req.FilenameFormat, req.TrackNumber, req.Position, req.TrackName, req.ArtistName, req.AlbumName, req.AlbumArtist, req.ReleaseDate, req.UseAlbumTrackNumber, req.CoverURL, req.EmbedMaxQualityCover, req.SpotifyTrackNumber, req.SpotifyDiscNumber, req.SpotifyTotalTracks, req.SpotifyTotalDiscs, req.Copyright, req.Publisher, req.Composer, metadataSeparator, spotifyURL, req.AllowFallback, req.UseFirstArtistOnly, req.UseSingleGenre, req.EmbedGenre)
default:
return DownloadResponse{
Success: false,
Error: fmt.Sprintf("Unknown service: %s", req.Service),
}, fmt.Errorf("unknown service: %s", req.Service)
}
if err != nil {
backend.FailDownloadItem(itemID, fmt.Sprintf("Download failed: %v", err))
if filename != "" && !strings.HasPrefix(filename, "EXISTS:") {
if _, statErr := os.Stat(filename); statErr == nil {
fmt.Printf("Removing corrupted/partial file after failed download: %s\n", filename)
if removeErr := os.Remove(filename); removeErr != nil {
fmt.Printf("Warning: Failed to remove corrupted file %s: %v\n", filename, removeErr)
}
}
}
return DownloadResponse{
Success: false,
Error: fmt.Sprintf("Download failed: %v", err),
ItemID: itemID,
}, err
}
alreadyExists := false
if strings.HasPrefix(filename, "EXISTS:") {
alreadyExists = true
filename = strings.TrimPrefix(filename, "EXISTS:")
}
if !alreadyExists {
validated, validationErr := backend.ValidateDownloadedTrackDuration(filename, req.Duration)
if validationErr != nil {
cleanupInvalidDownloadArtifacts(filename)
errorMessage := validationErr.Error()
backend.FailDownloadItem(itemID, errorMessage)
return DownloadResponse{
Success: false,
Error: errorMessage,
ItemID: itemID,
}, errors.New(errorMessage)
}
if !validated {
fmt.Printf("[DownloadValidation] Skipped duration validation for %s (expected=%ds)\n", filename, req.Duration)
}
}
if !alreadyExists && req.SpotifyID != "" && req.EmbedLyrics && (strings.HasSuffix(filename, ".flac") || strings.HasSuffix(filename, ".mp3") || strings.HasSuffix(filename, ".m4a")) {
fmt.Printf("\nWaiting for lyrics fetch to complete...\n")
lyrics := <-lyricsChan
if lyrics != "" {
fmt.Printf("\n--- Full LRC Content ---\n")
fmt.Println(lyrics)
fmt.Printf("--- End LRC Content ---\n\n")
fmt.Printf("Embedding into: %s\n", filename)
if err := backend.EmbedLyricsOnlyUniversal(filename, lyrics); err != nil {
fmt.Printf("Failed to embed lyrics: %v\n", err)
} else {
fmt.Printf("Lyrics embedded successfully!\n")
}
} else {
fmt.Println("No lyrics found to embed.")
}
} else {
select {
case <-lyricsChan:
default:
}
}
message := "Download completed successfully"
if alreadyExists {
message = "File already exists"
backend.SkipDownloadItem(itemID, filename)
} else {
if strings.EqualFold(filepath.Ext(filename), ".flac") && req.CoverURL != "" {
coverClient := backend.NewCoverClient()
if iconErr := coverClient.ApplyMacOSFLACFileIcon(filename, req.CoverURL, 256, req.EmbedMaxQualityCover); iconErr != nil {
fmt.Printf("Warning: failed to set macOS FLAC file icon: %v\n", iconErr)
} else {
fmt.Printf("macOS FLAC file icon set: %s\n", filename)
}
}
if fileInfo, statErr := os.Stat(filename); statErr == nil {
finalSize := float64(fileInfo.Size()) / (1024 * 1024)
backend.CompleteDownloadItem(itemID, filename, finalSize)
} else {
backend.CompleteDownloadItem(itemID, filename, 0)
}
historySource := req.Service
if req.Service == "tidal" && strings.EqualFold(strings.TrimSpace(req.TidalVariant), "alt") {
historySource = "tidal alt"
}
go func(fPath, track, artist, album, sID, cover, format, source string) {
time.Sleep(2 * time.Second)
quality := "Unknown"
durationStr := "0:00"
meta, err := backend.GetTrackMetadata(fPath)
if err == nil {
if meta.Bitrate > 0 {
quality = fmt.Sprintf("%dkbps/%.1fkHz", meta.Bitrate/1000, float64(meta.SampleRate)/1000.0)
} else if meta.SampleRate > 0 {
quality = fmt.Sprintf("%.1fkHz", float64(meta.SampleRate)/1000.0)
}
d := int(meta.Duration)
durationStr = fmt.Sprintf("%d:%02d", d/60, d%60)
} else {
fmt.Printf("[History] Failed to get metadata for %s: %v\n", fPath, err)
}
item := backend.HistoryItem{
SpotifyID: sID,
Title: track,
Artists: artist,
Album: album,
DurationStr: durationStr,
CoverURL: cover,
Quality: quality,
Format: strings.ToUpper(format),
Path: fPath,
Source: source,
}
if item.Format == "" || item.Format == "LOSSLESS" {
ext := filepath.Ext(fPath)
if len(ext) > 1 {
item.Format = strings.ToUpper(ext[1:])
}
}
switch item.Format {
case "6", "7", "27":
item.Format = "FLAC"
}
backend.AddHistoryItem(item, "SpotiFLAC")
}(filename, req.TrackName, req.ArtistName, req.AlbumName, req.SpotifyID, req.CoverURL, req.AudioFormat, historySource)
}
return DownloadResponse{
Success: true,
Message: message,
File: filename,
AlreadyExists: alreadyExists,
ItemID: itemID,
}, nil
}
func (a *App) OpenFolder(path string) error {
if path == "" {
return fmt.Errorf("path is required")
}
err := backend.OpenFolderInExplorer(path)
if err != nil {
return fmt.Errorf("failed to open folder: %v", err)
}
return nil
}
func (a *App) OpenConfigFolder() error {
configDir, err := backend.EnsureAppDir()
if err != nil {
return fmt.Errorf("failed to create config directory: %v", err)
}
return backend.OpenFolderInExplorer(configDir)
}
func (a *App) SelectFolder(defaultPath string) (string, error) {
return backend.SelectFolderDialog(a.ctx, defaultPath)
}
func (a *App) SelectFile() (string, error) {
return backend.SelectFileDialog(a.ctx)
}
func (a *App) GetDefaults() map[string]string {
return map[string]string{
"downloadPath": backend.GetDefaultMusicPath(),
}
}
func (a *App) GetDownloadProgress() backend.ProgressInfo {
return backend.GetDownloadProgress()
}
func (a *App) GetDownloadQueue() backend.DownloadQueueInfo {
return backend.GetDownloadQueue()
}
func (a *App) ClearCompletedDownloads() {
backend.ClearDownloadQueue()
}
func (a *App) ClearAllDownloads() {
backend.ClearAllDownloads()
}
func (a *App) AddToDownloadQueue(spotifyID, trackName, artistName, albumName string) string {
itemID := fmt.Sprintf("%s-%d", spotifyID, time.Now().UnixNano())
backend.AddToQueue(itemID, trackName, artistName, albumName, "")
return itemID
}
func (a *App) MarkDownloadItemFailed(itemID, errorMsg string) {
backend.FailDownloadItem(itemID, errorMsg)
}
func (a *App) CancelAllQueuedItems() {
backend.CancelAllQueuedItems()
}
func (a *App) ExportFailedDownloads() (string, error) {
queueInfo := backend.GetDownloadQueue()
var failedItems []string
hasFailed := false
for _, item := range queueInfo.Queue {
if item.Status == backend.StatusFailed {
hasFailed = true
break
}
}
if !hasFailed {
return "No failed downloads to export.", nil
}
failedItems = append(failedItems, fmt.Sprintf("Failed Downloads Report - %s", time.Now().Format("2006-01-02 15:04:05")))
failedItems = append(failedItems, strings.Repeat("-", 50))
failedItems = append(failedItems, "")
count := 0
for _, item := range queueInfo.Queue {
if item.Status == backend.StatusFailed {
count++
line := fmt.Sprintf("%d. %s - %s", count, item.TrackName, item.ArtistName)
if item.AlbumName != "" {
line += fmt.Sprintf(" (%s)", item.AlbumName)
}
failedItems = append(failedItems, line)
failedItems = append(failedItems, fmt.Sprintf(" Error: %s", item.ErrorMessage))
if item.SpotifyID != "" {
failedItems = append(failedItems, fmt.Sprintf(" ID: %s", item.SpotifyID))
failedItems = append(failedItems, fmt.Sprintf(" URL: https://open.spotify.com/track/%s", item.SpotifyID))
}
failedItems = append(failedItems, "")
}
}
content := strings.Join(failedItems, "\n")
defaultFilename := fmt.Sprintf("SpotiFLAC_%s_Failed.txt", time.Now().Format("20060102_150405"))
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
DefaultFilename: defaultFilename,
Title: "Export Failed Downloads",
Filters: []runtime.FileFilter{
{
DisplayName: "Text Files (*.txt)",
Pattern: "*.txt",
},
},
})
if err != nil {
return "", fmt.Errorf("failed to open save dialog: %v", err)
}
if path == "" {
return "Export cancelled", nil
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
return "", fmt.Errorf("failed to write file: %v", err)
}
return fmt.Sprintf("Successfully exported %d failed downloads to %s", count, path), nil
}
func (a *App) CheckAPIStatus(apiType string, apiURL string) bool {
isOnline, err := runWithTimeout(checkOperationTimeout, func() (bool, error) {
switch apiType {
case "tidal":
if checkGroupedAPIStatus("tidal", buildTidalStatusCheckURLs(apiURL)) {
return true, nil
}
if strings.TrimSpace(apiURL) == "" {
if _, refreshErr := backend.RefreshTidalAPIList(true); refreshErr == nil && checkGroupedAPIStatus("tidal", buildTidalStatusCheckURLs("")) {