-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
394 lines (347 loc) · 8.72 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
package firefly
import (
"bufio"
"bytes"
"container/list"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
. "github.com/Monibuca/utils/v3"
"github.com/Monibuca/utils/v3/codec"
"github.com/go-ping/ping"
"github.com/shirou/gopsutil/v3/disk"
"github.com/tidwall/gjson"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
)
var LOC, _ = time.LoadLocation("Asia/Shanghai")
func jsonFormat(data string) string {
var str bytes.Buffer
if err := json.Indent(&str, []byte(data), "", " "); err != nil {
return ""
}
return str.String()
}
func sdCardStat() (*disk.UsageStat, error) {
return disk.Usage(C_MNT_SD)
}
func getSdCardUsedPercent() (float64, error) {
sd, err := disk.Usage(C_MNT_SD)
if err != nil {
return 0, err
}
return sd.UsedPercent, nil
}
func readFile(filePath string) (content string, err error) {
res, err := ioutil.ReadFile(filePath)
if nil != err {
return "", err
}
return string(res), nil
}
func accessible(ipAddr string) (bool, error) {
pinger, err := ping.NewPinger(ipAddr)
if err != nil {
return false, err
}
pinger.Count = 5
pinger.SetPrivileged(true)
pinger.Timeout = 10 * time.Second
if err := pinger.Run(); err != nil {
return false, err
}
stats := pinger.Statistics()
if stats.PacketsRecv >= 1 {
return true, nil
}
return false, errors.New("error")
}
func readInterfaces(filePath string) (string, error) {
f, err := os.Open(filePath)
if err != nil {
return "", nil
}
defer f.Close()
s := bufio.NewScanner(f)
ready := false
var ipAddr = make(map[string]interface{}, 5)
for s.Scan() {
lines := strings.TrimSpace(s.Text())
if !ready && (strings.Compare(lines, C_AUTO_ETH0) == 0) {
ready = true
continue
}
if ready {
if len(lines) == 0 {
ready = false
} else {
if strings.Contains(lines, C_IFACE_ETH0) {
ary := strings.Split(lines, " ")
bootproto := strings.ToLower(ary[3])
if strings.Compare(bootproto, "dhcp") == 0 {
ready = false
}
ipAddr["bootproto"] = bootproto
} else {
line := strings.SplitN(lines, " ", 2)
switch line[0] {
case "address":
ipAddr["address"] = line[1]
case "netmask":
ipAddr["netmask"] = line[1]
case "gateway":
ipAddr["gateway"] = line[1]
case "dns-nameservers":
ipAddr["dns"] = line[1]
default:
}
}
}
}
}
rootJson, _ := json.Marshal(ipAddr)
return string(rootJson), nil
}
func checkIp(ip string) bool {
addr := strings.Trim(ip, " ")
regStr := `^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`
if match, _ := regexp.MatchString(regStr, addr); match {
return true
}
return false
}
func checkInet(inet string) bool {
for _, value := range InetList {
if strings.Compare(value, inet) == 0 {
return true
}
}
return false
}
func updateInterfaces(params, filePath string) error {
bootproto := gjson.Get(params, "bootproto").Str
if len(bootproto) == 0 {
return errors.New("IPv4方式不能为空")
}
bootproto = strings.ToLower(bootproto)
if ok := checkInet(bootproto); !ok {
return errors.New("请正确选择IPv4方式")
}
dhcp := false
if strings.Compare(bootproto, "dhcp") == 0 {
dhcp = true
}
var address, netmask, gateway, nameservers, dns1, dns2 string
if !dhcp {
address = gjson.Get(params, "address").Str
if !checkIp(address) {
return errors.New("ipv4地址格式不对")
}
netmask = gjson.Get(params, "netmask").Str
if !checkIp(netmask) {
return errors.New("ipv4子网掩码格式不对")
}
gateway = gjson.Get(params, "gateway").Str
if !checkIp(gateway) {
return errors.New("ipv4网关地址格式不对")
}
dns := gjson.Get(params, "dns")
if !dns.Exists() {
return errors.New("dns不能为空")
}
dnsList := strings.Split(dns.Str, " ")
if len(dnsList) > 0 {
dns1 = dnsList[0]
if !checkIp(dns1) {
return errors.New("首选DNS格式不对")
}
if len(dnsList) > 1 {
dns2 = dnsList[1]
if !checkIp(dns2) {
return errors.New("备选DNS格式不对")
}
}
} else {
return errors.New("dns不能为空")
}
nameservers = dns1 + " " + dns2
}
in, err := os.Open(filePath)
if err != nil {
return err
}
defer in.Close()
s := bufio.NewScanner(in)
l := list.New()
ready := false
cnt := 0
for s.Scan() {
lines := strings.TrimSpace(s.Text())
cnt++
if strings.Compare(lines, C_AUTO_ETH0) == 0 {
ready = true
l.PushBack(lines)
continue
}
if ready {
if len(lines) == 0 {
ready = false
l.PushBack(lines)
} else {
if strings.Contains(lines, C_IFACE_ETH0) {
o := strings.ToLower(strings.TrimSpace(lines[16:]))
lines = "iface eth0 inet " + bootproto
l.PushBack(lines)
if (strings.Compare(o, "dhcp") == 0) && (strings.Compare(o, bootproto) != 0) {
lines = "address " + address
l.PushBack(lines)
lines = "netmask " + netmask
l.PushBack(lines)
lines = "gateway " + gateway
l.PushBack(lines)
lines = "dns-nameservers " + nameservers
l.PushBack(lines)
}
} else {
if strings.Contains(lines, "address") {
lines = "address " + address
} else if strings.Contains(lines, "netmask") {
lines = "netmask " + netmask
} else if strings.Contains(lines, "gateway") {
lines = "gateway " + gateway
} else if strings.Contains(lines, "dns-nameservers") {
lines = "dns-nameservers " + nameservers
}
if !dhcp {
l.PushBack(lines)
}
}
}
} else {
l.PushBack(lines)
}
}
log.Printf("ip address [%d] rows affected is Changed", cnt)
flag := os.O_TRUNC | os.O_CREATE | os.O_WRONLY
out, err := os.OpenFile(filePath, flag, 0777)
if err != nil {
return err
}
defer func() {
if err := out.Close(); err == nil {
log.Println(filePath + " save is ok.")
} else {
log.Println("file close error: " + err.Error())
}
}()
for p := l.Front(); p != nil; p = p.Next() {
line := p.Value.(string)
log.Println(line)
out.WriteString(line + "\n")
}
return nil
}
//16进制解码
func HexDecode(s string) []byte {
dst := make([]byte, hex.DecodedLen(len(s))) //申请一个切片, 指明大小. 必须使用hex.DecodedLen
n, err := hex.Decode(dst, []byte(s)) //进制转换, src->dst
if err != nil {
log.Fatal(err)
return nil
}
return dst[:n] //返回0:n的数据.
}
//字符串转为16进制
func HexEncode(s string) []byte {
dst := make([]byte, hex.EncodedLen(len(s))) //申请一个切片, 指明大小. 必须使用hex.EncodedLen
n := hex.Encode(dst, []byte(s)) //字节流转化成16进制
return dst[:n]
}
func UnixTimeFormat(path int64) string {
return time.Unix(path, 0).Format("2006-01-02")
}
func StrToDatetime(t string) (time.Time, error) {
return time.ParseInLocation(YYYY_MM_DD_HH_MM_SS, t, LOC)
}
func FormatTime(ms int) string {
ss := 1000
mi := ss * 60
hh := mi * 60
dd := hh * 24
day := ms / dd
hour := (ms - day*dd) / hh
minute := (ms - day*dd - hour*hh) / mi
second := (ms - day*dd - hour*hh - minute*mi) / ss
milliSecond := ms - day*dd - hour*hh - minute*mi - second*ss
return fmt.Sprintf("%d:%d:%d.%d", hour, minute, second, milliSecond)
}
func FormatTimeStr(ms int) string {
ss := 1000
mi := ss * 60
hh := mi * 60
dd := hh * 24
day := ms / dd
hour := (ms - day*dd) / hh
minute := (ms - day*dd - hour*hh) / mi
second := (ms - day*dd - hour*hh - minute*mi) / ss
milliSecond := ms - day*dd - hour*hh - minute*mi - second*ss
return fmt.Sprintf("%d天%d小时%d分%d秒%d毫秒", day, hour, minute, second, milliSecond)
}
func httpGet(url string) (string, error) {
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
//live/hk/2021/09/24/143046.flv
func getFlvTimestamp(path string) time.Time {
return getTimestamp(path, 21, 4, "2006/01/02/150405")
}
//live/hw/2021-09-27/18-07-25.mp4
func getMp4Timestamp(path string) time.Time {
return getTimestamp(path, 23, 4, "2006-01-02/15-04-05")
}
func getTimestamp(path string, start, end int, layout string) time.Time {
s := path[len(path)-start : len(path)-end]
l, err := time.LoadLocation("Local")
if err != nil {
return time.Unix(0, 0)
}
tmp, err := time.ParseInLocation(layout, s, l)
if err != nil {
return time.Unix(0, 0)
}
return tmp
}
func getDuration(file FileWr) uint32 {
_, err := file.Seek(-4, io.SeekEnd)
if err == nil {
var tagSize uint32
if tagSize, err = ReadByteToUint32(file, true); err == nil {
_, err = file.Seek(-int64(tagSize)-4, io.SeekEnd)
if err == nil {
_, timestamp, _, err := codec.ReadFLVTag(file)
if err == nil {
return timestamp
}
}
}
}
return 0
}