util.go 13 KB

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