1
0

util.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. package pkg
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "crypto/tls"
  8. "encoding/binary"
  9. "encoding/hex"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "math"
  14. "net/http"
  15. "net/url"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "path/filepath"
  20. "regexp"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/allanpk716/ChineseSubFinder/pkg/local_http_proxy_server"
  26. "github.com/allanpk716/ChineseSubFinder/pkg/types/common"
  27. "github.com/allanpk716/ChineseSubFinder/pkg/regex_things"
  28. "github.com/allanpk716/ChineseSubFinder/pkg/settings"
  29. browser "github.com/allanpk716/fake-useragent"
  30. "github.com/go-resty/resty/v2"
  31. "github.com/google/uuid"
  32. "github.com/sirupsen/logrus"
  33. )
  34. // NewHttpClient 新建一个 resty 的对象
  35. func NewHttpClient(referer ...string) (*resty.Client, error) {
  36. //const defUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"
  37. //const defUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41"
  38. var UserAgent, Referer string
  39. // ------------------------------------------------
  40. // 随机的 Browser
  41. UserAgent = browser.Random()
  42. // ------------------------------------------------
  43. httpClient := resty.New().SetTransport(&http.Transport{
  44. DisableKeepAlives: true,
  45. MaxIdleConns: 1000,
  46. MaxIdleConnsPerHost: 1000,
  47. })
  48. httpClient.SetTimeout(common.HTMLTimeOut)
  49. httpClient.SetRetryCount(1)
  50. // ------------------------------------------------
  51. // 设置 Referer
  52. if len(referer) > 0 {
  53. Referer = referer[0]
  54. if len(Referer) > 0 {
  55. httpClient.SetHeader("Referer", Referer)
  56. }
  57. }
  58. // ------------------------------------------------
  59. // 设置 Header
  60. httpClient.SetHeaders(map[string]string{
  61. "Content-Type": "application/json",
  62. "User-Agent": UserAgent,
  63. })
  64. // ------------------------------------------------
  65. // 不要求安全链接
  66. httpClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
  67. // ------------------------------------------------
  68. // http 代理
  69. HttpProxyAddress := local_http_proxy_server.GetProxyUrl()
  70. if HttpProxyAddress != "" {
  71. httpClient.SetProxy(HttpProxyAddress)
  72. } else {
  73. httpClient.RemoveProxy()
  74. }
  75. return httpClient, nil
  76. }
  77. func getPublicIP(inputSite string) string {
  78. var client *resty.Client
  79. client, err := NewHttpClient()
  80. if err != nil {
  81. return ""
  82. }
  83. response, err := client.R().Get(inputSite)
  84. if err != nil {
  85. return ""
  86. }
  87. return response.String()
  88. }
  89. func GetPublicIP(log *logrus.Logger, queue *settings.TaskQueue) string {
  90. defPublicIPSites := []string{
  91. "https://myip.biturl.top/",
  92. "https://ip4.seeip.org/",
  93. "https://ipecho.net/plain",
  94. "https://api-ipv4.ip.sb/ip",
  95. "https://api.ipify.org/",
  96. "http://myexternalip.com/raw",
  97. }
  98. customPublicIPSites := make([]string, 0)
  99. if queue.CheckPublicIPTargetSite != "" {
  100. // 自定义了公网IP查询网站
  101. tSites := strings.Split(queue.CheckPublicIPTargetSite, ";")
  102. if tSites != nil && len(tSites) > 0 {
  103. customPublicIPSites = append(customPublicIPSites, tSites...)
  104. }
  105. } else {
  106. customPublicIPSites = append(customPublicIPSites, defPublicIPSites...)
  107. }
  108. for i, publicIPSite := range customPublicIPSites {
  109. log.Debugln("[GetPublicIP]", i, publicIPSite)
  110. publicIP := getPublicIP(publicIPSite)
  111. matcheds := regex_things.ReMatchIP.FindAllString(publicIP, -1)
  112. if publicIP != "" || matcheds == nil || len(matcheds) == 0 {
  113. log.Infoln("[GetPublicIP]", publicIP)
  114. return publicIP
  115. }
  116. }
  117. return ""
  118. }
  119. // DownFile 从指定的 url 下载文件
  120. func DownFile(l *logrus.Logger, urlStr string) ([]byte, string, error) {
  121. var err error
  122. var httpClient *resty.Client
  123. httpClient, err = NewHttpClient()
  124. if err != nil {
  125. return nil, "", err
  126. }
  127. resp, err := httpClient.R().Get(urlStr)
  128. if err != nil {
  129. return nil, "", err
  130. }
  131. filename := GetFileName(l, resp.RawResponse)
  132. if filename == "" {
  133. l.Warningln("DownFile.GetFileName is string.empty", urlStr)
  134. }
  135. return resp.Body(), filename, nil
  136. }
  137. // GetFileName 获取下载文件的文件名
  138. func GetFileName(l *logrus.Logger, resp *http.Response) string {
  139. contentDisposition := resp.Header.Get("Content-Disposition")
  140. if len(contentDisposition) == 0 {
  141. m := regexp.MustCompile(`^(.*/)?(?:$|(.+?)(?:(\.[^.]*$)|$))`).FindStringSubmatch(resp.Request.URL.String())
  142. if m == nil || len(m) < 4 {
  143. l.Warningln("GetFileName.regexp.MustCompile.FindStringSubmatch", resp.Request.URL.String())
  144. return ""
  145. }
  146. return m[2] + m[3]
  147. }
  148. re := regexp.MustCompile(`filename=["]*([^"]+)["]*`)
  149. matched := re.FindStringSubmatch(contentDisposition)
  150. if matched == nil || len(matched) == 0 || len(matched[0]) == 0 {
  151. l.Errorln("GetFileName.Content-Disposition", contentDisposition)
  152. return ""
  153. }
  154. return matched[1]
  155. }
  156. // AddBaseUrl 判断传入的 url 是否需要拼接 baseUrl
  157. func AddBaseUrl(baseUrl, url string) string {
  158. if strings.Contains(url, "://") {
  159. return url
  160. }
  161. return fmt.Sprintf("%s%s", baseUrl, url)
  162. }
  163. // IsDir 存在且是文件夹
  164. func IsDir(path string) bool {
  165. s, err := os.Stat(path)
  166. if err != nil {
  167. return false
  168. }
  169. return s.IsDir()
  170. }
  171. // IsFile 存在且是文件
  172. func IsFile(filePath string) bool {
  173. s, err := os.Stat(filePath)
  174. if err != nil {
  175. return false
  176. }
  177. return !s.IsDir()
  178. }
  179. // FileNameIsBDMV 是否是 BDMV 蓝光目录,符合返回 true,以及 fakseVideoFPath
  180. func FileNameIsBDMV(id_bdmv_fileFPath string) (bool, string) {
  181. /*
  182. 这类蓝光视频比较特殊,它没有具体的一个后缀名的视频文件而是由两个文件夹来存储视频数据
  183. * BDMV
  184. * CERTIFICATE
  185. 但是不管如何,都需要使用一个文件作为锚点,就选定 CERTIFICATE 中的 id.bdmv 文件
  186. 后续的下载逻辑也需要单独为这个文件进行处理,比如,从这个文件向上一层获取 nfo 文件,
  187. 以及再上一层得到视频文件夹名称等
  188. */
  189. if strings.ToLower(filepath.Base(id_bdmv_fileFPath)) == common.FileBDMV {
  190. // 这个文件是确认了,那么就需要查看这个文件父级目录是不是 CERTIFICATE 文件夹
  191. // 且 CERTIFICATE 需要和 BDMV 文件夹都存在
  192. CERDir := filepath.Dir(id_bdmv_fileFPath)
  193. BDMVDir := filepath.Join(filepath.Dir(CERDir), "BDMV")
  194. if IsDir(CERDir) == true && IsDir(BDMVDir) == true {
  195. return true, filepath.Join(filepath.Dir(CERDir), filepath.Base(filepath.Dir(CERDir))+common.VideoExtMp4)
  196. }
  197. }
  198. return false, ""
  199. }
  200. // IsWantedVideoExtDef 后缀名是否符合规则
  201. func IsWantedVideoExtDef(fileName string) bool {
  202. if len(_wantedExtMap) < 1 {
  203. _defExtMap[common.VideoExtMp4] = common.VideoExtMp4
  204. _defExtMap[common.VideoExtMkv] = common.VideoExtMkv
  205. _defExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  206. _defExtMap[common.VideoExtIso] = common.VideoExtIso
  207. _defExtMap[common.VideoExtM2ts] = common.VideoExtM2ts
  208. _wantedExtMap[common.VideoExtMp4] = common.VideoExtMp4
  209. _wantedExtMap[common.VideoExtMkv] = common.VideoExtMkv
  210. _wantedExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  211. _wantedExtMap[common.VideoExtIso] = common.VideoExtIso
  212. _wantedExtMap[common.VideoExtM2ts] = common.VideoExtM2ts
  213. for _, videoExt := range _customVideoExts {
  214. _wantedExtMap[videoExt] = videoExt
  215. }
  216. }
  217. fileExt := strings.ToLower(filepath.Ext(fileName))
  218. _, bFound := _wantedExtMap[fileExt]
  219. return bFound
  220. }
  221. func GetEpisodeKeyName(season, eps int, zerofill ...bool) string {
  222. if len(zerofill) < 1 || zerofill[0] == false {
  223. return "S" + strconv.Itoa(season) + "E" + strconv.Itoa(eps)
  224. } else {
  225. return fmt.Sprintf("S%02dE%02d", season, eps)
  226. }
  227. }
  228. // CopyFile copies a single file from src to dst
  229. func CopyFile(src, dst string) error {
  230. var err error
  231. var srcFd *os.File
  232. var dstFd *os.File
  233. var srcInfo os.FileInfo
  234. if srcFd, err = os.Open(src); err != nil {
  235. return err
  236. }
  237. defer func() {
  238. _ = srcFd.Close()
  239. }()
  240. if dstFd, err = os.Create(dst); err != nil {
  241. return err
  242. }
  243. defer func() {
  244. _ = dstFd.Close()
  245. }()
  246. if _, err = io.Copy(dstFd, srcFd); err != nil {
  247. return err
  248. }
  249. if srcInfo, err = os.Stat(src); err != nil {
  250. return err
  251. }
  252. return os.Chmod(dst, srcInfo.Mode())
  253. }
  254. // CopyDir copies a whole directory recursively
  255. func CopyDir(src string, dst string) error {
  256. var err error
  257. var fds []os.DirEntry
  258. var srcInfo os.FileInfo
  259. if srcInfo, err = os.Stat(src); err != nil {
  260. return err
  261. }
  262. if err = os.MkdirAll(dst, srcInfo.Mode()); err != nil {
  263. return err
  264. }
  265. if fds, err = os.ReadDir(src); err != nil {
  266. return err
  267. }
  268. for _, fd := range fds {
  269. srcfp := filepath.Join(src, fd.Name())
  270. dstfp := filepath.Join(dst, fd.Name())
  271. if fd.IsDir() {
  272. if err = CopyDir(srcfp, dstfp); err != nil {
  273. fmt.Println(err)
  274. }
  275. } else {
  276. if err = CopyFile(srcfp, dstfp); err != nil {
  277. fmt.Println(err)
  278. }
  279. }
  280. }
  281. return nil
  282. }
  283. // CloseChrome 强行结束没有关闭的 Chrome 进程
  284. func CloseChrome(l *logrus.Logger) {
  285. defer func() {
  286. l.Infoln("CloseChrome End")
  287. }()
  288. l.Infoln("CloseChrome Start...")
  289. cmdString := ""
  290. var command *exec.Cmd
  291. sysType := runtime.GOOS
  292. if sysType == "linux" {
  293. // LINUX系统
  294. cmdString = "pkill chrome"
  295. command = exec.Command("/bin/sh", "-c", cmdString)
  296. }
  297. if sysType == "windows" {
  298. // windows系统
  299. cmdString = "taskkill /F /im chrome.exe"
  300. command = exec.Command("cmd.exe", "/c", cmdString)
  301. }
  302. if sysType == "darwin" {
  303. // macOS
  304. // https://stackoverflow.com/questions/57079120/using-exec-command-in-golang-how-do-i-open-a-new-terminal-and-execute-a-command
  305. cmdString = `tell application "/Applications/Google Chrome.app" to quit`
  306. command = exec.Command("osascript", "-s", "h", "-e", cmdString)
  307. }
  308. if cmdString == "" || command == nil {
  309. l.Errorln("CloseChrome OS:", sysType)
  310. return
  311. }
  312. err := command.Run()
  313. if err != nil {
  314. l.Warningln("CloseChrome", err)
  315. }
  316. }
  317. // OSCheck 强制的系统支持检查
  318. func OSCheck() bool {
  319. sysType := runtime.GOOS
  320. if sysType == "linux" {
  321. return true
  322. }
  323. if sysType == "windows" {
  324. return true
  325. }
  326. if sysType == "darwin" {
  327. return true
  328. }
  329. return false
  330. }
  331. // FixWindowPathBackSlash 修复 Windows 反斜杠的梗
  332. func FixWindowPathBackSlash(path string) string {
  333. return strings.Replace(path, string(filepath.Separator), "/", -1)
  334. }
  335. func WriteStrings2File(desfilePath string, strings []string) error {
  336. dstFile, err := os.Create(desfilePath)
  337. if err != nil {
  338. return err
  339. }
  340. defer func() {
  341. _ = dstFile.Close()
  342. }()
  343. allString := ""
  344. for _, s := range strings {
  345. allString += s + "\r\n"
  346. }
  347. _, err = dstFile.WriteString(allString)
  348. if err != nil {
  349. return err
  350. }
  351. return nil
  352. }
  353. func TimeNumber2Time(inputTimeNumber float64) time.Time {
  354. newTime := time.Time{}.Add(time.Duration(inputTimeNumber * math.Pow10(9)))
  355. return newTime
  356. }
  357. func Time2SecondNumber(inTime time.Time) float64 {
  358. outSecond := 0.0
  359. outSecond += float64(inTime.Hour() * 60 * 60)
  360. outSecond += float64(inTime.Minute() * 60)
  361. outSecond += float64(inTime.Second())
  362. outSecond += float64(inTime.Nanosecond()) / 1000 / 1000 / 1000
  363. return outSecond
  364. }
  365. func Time2Duration(inTime time.Time) time.Duration {
  366. return time.Duration(Time2SecondNumber(inTime) * math.Pow10(9))
  367. }
  368. func Second2Time(sec int64) time.Time {
  369. return time.Unix(sec, 0)
  370. }
  371. // ReplaceSpecString 替换特殊的字符
  372. func ReplaceSpecString(inString string, rep string) string {
  373. return regex_things.RegMatchSpString.ReplaceAllString(inString, rep)
  374. }
  375. func Bool2Int(inBool bool) int {
  376. if inBool == true {
  377. return 1
  378. } else {
  379. return 0
  380. }
  381. }
  382. // Round 取整
  383. func Round(x float64) int64 {
  384. if x-float64(int64(x)) > 0 {
  385. return int64(x) + 1
  386. } else {
  387. return int64(x)
  388. }
  389. //return int64(math.Floor(x + 0.5))
  390. }
  391. // MakePowerOfTwo 2的整次幂数 buffer length is not a power of two
  392. func MakePowerOfTwo(x int64) int64 {
  393. power := math.Log2(float64(x))
  394. tmpRound := Round(power)
  395. return int64(math.Pow(2, float64(tmpRound)))
  396. }
  397. // MakeCeil10msMultipleFromFloat 将传入的秒,规整到 10ms 的倍数,返回依然是 秒,向上取整
  398. func MakeCeil10msMultipleFromFloat(input float64) float64 {
  399. const bb = 100
  400. // 先转到 10 ms 单位,比如传入是 1.912 - > 191.2
  401. t10ms := input * bb
  402. // 191.2 - > 192.0
  403. newT10ms := math.Ceil(t10ms)
  404. // 转换回来
  405. return newT10ms / bb
  406. }
  407. // MakeFloor10msMultipleFromFloat 将传入的秒,规整到 10ms 的倍数,返回依然是 秒,向下取整
  408. func MakeFloor10msMultipleFromFloat(input float64) float64 {
  409. const bb = 100
  410. // 先转到 10 ms 单位,比如传入是 1.912 - > 191.2
  411. t10ms := input * bb
  412. // 191.2 - > 191.0
  413. newT10ms := math.Floor(t10ms)
  414. // 转换回来
  415. return newT10ms / bb
  416. }
  417. // MakeCeil10msMultipleFromTime 向上取整,规整到 10ms 的倍数
  418. func MakeCeil10msMultipleFromTime(input time.Time) time.Time {
  419. nowTime := MakeCeil10msMultipleFromFloat(Time2SecondNumber(input))
  420. newTime := time.Time{}.Add(time.Duration(nowTime * math.Pow10(9)))
  421. return newTime
  422. }
  423. // MakeFloor10msMultipleFromTime 向下取整,规整到 10ms 的倍数
  424. func MakeFloor10msMultipleFromTime(input time.Time) time.Time {
  425. nowTime := MakeFloor10msMultipleFromFloat(Time2SecondNumber(input))
  426. newTime := time.Time{}.Add(time.Duration(nowTime * math.Pow10(9)))
  427. return newTime
  428. }
  429. // Time2SubTimeString 时间转字幕格式的时间字符串
  430. func Time2SubTimeString(inTime time.Time, timeFormat string) string {
  431. /*
  432. 这里进行时间转字符串的时候有一点比较特殊
  433. 正常来说输出的格式是类似 15:04:05.00
  434. 那么有个问题,字幕的时间格式是 0:00:12.00, 小时,是个数,除非有跨度到 20 小时的视频,不然小时就应该是个数
  435. 这就需要一个额外的函数去处理这些情况
  436. */
  437. outTimeString := inTime.Format(timeFormat)
  438. if inTime.Hour() > 9 {
  439. // 小时,两位数
  440. return outTimeString
  441. } else {
  442. // 小时,一位数
  443. items := strings.SplitN(outTimeString, ":", -1)
  444. if len(items) == 3 {
  445. outTimeString = strings.Replace(outTimeString, items[0], fmt.Sprintf("%d", inTime.Hour()), 1)
  446. return outTimeString
  447. }
  448. return outTimeString
  449. }
  450. }
  451. // IsEqual 比较 float64
  452. func IsEqual(f1, f2 float64) bool {
  453. const MIN = 0.000001
  454. if f1 > f2 {
  455. return math.Dim(f1, f2) < MIN
  456. } else {
  457. return math.Dim(f2, f1) < MIN
  458. }
  459. }
  460. // ParseTime 解析字幕时间字符串,这里可能小数点后面有 2-4 位
  461. func ParseTime(inTime string) (time.Time, error) {
  462. parseTime, err := time.Parse(common.TimeFormatPoint2, inTime)
  463. if err != nil {
  464. parseTime, err = time.Parse(common.TimeFormatPoint3, inTime)
  465. if err != nil {
  466. parseTime, err = time.Parse(common.TimeFormatPoint4, inTime)
  467. }
  468. }
  469. return parseTime, err
  470. }
  471. // GetFileSHA1 获取文件的 SHA1 值
  472. func GetFileSHA1(srcFileFPath string) (string, error) {
  473. infile, err := os.Open(srcFileFPath)
  474. if err != nil {
  475. return "", err
  476. }
  477. defer func() {
  478. _ = infile.Close()
  479. }()
  480. h := sha1.New()
  481. _, err = io.Copy(h, infile)
  482. if err != nil {
  483. return "", err
  484. }
  485. return hex.EncodeToString(h.Sum(nil)), nil
  486. }
  487. // WriteFile 写文件
  488. func WriteFile(desFileFPath string, bytes []byte) error {
  489. var err error
  490. nowDesPath := desFileFPath
  491. if filepath.IsAbs(nowDesPath) == false {
  492. nowDesPath, err = filepath.Abs(nowDesPath)
  493. if err != nil {
  494. return err
  495. }
  496. }
  497. // 创建对应的目录
  498. nowDirPath := filepath.Dir(nowDesPath)
  499. err = os.MkdirAll(nowDirPath, os.ModePerm)
  500. if err != nil {
  501. return err
  502. }
  503. file, err := os.Create(nowDesPath)
  504. if err != nil {
  505. return err
  506. }
  507. defer func() {
  508. _ = file.Close()
  509. }()
  510. _, err = file.Write(bytes)
  511. if err != nil {
  512. return err
  513. }
  514. return nil
  515. }
  516. // GetNowTimeString 获取当前的时间,没有秒
  517. func GetNowTimeString() (string, int, int, int) {
  518. nowTime := time.Now()
  519. addString := fmt.Sprintf("%d-%d-%d", nowTime.Hour(), nowTime.Minute(), nowTime.Nanosecond())
  520. return addString, nowTime.Hour(), nowTime.Minute(), nowTime.Nanosecond()
  521. }
  522. // GenerateAccessToken 生成随机的 AccessToken
  523. func GenerateAccessToken() string {
  524. u4 := uuid.New()
  525. return u4.String()
  526. }
  527. func Get2UUID() string {
  528. u4 := uuid.New()
  529. u5 := uuid.New()
  530. return u4.String() + u5.String()
  531. }
  532. func UrlJoin(hostUrl, subUrl string) (string, error) {
  533. u, err := url.Parse(hostUrl)
  534. if err != nil {
  535. return "", err
  536. }
  537. u.Path = path.Join(u.Path, subUrl)
  538. return u.String(), nil
  539. }
  540. // GetFileSHA1String 获取文件的 SHA1 字符串
  541. func GetFileSHA1String(fileFPath string) (string, error) {
  542. h := sha1.New()
  543. fp, err := os.Open(fileFPath)
  544. if err != nil {
  545. return "", err
  546. }
  547. defer func() {
  548. _ = fp.Close()
  549. }()
  550. partAll, err := io.ReadAll(fp)
  551. if err != nil {
  552. return "", err
  553. }
  554. h.Write(partAll)
  555. hashBytes := h.Sum(nil)
  556. return fmt.Sprintf("%x", md5.Sum(hashBytes)), nil
  557. }
  558. // GetFileSHA256String 获取文件的 SHA256 字符串
  559. func GetFileSHA256String(fileFPath string) (string, error) {
  560. fp, err := os.Open(fileFPath)
  561. if err != nil {
  562. return "", err
  563. }
  564. defer func() {
  565. _ = fp.Close()
  566. }()
  567. partAll, err := io.ReadAll(fp)
  568. if err != nil {
  569. return "", err
  570. }
  571. return fmt.Sprintf("%x", sha256.Sum256(partAll)), nil
  572. }
  573. func GetRestOfDaySec() time.Duration {
  574. nowTime := time.Now()
  575. todayLast := nowTime.Format("2006-01-02") + " 23:59:59"
  576. todayLastTime, _ := time.ParseInLocation("2006-01-02 15:04:05", todayLast, time.Local)
  577. // 今天剩余的时间(s)
  578. restOfDaySec := time.Duration(todayLastTime.Unix()-time.Now().Local().Unix()) * time.Second
  579. return restOfDaySec
  580. }
  581. // IntToBytes 整形转换成字节
  582. func IntToBytes(n int) ([]byte, error) {
  583. x := int32(n)
  584. bytesBuffer := bytes.NewBuffer([]byte{})
  585. err := binary.Write(bytesBuffer, binary.BigEndian, x)
  586. if err != nil {
  587. return nil, err
  588. }
  589. return bytesBuffer.Bytes(), nil
  590. }
  591. // BytesToInt 字节转换成整形
  592. func BytesToInt(b []byte) (int, error) {
  593. bytesBuffer := bytes.NewBuffer(b)
  594. var x int32
  595. err := binary.Read(bytesBuffer, binary.BigEndian, &x)
  596. if err != nil {
  597. return 0, err
  598. }
  599. return int(x), nil
  600. }
  601. func PrintPanicStack(log *logrus.Logger) {
  602. var buf [4096]byte
  603. n := runtime.Stack(buf[:], false)
  604. log.Errorln(fmt.Sprintf("%s", buf[:n]))
  605. }
  606. func GetMaxSizeFile(path string) string {
  607. files, err := ioutil.ReadDir(path)
  608. if err != nil {
  609. return ""
  610. }
  611. var maxFile os.FileInfo
  612. for _, file := range files {
  613. if maxFile == nil {
  614. maxFile = file
  615. } else {
  616. if file.Size() > maxFile.Size() {
  617. maxFile = file
  618. }
  619. }
  620. }
  621. return filepath.Join(path, maxFile.Name())
  622. }
  623. var (
  624. _wantedExtMap = make(map[string]string) // 人工确认的需要监控的视频后缀名
  625. _defExtMap = make(map[string]string) // 内置支持的视频后缀名列表
  626. _customVideoExts = make([]string, 0) // 用户额外自定义的视频后缀名列表
  627. )