util.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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/ChineseSubFinder/ChineseSubFinder/pkg/local_http_proxy_server"
  26. "github.com/ChineseSubFinder/ChineseSubFinder/pkg/types/common"
  27. "github.com/ChineseSubFinder/ChineseSubFinder/pkg/regex_things"
  28. "github.com/ChineseSubFinder/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. // ResetWantedVideoExt 重置视频后缀名
  201. func ResetWantedVideoExt() {
  202. _wantedExtMap = make(map[string]string)
  203. _defExtMap = make(map[string]string)
  204. }
  205. // IsWantedVideoExtDef 后缀名是否符合规则
  206. func IsWantedVideoExtDef(fileName string) bool {
  207. if len(_wantedExtMap) < 1 {
  208. _defExtMap[common.VideoExtMp4] = common.VideoExtMp4
  209. _defExtMap[common.VideoExtMkv] = common.VideoExtMkv
  210. _defExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  211. _defExtMap[common.VideoExtIso] = common.VideoExtIso
  212. _defExtMap[common.VideoExtM2ts] = common.VideoExtM2ts
  213. _wantedExtMap[common.VideoExtMp4] = common.VideoExtMp4
  214. _wantedExtMap[common.VideoExtMkv] = common.VideoExtMkv
  215. _wantedExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  216. _wantedExtMap[common.VideoExtIso] = common.VideoExtIso
  217. _wantedExtMap[common.VideoExtM2ts] = common.VideoExtM2ts
  218. for _, videoExt := range settings.Get().AdvancedSettings.CustomVideoExts {
  219. _wantedExtMap[videoExt] = videoExt
  220. }
  221. }
  222. fileExt := strings.ToLower(filepath.Ext(fileName))
  223. _, bFound := _wantedExtMap[fileExt]
  224. return bFound
  225. }
  226. func GetEpisodeKeyName(season, eps int, zerofill ...bool) string {
  227. if len(zerofill) < 1 || zerofill[0] == false {
  228. return "S" + strconv.Itoa(season) + "E" + strconv.Itoa(eps)
  229. } else {
  230. return fmt.Sprintf("S%02dE%02d", season, eps)
  231. }
  232. }
  233. // CopyFile copies a single file from src to dst
  234. func CopyFile(src, dst string) error {
  235. var err error
  236. var srcFd *os.File
  237. var dstFd *os.File
  238. var srcInfo os.FileInfo
  239. if srcFd, err = os.Open(src); err != nil {
  240. return err
  241. }
  242. defer func() {
  243. _ = srcFd.Close()
  244. }()
  245. if dstFd, err = os.Create(dst); err != nil {
  246. return err
  247. }
  248. defer func() {
  249. _ = dstFd.Close()
  250. }()
  251. if _, err = io.Copy(dstFd, srcFd); err != nil {
  252. return err
  253. }
  254. if srcInfo, err = os.Stat(src); err != nil {
  255. return err
  256. }
  257. return os.Chmod(dst, srcInfo.Mode())
  258. }
  259. // CopyDir copies a whole directory recursively
  260. func CopyDir(src string, dst string) error {
  261. var err error
  262. var fds []os.DirEntry
  263. var srcInfo os.FileInfo
  264. if srcInfo, err = os.Stat(src); err != nil {
  265. return err
  266. }
  267. if err = os.MkdirAll(dst, srcInfo.Mode()); err != nil {
  268. return err
  269. }
  270. if fds, err = os.ReadDir(src); err != nil {
  271. return err
  272. }
  273. for _, fd := range fds {
  274. srcfp := filepath.Join(src, fd.Name())
  275. dstfp := filepath.Join(dst, fd.Name())
  276. if fd.IsDir() {
  277. if err = CopyDir(srcfp, dstfp); err != nil {
  278. fmt.Println(err)
  279. }
  280. } else {
  281. if err = CopyFile(srcfp, dstfp); err != nil {
  282. fmt.Println(err)
  283. }
  284. }
  285. }
  286. return nil
  287. }
  288. // CloseChrome 强行结束没有关闭的 Chrome 进程
  289. func CloseChrome(l *logrus.Logger) {
  290. defer func() {
  291. l.Infoln("CloseChrome End")
  292. }()
  293. l.Infoln("CloseChrome Start...")
  294. cmdString := ""
  295. var command *exec.Cmd
  296. sysType := runtime.GOOS
  297. if sysType == "linux" {
  298. // LINUX系统
  299. cmdString = "pkill chrome"
  300. command = exec.Command("/bin/sh", "-c", cmdString)
  301. }
  302. if sysType == "windows" {
  303. // windows系统
  304. cmdString = "taskkill /F /im chrome.exe"
  305. command = exec.Command("cmd.exe", "/c", cmdString)
  306. }
  307. if sysType == "darwin" {
  308. // macOS
  309. // https://stackoverflow.com/questions/57079120/using-exec-command-in-golang-how-do-i-open-a-new-terminal-and-execute-a-command
  310. cmdString = `tell application "/Applications/Google Chrome.app" to quit`
  311. command = exec.Command("osascript", "-s", "h", "-e", cmdString)
  312. }
  313. if cmdString == "" || command == nil {
  314. l.Errorln("CloseChrome OS:", sysType)
  315. return
  316. }
  317. err := command.Run()
  318. if err != nil {
  319. l.Warningln("CloseChrome", err)
  320. }
  321. }
  322. // OSCheck 强制的系统支持检查
  323. func OSCheck() bool {
  324. sysType := runtime.GOOS
  325. if sysType == "linux" {
  326. return true
  327. }
  328. if sysType == "windows" {
  329. return true
  330. }
  331. if sysType == "darwin" {
  332. return true
  333. }
  334. return false
  335. }
  336. // FixWindowPathBackSlash 修复 Windows 反斜杠的梗
  337. func FixWindowPathBackSlash(path string) string {
  338. return strings.Replace(path, string(filepath.Separator), "/", -1)
  339. }
  340. func WriteStrings2File(desfilePath string, strings []string) error {
  341. dstFile, err := os.Create(desfilePath)
  342. if err != nil {
  343. return err
  344. }
  345. defer func() {
  346. _ = dstFile.Close()
  347. }()
  348. allString := ""
  349. for _, s := range strings {
  350. allString += s + "\r\n"
  351. }
  352. _, err = dstFile.WriteString(allString)
  353. if err != nil {
  354. return err
  355. }
  356. return nil
  357. }
  358. func TimeNumber2Time(inputTimeNumber float64) time.Time {
  359. newTime := time.Time{}.Add(time.Duration(inputTimeNumber * math.Pow10(9)))
  360. return newTime
  361. }
  362. func Time2SecondNumber(inTime time.Time) float64 {
  363. outSecond := 0.0
  364. outSecond += float64(inTime.Hour() * 60 * 60)
  365. outSecond += float64(inTime.Minute() * 60)
  366. outSecond += float64(inTime.Second())
  367. outSecond += float64(inTime.Nanosecond()) / 1000 / 1000 / 1000
  368. return outSecond
  369. }
  370. func Time2Duration(inTime time.Time) time.Duration {
  371. return time.Duration(Time2SecondNumber(inTime) * math.Pow10(9))
  372. }
  373. func Second2Time(sec int64) time.Time {
  374. return time.Unix(sec, 0)
  375. }
  376. // ReplaceSpecString 替换特殊的字符
  377. func ReplaceSpecString(inString string, rep string) string {
  378. return regex_things.RegMatchSpString.ReplaceAllString(inString, rep)
  379. }
  380. func Bool2Int(inBool bool) int {
  381. if inBool == true {
  382. return 1
  383. } else {
  384. return 0
  385. }
  386. }
  387. // Round 取整
  388. func Round(x float64) int64 {
  389. if x-float64(int64(x)) > 0 {
  390. return int64(x) + 1
  391. } else {
  392. return int64(x)
  393. }
  394. //return int64(math.Floor(x + 0.5))
  395. }
  396. // MakePowerOfTwo 2的整次幂数 buffer length is not a power of two
  397. func MakePowerOfTwo(x int64) int64 {
  398. power := math.Log2(float64(x))
  399. tmpRound := Round(power)
  400. return int64(math.Pow(2, float64(tmpRound)))
  401. }
  402. // MakeCeil10msMultipleFromFloat 将传入的秒,规整到 10ms 的倍数,返回依然是 秒,向上取整
  403. func MakeCeil10msMultipleFromFloat(input float64) float64 {
  404. const bb = 100
  405. // 先转到 10 ms 单位,比如传入是 1.912 - > 191.2
  406. t10ms := input * bb
  407. // 191.2 - > 192.0
  408. newT10ms := math.Ceil(t10ms)
  409. // 转换回来
  410. return newT10ms / bb
  411. }
  412. // MakeFloor10msMultipleFromFloat 将传入的秒,规整到 10ms 的倍数,返回依然是 秒,向下取整
  413. func MakeFloor10msMultipleFromFloat(input float64) float64 {
  414. const bb = 100
  415. // 先转到 10 ms 单位,比如传入是 1.912 - > 191.2
  416. t10ms := input * bb
  417. // 191.2 - > 191.0
  418. newT10ms := math.Floor(t10ms)
  419. // 转换回来
  420. return newT10ms / bb
  421. }
  422. // MakeCeil10msMultipleFromTime 向上取整,规整到 10ms 的倍数
  423. func MakeCeil10msMultipleFromTime(input time.Time) time.Time {
  424. nowTime := MakeCeil10msMultipleFromFloat(Time2SecondNumber(input))
  425. newTime := time.Time{}.Add(time.Duration(nowTime * math.Pow10(9)))
  426. return newTime
  427. }
  428. // MakeFloor10msMultipleFromTime 向下取整,规整到 10ms 的倍数
  429. func MakeFloor10msMultipleFromTime(input time.Time) time.Time {
  430. nowTime := MakeFloor10msMultipleFromFloat(Time2SecondNumber(input))
  431. newTime := time.Time{}.Add(time.Duration(nowTime * math.Pow10(9)))
  432. return newTime
  433. }
  434. // Time2SubTimeString 时间转字幕格式的时间字符串
  435. func Time2SubTimeString(inTime time.Time, timeFormat string) string {
  436. /*
  437. 这里进行时间转字符串的时候有一点比较特殊
  438. 正常来说输出的格式是类似 15:04:05.00
  439. 那么有个问题,字幕的时间格式是 0:00:12.00, 小时,是个数,除非有跨度到 20 小时的视频,不然小时就应该是个数
  440. 这就需要一个额外的函数去处理这些情况
  441. */
  442. outTimeString := inTime.Format(timeFormat)
  443. if inTime.Hour() > 9 {
  444. // 小时,两位数
  445. return outTimeString
  446. } else {
  447. // 小时,一位数
  448. items := strings.SplitN(outTimeString, ":", -1)
  449. if len(items) == 3 {
  450. outTimeString = strings.Replace(outTimeString, items[0], fmt.Sprintf("%d", inTime.Hour()), 1)
  451. return outTimeString
  452. }
  453. return outTimeString
  454. }
  455. }
  456. // IsEqual 比较 float64
  457. func IsEqual(f1, f2 float64) bool {
  458. const MIN = 0.000001
  459. if f1 > f2 {
  460. return math.Dim(f1, f2) < MIN
  461. } else {
  462. return math.Dim(f2, f1) < MIN
  463. }
  464. }
  465. // ParseTime 解析字幕时间字符串,这里可能小数点后面有 2-4 位
  466. func ParseTime(inTime string) (time.Time, error) {
  467. parseTime, err := time.Parse(common.TimeFormatPoint2, inTime)
  468. if err != nil {
  469. parseTime, err = time.Parse(common.TimeFormatPoint3, inTime)
  470. if err != nil {
  471. parseTime, err = time.Parse(common.TimeFormatPoint4, inTime)
  472. }
  473. }
  474. return parseTime, err
  475. }
  476. // GetFileSHA1 获取文件的 SHA1 值
  477. func GetFileSHA1(srcFileFPath string) (string, error) {
  478. infile, err := os.Open(srcFileFPath)
  479. if err != nil {
  480. return "", err
  481. }
  482. defer func() {
  483. _ = infile.Close()
  484. }()
  485. h := sha1.New()
  486. _, err = io.Copy(h, infile)
  487. if err != nil {
  488. return "", err
  489. }
  490. return hex.EncodeToString(h.Sum(nil)), nil
  491. }
  492. // WriteFile 写文件
  493. func WriteFile(desFileFPath string, bytes []byte) error {
  494. var err error
  495. nowDesPath := desFileFPath
  496. if filepath.IsAbs(nowDesPath) == false {
  497. nowDesPath, err = filepath.Abs(nowDesPath)
  498. if err != nil {
  499. return err
  500. }
  501. }
  502. // 创建对应的目录
  503. nowDirPath := filepath.Dir(nowDesPath)
  504. err = os.MkdirAll(nowDirPath, os.ModePerm)
  505. if err != nil {
  506. return err
  507. }
  508. file, err := os.Create(nowDesPath)
  509. if err != nil {
  510. return err
  511. }
  512. defer func() {
  513. _ = file.Close()
  514. }()
  515. _, err = file.Write(bytes)
  516. if err != nil {
  517. return err
  518. }
  519. return nil
  520. }
  521. // GetNowTimeString 获取当前的时间,没有秒
  522. func GetNowTimeString() (string, int, int, int) {
  523. nowTime := time.Now()
  524. addString := fmt.Sprintf("%d-%d-%d", nowTime.Hour(), nowTime.Minute(), nowTime.Nanosecond())
  525. return addString, nowTime.Hour(), nowTime.Minute(), nowTime.Nanosecond()
  526. }
  527. // GenerateAccessToken 生成随机的 AccessToken
  528. func GenerateAccessToken() string {
  529. u4 := uuid.New()
  530. return u4.String()
  531. }
  532. func Get2UUID() string {
  533. u4 := uuid.New()
  534. u5 := uuid.New()
  535. return u4.String() + u5.String()
  536. }
  537. func UrlJoin(hostUrl, subUrl string) (string, error) {
  538. u, err := url.Parse(hostUrl)
  539. if err != nil {
  540. return "", err
  541. }
  542. u.Path = path.Join(u.Path, subUrl)
  543. return u.String(), nil
  544. }
  545. // GetFileSHA1String 获取文件的 SHA1 字符串
  546. func GetFileSHA1String(fileFPath string) (string, error) {
  547. h := sha1.New()
  548. fp, err := os.Open(fileFPath)
  549. if err != nil {
  550. return "", err
  551. }
  552. defer func() {
  553. _ = fp.Close()
  554. }()
  555. partAll, err := io.ReadAll(fp)
  556. if err != nil {
  557. return "", err
  558. }
  559. h.Write(partAll)
  560. hashBytes := h.Sum(nil)
  561. return fmt.Sprintf("%x", md5.Sum(hashBytes)), nil
  562. }
  563. // GetFileSHA256String 获取文件的 SHA256 字符串
  564. func GetFileSHA256String(fileFPath string) (string, error) {
  565. fp, err := os.Open(fileFPath)
  566. if err != nil {
  567. return "", err
  568. }
  569. defer func() {
  570. _ = fp.Close()
  571. }()
  572. partAll, err := io.ReadAll(fp)
  573. if err != nil {
  574. return "", err
  575. }
  576. return fmt.Sprintf("%x", sha256.Sum256(partAll)), nil
  577. }
  578. func GetRestOfDaySec() time.Duration {
  579. nowTime := time.Now()
  580. todayLast := nowTime.Format("2006-01-02") + " 23:59:59"
  581. todayLastTime, _ := time.ParseInLocation("2006-01-02 15:04:05", todayLast, time.Local)
  582. // 今天剩余的时间(s)
  583. restOfDaySec := time.Duration(todayLastTime.Unix()-time.Now().Local().Unix()) * time.Second
  584. return restOfDaySec
  585. }
  586. // IntToBytes 整形转换成字节
  587. func IntToBytes(n int) ([]byte, error) {
  588. x := int32(n)
  589. bytesBuffer := bytes.NewBuffer([]byte{})
  590. err := binary.Write(bytesBuffer, binary.BigEndian, x)
  591. if err != nil {
  592. return nil, err
  593. }
  594. return bytesBuffer.Bytes(), nil
  595. }
  596. // BytesToInt 字节转换成整形
  597. func BytesToInt(b []byte) (int, error) {
  598. bytesBuffer := bytes.NewBuffer(b)
  599. var x int32
  600. err := binary.Read(bytesBuffer, binary.BigEndian, &x)
  601. if err != nil {
  602. return 0, err
  603. }
  604. return int(x), nil
  605. }
  606. func PrintPanicStack(log *logrus.Logger) {
  607. var buf [4096]byte
  608. n := runtime.Stack(buf[:], false)
  609. log.Errorln(fmt.Sprintf("%s", buf[:n]))
  610. }
  611. func GetMaxSizeFile(path string) string {
  612. files, err := ioutil.ReadDir(path)
  613. if err != nil {
  614. return ""
  615. }
  616. var maxFile os.FileInfo
  617. for _, file := range files {
  618. if maxFile == nil {
  619. maxFile = file
  620. } else {
  621. if file.Size() > maxFile.Size() {
  622. maxFile = file
  623. }
  624. }
  625. }
  626. return filepath.Join(path, maxFile.Name())
  627. }
  628. func Sha256File(fileFPath string) (string, int, error) {
  629. fp, err := os.Open(fileFPath)
  630. if err != nil {
  631. return "", 0, err
  632. }
  633. defer func() {
  634. _ = fp.Close()
  635. }()
  636. partAll, err := io.ReadAll(fp)
  637. if err != nil {
  638. return "", 0, err
  639. }
  640. return fmt.Sprintf("%x", sha256.Sum256(partAll)), len(partAll), nil
  641. }
  642. var (
  643. _wantedExtMap = make(map[string]string) // 人工确认的需要监控的视频后缀名
  644. _defExtMap = make(map[string]string) // 内置支持的视频后缀名列表
  645. )