forked from iawia002/lux
/
utils.go
271 lines (243 loc) · 6.09 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
package utils
import (
"bufio"
"bytes"
"crypto/md5"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"github.com/tidwall/gjson"
"github.com/iawia002/annie/request"
)
// GetStringFromJSON get the string value from json path
func GetStringFromJSON(json, path string) string {
return gjson.Get(json, path).String()
}
// MatchOneOf match one of the patterns
func MatchOneOf(text string, patterns ...string) []string {
var (
re *regexp.Regexp
value []string
)
for _, pattern := range patterns {
// (?flags): set flags within current group; non-capturing
// s: let . match \n (default false)
// https://github.com/google/re2/wiki/Syntax
re = regexp.MustCompile(pattern)
value = re.FindStringSubmatch(text)
if len(value) > 0 {
return value
}
}
return nil
}
// MatchAll return all matching results
func MatchAll(text, pattern string) [][]string {
re := regexp.MustCompile(pattern)
value := re.FindAllStringSubmatch(text, -1)
return value
}
// FileSize return the file size of the specified path file
func FileSize(filePath string) (int64, bool, error) {
file, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
return 0, false, nil
}
return 0, false, err
}
return file.Size(), true, nil
}
// Domain get the domain of given URL
func Domain(url string) string {
domainPattern := `([a-z0-9][-a-z0-9]{0,62})\.` +
`(com\.cn|com\.hk|` +
`cn|com|net|edu|gov|biz|org|info|pro|name|xxx|xyz|be|` +
`me|top|cc|tv|tt)`
domain := MatchOneOf(url, domainPattern)
if domain != nil {
return domain[1]
}
return ""
}
// LimitLength Handle overly long strings
func LimitLength(s string, length int) string {
// 0 means unlimited
if length == 0 {
return s
}
const ELLIPSES = "..."
str := []rune(s)
if len(str) > length {
return string(str[:length-len(ELLIPSES)]) + ELLIPSES
}
return s
}
// FileName Converts a string to a valid filename
func FileName(name, ext string, length int) string {
rep := strings.NewReplacer("\n", " ", "/", " ", "|", "-", ": ", ":", ":", ":", "'", "’")
name = rep.Replace(name)
if runtime.GOOS == "windows" {
rep = strings.NewReplacer("\"", " ", "?", " ", "*", " ", "\\", " ", "<", " ", ">", " ")
name = rep.Replace(name)
}
limitedName := LimitLength(name, length)
if ext == "" {
return limitedName
}
return fmt.Sprintf("%s.%s", limitedName, ext)
}
// FilePath gen valid file path
func FilePath(name, ext string, length int, outputPath string, escape bool) (string, error) {
if outputPath != "" {
if _, err := os.Stat(outputPath); err != nil {
return "", err
}
}
var fileName string
if escape {
fileName = FileName(name, ext, length)
} else {
fileName = fmt.Sprintf("%s.%s", name, ext)
}
return filepath.Join(outputPath, fileName), nil
}
// FileLineCounter Counts line in file
func FileLineCounter(r io.Reader) (int, error) {
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
// ParseInputFile Parses input file into args
func ParseInputFile(r io.Reader, items string, itemStart, itemEnd int) []string {
scanner := bufio.NewScanner(r)
temp := make([]string, 0)
totalLines := 0
for scanner.Scan() {
totalLines++
universalURL := strings.TrimSpace(scanner.Text())
temp = append(temp, universalURL)
}
wantedItems := NeedDownloadList(items, itemStart, itemEnd, totalLines)
itemList := make([]string, 0, len(wantedItems))
for i, item := range temp {
if ItemInSlice(i+1, wantedItems) {
itemList = append(itemList, item)
}
}
return itemList
}
// ItemInSlice if a item is in the list
func ItemInSlice(item, list interface{}) bool {
v1 := reflect.ValueOf(item)
v2 := reflect.ValueOf(list)
for i := 0; i < v2.Len(); i++ {
indexType := v2.Index(i).Type().String()
if v1.Type().String() != indexType {
continue
}
switch indexType {
case "int":
if v1.Int() == v2.Index(i).Int() {
return true
}
case "string":
if v1.String() == v2.Index(i).String() {
return true
}
}
}
return false
}
// GetNameAndExt return the name and ext of the URL
// https://img9.bcyimg.com/drawer/15294/post/1799t/1f5a87801a0711e898b12b640777720f.jpg ->
// 1f5a87801a0711e898b12b640777720f, jpg
func GetNameAndExt(uri string) (string, string, error) {
u, err := url.ParseRequestURI(uri)
if err != nil {
return "", "", err
}
s := strings.Split(u.Path, "/")
filename := strings.Split(s[len(s)-1], ".")
if len(filename) > 1 {
return filename[0], filename[1], nil
}
// Image url like this
// https://img9.bcyimg.com/drawer/15294/post/1799t/1f5a87801a0711e898b12b640777720f.jpg/w650
// has no suffix
contentType, err := request.ContentType(uri, uri)
if err != nil {
return "", "", err
}
return filename[0], strings.Split(contentType, "/")[1], nil
}
// Md5 md5 hash
func Md5(text string) string {
sign := md5.New()
sign.Write([]byte(text)) // nolint
return fmt.Sprintf("%x", sign.Sum(nil))
}
// M3u8URLs get all urls from m3u8 url
func M3u8URLs(uri string) ([]string, error) {
if len(uri) == 0 {
return nil, errors.New("url is null")
}
html, err := request.Get(uri, "", nil)
if err != nil {
return nil, err
}
lines := strings.Split(html, "\n")
var urls []string
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 urls, nil
}
// Reverse Reverse a string
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
// Range generate a sequence of numbers by range
func Range(min, max int) []int {
items := make([]int, max-min+1)
for index := range items {
items[index] = min + index
}
return items
}