util.go 18 KB

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