util.go 20 KB

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