-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
574 lines (472 loc) · 12.7 KB
/
utils.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
package main
import (
"archive/zip"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/google/uuid"
lnk "github.com/parsiya/golnk"
"github.com/wailsapp/wails/v2/pkg/runtime"
"gopkg.in/ini.v1"
)
func writeJSON(path string, data interface{}) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return json.NewEncoder(file).Encode(data)
}
func readJSON(path string, data interface{}) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
return json.NewDecoder(file).Decode(data)
}
// Create folder if it doesn't exist, return error
func create_folder(folder string) error {
if _, err := os.Stat(folder); os.IsNotExist(err) {
err = os.MkdirAll(folder, 0o755)
if err != nil {
return err
}
} else {
runtime.LogDebug(appContext, "Folder already exists: "+folder)
return nil
}
runtime.LogDebug(appContext, "Created folder: "+folder)
return nil
}
func downloadFile(url, dest string, progress chan<- int64, errors chan<- error, wg *sync.WaitGroup) {
defer wg.Done()
// Create file
out, err := os.Create(dest)
if err != nil {
errors <- err
return
}
defer out.Close()
// Fetch file size
resp, err := http.Get(url)
if err != nil {
errors <- err
return
}
defer resp.Body.Close()
buf := make([]byte, 1024*8)
for {
n, err := resp.Body.Read(buf)
if n > 0 {
_, writeErr := out.Write(buf[:n])
if writeErr != nil {
errors <- writeErr
return
}
progress <- int64(n) // Report the number of bytes read
}
if err != nil {
if err != io.EOF {
errors <- err
}
break
}
}
}
func GenerateBase64Png(bytes []byte) string {
var base64Encoding string
// Determine the content type of the image file
mimeType := http.DetectContentType(bytes)
// Prepend the appropriate URI scheme header depending
// on the MIME type
switch mimeType {
case "image/png":
base64Encoding += "data:image/png;base64,"
case "image/x-icon":
base64Encoding += "data:image/x-icon;base64,"
default:
runtime.LogWarning(appContext, "Unrecognized image mime type: "+mimeType)
return ""
}
// Append the base64 encoded output
base64Encoding += base64.StdEncoding.EncodeToString(bytes)
return base64Encoding
}
func GenerateBase64PngFromPath(filePath string) string {
// Read the entire file into a byte slice
bytes, err := os.ReadFile(filePath)
if err != nil {
runtime.LogError(appContext, "Error reading file: "+err.Error())
}
ext := filepath.Ext(filePath)
switch strings.ToLower(ext) {
case ".png":
return GenerateBase64Png(bytes)
case ".ico":
return GenerateBase64Png(bytes)
case ".lnk":
link, err := lnk.File(filePath)
if err != nil {
runtime.LogError(appContext, "Error reading link: "+err.Error())
}
runtime.LogDebug(appContext, "Icon location: "+link.StringData.IconLocation)
if strings.ToLower(filepath.Ext(link.StringData.IconLocation)) == ".ico" {
return GenerateBase64PngFromPath(link.StringData.IconLocation)
}
default:
runtime.LogWarning(appContext, "Unrecognized file type: "+ext)
return ""
}
return ""
}
func ConvertToGeneralPath(path string) string {
desktop, public := get_desktop_paths()
// List of common environment variables to replace
envVars := []string{
"PROGRAMFILES(X86)",
"PROGRAMFILES",
"APPDATA",
"LOCALAPPDATA",
"PROGRAMDATA",
"USERPROFILE",
"PUBLIC",
"SYSTEMROOT",
"WINDIR",
"HOMEDRIVE",
"SYSTEMDRIVE",
}
if strings.HasPrefix(strings.ToLower(path), strings.ToLower(desktop)) {
path = strings.ReplaceAll(path, desktop, "${DESKTOP}")
} else if strings.HasPrefix(strings.ToLower(path), strings.ToLower(public)) {
path = strings.ReplaceAll(path, public, "${DESKTOP}")
}
// Replace environment variables
for _, envVar := range envVars {
placeholder := "${" + envVar + "}"
envValue := os.Getenv(envVar)
if strings.Contains(strings.ToLower(path), strings.ToLower(envValue)) {
path = strings.ReplaceAll(path, envValue, placeholder)
}
}
return path
}
func ConvertToFullPath(path string) string {
path = filepath.Clean(path)
os.Setenv("DESKTOP", "<DESKTOP>")
path = os.ExpandEnv(path)
paths := []string{path}
if strings.Contains(strings.ToUpper(path), "<DESKTOP>") {
desktop, public := get_desktop_paths()
path1 := strings.ReplaceAll(path, "<DESKTOP>", desktop)
path2 := strings.ReplaceAll(path, "<DESKTOP>", public)
paths = []string{path1, path2}
}
if strings.Contains(path, `**`) {
newPaths := []string{}
for _, path := range paths {
paths := generateCombinations(path)
newPaths = append(newPaths, paths...)
}
paths = newPaths
}
for _, path := range paths {
matches, err := filepath.Glob(path)
if err != nil {
runtime.LogErrorf(appContext, "Error globbing path: %s", err)
continue
}
if len(matches) > 0 {
return matches[0]
}
}
return ""
}
func generateCombinations(path string) []string {
// Find the first occurrence of multiple consecutive asterisks pattern (e.g., **, ***)
index := strings.Index(path, "**")
if index == -1 {
return []string{filepath.Clean(path)} // No more '**' to replace, return cleaned path
}
// Count consecutive asterisks to determine maximum depth
maxDepth := 0
for i := index; i < len(path) && path[i] == '*'; i++ {
maxDepth++
}
runtime.LogDebugf(appContext, "Generating combinations with max depth: %d", maxDepth-1)
var results []string
base := path[:index]
suffix := path[index+maxDepth:] // Adjust suffix to skip over the asterisks
// Generate combinations based on current asterisk count (depth)
for i := 0; i < maxDepth; i++ {
// Combine path with varying depth of wildcards
if i == 0 {
// Add combination without extra depth
combinedPath := filepath.Clean(base + suffix)
results = append(results, generateCombinations(combinedPath)...)
} else {
// Add combinations with increasing depth
wildcards := strings.Repeat(`*\`, i)
combinedPath := filepath.Clean(base + wildcards + suffix)
results = append(results, generateCombinations(combinedPath)...)
}
}
return results
}
func copy_file(src string, dst string) error {
input, err := os.ReadFile(src)
if err != nil {
return err
}
err = os.WriteFile(dst, input, 0o644)
if err != nil {
return err
}
return nil
}
func zip_folder(src string, dst string) error {
// Create the destination zip file
zipFile, err := os.Create(dst)
if err != nil {
return fmt.Errorf("failed to create zip file: %w", err)
}
defer zipFile.Close()
// Initialize the zip writer
archive := zip.NewWriter(zipFile)
defer func() {
if cerr := archive.Close(); cerr != nil && err == nil {
err = fmt.Errorf("failed to close archive: %w", cerr)
}
}()
// Walk the directory tree
err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error accessing path %s: %w", path, err)
}
// Skip directories but add them to the zip archive to preserve structure
if info.IsDir() {
return nil
}
if info.Name() == "apply.json" {
return nil
}
// Open the file to be zipped
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open file %s: %w", path, err)
}
defer file.Close()
// Create the file header in the archive
relPath, err := filepath.Rel(filepath.Dir(src), path)
if err != nil {
return fmt.Errorf("failed to get relative path: %w", err)
}
f, err := archive.Create(relPath)
if err != nil {
return fmt.Errorf("failed to create entry for %s in zip file: %w", relPath, err)
}
// Copy the file content to the archive
if _, err = io.Copy(f, file); err != nil {
return fmt.Errorf("failed to write file %s to archive: %w", relPath, err)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to zip folder %s: %w", src, err)
}
return nil
}
func unzip_folder(src, dst string) error {
// Open the ZIP file
zipFile, err := os.Open(src)
if err != nil {
return fmt.Errorf("failed to open zip file: %w", err)
}
defer zipFile.Close()
// Read the ZIP file
stat, err := zipFile.Stat()
if err != nil {
return fmt.Errorf("failed to get zip file info: %w", err)
}
reader, err := zip.NewReader(zipFile, stat.Size())
if err != nil {
return fmt.Errorf("failed to create zip reader: %w", err)
}
// Extract each file and directory
for _, file := range reader.File {
if filepath.Base(file.FileInfo().Name()) == "apply.json" {
continue
}
filePath := filepath.Join(dst, file.Name)
// Ensure the path is within the destination folder
if !strings.HasPrefix(filePath, filepath.Clean(dst)+string(os.PathSeparator)) {
return fmt.Errorf("illegal file path: %s", filePath)
}
// If the file is a directory, create it
if file.FileInfo().IsDir() {
if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
continue
}
// Ensure parent directory exists
if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return fmt.Errorf("failed to create directory for file: %w", err)
}
// Extract the file
destFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return fmt.Errorf("failed to open file for writing: %w", err)
}
defer destFile.Close()
fileInArchive, err := file.Open()
if err != nil {
return fmt.Errorf("failed to open file in archive: %w", err)
}
defer fileInArchive.Close()
if _, err := io.Copy(destFile, fileInArchive); err != nil {
return fmt.Errorf("failed to copy file content: %w", err)
}
}
return nil
}
func exists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
func is_dir(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return info.IsDir()
}
func (a *App) UUID() string {
return uuid.NewString()
}
func (a *App) GeneralPathExits(path string) bool {
return ConvertToFullPath(path) != ""
}
func (a *App) Ext(path string) string {
fullPath := ConvertToFullPath(path)
if fullPath == "" {
return strings.ToLower(filepath.Ext(path))
} else {
return strings.ToLower(filepath.Ext(fullPath))
}
}
func (a *App) Name(path string) string {
fullPath := ConvertToFullPath(path)
if fullPath == "" {
base := filepath.Base(path)
return strings.TrimSuffix(base, filepath.Ext(base))
}
base := filepath.Base(fullPath)
return strings.TrimSuffix(base, filepath.Ext(base))
}
func (a *App) Description(path string) string {
path = ConvertToFullPath(path)
if path == "" {
return ""
}
link, err := lnk.File(path)
if err != nil {
return ""
}
return link.StringData.NameString
}
func (a *App) Destination(path string) string {
path = ConvertToFullPath(path)
if path == "" {
return ""
}
ext := a.Ext(path)
var destination string
if ext == ".lnk" {
link, err := lnk.File(path)
if err != nil {
return ""
}
if link.LinkInfo.LocalBasePath != "" {
destination = link.LinkInfo.LocalBasePath
}
if link.LinkInfo.LocalBasePathUnicode != "" {
destination = link.LinkInfo.LocalBasePathUnicode
}
} else if ext == ".url" {
iniPath := filepath.Join(path)
if !exists(iniPath) {
return ""
}
iniContent, err := os.ReadFile(iniPath)
if err != nil {
return ""
}
iniFile, err := ini.Load(iniContent)
if err != nil {
return ""
}
section := iniFile.Section("InternetShortcut")
destination = section.Key("URL").String()
}
runtime.LogDebugf(appContext, "Destination: %s", destination)
return ConvertToGeneralPath(destination)
}
func (a *App) IconLocation(path string) string {
path = ConvertToFullPath(path)
if path == "" {
return ""
}
if a.Ext(path) == ".lnk" {
link, err := lnk.File(path)
if err != nil {
return ""
}
return link.StringData.IconLocation
} else if a.Ext(path) == ".url" {
iniPath := filepath.Join(path)
if !exists(iniPath) {
return ""
}
iniContent, err := os.ReadFile(iniPath)
if err != nil {
return ""
}
iniFile, err := ini.Load(iniContent)
if err != nil {
return ""
}
section := iniFile.Section("InternetShortcut")
return section.Key("IconFile").String()
}
return ""
}
func (a *App) CreateLastTab(path string) {
tempFilePath := filepath.Join(tempFolder, "iconium-last-tab.txt")
if err := os.WriteFile(tempFilePath, []byte(path), 0o644); err != nil {
runtime.LogErrorf(appContext, "Error writing last tab path: %s", err)
}
}
func (a *App) ReadLastTab() string {
tempFilePath := filepath.Join(tempFolder, "iconium-last-tab.txt")
if _, err := os.Stat(tempFilePath); errors.Is(err, os.ErrNotExist) {
return ""
}
content, err := os.ReadFile(tempFilePath)
if err != nil {
runtime.LogErrorf(appContext, "Error reading last tab path: %s", err)
return ""
}
// Delete the temp file
if err := os.Remove(tempFilePath); err != nil {
runtime.LogErrorf(appContext, "Error removing temp file: %s", err)
}
return string(content)
}