util.go 19 KB

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