-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.go
More file actions
1207 lines (1044 loc) · 35.2 KB
/
manager.go
File metadata and controls
1207 lines (1044 loc) · 35.2 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 (
"bufio"
"embed"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/fs"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
//go:embed manifests.json
var manifestsJSON []byte
//go:embed firefox
var firefoxAssets embed.FS
type PWAMetadata struct {
Name string `json:"name"`
Description string `json:"description"`
URL string `json:"url"`
Icon string `json:"icon"`
}
// Constants for directories (mirrored from common.py)
var (
HomeDir, _ = os.UserHomeDir()
IceDir = filepath.Join(HomeDir, ".local", "share", "ice")
AppsDir = filepath.Join(HomeDir, ".local", "share", "applications")
ProfilesDir = filepath.Join(IceDir, "profiles")
FirefoxProfilesDir = filepath.Join(IceDir, "firefox")
FirefoxFlatpakProfilesDir = filepath.Join(HomeDir, ".var", "app", "org.mozilla.firefox", "data", "ice", "firefox")
FirefoxSnapProfilesDir = filepath.Join(HomeDir, "snap", "firefox", "common", ".mozilla", "firefox")
ZenFlatpakProfilesDir = filepath.Join(HomeDir, ".var", "app", "app.zen_browser.zen", "data", "ice", "zen")
LibreWolfFlatpakProfilesDir = filepath.Join(HomeDir, ".var", "app", "io.gitlab.librewolf-community", "data", "ice", "librewolf")
WaterfoxFlatpakProfilesDir = filepath.Join(HomeDir, ".var", "app", "net.waterfox.waterfox", "data")
FloorpFlatpakProfilesDir = filepath.Join(HomeDir, ".var", "app", "one.ablaze.floorp", "data")
IconsDir = filepath.Join(HomeDir, ".local", "share", "icons")
)
// Manager handles the logic
type Manager struct {
httpClient *http.Client
}
// isSnapFirefox checks if the given firefox executable is actually a Snap wrapper.
// On Ubuntu, /usr/bin/firefox is a shell script that launches the Snap version.
func isSnapFirefox(execPath string) bool {
// If it's already the snap path, it's definitely snap
if execPath == "/snap/bin/firefox" {
return true
}
// Check if the snap firefox package is installed
if _, err := os.Stat("/snap/bin/firefox"); err == nil {
return true
}
// Check if /usr/bin/firefox is a script (snap wrapper) rather than an ELF binary
resolved := execPath
if p, err := exec.LookPath(execPath); err == nil {
resolved = p
}
data, err := os.ReadFile(resolved)
if err == nil && len(data) > 2 && string(data[:2]) == "#!" {
return true // It's a shell script wrapper -> snap
}
return false
}
func NewManager() *Manager {
// Ensure directories exist
dirs := []string{IceDir, AppsDir, ProfilesDir, FirefoxProfilesDir, IconsDir}
for _, d := range dirs {
_ = os.MkdirAll(d, 0755)
}
return &Manager{
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (m *Manager) GetWebApps() ([]WebApp, error) {
var webapps []WebApp
files, err := os.ReadDir(AppsDir)
if err != nil {
fmt.Println("Error reading AppsDir:", err)
return webapps, nil
}
for _, file := range files {
if file.IsDir() {
continue
}
filename := file.Name()
lowerName := strings.ToLower(filename)
if strings.HasPrefix(lowerName, "webapp-") && strings.HasSuffix(lowerName, ".desktop") {
path := filepath.Join(AppsDir, filename)
// Codename extraction: remove "webapp-" and ".desktop"
codename := filename[7 : len(filename)-8] // "webapp-" length is 7, ".desktop" is 8
// Case insensitive replacement in original: filename.replace("webapp-", "").replace("WebApp-", "")
// We'll stick to simple slice since we checked prefix.
// Actually, original code: filename.replace("webapp-", "").replace("WebApp-", "").replace(".desktop", "")
// My slice logic: "webapp-" (7 chars) ... ".desktop" (8 chars)
// Example: "WebApp-Google.desktop" -> "Google"
// Adjust for case sensitivity if needed, but for now simple slice:
// Check if it starts with WebApp- or webapp-
prefixLen := 7
if strings.HasPrefix(filename, "WebApp-") {
prefixLen = 7
}
if len(filename) > prefixLen+8 {
codename = filename[prefixLen : len(filename)-8]
}
webapp, err := ParseDesktopFile(path, codename)
if err == nil && webapp.IsValid {
// Read icon file and convert to base64 for frontend display
if _, err := os.Stat(webapp.Icon); err == nil {
bytes, err := os.ReadFile(webapp.Icon)
if err == nil {
mime := "image/png"
lowered := strings.ToLower(webapp.Icon)
if strings.HasSuffix(lowered, ".jpg") || strings.HasSuffix(lowered, ".jpeg") {
mime = "image/jpeg"
} else if strings.HasSuffix(lowered, ".svg") {
mime = "image/svg+xml"
} else if strings.HasSuffix(lowered, ".ico") {
mime = "image/x-icon"
}
base64Str := base64.StdEncoding.EncodeToString(bytes)
webapp.Icon = fmt.Sprintf("data:%s;base64,%s", mime, base64Str)
}
}
webapps = append(webapps, webapp)
}
}
}
return webapps, nil
}
func ParseDesktopFile(path string, codename string) (WebApp, error) {
file, err := os.Open(path)
if err != nil {
return WebApp{}, err
}
defer file.Close()
var app WebApp
app.Path = path
app.Codename = codename
isWebApp := false
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.Contains(line, "StartupWMClass=WebApp") ||
strings.Contains(line, "StartupWMClass=Chromium") ||
strings.Contains(line, "StartupWMClass=ICE-SSB") {
isWebApp = true
}
if strings.HasPrefix(line, "Name=") {
app.Name = strings.TrimPrefix(line, "Name=")
} else if strings.HasPrefix(line, "Icon=") {
app.Icon = strings.TrimPrefix(line, "Icon=")
} else if strings.HasPrefix(line, "Exec=") {
app.Exec = strings.TrimPrefix(line, "Exec=")
} else if strings.HasPrefix(line, "Categories=") {
app.Category = strings.TrimPrefix(line, "Categories=")
app.Category = strings.ReplaceAll(app.Category, "GTK;", "")
app.Category = strings.ReplaceAll(app.Category, ";", "")
} else if strings.HasPrefix(line, "X-WebApp-Browser=") {
app.Browser = strings.TrimPrefix(line, "X-WebApp-Browser=")
} else if strings.HasPrefix(line, "X-WebApp-URL=") {
app.URL = strings.TrimPrefix(line, "X-WebApp-URL=")
} else if strings.HasPrefix(line, "X-WebApp-CustomParameters=") {
app.CustomParameters = strings.TrimPrefix(line, "X-WebApp-CustomParameters=")
} else if strings.HasPrefix(line, "X-WebApp-Isolated=") {
val := strings.ToLower(strings.TrimPrefix(line, "X-WebApp-Isolated="))
app.IsolateProfile = (val == "true")
} else if strings.HasPrefix(line, "X-WebApp-Navbar=") {
val := strings.ToLower(strings.TrimPrefix(line, "X-WebApp-Navbar="))
app.Navbar = (val == "true")
} else if strings.HasPrefix(line, "X-WebApp-PrivateWindow=") {
val := strings.ToLower(strings.TrimPrefix(line, "X-WebApp-PrivateWindow="))
app.PrivateWindow = (val == "true")
} else if strings.HasPrefix(line, "Comment=") {
app.Description = strings.TrimPrefix(line, "Comment=")
}
}
if isWebApp && app.Name != "" && app.Icon != "" {
app.IsValid = true
}
return app, scanner.Err()
}
// CreateWebApp creates a new web app
func (m *Manager) CreateWebApp(app WebApp) error {
// Ensure URL has protocol
if !strings.HasPrefix(app.URL, "http://") && !strings.HasPrefix(app.URL, "https://") {
app.URL = "https://" + app.URL
}
// Generate codename if not present (simple approach)
if app.Codename == "" {
app.Codename = SanitizeFilename(app.Name)
}
app.Codename = SanitizeFilename(app.Codename)
// Process Icon (persist if temp)
var err error
app.Icon, err = m.ProcessIcon(app.Icon, app.Name)
if err != nil {
fmt.Println("Error processing icon:", err)
// Proceed anyway, maybe valid system icon
}
path := filepath.Join(AppsDir, fmt.Sprintf("WebApp-%s.desktop", app.Codename))
app.Path = path
// Save .desktop file
return m.SaveDesktopFile(app)
}
// EditWebApp edits an existing web app
func (m *Manager) EditWebApp(app WebApp) error {
// Ensure URL has protocol
if !strings.HasPrefix(app.URL, "http://") && !strings.HasPrefix(app.URL, "https://") {
app.URL = "https://" + app.URL
}
// Re-calculate Path validation to avoid empty path error
if app.Path == "" && app.Codename != "" {
app.Path = filepath.Join(AppsDir, fmt.Sprintf("WebApp-%s.desktop", app.Codename))
}
// Process Icon (persist if temp)
var err error
app.Icon, err = m.ProcessIcon(app.Icon, app.Name)
if err != nil {
fmt.Println("Error processing icon:", err)
}
return m.SaveDesktopFile(app)
}
// DeleteWebApp deletes a web app
func (m *Manager) DeleteWebApp(app WebApp) error {
// Delete .desktop file
if err := os.Remove(app.Path); err != nil && !os.IsNotExist(err) {
return err
}
// Delete profile directories
_ = os.RemoveAll(filepath.Join(FirefoxProfilesDir, app.Codename))
_ = os.RemoveAll(filepath.Join(ProfilesDir, app.Codename))
// Epiphany cleanup
epiphanyProfile := filepath.Join(HomeDir, ".local", "share", "org.gnome.Epiphany.WebApp-"+app.Codename)
if _, err := os.Stat(epiphanyProfile); err == nil {
_ = os.Remove(epiphanyProfile) // It's a symlink usually
}
_ = os.RemoveAll(filepath.Join(IceDir, "epiphany", "org.gnome.Epiphany.WebApp-"+app.Codename))
// Falkon cleanup
falkonProfileLink := filepath.Join(HomeDir, ".config", "falkon", "profiles", app.Codename)
if _, err := os.Stat(falkonProfileLink); err == nil {
_ = os.Remove(falkonProfileLink)
}
_ = os.RemoveAll(filepath.Join(IceDir, "falkon", app.Codename))
return nil
}
func (m *Manager) SaveDesktopFile(app WebApp) error {
// 1. Get Exec String
execString, err := m.GetExecString(app)
if err != nil {
fmt.Println("Warning: Browser not found for Exec string:", err)
// We still save, but maybe fall back to xdg-open for the file?
// Or just save what we can?
// If we return error, user can't save.
// Let's fallback to xdg-open ONLY here so we can at least save, but log it.
execString = fmt.Sprintf("xdg-open \"%s\"", app.URL)
}
// 2. Prepare content
content := fmt.Sprintf(`[Desktop Entry]
Version=1.0
Name=%s
Comment=%s
Exec=%s
Terminal=false
X-MultipleArgs=false
Type=Application
Icon=%s
Categories=GTK;%s;
MimeType=text/html;text/xml;application/xhtml_xml;
StartupWMClass=WebApp-%s
StartupNotify=true
X-WebApp-Browser=%s
X-WebApp-URL=%s
X-WebApp-CustomParameters=%s
X-WebApp-Navbar=%v
X-WebApp-PrivateWindow=%v
X-WebApp-Isolated=%v
`, app.Name, app.Description, execString, app.Icon, app.Category, app.Codename, app.Browser, app.URL, app.CustomParameters, app.Navbar, app.PrivateWindow, app.IsolateProfile)
// 3. Write to file
err = os.WriteFile(app.Path, []byte(content), 0644)
if err != nil {
return err
}
// 4. Update desktop database to refresh menu
// We ignore error here as it might not be available on all systems or might fail harmlessly
_ = exec.Command("update-desktop-database", AppsDir).Run()
return nil
}
func (m *Manager) GetExecString(app WebApp) (string, error) {
// Find the browser struct based on app.Browser name
browsers := GetSupportedBrowsers()
var browser Browser
found := false
for _, b := range browsers {
if b.Name == app.Browser {
browser = b
found = true
break
}
}
if !found {
// Log available browsers for debug
fmt.Printf("Browser '%s' not found. Available: ", app.Browser)
for _, b := range browsers {
fmt.Printf("'%s' ", b.Name)
}
fmt.Println()
return "", fmt.Errorf("browser %s not found", app.Browser)
}
// Helper to wrap command with isolation env vars if needed
wrapIsolation := func(cmd string, profilePath string) string {
if app.IsolateProfile {
// We want to force the browser to think 'profilePath' is its entire world (HOME).
// This forces caches, configs, everything into that folder.
// We use `env` to set these variables for the command.
// Ensure the profile directory exists
_ = os.MkdirAll(profilePath, 0755)
// We need to set HOME, XDG_CONFIG_HOME, XDG_DATA_HOME, XDG_CACHE_HOME
// Note: Some browsers might behave weirdly if HOME is empty or weird, but usually this is what "full isolation" means.
envVars := fmt.Sprintf("env HOME=\"%s\" XDG_DATA_HOME=\"%s\" XDG_CONFIG_HOME=\"%s\" XDG_CACHE_HOME=\"%s\"",
profilePath,
filepath.Join(profilePath, ".local", "share"),
filepath.Join(profilePath, ".config"),
filepath.Join(profilePath, ".cache"))
return fmt.Sprintf("%s %s", envVars, cmd)
}
return cmd
}
if browser.Type == BrowserTypeFirefox || browser.Type == BrowserTypeFirefoxFlatpak || browser.Type == BrowserTypeFirefoxSnap || browser.Type == BrowserTypeZenFlatpak || browser.Type == BrowserTypeLibreWolfFlatpak || browser.Type == BrowserTypeWaterfoxFlatpak || browser.Type == BrowserTypeFloorpFlatpak {
// Firefox based - use the correct profile directory per browser type
var firefoxProfilesDir string
switch browser.Type {
case BrowserTypeFirefoxFlatpak:
firefoxProfilesDir = FirefoxFlatpakProfilesDir
case BrowserTypeFirefoxSnap:
firefoxProfilesDir = FirefoxSnapProfilesDir
case BrowserTypeZenFlatpak:
firefoxProfilesDir = ZenFlatpakProfilesDir
case BrowserTypeLibreWolfFlatpak:
firefoxProfilesDir = LibreWolfFlatpakProfilesDir
case BrowserTypeWaterfoxFlatpak:
firefoxProfilesDir = WaterfoxFlatpakProfilesDir
case BrowserTypeFloorpFlatpak:
firefoxProfilesDir = FloorpFlatpakProfilesDir
case BrowserTypeFirefox:
// On Ubuntu, /usr/bin/firefox is a Snap wrapper script
if isSnapFirefox(browser.ExecPath) {
firefoxProfilesDir = FirefoxSnapProfilesDir
} else {
firefoxProfilesDir = FirefoxProfilesDir
}
default:
firefoxProfilesDir = FirefoxProfilesDir
}
profilePath := filepath.Join(firefoxProfilesDir, app.Codename)
// Resolve template paths relative to the executable, not CWD
exePath, _ := os.Executable()
exeDir := filepath.Dir(exePath)
fmt.Printf("[DEBUG] Executable: %s\n", exePath)
fmt.Printf("[DEBUG] Exe dir: %s\n", exeDir)
fmt.Printf("[DEBUG] Profile path: %s\n", profilePath)
// 1. Try to find an external template first (override)
// 2. If not found, use the embedded template
srcProfile := ""
// Check external candidates
for _, candidate := range []string{
filepath.Join(exeDir, "firefox", "profile"),
"firefox/profile", // CWD fallback
"/usr/share/webapp-manager/firefox/profile",
} {
_, err := os.Stat(candidate)
if err == nil {
srcProfile = candidate
break
}
}
_ = os.MkdirAll(profilePath, 0755)
if srcProfile != "" {
fmt.Printf("[DEBUG] Using external template: %s\n", srcProfile)
// Explicitly copy user.js first
userJsSrc := filepath.Join(srcProfile, "user.js")
userJsDest := filepath.Join(profilePath, "user.js")
if _, err := os.Stat(userJsSrc); err == nil {
if err := CopyFile(userJsSrc, userJsDest); err != nil {
fmt.Printf("[ERROR] Failed to copy user.js: %v\n", err)
} else {
fmt.Printf("[DEBUG] Copied user.js successfully\n")
}
}
if err := CopyDir(srcProfile, profilePath); err != nil {
fmt.Printf("[ERROR] CopyDir failed: %v\n", err)
}
} else {
fmt.Printf("[DEBUG] No external template found. Using embedded 'firefox' assets.\n")
// Extract embedded 'firefox/profile' to profilePath
// The embed variable is 'firefoxAssets' (fs.FS)
// Structure in embed: "firefox/profile/..."
fs.WalkDir(firefoxAssets, "firefox/profile", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// Calculate relative path from "firefox/profile"
relPath, err := filepath.Rel("firefox/profile", path)
if err != nil {
return err
}
destPath := filepath.Join(profilePath, relPath)
if d.IsDir() {
return os.MkdirAll(destPath, 0755)
}
// Read from embedded FS
data, err := fs.ReadFile(firefoxAssets, path)
if err != nil {
fmt.Printf("[ERROR] Failed to read embedded file %s: %v\n", path, err)
return nil // Continue
}
// Write to disk
if err := os.WriteFile(destPath, data, 0644); err != nil {
fmt.Printf("[ERROR] Failed to write embedded file to %s: %v\n", destPath, err)
} else {
fmt.Printf("[DEBUG] Extracted embedded file: %s\n", relPath)
}
return nil
})
}
// Handle userChrome.css for showing/hiding Navbar
chromeDir := filepath.Join(profilePath, "chrome")
_ = os.MkdirAll(chromeDir, 0755)
if !app.Navbar {
// Default: hide toolbar (webapp mode) - already in template
// But ensure userChrome.css exists from template
srcCss := ""
for _, candidate := range []string{
filepath.Join(exeDir, "firefox", "profile", "chrome", "userChrome.css"),
"firefox/profile/chrome/userChrome.css",
"/usr/share/webapp-manager/firefox/profile/chrome/userChrome.css",
} {
if _, err := os.Stat(candidate); err == nil {
srcCss = candidate
break
}
}
if srcCss != "" {
_ = CopyFile(srcCss, filepath.Join(chromeDir, "userChrome.css"))
}
} else {
// Show navbar - copy the navbar-enabled CSS
srcCss := ""
for _, candidate := range []string{
filepath.Join(exeDir, "firefox", "userChrome-with-navbar.css"),
"firefox/userChrome-with-navbar.css",
"/usr/share/webapp-manager/firefox/userChrome-with-navbar.css",
} {
if _, err := os.Stat(candidate); err == nil {
srcCss = candidate
break
}
}
if srcCss != "" {
_ = CopyFile(srcCss, filepath.Join(chromeDir, "userChrome.css"))
} else {
// Fallback: remove userChrome.css to show navbar
_ = os.Remove(filepath.Join(chromeDir, "userChrome.css"))
}
}
// Build Firefox command
// Reverting to --no-remote to match original webapp-manager behavior
cmd := fmt.Sprintf("sh -c 'XAPP_FORCE_GTKWINDOW_ICON=\"%s\" %s --class WebApp-%s --name WebApp-%s --profile %s --no-remote",
app.Icon, browser.ExecPath, app.Codename, app.Codename, profilePath)
if app.PrivateWindow {
cmd += " --private-window"
}
if app.CustomParameters != "" {
cmd += " " + app.CustomParameters
}
cmd += fmt.Sprintf(" \"%s\"'", app.URL)
// Note: We do NOT inject HOME/XDG env vars for Firefox here, matching common.py
// Firefox isolation is handled by --profile and --no-remote
return cmd, nil
} else if browser.Type == BrowserTypeEpiphany {
// Epiphany based
// Symlink profile to ~/.local/share
// Profile path in ICE directory
iceProfile := filepath.Join(IceDir, "epiphany", "org.gnome.Epiphany.WebApp-"+app.Codename)
_ = os.MkdirAll(iceProfile, 0755)
// Target path in ~/.local/share
localShare := filepath.Join(HomeDir, ".local", "share")
targetLink := filepath.Join(localShare, "org.gnome.Epiphany.WebApp-"+app.Codename)
// Create symlink if not exists
if _, err := os.Lstat(targetLink); os.IsNotExist(err) {
_ = os.Symlink(iceProfile, targetLink)
}
// Copy app-icon.png if exists
// (Simplified logic: we rely on Epiphany creating structure or just passing args)
// Original creates .app file too
_ = os.WriteFile(filepath.Join(iceProfile, ".app"), []byte{}, 0644)
cmd := fmt.Sprintf("%s --application-mode --profile=\"%s\" \"%s\"", browser.ExecPath, targetLink, app.URL)
if app.CustomParameters != "" {
cmd += " " + app.CustomParameters
}
// Isolation for Epiphany
if app.IsolateProfile {
// Epiphany uses --profile but might leak other things.
// Wrap it.
cmd = wrapIsolation(cmd, iceProfile)
}
return cmd, nil
} else if browser.Type == BrowserTypeFalkon {
// Falkon
// Symlink profile to ~/.config/falkon/profiles
iceProfile := filepath.Join(IceDir, "falkon", app.Codename)
_ = os.MkdirAll(iceProfile, 0755)
configDir := filepath.Join(HomeDir, ".config", "falkon", "profiles")
_ = os.MkdirAll(configDir, 0755)
targetLink := filepath.Join(configDir, app.Codename)
if _, err := os.Lstat(targetLink); os.IsNotExist(err) {
_ = os.Symlink(iceProfile, targetLink)
}
cmd := fmt.Sprintf("%s --wmclass=WebApp-%s", browser.ExecPath, app.Codename)
if app.IsolateProfile {
cmd += " --profile=" + app.Codename
}
if app.PrivateWindow {
cmd += " --private-browsing"
}
if app.CustomParameters != "" {
cmd += " " + app.CustomParameters
}
cmd += " --no-remote " + app.URL
if app.IsolateProfile {
cmd = wrapIsolation(cmd, iceProfile)
}
return cmd, nil
} else {
// Chromium based
cmd := browser.ExecPath
var profilePath string
if app.IsolateProfile {
profilePath = filepath.Join(ProfilesDir, app.Codename)
cmd += fmt.Sprintf(" --app=\"%s\" --class=WebApp-%s --name=WebApp-%s --user-data-dir=%s --no-first-run --no-default-browser-check", app.URL, app.Codename, app.Codename, profilePath)
} else {
cmd += fmt.Sprintf(" --app=\"%s\" --class=WebApp-%s --name=WebApp-%s --no-first-run --no-default-browser-check", app.URL, app.Codename, app.Codename)
}
if app.PrivateWindow {
cmd += " --incognito"
}
if app.CustomParameters != "" {
cmd += " " + app.CustomParameters
}
if app.IsolateProfile && profilePath != "" {
cmd = wrapIsolation(cmd, profilePath)
}
return cmd, nil
}
}
func SanitizeFilename(name string) string {
return strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
return r
}
return -1
}, name)
}
// RunWebApp launches the web app
func (m *Manager) RunWebApp(app WebApp) error {
if app.Exec == "" {
// Fallback if Exec not present in struct (e.g. freshly created object not reloaded from file)
var err error
app.Exec, err = m.GetExecString(app)
if err != nil {
return err
}
}
// Execute exactly like Python's subprocess.Popen(webapp.exec, shell=True)
// The Exec string already contains "sh -c '...'" so we need to execute it directly
// NOT wrap it again with another sh -c
cmd := exec.Command("/bin/sh", "-c", app.Exec)
// Detach process so it doesn't die when we close
if err := cmd.Start(); err != nil {
fmt.Println("Error starting app:", err)
return err
}
return nil
}
func CopyDir(src string, dst string) error {
return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(src, path)
if err != nil {
return err
}
targetPath := filepath.Join(dst, relPath)
if info.IsDir() {
return os.MkdirAll(targetPath, info.Mode())
}
return CopyFile(path, targetPath)
})
}
func CopyFile(src, dst string) error {
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
destFile, err := os.Create(dst)
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, sourceFile)
if err != nil {
return err
}
// Copy permissions
info, err := os.Stat(src)
if err == nil {
_ = os.Chmod(dst, info.Mode())
}
return nil
}
// GetFavicons fetches possible icon URLs for a given website
func (m *Manager) GetFavicons(urlStr string) ([]string, error) {
if !strings.HasPrefix(urlStr, "http") {
urlStr = "https://" + urlStr
}
var icons []string
// 1. Fetch HTML
req, _ := http.NewRequest("GET", urlStr, nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err := m.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Capture the final URL after redirects
finalURL := resp.Request.URL.String()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
html := string(bodyBytes)
// 2. Parse for <link rel="...icon"...>
// Regex is rough but works for most standard compliant sites
// Matches href="..." in link tags with icon rel
re := regexp.MustCompile(`<link[^>]+rel=["']?((?:shortcut )?icon)["']?[^>]+href=["']?([^"']+)["']?`)
matches := re.FindAllStringSubmatch(html, -1)
for _, match := range matches {
if len(match) >= 3 {
iconURL := match[2]
icons = append(icons, resolveURL(finalURL, iconURL))
}
}
// Also try simple href="...icon..." matching if rel is elsewhere (less reliable, skip for now)
// 3. Fallback: /favicon.ico
faviconURL := resolveURL(finalURL, "/favicon.ico")
// Check if it exists/200 OK (optional, but good UX to filter broken ones)
// For now, just append it.
icons = append(icons, faviconURL)
// Deduplicate
uniqueIcons := make(map[string]bool)
var result []string
for _, i := range icons {
if !uniqueIcons[i] {
uniqueIcons[i] = true
result = append(result, i)
}
}
return result, nil
}
func resolveURL(base, ref string) string {
if strings.HasPrefix(ref, "data:") {
return ref
}
// Handle protocol-relative URLs (//example.com/icon.png)
if strings.HasPrefix(ref, "//") {
baseUrl, err := url.Parse(base)
if err != nil {
return ref
}
return baseUrl.Scheme + ":" + ref
}
baseUrl, err := url.Parse(base)
if err != nil {
return ref
}
refUrl, err := url.Parse(ref)
if err != nil {
return ref
}
return baseUrl.ResolveReference(refUrl).String()
}
// ProcessIcon checks if the icon is a file and copies it to the permanent icons directory.
func (m *Manager) ProcessIcon(iconPath string, appName string) (string, error) {
// 0. Handle Data URIs
if strings.HasPrefix(iconPath, "data:") {
// Format: data:[<mediatype>][;base64],<data>
parts := strings.SplitN(iconPath, ",", 2)
if len(parts) != 2 {
return iconPath, fmt.Errorf("invalid data URI")
}
meta := parts[0]
data := parts[1]
// Determine extension from mime type in meta
ext := ".png" // default
if strings.Contains(meta, "image/jpeg") || strings.Contains(meta, "image/jpg") {
ext = ".jpg"
} else if strings.Contains(meta, "image/svg+xml") {
ext = ".svg"
} else if strings.Contains(meta, "image/x-icon") || strings.Contains(meta, "image/vnd.microsoft.icon") {
ext = ".ico"
} else if strings.Contains(meta, "image/webp") {
ext = ".webp"
}
// Decode base64
decoded, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return iconPath, fmt.Errorf("failed to decode base64 icon: %w", err)
}
cleanName := SanitizeFilename(appName)
if cleanName == "" {
cleanName = "webapp"
}
newFilename := cleanName + ext
newPath := filepath.Join(IconsDir, newFilename)
if err := os.WriteFile(newPath, decoded, 0644); err != nil {
return iconPath, err
}
return newPath, nil
}
// 1. Handle HTTP/HTTPS URLs (Fetcher)
if strings.HasPrefix(iconPath, "http://") || strings.HasPrefix(iconPath, "https://") {
// Generate filename
cleanName := SanitizeFilename(appName)
if cleanName == "" {
cleanName = "webapp"
}
// Guess extension from URL or default to png
ext := filepath.Ext(iconPath)
if ext == "" || len(ext) > 5 { // Basic sanity check
ext = ".png"
}
// Remove query params if any
if strings.Contains(ext, "?") {
ext = strings.Split(ext, "?")[0]
}
newFilename := cleanName + ext
newPath := filepath.Join(IconsDir, newFilename)
// Download
resp, err := http.Get(iconPath)
if err != nil {
fmt.Println("Error downloading icon:", err)
return iconPath, err
}
defer resp.Body.Close()
// Read body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return iconPath, err
}
// Validate content type
contentType := http.DetectContentType(body)
if !strings.HasPrefix(contentType, "image/") {
fmt.Println("Warning: Downloaded icon is not an image:", contentType)
// Return original path/url if it's not a valid image, potentially fallback?
// But maybe the content type detection is wrong?
// Let's assume if it's text/html it's definitely wrong.
if strings.HasPrefix(contentType, "text/") {
return iconPath, fmt.Errorf("icon URL returned text content: %s", contentType)
}
}
if err := os.WriteFile(newPath, body, 0644); err != nil {
return iconPath, err
}
return newPath, nil
}
// 2. Check if it is a local file
info, err := os.Stat(iconPath)
if err == nil && !info.IsDir() {
// It is a file. Check if it's already in IconsDir
absIconPath, _ := filepath.Abs(iconPath)
absIconsDir, _ := filepath.Abs(IconsDir)
if strings.HasPrefix(absIconPath, absIconsDir) {
// Already in the right place
return iconPath, nil
}
// It's a file outside our managed dir (e.g. /tmp, Downloads). Copy it.
// Generate new filename
cleanName := SanitizeFilename(appName)
if cleanName == "" {
cleanName = "webapp"
}
// Preserve extension if possible, default to .png
ext := filepath.Ext(iconPath)
if ext == "" {
ext = ".png"
}
newFilename := cleanName + ext
newPath := filepath.Join(IconsDir, newFilename)
// Copy file
err := CopyFile(iconPath, newPath)
if err != nil {
return iconPath, err
}
return newPath, nil
}
// Not a file, probably an icon name (e.g. "webapp-manager")
return iconPath, nil
}
// tryManifestURL checks if a given URL returns a valid manifest
func (m *Manager) tryManifestURL(testURL string) bool {
req, err := http.NewRequest("GET", testURL, nil)
if err != nil {
return false
}
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err := m.httpClient.Do(req)
if err != nil || resp.StatusCode != 200 {
return false
}
defer resp.Body.Close()
// Try to parse as JSON
var testData map[string]interface{}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false
}
if json.Unmarshal(body, &testData) != nil {
return false
}
// Check if it has required manifest fields
if _, hasName := testData["name"]; hasName {
return true
}
if _, hasShortName := testData["short_name"]; hasShortName {
return true
}
return false
}
func (m *Manager) GetPWAMetadata(websiteURL string) (PWAMetadata, error) {
var meta PWAMetadata
// 1. Fetch HTML
req, _ := http.NewRequest("GET", websiteURL, nil)
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
resp, err := m.httpClient.Do(req)
if err != nil {
fmt.Printf("PWA Fetch Error: %v\n", err)
return meta, err
}
defer resp.Body.Close()
finalURL := resp.Request.URL.String()