-
Notifications
You must be signed in to change notification settings - Fork 16
/
app.go
760 lines (671 loc) · 22.3 KB
/
app.go
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
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
. "ytd/constants"
. "ytd/db"
offline "ytd/internal/offline"
. "ytd/models"
. "ytd/plugins"
"github.com/denisbrodbeck/machineid"
"github.com/leonelquinteros/gotext"
"github.com/mitchellh/mapstructure"
"github.com/wailsapp/wails/v2"
"github.com/wailsapp/wails/v2/pkg/mac"
"github.com/wailsapp/wails/v2/pkg/options/dialog"
"github.com/xujiajun/nutsdb"
)
var i18nPath string
var wailsRuntime *wails.Runtime
type HostInfo struct {
ID string `json:"id"`
Username string `json:"username"`
}
type AppState struct {
runtime *wails.Runtime
db *nutsdb.DB
plugins []Plugin
Entries []GenericEntry `json:"entries"`
OfflinePlaylists []OfflinePlaylist `json:"offlinePlaylists"`
Config *AppConfig `json:"config"`
Stats *AppStats `json:"stats"`
AppVersion string `json:"appVersion"`
Host HostInfo `json:"host"`
PwaUrl string `json:"pwaUrl"`
context.Context `json:"-"`
*sync.Mutex `json:"-"`
isInForeground bool
canStartAtLogin bool
tray TrayMenu
updater *Updater
offlinePlaylistService *offline.OfflinePlaylistService
ngrok *NgrokService
convertQueue chan GenericEntry
downloadQueue []GenericEntry
downloadQueueChan chan GenericEntry
downloadParralel chan int
}
func (state *AppState) PreWailsInit(ctx context.Context) {
state.db = InitializeDb()
state.Entries = DbGetAllEntries()
state.OfflinePlaylists = DbGetAllOfflinePlaylists()
state.offlinePlaylistService = &offline.OfflinePlaylistService{}
state.ngrok = &NgrokService{}
state.ngrok.Context = ctx
state.Config = state.Config.Init()
state.AppVersion = version
state.convertQueue = make(chan GenericEntry, 100)
state.downloadQueueChan = make(chan GenericEntry, 100)
state.downloadParralel = make(chan int, state.Config.MaxParrallelDownloads)
// configure i18n paths
gotext.Configure("/Users/oskarmarciniak/projects/golang/ytd/i18n", state.Config.Language, "default")
if _, err := mac.StartsAtLogin(); err == nil {
state.canStartAtLogin = true
}
if machineid, err := machineid.ProtectedID("ytd"); err == nil {
state.Host.ID = machineid
}
if user, err := user.Current(); err == nil {
state.Host.Username = user.Username
}
}
func (state *AppState) GetAll() *AppState {
state.Entries = DbGetAllEntries()
state.OfflinePlaylists = DbGetAllOfflinePlaylists()
return state
}
func (state *AppState) WailsInit(runtime *wails.Runtime) {
// Save runtime
state.runtime = runtime
state.offlinePlaylistService.Runtime = runtime
state.ngrok.runtime = runtime
state.Config.SetRuntime(runtime)
// Do some other initialisation
state.Stats = &AppStats{}
appState = state
// this is sync so it blocks until finished and wails:loaded are not dispatched until this finishes
if runtime.System.AppType() == "default" { // wails serve & ng serve
runtime.Events.On("wails:loaded", func(...interface{}) {
time.Sleep(100 * time.Millisecond)
fmt.Println("EMIT YTD:ONLOAD")
runtime.Events.Emit("ytd:onload", state)
})
} else { // dekstop build
go func() {
runtime.Events.Emit("ytd:onload", state)
}()
}
// initialize plugins
for _, plugin := range plugins {
plugin.SetWailsRuntime(runtime)
plugin.SetContext(state.Context)
plugin.SetAppConfig(state.Config)
plugin.SetAppStats(state.Stats)
plugin.SetQueue(state.downloadQueueChan)
plugin.SetOfflineService(state.offlinePlaylistService)
}
fmt.Println("APP STATE INITIALIZED")
state.InitializeListeners()
// create app sys tray menu
state.tray.runtime = runtime
state.tray.createTray()
state.runtime.Menu.SetTrayMenu(state.tray.defaultTrayMenu)
// event emitted from fe if tray should be updated
runtime.Events.On("ytd:app:tray:update", func(data ...interface{}) {
state.tray.reRenderTray(func() {})
})
state.checkStartsAtLogin()
go func() {
for {
time.Sleep(5 * time.Second)
state.checkForTracksToDownload()
}
}()
go func() {
ticker := time.NewTicker(3 * time.Second)
pending := make(chan int, maxConvertJobs)
for {
select {
case entry := <-state.convertQueue:
fmt.Println("CONVERT REQQQQQQQQ", entry.Track.Name)
go func() {
if len(pending) == cap(pending) {
state.runtime.Events.Emit("ytd:track:convert:queued", entry)
}
pending <- 1
state.convertToMp3(ticker, &entry, true)
<-pending
}()
case <-ticker.C:
// get entries that could be converted
for _, t := range DbGetAllEntries() {
entry := t
plugin := getPluginFor(entry.Source)
if entry.Type == "track" && entry.Track.Status == TrackStatusDownladed && !entry.Track.IsConvertedToMp3 && plugin.IsTrackFileExists(entry.Track, "webm") {
// skip tracks which has failed at least 3 times in a row
if entry.Track.ConvertingStatus.Attempts >= 3 {
fmt.Printf("Skipping audio extraction for %s(%s)...due to too many attempts\n", entry.Track.Name, entry.Track.ID)
continue
}
go func() {
// this will block until pending channel is full
pending <- 1
state.convertToMp3(ticker, &entry, false)
<-pending
}()
}
}
default:
fmt.Printf("Convert to mp3 nothing to do....max parralel %d | converting %d | pending %d entries\n\n", maxConvertJobs, state.Stats.ConvertingCount, len(pending))
time.Sleep(1 * time.Second)
}
}
}()
go func() {
time.Sleep(10 * time.Second)
for {
state.checkForUpdates()
// check again in twelve hours
time.Sleep(12 * time.Hour)
}
}()
if state.Config.PublicServer.Enabled {
ShowLoader(state.runtime, "Starting public server...")
result := state.ngrok.StartProcess(false)
if result.err != nil {
state.runtime.Events.Emit("ytd:ngrok", NgrokStateEventPayload{Status: NgrokStatusError, ErrCode: result.errCode})
HideLoader(state.runtime)
return
}
state.runtime.Events.Emit("ytd:ngrok", NgrokStateEventPayload{Status: result.status, Url: result.publicUrl})
HideLoader(state.runtime)
// monitor ngrok state
go state.ngrok.MonitorNgrokProcess()
}
}
func (state *AppState) WailsShutdown() {
err := state.ngrok.KillProcess()
if err != nil {
fmt.Println("WailsShutdown state.ngrok.KillProcess() failed", err)
}
err = state.db.Merge()
if err != nil {
fmt.Println("WailsShutdown db.Merge() failed", err)
}
CloseDb()
}
func (state *AppState) ReloadNewLanguage() {
gotext.Configure(i18nPath, state.Config.Language, "default")
// re render tray to take effect for new language translations
state.tray.reRenderTray(func() {})
// do other stuff if needed to reload translations from some ui native elements
}
func (state *AppState) InitializeListeners() {
state.runtime.Events.On("ytd:app:foreground", func(optionalData ...interface{}) {
var json map[string]interface{} = optionalData[0].(map[string]interface{})
if isInForeground, ok := json["isInForeground"]; ok {
state.isInForeground = isInForeground.(bool)
}
})
state.runtime.Events.On("ytd:offline:playlists:addedTrack", func(optionalData ...interface{}) {
state.OfflinePlaylists, _ = state.offlinePlaylistService.GetPlaylists(true)
})
state.runtime.Events.On("ytd:offline:playlists:removedTrack", func(optionalData ...interface{}) {
state.OfflinePlaylists, _ = state.offlinePlaylistService.GetPlaylists(true)
})
state.runtime.Events.On("ytd:offline:playlists:created", func(optionalData ...interface{}) {
state.OfflinePlaylists, _ = state.offlinePlaylistService.GetPlaylists(true)
})
state.runtime.Events.On("ytd:offline:playlists:removed", func(optionalData ...interface{}) {
state.OfflinePlaylists, _ = state.offlinePlaylistService.GetPlaylists(true)
})
state.runtime.Events.On("ngrok:configured", func(optionalData ...interface{}) {
if state.Config.PublicServer.Enabled {
ShowLoader(state.runtime, "Configuring public server...")
result := state.ngrok.StartProcess(true)
if result.err != nil {
state.runtime.Events.Emit("ytd:ngrok", NgrokStateEventPayload{Status: NgrokStatusError, ErrCode: result.errCode})
HideLoader(state.runtime)
return
}
state.runtime.Events.Emit("ytd:ngrok", NgrokStateEventPayload{Status: result.status, Url: result.publicUrl})
HideLoader(state.runtime)
// monitor ngrok process
go state.ngrok.MonitorNgrokProcess()
}
if !state.Config.PublicServer.Enabled {
err := state.ngrok.KillProcess()
if err != nil {
SendNotification(state.runtime, NotificationEventPayload{Type: "error", Label: "Cannot shutdown public server"}, state.isInForeground)
}
}
})
}
func (state *AppState) GetAppConfig() *AppConfig {
return state.Config
}
func (state *AppState) SelectDirectory() (string, error) {
selectedDirectory, err := state.runtime.Dialog.OpenDirectory(&dialog.OpenDialog{
AllowFiles: false,
CanCreateDirectories: true,
AllowDirectories: true,
Title: gotext.Get("Choose directory"),
})
return selectedDirectory, err
}
func (state *AppState) GetEntryById(entry GenericEntry) *GenericEntry {
for _, t := range state.Entries {
if t.Type == "track" && t.Track.ID == entry.Track.ID {
return &t
}
}
return nil
}
func (state *AppState) checkForTracksToDownload() error {
fmt.Printf("Check for tracks to start downloads...%d/%d\n", state.Stats.DownloadingCount, state.Config.MaxParrallelDownloads)
/* if state.Stats.DownloadingCount >= state.Config.MaxParrallelDownloads {
return nil
} */
fmt.Printf("Checking...%d entries\n", len(state.Entries))
ticker := time.NewTicker(5 * time.Second)
for {
select {
case entry := <-state.downloadQueueChan:
state.downloadQueue = append(state.downloadQueue, entry)
case <-ticker.C:
fmt.Printf("TICKER PARRALELE %d/%d | IN QUEUE %d | MAX QUEUE SLICE %d", len(state.downloadParralel), cap(state.downloadParralel), len(state.downloadQueue), cap(state.downloadQueue))
for _, t := range state.downloadQueue {
fmt.Printf("\n[+] Found track %s in state.downloadQueue\n", t.Track.Url)
}
if len(state.downloadQueue) > 0 && len(state.downloadParralel) < cap(state.downloadParralel) {
fmt.Printf("Found %d tracks in queue...BEFORE\n\n", len(state.downloadQueue))
entry := state.downloadQueue[0]
newState := state.downloadQueue[1:]
fmt.Println("\nNEW QUEUE\n", newState)
state.downloadQueue = newState
fmt.Printf("Found %d tracks in queue...AFTER\n\n", len(state.downloadQueue))
fmt.Println("New track can be downloaded", entry.Track.Url, entry.Track.Status)
if entry.Track.Status == TrackStatusQueued {
fmt.Println("________FOUND QUEIUED TRACk___________", entry.Track.ID)
}
if entry.Track.Status == TrackStatusDownloading {
fmt.Println("________FOUND DOWNLOADING TRACk______", entry.Track.ID)
}
if entry.Track.Status == TrackStatusDownladed {
fmt.Println("________FOUND DOWNLOADED TRACk______", entry.Track.ID)
}
go func(entry GenericEntry) {
state.downloadParralel <- 1
plugin := getPluginFor(entry.Source)
plugin.Fetch(entry.Track.Url, false)
<-state.downloadParralel
}(entry)
}
default:
fmt.Printf("No tracks in queue....max parralel %d | downloading %d | pending %d entries\n\n", state.Config.MaxParrallelDownloads, state.Stats.DownloadingCount, len(state.downloadQueue))
time.Sleep(3 * time.Second)
}
}
// qui un for che legge dal channel e ogni volta che riceve una entry downloadata
return nil
}
func (state *AppState) convertToMp3(restartTicker *time.Ticker, entry *GenericEntry, force bool) error {
if !state.Config.ConvertToMp3 {
// if option is not enabled restart check after 3s
restartTicker.Stop()
restartTicker.Reset(3 * time.Second)
return nil
}
fmt.Println("Converting....")
ffmpeg, _ := state.IsFFmpegInstalled()
plugin := getPluginFor(entry.Source)
if entry.Type == "track" && entry.Track.Status == TrackStatusDownladed && !entry.Track.IsConvertedToMp3 && plugin.IsTrackFileExists(entry.Track, "webm") {
// skip tracks which has failed at least 3 times in a row
if entry.Track.ConvertingStatus.Attempts >= 3 && !force {
fmt.Printf("Skipping audio extraction for %s - (%s)...due to too many attempts\n", entry.Track.Name, entry.Track.ID)
return nil
}
fmt.Printf("Extracting audio for %s - (%s)...\n", entry.Track.Name, entry.Track.ID)
entry.Track.ConvertingStatus.Status = TrakcConverting
DbWriteEntry(entry.Track.ID, entry)
state.Stats.IncConvertCount()
state.runtime.Events.Emit("ytd:track", entry)
// ffmpeg -i "41qC3w3UUkU.webm" -vn -ab 128k -ar 44100 -y "41qC3w3UUkU.mp3"
outputPath := fmt.Sprintf("%s/%s.mp3", plugin.GetDir(), entry.Track.ID)
cmd := exec.CommandContext(
state.Context,
ffmpeg,
"-loglevel", "quiet",
"-i", fmt.Sprintf("%s/%s.webm", plugin.GetDir(), entry.Track.ID),
"-metadata", fmt.Sprintf("title=%s", entry.Track.Name),
"-metadata", fmt.Sprintf("author=%s", entry.Track.Author),
"-vn",
"-ab", "128k",
"-ar", "44100",
"-y", outputPath,
)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Println("Failed to extract audio:", err)
entry.Track.ConvertingStatus.Status = TrakcConvertFailed
entry.Track.ConvertingStatus.Err = err.Error()
entry.Track.ConvertingStatus.Attempts += 1
DbWriteEntry(entry.Track.ID, entry)
state.Stats.DecConvertCount()
state.runtime.Events.Emit("ytd:track", entry)
} else {
entry.Track.ConvertingStatus.Status = TrakcConverted
entry.Track.IsConvertedToMp3 = true
// check new filesize and save it
fileInfo, err := os.Stat(outputPath)
if err == nil {
entry.Track.ConvertingStatus.Filesize = int(fileInfo.Size())
}
DbWriteEntry(entry.Track.ID, entry)
state.Stats.DecConvertCount()
state.runtime.Events.Emit("ytd:track", entry)
// remove webm if needed
if state.Config.CleanWebmFiles && plugin.IsTrackFileExists(entry.Track, "webm") {
err = os.Remove(fmt.Sprintf("%s/%s.webm", plugin.GetDir(), entry.Track.ID))
if err != nil && !os.IsNotExist(err) {
fmt.Printf("Cannot remove %s.webm file after successfull converting to mp3\n", entry.Track.ID)
}
}
}
return nil
}
return nil
}
func (state *AppState) checkForUpdates() {
if !state.Config.CheckForUpdates {
return
}
state.updater = &Updater{
CurrentVersion: version,
LatestReleaseGitHubEndpoint: "https://api.github.com/repos/marcio199226/ytd/releases",
Client: &http.Client{Timeout: 10 * time.Minute},
SelectAsset: func(release Release, asset Asset) bool {
// look for the zip file
return strings.Contains(asset.Name, fmt.Sprintf("%s-%s", runtime.GOOS, runtime.GOARCH)) && filepath.Ext(asset.Name) == ".zip"
},
DownloadBytesLimit: 10_741_824, // 10MB
}
latest, hasUpdate, err := state.updater.HasUpdate()
if err != nil {
_, err := state.runtime.Dialog.Message(&dialog.MessageDialog{
Type: dialog.ErrorDialog,
Title: gotext.Get("Update check failed"),
Message: err.Error(),
Buttons: []string{"OK"},
CancelButton: "OK",
})
if err != nil {
log.Println(err)
return
}
return
}
if !hasUpdate {
_, err := state.runtime.Dialog.Message(&dialog.MessageDialog{
Type: dialog.InfoDialog,
Title: gotext.Get("You're up to date"),
Message: fmt.Sprintf(gotext.Get("%s is the latest version.", latest.TagName)),
Buttons: []string{"OK"},
CancelButton: "OK",
})
if err != nil {
log.Println(err)
return
}
return
}
clickedAction, _ := state.runtime.Dialog.Message(&dialog.MessageDialog{
Type: dialog.InfoDialog,
Title: fmt.Sprintf(gotext.Get("New version available: %s", latest.TagName)),
Message: gotext.Get("Would you like to update?"),
Buttons: []string{"OK", "Changelog", gotext.Get("Update")},
CancelButton: "OK",
})
state.tray.reRenderTray(func() {
state.tray.versionMenuItem.Label = fmt.Sprintf(gotext.Get("⚠️ ytd (%s) (new version %s)", version, latest.TagName))
})
switch clickedAction {
case "Update":
// continue
case "Changelog":
state.runtime.Window.Show()
state.runtime.Events.Emit("ytd:app:update:changelog", latest)
return
case "OK":
state.runtime.Events.Emit("ytd:app:update:available", latest)
return
}
state.Update(false)
}
func (state *AppState) Update(restart bool) {
_, err := state.updater.Update()
if err != nil {
_, err := state.runtime.Dialog.Message(&dialog.MessageDialog{
Type: dialog.WarningDialog,
Title: gotext.Get("Update not successful"),
Message: err.Error(),
Buttons: []string{"OK"},
CancelButton: "OK",
})
if err != nil {
log.Println(err)
return
}
}
// restart for now does not work properly, it closes current ytd instance but not launch the new one
// so notify user that update has been done and could restart app
// err = u.Restart()
state.runtime.Dialog.Message(&dialog.MessageDialog{
Type: dialog.InfoDialog,
Title: gotext.Get("Update successful"),
Message: gotext.Get("Please restart ytd for the changes to take effect."),
Buttons: []string{"OK"},
CancelButton: "OK",
})
}
func (state *AppState) checkStartsAtLogin() {
startsAtLogin, err := mac.StartsAtLogin()
if err != nil {
state.tray.reRenderTray(func() {
state.tray.startAtLoginMenuItem.Label = gotext.Get("⚠ Start at Login unavailable")
state.tray.startAtLoginMenuItem.Disabled = true
})
} else if startsAtLogin {
mac.ShowNotification("Ytd", gotext.Get("App has been started in background"), "", "")
state.tray.reRenderTray(func() {
state.tray.startAtLoginMenuItem.Checked = true
state.tray.startAtLoginMenuItem.Disabled = false
})
}
}
func (state *AppState) SaveSettingBoolValue(name string, val bool) (err error) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovering from panic saveSettingValue:", r)
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
// Fallback err (per specs, error strings should be lowercase w/o punctuation
err = errors.New("unknown panic")
}
}
}()
error := DbSaveSettingBoolValue(name, val)
if err != nil {
return error
}
appState.Config.Set(name, val)
return nil
}
func (state *AppState) SaveSettingValue(name string, val string) (err error) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovering from panic saveSettingValue:", r)
switch x := r.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
// Fallback err (per specs, error strings should be lowercase w/o punctuation
err = errors.New("unknown panic")
}
}
}()
error := DbWriteSetting(name, val)
if err != nil {
return error
}
appState.Config.Set(name, val)
return nil
}
func (state *AppState) ReadSettingBoolValue(name string) (bool, error) {
return DbReadSettingBoolValue(name)
}
func (state *AppState) ReadSettingValue(name string) (string, error) {
return DbReadSetting(name)
}
func (state *AppState) RemoveEntry(record map[string]interface{}) error {
var err error
var entry GenericEntry
err = mapstructure.Decode(record, &entry)
if err != nil {
return err
}
if entry.Type == "track" {
if err = DbDeleteEntry(entry.Track.ID); err == nil {
plugin := getPluginFor(entry.Source)
if plugin.IsTrackFileExists(entry.Track, "webm") {
err = os.Remove(fmt.Sprintf("%s/%s.webm", plugin.GetDir(), entry.Track.ID))
if err != nil && !os.IsNotExist(err) {
return err
}
}
// remove mp3 if file has been already converted
if plugin.IsTrackFileExists(entry.Track, "mp3") {
err = os.Remove(fmt.Sprintf("%s/%s.mp3", plugin.GetDir(), entry.Track.ID))
if err != nil && !os.IsNotExist(err) {
return err
}
}
// remove track from playlists
for _, p := range state.OfflinePlaylists {
for _, tid := range p.TracksIds {
if tid == entry.Track.ID {
state.offlinePlaylistService.RemoveTrackFromPlaylist(tid, p)
}
}
}
state.OfflinePlaylists, _ = state.offlinePlaylistService.GetPlaylists(true)
return nil
}
}
return err
}
func (state *AppState) AddToDownload(url string, isFromClipboard bool) error {
for _, plugin := range plugins {
if support := plugin.Supports(url); support {
go func() {
if len(state.downloadParralel) == cap(state.downloadParralel) {
ytEntry := GenericEntry{Source: plugin.GetName(), Type: "track", Track: NewQueuedTrack(url)}
state.runtime.Events.Emit("ytd:track", ytEntry)
state.downloadQueueChan <- ytEntry
return
}
state.downloadParralel <- 1
plugin.Fetch(url, isFromClipboard)
<-state.downloadParralel
}()
continue
}
}
return nil
}
func (state *AppState) StartDownload(record map[string]interface{}) error {
var err error
var entry GenericEntry
err = mapstructure.Decode(record, &entry)
if err != nil {
return err
}
if appState.Stats.DownloadingCount >= appState.Config.MaxParrallelDownloads {
return errors.New("Max simultaneous downloads are reached please retry after some track finished downloading")
}
for _, plugin := range plugins {
if plugin.GetName() == entry.Source && entry.Type == "track" {
if appState.GetAppConfig().ConcurrentDownloads {
go func() {
plugin.StartDownload(&entry)
}()
} else {
plugin.StartDownload(&entry)
}
continue
}
}
return nil
}
func (state *AppState) AddToConvertQueue(entry GenericEntry) error {
state.convertQueue <- entry
return nil
}
func (state *AppState) IsSupportedUrl(url string) bool {
for _, plugin := range plugins {
if support := plugin.Supports(url); support {
return true
}
}
return false
}
func (state *AppState) IsFFmpegInstalled() (string, error) {
ffmpeg, err := exec.LookPath("ffmpeg")
if state.runtime.System.Platform() == "darwin" && err != nil {
// on darwin check if ffmpeg is maybe installed by homebrew
// (searching for ffmpeg only give wrong results if installed with homebrew)
ffmpeg, err := exec.LookPath("/opt/homebrew/bin/ffmpeg")
return ffmpeg, err
}
return ffmpeg, err
}
func (state *AppState) OpenUrl(url string) error {
return state.runtime.Browser.Open(url)
}
func (state *AppState) ForceQuit() {
state.runtime.Quit()
}
func (state *AppState) ShowWindow() {
state.runtime.Window.Show()
}
func getPluginFor(name string) Plugin {
for _, plugin := range plugins {
if plugin.GetName() == name {
return plugin
}
}
return nil
}
//WailsRuntime .
type WailsRuntime struct {
runtime *wails.Runtime
}