util.go 18 KB

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