-
Notifications
You must be signed in to change notification settings - Fork 48
/
utils.go
265 lines (228 loc) · 5.46 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
package utils
import (
"bufio"
"crypto/md5"
"errors"
"fmt"
"io"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"unicode"
"unicode/utf8"
"unsafe"
"github.com/yann0917/dedao-gui/backend/request"
)
// MAXLENGTH Maximum length of file name
const MAXLENGTH = 80
// TimeFormat format
const TimeFormat = "2006-01-02 15:04:05"
// FileName filter invalid string
func FileName(name, ext string) string {
rep := strings.NewReplacer("\n", " ", "/", " ", "|", "-", ": ", ":", ":", ":", "'", "’", "\t", " ")
name = rep.Replace(name)
if runtime.GOOS == "windows" {
rep = strings.NewReplacer("\"", " ", "?", " ", "*", " ", "\\", " ", "<", " ", ">", " ", ":", " ", ":", " ")
name = rep.Replace(name)
}
name = strings.TrimSpace(name)
limitedName := LimitLength(name, MAXLENGTH)
if ext != "" {
return fmt.Sprintf("%s.%s", limitedName, ext)
}
return limitedName
}
// LimitLength cut string
func LimitLength(s string, length int) string {
ellipses := "..."
str := []rune(s)
if len(str) > length {
s = string(str[:length-len(ellipses)]) + ellipses
}
return s
}
// FilePath gen valid file path
func FilePath(name, ext string, escape bool) (string, error) {
var outputPath string
fileName := name
if escape {
fileName = FileName(name, ext)
} else {
if ext != "" {
fileName = fmt.Sprintf("%s.%s", name, ext)
}
}
outputPath = filepath.Join(fileName)
return outputPath, nil
}
// Mkdir mkdir path
func Mkdir(elem ...string) (string, error) {
path := filepath.Join(elem...)
err := os.MkdirAll(path, os.ModePerm)
return path, err
}
// FileSize return the file size of the specified path file
func FileSize(filePath string) (int, bool, error) {
file, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
return 0, false, nil
}
return 0, false, err
}
return int(file.Size()), true, nil
}
// M3u8URLs get all ts urls from m3u8 url
func M3u8URLs(uri string) (urls []string, err error) {
if len(uri) == 0 {
return nil, errors.New("M3u8地址为空")
}
html, err := request.HTTPGet(uri)
if err != nil {
return nil, err
}
lines := strings.Split(string(html), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "#") {
if strings.HasPrefix(line, "http") {
urls = append(urls, line)
} else {
base, err := url.Parse(uri)
if err != nil {
continue
}
u, err := url.Parse(line)
if err != nil {
continue
}
urls = append(urls, base.ResolveReference(u).String())
}
}
}
return
}
// CurrentDir CurrentDir
func CurrentDir(joinPath ...string) (string, error) {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return "", err
}
p := strings.Replace(dir, "\\", "/", -1)
whole := filepath.Join(joinPath...)
whole = filepath.Join(p, whole)
return whole, nil
}
// ResolveURL parse url
func ResolveURL(u *url.URL, p string) string {
if strings.HasPrefix(p, "https://") || strings.HasPrefix(p, "http://") {
return p
}
var baseURL string
if strings.Index(p, "/") == 0 {
baseURL = u.Scheme + "://" + u.Host
} else {
tU := u.String()
baseURL = tU[0:strings.LastIndex(tU, "/")]
}
return baseURL + path.Join("/", p)
}
// DrawProgressBar Draw ProgressBar
func DrawProgressBar(prefix string, proportion float32, width int, suffix ...string) {
pos := int(proportion * float32(width))
s := fmt.Sprintf("[%s] %s%*s %6.2f%% %s",
prefix, strings.Repeat("■", pos), width-pos, "", proportion*100, strings.Join(suffix, ""))
fmt.Print("\r" + s)
}
// Unix2String 时间戳[转换为]字符串 eg:(2019-09-09 09:09:09)
func Unix2String(stamp int64) string {
str := time.Unix(stamp, 0).Format(TimeFormat)
return str
}
// Contains int in array
func Contains(s []int, n int) bool {
for _, a := range s {
if a == n {
return true
}
}
return false
}
func StringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(
&struct {
string
Cap int
}{s, len(s)},
))
}
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func CheckFileExist(filename string) bool {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false
}
return true
}
func WriteFileWithTrunc(filename, content string) (err error) {
var f *os.File
if CheckFileExist(filename) {
f, err = os.OpenFile(filename, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
return
}
} else {
f, err = os.Create(filename)
if err != nil {
return
}
}
defer f.Close()
_, err = io.WriteString(f, content)
if err != nil {
return
}
err = f.Sync()
return
}
func MD5str(s string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}
func TimeCost(start time.Time) {
tc := time.Since(start)
fmt.Printf("time cost = %v\n", tc)
}
// ValidUTF8Reader implements a Reader which reads only bytes that constitute valid UTF-8
type ValidUTF8Reader struct {
buffer *bufio.Reader
}
// Function Read reads bytes in the byte array b. n is the number of bytes read.
func (rd ValidUTF8Reader) Read(b []byte) (n int, err error) {
for {
var r rune
var size int
r, size, err = rd.buffer.ReadRune()
if err != nil {
return
}
if r == unicode.ReplacementChar && size == 1 {
continue
} else if n+size < len(b) {
utf8.EncodeRune(b[n:], r)
n += size
} else {
rd.buffer.UnreadRune()
break
}
}
return
}
// NewValidUTF8Reader constructs a new ValidUTF8Reader that wraps an existing io.Reader
func NewValidUTF8Reader(rd io.Reader) ValidUTF8Reader {
return ValidUTF8Reader{bufio.NewReader(rd)}
}