-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
127 lines (102 loc) · 2.36 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
// Utils
package main
import (
"fmt"
"io"
"os"
"regexp"
"strings"
"time"
)
const (
FILE_PERMISSION = 0600 // Read/Write
FOLDER_PERMISSION = 0700 // Read/Write/Run
ENCRYPTED_BLOCK_MAX_SIZE = 5 * 1024 * 1024
)
// Copy file
// src - Source file
// dst - Destination path
// Returns the number of bytes copied
func CopyFile(src, dst string) (int64, error) {
sourceFileStat, err := os.Stat(src)
if err != nil {
return 0, err
}
if !sourceFileStat.Mode().IsRegular() {
return 0, fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}
// Gets extension from file name
// fileName - File name
func GetExtensionFromFileName(fileName string) string {
parts := strings.Split(fileName, ".")
if len(parts) > 1 {
ext := strings.ToLower(parts[len(parts)-1])
r := regexp.MustCompile("[^a-z0-9]+")
ext = r.ReplaceAllString(ext, "")
if ext != "" {
return ext
} else {
return "bin"
}
} else {
return "bin"
}
}
// Removes extension from file name
// fileName - File name
func GetNameFromFileName(fileName string) string {
parts := strings.Split(fileName, ".")
if len(parts) > 1 {
return strings.Join(parts[:len(parts)-1], ".")
} else {
return fileName
}
}
// Renames and replaces file (Atomic)
// If it fails, tries again up to 3 times, waiting 500 ms (this is to wait for any other program to unlock the file)
// tmpFile - The temporal file to move
// destFile - The destination file name
// returns the error
func RenameAndReplace(tmpFile string, destFile string) error {
retriesLeft := 3
var err error = nil
for retriesLeft > 0 {
err = os.Rename(tmpFile, destFile)
if err == nil {
return nil
}
retriesLeft--
time.Sleep(500 * time.Millisecond)
}
return err
}
// Checks if an album list has repeated elements, and removes them
// list - The media IDs list
// Returns the list without repeated elements
func AlbumListPruneRepeatedElements(list []uint64) []uint64 {
m := make(map[uint64]struct{})
res := make([]uint64, 0)
for i := 0; i < len(list); i++ {
e := list[i]
_, repeated := m[e]
if repeated {
continue
}
res = append(res, e)
m[e] = struct{}{}
}
return res
}