-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
811 lines (695 loc) · 25.6 KB
/
app.go
File metadata and controls
811 lines (695 loc) · 25.6 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
package main
import (
"context"
"embed"
"fmt"
"os"
"runtime/debug"
"strings"
"time"
"videoarchiver/backend/daemonsignal"
"videoarchiver/backend/domains/closeconfirm"
"videoarchiver/backend/domains/config"
"videoarchiver/backend/domains/db"
"videoarchiver/backend/domains/download"
"videoarchiver/backend/domains/fileregistry"
"videoarchiver/backend/domains/lockfile"
"videoarchiver/backend/domains/logging"
"videoarchiver/backend/domains/playlist"
"videoarchiver/backend/domains/runner"
"videoarchiver/backend/domains/settings"
"videoarchiver/backend/domains/utils"
"videoarchiver/backend/domains/ytdlp"
goruntime "runtime" // renamed standard library runtime
"github.com/NotCoffee418/dbmigrator"
"github.com/pkg/errors"
"github.com/shirou/gopsutil/v3/process"
"github.com/wailsapp/wails/v2/pkg/runtime" // keep wails runtime as is
)
//go:embed all:migrations
var migrationFS embed.FS
const (
WindowsServiceName = "VideoArchiverDaemon" // Must match definition in project.nsi
LinuxServiceName = "video-archiver.service"
)
// App struct
type App struct {
ctx context.Context
WailsEnabled bool
StartupComplete bool
Utils *utils.Utils
ConfigService *config.ConfigService
DB *db.DatabaseService
PlaylistDB *playlist.PlaylistDB
PlaylistService *playlist.PlaylistService
SettingsService *settings.SettingsService
DaemonSignalService *daemonsignal.DaemonSignalService
DownloadDB *download.DownloadDB
DownloadService *download.DownloadService
FileRegistryService *fileregistry.FileRegistryService
LogService *logging.LogService
CloseConfirmService *closeconfirm.CloseConfirmService
StartupProgress string
isDaemonRunning bool
mode string
confirmCloseEnabled bool
}
// NewApp creates a new App application struct
func NewApp(wailsEnabled bool, mode string) *App {
fmt.Printf("NewApp called: wailsEnabled=%v, mode=%s\n", wailsEnabled, mode)
app := &App{
WailsEnabled: wailsEnabled,
mode: mode,
confirmCloseEnabled: false, // Default to disabled, manually enabled when needed
}
// Check initial daemon state
fmt.Printf("Checking if daemon is running...\n")
app.isDaemonRunning = app.IsDaemonRunning()
fmt.Printf("Daemon running status: %v\n", app.isDaemonRunning)
return app
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
fmt.Printf("startup() called for mode: %s, WailsEnabled: %v\n", a.mode, a.WailsEnabled)
a.ctx = ctx
// Initialize logging service early so it can be used throughout startup
a.LogService = logging.NewLogService(a.mode)
a.LogService.Info(fmt.Sprintf("Starting application startup for mode: %s", a.mode))
// Log application version
a.LogService.Info(fmt.Sprintf("Application version: %s", GetVersionInfo()))
// Add panic catcher with logging
defer func() {
if r := recover(); r != nil {
crashMsg := fmt.Sprintf("Application panic: %v\nStack trace:\n%s",
r, string(debug.Stack()))
a.LogService.Fatal(crashMsg)
os.Exit(1)
}
}()
// Start thread for spamming startup progress early
// We need this because desync between js/backend
if a.WailsEnabled {
a.LogService.Info("Starting startup progress thread for UI mode")
go func() {
for !a.StartupComplete {
if a.StartupProgress != "" {
runtime.EventsEmit(a.ctx, "startup-progress", a.StartupProgress)
}
time.Sleep(100 * time.Millisecond)
}
}()
}
// Create configuration service FIRST
configService, err := config.NewConfigService()
if err != nil {
a.HandleFatalError("Failed to create configuration service: " + err.Error())
}
a.ConfigService = configService
// LogService already initialized early in startup function
// Create database service using configuration
dbService, err := db.NewDatabaseService(configService, a.LogService)
if err != nil {
a.HandleFatalError("Failed to create database service: " + err.Error())
}
a.DB = dbService
// Create SettingsService using dbService
a.SettingsService = settings.NewSettingsService(dbService, a.LogService)
// Create DaemonTrigger service
a.DaemonSignalService = daemonsignal.NewDaemonSignalService(a.SettingsService)
// Create PlaylistDB using dbService
a.PlaylistDB = playlist.NewPlaylistDB(dbService)
a.PlaylistService = playlist.NewPlaylistService(a.PlaylistDB, a.DaemonSignalService, a.LogService)
// Create DownloadService using dbService
a.DownloadDB = download.NewDownloadDB(dbService)
a.FileRegistryService = fileregistry.NewFileRegistryService(dbService)
a.DownloadService = download.NewDownloadService(
ctx,
a.SettingsService,
a.DownloadDB,
a.FileRegistryService,
a.DaemonSignalService,
a.LogService,
)
// Init utils with context
a.Utils = utils.NewUtils(ctx)
// Initialize CloseConfirmService with context
a.CloseConfirmService = closeconfirm.NewCloseConfirmService(ctx, a.LogService)
// Apply database migrations (AFTER setting up DB)
a.StartupProgress = "Applying database updates..."
db := dbService.GetDB()
dbmigrator.SetDatabaseType(dbmigrator.SQLite)
<-dbmigrator.MigrateUpCh(
db,
migrationFS,
"migrations",
)
// For UI mode, wait for legal disclaimer acceptance before installing dependencies
if a.WailsEnabled {
a.StartupProgress = "Waiting for legal disclaimer acceptance..."
a.LogService.Info("UI mode: waiting for legal disclaimer acceptance before installing dependencies")
for {
accepted, err := a.GetLegalDisclaimerAccepted()
if err != nil {
a.LogService.Error(fmt.Sprintf("Failed to check legal disclaimer status: %v", err))
time.Sleep(5 * time.Second)
continue
}
if accepted {
a.LogService.Info("Legal disclaimer accepted, proceeding with dependency installation")
break
}
a.LogService.Debug("Waiting for legal disclaimer acceptance before proceeding...")
time.Sleep(1 * time.Second)
}
// Then handle locking for UI mode
if a.WailsEnabled {
a.LogService.Info("UI mode detected, checking for daemon locking...")
// UI mode (slave) - wait for daemon lock if present
if err := a.handleUILocking(); err != nil {
a.LogService.Error(fmt.Sprintf("LOG: UI about to exit due to locking error: %v", err))
a.HandleFatalError("Failed to handle UI locking: " + err.Error())
}
a.LogService.Info("UI locking check completed successfully")
}
}
// For daemon mode, wait for legal disclaimer acceptance before installing dependencies
if !a.WailsEnabled {
// Create lock before waiting for legal disclaimer acceptance
a.LogService.Info("Creating lock file to coordinate with UI...")
if err := lockfile.CreateLock(); err != nil {
a.HandleFatalError("Failed to create lock file: " + err.Error())
}
// Ensure lock is removed on exit
defer func() {
if err := lockfile.RemoveLock(); err != nil {
a.LogService.Warn(fmt.Sprintf("Failed to remove lock file: %v", err))
}
}()
a.StartupProgress = "Waiting for legal disclaimer acceptance..."
for {
accepted, err := a.GetLegalDisclaimerAccepted()
if err != nil {
a.LogService.Error(fmt.Sprintf("Failed to check legal disclaimer status: %v", err))
time.Sleep(5 * time.Second)
continue
}
if accepted {
a.LogService.Info("Legal disclaimer accepted, proceeding with dependency installation")
break
}
a.LogService.Info("Waiting for legal disclaimer acceptance before proceeding...")
time.Sleep(5 * time.Second)
}
}
// ✅ Install ytdlp in background channel (after legal disclaimer is accepted)
a.LogService.Info("Starting dependency installation after legal disclaimer acceptance")
ytdlpUpdateChan := make(chan error)
go func() {
defer close(ytdlpUpdateChan)
err := ytdlp.InstallOrUpdate(false, a.SettingsService, a.LogService)
if err != nil {
ytdlpUpdateChan <- err
}
}()
// Prepare message for ytdlp update if it needs to do a full install/update
a.StartupProgress = "Checking dependencies..."
ytdlpUpdateDone := false
ytdlpUpdateStartTime := time.Now()
go func() {
for !ytdlpUpdateDone {
if time.Since(ytdlpUpdateStartTime) > 3*time.Second {
a.StartupProgress = "Updating dependencies. This may take a minute or two. Please wait..."
break
}
time.Sleep(100 * time.Millisecond)
}
}()
// Install/update ytdlp/ffmpeg
err = <-ytdlpUpdateChan
if err != nil {
a.HandleFatalError("Failed to install ytdlp: " + err.Error())
}
ytdlpUpdateDone = true
a.LogService.Info("Application startup completed successfully")
// For daemon mode, remove lock file after successful startup
if !a.WailsEnabled {
if err := lockfile.RemoveLock(); err != nil {
a.LogService.Warn(fmt.Sprintf("Failed to remove lock file after startup: %v", err))
} else {
a.LogService.Info("Lock file removed, daemon ready for normal operation")
}
}
// Emit startup complete event in background
a.StartupProgress = "Startup complete"
if a.WailsEnabled {
go func() {
// Listen for confirmed event
awaitingConfirmation := true
runtime.EventsOn(a.ctx, "startup-complete-confirmed", func(data ...interface{}) {
awaitingConfirmation = false
})
// emit complete event
a.StartupComplete = true
for i := 0; i < 300; i++ {
if !awaitingConfirmation {
break
}
runtime.EventsEmit(a.ctx, "startup-complete")
time.Sleep(250 * time.Millisecond)
}
}()
}
}
// handleUILocking handles locking for UI mode (slave)
func (a *App) handleUILocking() error {
a.LogService.Info("Starting handleUILocking check...")
// Check if daemon lock exists
locked, err := lockfile.IsLocked()
if err != nil {
a.LogService.Error(fmt.Sprintf("Failed to check lock status: %v", err))
return fmt.Errorf("failed to check lock status: %w", err)
}
a.LogService.Info(fmt.Sprintf("Lock file check result: locked=%v", locked))
if !locked {
// No daemon lock, proceed normally
a.LogService.Info("No daemon lock found, proceeding normally")
return nil
}
// Lock exists - check if daemon is already running
isDaemonAlreadyRunning := a.IsDaemonRunning()
a.LogService.Info(fmt.Sprintf("Daemon running status while lock exists: %v", isDaemonAlreadyRunning))
// Lock exists, wait for daemon to complete startup
a.LogService.Info("Daemon lock found, waiting for daemon initialization to complete...")
a.StartupProgress = "Waiting for daemon initialization... This may take a few minutes on first run."
a.LogService.Info("Waiting for daemon initialization...")
// Wait up to 10 minutes for the lock to be released
a.LogService.Info("Starting 10-minute wait for lock release...")
released, err := lockfile.WaitForLockRelease(10 * time.Minute)
if err != nil {
a.LogService.Error(fmt.Sprintf("Error while waiting for lock release: %v", err))
return fmt.Errorf("error while waiting for lock release: %w", err)
}
a.LogService.Info(fmt.Sprintf("Lock release wait completed: released=%v", released))
if !released {
// Timeout reached, check if daemon is actually running
a.LogService.Warn("Timeout waiting for daemon startup, checking if daemon is running...")
isDaemonRunning := a.IsDaemonRunning()
a.LogService.Info(fmt.Sprintf("Daemon running check result: %v", isDaemonRunning))
if !isDaemonRunning {
// Daemon not running but lock exists, try to start daemon
a.LogService.Info("Daemon not running, attempting to start daemon...")
a.StartupProgress = "Starting daemon..."
if err := a.StartDaemon(); err != nil {
a.LogService.Error(fmt.Sprintf("Failed to start daemon: %v", err))
return fmt.Errorf("failed to start daemon: %w", err)
}
// Wait again for daemon to complete startup
a.LogService.Info("Daemon started, waiting for startup completion...")
a.StartupProgress = "Waiting for daemon initialization..."
released, err := lockfile.WaitForLockRelease(5 * time.Minute)
if err != nil {
a.LogService.Error(fmt.Sprintf("Error while waiting for daemon startup: %v", err))
return fmt.Errorf("error while waiting for daemon startup: %w", err)
}
if !released {
a.LogService.Error("Timeout waiting for daemon startup after starting daemon")
return fmt.Errorf("timeout waiting for daemon startup after starting daemon")
}
} else {
a.LogService.Error("LOG: UI about to exit - daemon is running but lock file is not being released")
a.LogService.Error("This suggests daemon (PID unknown) has a stale lock file")
a.LogService.Error("Possible causes: daemon didn't remove lock properly, race condition, or multiple daemon instances")
a.LogService.Error("LOG: UI exiting due to: timeout waiting for daemon startup, but daemon is running")
return fmt.Errorf("timeout waiting for daemon startup, but daemon is running")
}
}
a.LogService.Info("Daemon startup complete, proceeding with UI startup...")
return nil
}
// Centralized error handling
func (a *App) HandleFatalError(message string) {
if a.WailsEnabled {
if a.LogService != nil {
a.LogService.Error("LOG: HandleFatalError called in UI mode: " + message)
}
runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.ErrorDialog,
Title: "Application Error",
Message: message,
})
if a.LogService != nil {
a.LogService.Error("Fatal error: " + message)
}
fmt.Printf("LOG: UI exiting due to fatal error: %s\n", message)
os.Exit(1)
} else {
if a.LogService != nil {
a.LogService.Error("LOG: HandleFatalError called in daemon mode: " + message)
a.LogService.Error("Fatal error: " + message)
} else {
fmt.Println("LOG: Daemon exiting due to fatal error: " + message)
fmt.Println("Fatal error: " + message)
}
os.Exit(1)
}
}
// -- Bind functions - Dont try to fix, just add them here
// -- Hours wasted: 2
func (a *App) GetActivePlaylists() ([]playlist.Playlist, error) {
return a.PlaylistDB.GetActivePlaylists()
}
func (a *App) OpenDirectory(path string) error {
return a.Utils.OpenDirectory(path)
}
func (a *App) SelectDirectory() (string, error) {
return a.Utils.SelectDirectory()
}
func (a *App) GetClipboard() (string, error) {
return a.Utils.GetClipboard()
}
func (a *App) GetDownloadsDirectory() (string, error) {
return a.Utils.GetDownloadsDirectory()
}
func (a *App) UpdatePlaylistDirectory(id int, newDirectory string) error {
return a.PlaylistService.TryUpdatePlaylistDirectory(id, newDirectory)
}
func (a *App) ValidateAndAddPlaylist(url, directory, format string) error {
return a.PlaylistService.TryAddNewPlaylist(url, directory, format)
}
func (a *App) DeletePlaylist(id int) error {
return a.PlaylistService.TryDeletePlaylist(id)
}
func (a *App) IsStartupComplete() bool {
return a.StartupComplete
}
func (a *App) GetSettingString(key string) (string, error) {
return a.SettingsService.GetSettingString(key)
}
func (a *App) SetSettingPreparsed(key string, value string) error {
err := a.SettingsService.SetPreparsed(key, value)
if err != nil {
return errors.Wrap(err, "failed to set setting")
}
// UI Settings changes trigger daemon change signal
return a.DaemonSignalService.TriggerChange()
}
func (a *App) GetConfigString(key string) (string, error) {
return a.ConfigService.GetConfigString(key)
}
func (a *App) SetConfigString(key string, value string) error {
err := a.ConfigService.SetConfigString(key, value)
if err != nil {
return errors.Wrap(err, "failed to set config")
}
// Config changes trigger daemon change signal
return a.DaemonSignalService.TriggerChange()
}
func (a *App) DirectDownload(url, directory, format string) (string, error) {
// Save current used settings for next time
_ = a.SettingsService.SetPreparsed("direct_download_last_path", directory)
_ = a.SettingsService.SetPreparsed("direct_download_last_format", format)
// Export browser credentials before download if configured
browserSource, err := a.SettingsService.GetSettingString("browser_credentials_source")
if err == nil && browserSource != "" && browserSource != "none" {
_, err := ytdlp.ExportBrowserCredentials(browserSource, a.LogService)
if err != nil {
a.LogService.Warn(fmt.Sprintf("Failed to export browser credentials from %s: %v", browserSource, err))
}
}
// Ensure credentials are cleaned up after download
defer func() {
if err := ytdlp.CleanupCredentialsFile(a.LogService); err != nil {
a.LogService.Warn(fmt.Sprintf("Failed to cleanup credentials file: %v", err))
}
}()
// Download File
result, err := a.DownloadService.DownloadFile(url, directory, format)
if err != nil {
return "", err
}
// Move to final location
err = result.MoveToFinalLocation(directory)
if err != nil {
return "", err
}
// Return final path
return result.FinalFullPath, nil
}
func (a *App) GetDownloadHistoryPage(offset int, limit int, showSuccess, showFailed, showDuplicate bool) ([]download.Download, error) {
return a.DownloadDB.GetDownloadHistoryPage(offset, limit, showSuccess, showFailed, showDuplicate)
}
func (a *App) SetManualRetry(downloadId int) error {
return a.DownloadService.SetManualRetry(downloadId)
}
func (a *App) RegisterAllFailedForRetryManual() error {
return a.DownloadService.RegisterAllFailedForRetryManual()
}
func (a *App) StartDaemon() error {
if a.isDaemonRunning {
a.LogService.Info("StartDaemon called but daemon is already running")
return nil
}
a.LogService.Info("Starting daemon process...")
switch goruntime.GOOS {
case "windows":
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %v", err)
}
err = runner.StartDetachedWithFlags(exePath, 0x00000200|0x00000008, "--mode", "daemon")
if err != nil {
return fmt.Errorf("failed to start daemon: %v", err)
}
// Wait a moment to check if process started successfully
time.Sleep(500 * time.Millisecond)
if !a.IsDaemonRunning() {
return fmt.Errorf("daemon process failed to start")
}
a.LogService.Info("Daemon process started successfully")
case "linux":
err := runner.RunAndWait("systemctl", "start", LinuxServiceName)
if err != nil {
// Fallback to direct execution if service not installed
err = runner.StartDetached(os.Args[0], "--daemon")
if err != nil {
return fmt.Errorf("failed to start daemon: %v", err)
}
time.Sleep(500 * time.Millisecond)
if !a.IsDaemonRunning() {
return fmt.Errorf("daemon process failed to start")
}
a.LogService.Info("Daemon process started successfully via direct execution")
}
default:
return fmt.Errorf("unsupported operating system: %s", goruntime.GOOS)
}
a.isDaemonRunning = true
return nil
}
func (a *App) StopDaemon() error {
if !a.isDaemonRunning {
return nil
}
switch goruntime.GOOS {
case "windows":
selfPid := os.Getpid()
processes, err := process.Processes()
if err != nil {
return fmt.Errorf("failed to list processes: %v", err)
}
selfExe, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %v", err)
}
selfExe = strings.ToLower(selfExe)
for _, p := range processes {
if int32(selfPid) == p.Pid {
continue
}
exe, err := p.Exe()
if err != nil {
continue
}
cmdline, _ := p.Cmdline()
exe = strings.ToLower(exe)
// Only kill processes running in daemon mode
if exe == selfExe && strings.Contains(cmdline, "--mode daemon") {
if err := p.Kill(); err != nil {
return fmt.Errorf("failed to kill process %d: %v", p.Pid, err)
}
a.LogService.Info(fmt.Sprintf("Killed daemon process: PID=%d", p.Pid))
}
}
case "linux":
err := runner.RunAndWait("systemctl", "stop", LinuxServiceName)
if err != nil {
// Fallback to finding and killing the process
runner.RunAndWait("pkill", "-f", os.Args[0])
}
default:
return fmt.Errorf("unsupported operating system: %s", goruntime.GOOS)
}
a.isDaemonRunning = false
return nil
}
// GetRecentLogs returns empty array as database logging is no longer supported
// Use GetDaemonLogLines() or GetUILogLines() for file-based logs instead
func (a *App) GetRecentLogs() ([]interface{}, error) {
return []interface{}{}, nil
}
// GetDaemonLogLines returns the last N lines from daemon.log file
func (a *App) GetDaemonLogLines(lines int) ([]string, error) {
return a.LogService.GetLogLinesFromFile("daemon.log", lines)
}
// GetUILogLines returns the last N lines from ui.log file
func (a *App) GetUILogLines(lines int) ([]string, error) {
return a.LogService.GetLogLinesFromFile("ui.log", lines)
}
// GetDaemonLogLinesWithLevel returns the last N lines from daemon.log file filtered by minimum log level
func (a *App) GetDaemonLogLinesWithLevel(lines int, minLevel string) ([]string, error) {
return a.LogService.GetLogLinesFromFileWithLevel("daemon.log", lines, minLevel)
}
// GetUILogLinesWithLevel returns the last N lines from ui.log file filtered by minimum log level
func (a *App) GetUILogLinesWithLevel(lines int, minLevel string) ([]string, error) {
return a.LogService.GetLogLinesFromFileWithLevel("ui.log", lines, minLevel)
}
func (a *App) IsDaemonRunning() bool {
switch goruntime.GOOS {
case "windows":
selfPid := os.Getpid()
processes, err := process.Processes()
if err != nil {
return false
}
selfExe, err := os.Executable()
if err != nil {
return false
}
selfExe = strings.ToLower(selfExe)
for _, p := range processes {
if int32(selfPid) == p.Pid {
continue
}
exe, err := p.Exe()
if err != nil {
continue
}
cmdline, _ := p.Cmdline()
exe = strings.ToLower(exe)
// Check if it's our executable AND it's running in daemon mode
if exe == selfExe && strings.Contains(cmdline, "--mode daemon") {
return true
}
}
return false
case "linux":
err := runner.RunAndWait("systemctl", "is-active", LinuxServiceName)
if err == nil {
a.isDaemonRunning = true
return true
}
}
// Check for running process in case of direct execution
// This is a simplified check and might need improvement
a.isDaemonRunning = false
return false
}
func (a *App) GetLegalDisclaimerAccepted() (bool, error) {
value, err := a.SettingsService.GetSettingString("legal_disclaimer_accepted")
if err != nil {
return false, err
}
return value == "true", nil
}
func (a *App) SetLegalDisclaimerAccepted(accepted bool) error {
value := "false"
if accepted {
value = "true"
}
return a.SettingsService.SetPreparsed("legal_disclaimer_accepted", value)
}
func (a *App) GetConfirmCloseEnabled() (bool, error) {
// Use service if available, fallback to field for backward compatibility
if a.CloseConfirmService != nil {
return a.CloseConfirmService.IsEnabled(), nil
}
return a.confirmCloseEnabled, nil
}
func (a *App) SetConfirmCloseEnabled(enabled bool) error {
// Use service if available, also update field for backward compatibility
if a.CloseConfirmService != nil {
a.CloseConfirmService.SetEnabled(enabled)
}
a.confirmCloseEnabled = enabled
return nil
}
func (a *App) CloseApplication() {
if a.WailsEnabled {
// Simply call runtime.Quit() and let OnBeforeClose handler handle confirmation
// This prevents double dialogs since OnBeforeClose will handle the confirmation
runtime.Quit(a.ctx)
} else {
os.Exit(0)
}
}
// GetRegisteredFiles returns a paginated list of registered files
func (a *App) GetRegisteredFiles(offset int, limit int) ([]fileregistry.RegisteredFile, error) {
return a.FileRegistryService.GetAllPaginated(offset, limit)
}
// GetRegisteredFilesWithSearch returns a paginated list of registered files filtered by search query
func (a *App) GetRegisteredFilesWithSearch(offset int, limit int, searchQuery string) ([]fileregistry.RegisteredFile, error) {
return a.FileRegistryService.GetAllPaginatedWithSearch(offset, limit, searchQuery)
}
// GetRegisteredFilesCount returns the total count of registered files
func (a *App) GetRegisteredFilesCount() (int, error) {
return a.FileRegistryService.GetCount()
}
// GetRegisteredFilesCountWithSearch returns the count of registered files filtered by search query
func (a *App) GetRegisteredFilesCountWithSearch(searchQuery string) (int, error) {
return a.FileRegistryService.GetCountWithSearch(searchQuery)
}
// RegisterDirectory registers all files in a directory for duplicate detection with progress reporting
func (a *App) RegisterDirectory(directoryPath string) error {
a.LogService.Info(fmt.Sprintf("RegisterDirectory called with path: '%s' (length: %d)", directoryPath, len(directoryPath)))
// If Wails is enabled, emit progress events in background
if a.WailsEnabled {
go func() {
a.SetConfirmCloseEnabled(true) // Enable close confirmation during long operation
defer a.SetConfirmCloseEnabled(false)
// Create progress callback for UI mode
progressCallback := func(percent int, message string) {
runtime.EventsEmit(a.ctx, "file-registration-progress", map[string]interface{}{
"percent": percent,
"message": message,
})
}
// All validation and processing happens in the service with consistent error handling
err := a.FileRegistryService.RegisterDirectoryWithProgress(directoryPath, a.LogService, progressCallback)
if err != nil {
a.LogService.Error(fmt.Sprintf("Directory registration failed: %v", err))
// Emit error completion event
runtime.EventsEmit(a.ctx, "file-registration-error", map[string]interface{}{
"error": err.Error(),
})
} else {
// Only emit success completion if no error
runtime.EventsEmit(a.ctx, "file-registration-complete")
}
a.LogService.Info("Directory registration process completed")
}()
} else {
// Direct execution for non-UI mode (no progress callback needed)
return a.FileRegistryService.RegisterDirectoryWithProgress(directoryPath, a.LogService, nil)
}
return nil
}
// ClearAllRegisteredFiles removes all registered files from the database
func (a *App) ClearAllRegisteredFiles() error {
a.LogService.Info("Clearing all registered files")
return a.FileRegistryService.ClearAll()
}
// GetVersion returns the application version for frontend display
func (a *App) GetVersion() string {
return GetVersionInfo()
}