util.go 19 KB

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