util.go 23 KB

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