util.go 21 KB

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