util.go 16 KB

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