util.go 16 KB

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