util.go 14 KB

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