util.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. "io/ioutil"
  13. "math"
  14. "net/http"
  15. "os"
  16. "os/exec"
  17. "path/filepath"
  18. "regexp"
  19. "runtime"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. // NewHttpClient 新建一个 resty 的对象
  25. func NewHttpClient(_reqParam ...types.ReqParam) *resty.Client {
  26. //const defUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS XLen 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"
  27. //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"
  28. // 随机的 Browser
  29. defUserAgent := browser.Random()
  30. var reqParam types.ReqParam
  31. var HttpProxy, UserAgent, Referer string
  32. if len(_reqParam) > 0 {
  33. reqParam = _reqParam[0]
  34. }
  35. if len(reqParam.HttpProxy) > 0 {
  36. HttpProxy = reqParam.HttpProxy
  37. }
  38. if len(reqParam.UserAgent) > 0 {
  39. UserAgent = reqParam.UserAgent
  40. } else {
  41. UserAgent = defUserAgent
  42. }
  43. if len(reqParam.Referer) > 0 {
  44. Referer = reqParam.Referer
  45. }
  46. httpClient := resty.New()
  47. httpClient.SetTimeout(common.HTMLTimeOut)
  48. httpClient.SetRetryCount(2)
  49. if HttpProxy != "" {
  50. httpClient.SetProxy(HttpProxy)
  51. } else {
  52. httpClient.RemoveProxy()
  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, _reqParam ...types.ReqParam) ([]byte, string, error) {
  65. var reqParam types.ReqParam
  66. if len(_reqParam) > 0 {
  67. reqParam = _reqParam[0]
  68. }
  69. httpClient := NewHttpClient(reqParam)
  70. resp, err := httpClient.R().Get(urlStr)
  71. if err != nil {
  72. return nil, "", err
  73. }
  74. filename := GetFileName(resp.RawResponse)
  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. //fmt.Println("######")
  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. // SearchMatchedVideoFile 搜索符合后缀名的视频文件
  129. func SearchMatchedVideoFile(dir string) ([]string, error) {
  130. var fileFullPathList = make([]string, 0)
  131. pathSep := string(os.PathSeparator)
  132. files, err := ioutil.ReadDir(dir)
  133. if err != nil {
  134. return nil, err
  135. }
  136. for _, curFile := range files {
  137. fullPath := dir + pathSep + curFile.Name()
  138. if curFile.IsDir() {
  139. // 内层的错误就无视了
  140. oneList, _ := SearchMatchedVideoFile(fullPath)
  141. if oneList != nil {
  142. fileFullPathList = append(fileFullPathList, oneList...)
  143. }
  144. } else {
  145. // 这里就是文件了
  146. if IsWantedVideoExtDef(curFile.Name()) == true {
  147. fileFullPathList = append(fileFullPathList, fullPath)
  148. }
  149. }
  150. }
  151. return fileFullPathList, nil
  152. }
  153. // IsWantedVideoExtDef 后缀名是否符合规则
  154. func IsWantedVideoExtDef(fileName string) bool {
  155. if len(global_value.WantedExtMap) < 1 {
  156. global_value.DefExtMap[common.VideoExtMp4] = common.VideoExtMp4
  157. global_value.DefExtMap[common.VideoExtMkv] = common.VideoExtMkv
  158. global_value.DefExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  159. global_value.DefExtMap[common.VideoExtIso] = common.VideoExtIso
  160. global_value.WantedExtMap[common.VideoExtMp4] = common.VideoExtMp4
  161. global_value.WantedExtMap[common.VideoExtMkv] = common.VideoExtMkv
  162. global_value.WantedExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  163. global_value.WantedExtMap[common.VideoExtIso] = common.VideoExtIso
  164. for _, videoExt := range global_value.CustomVideoExts {
  165. global_value.WantedExtMap[videoExt] = videoExt
  166. }
  167. }
  168. fileExt := strings.ToLower(filepath.Ext(fileName))
  169. _, bFound := global_value.WantedExtMap[fileExt]
  170. return bFound
  171. }
  172. func GetEpisodeKeyName(season, eps int) string {
  173. return "S" + strconv.Itoa(season) + "E" + strconv.Itoa(eps)
  174. }
  175. // CopyFile copies a single file from src to dst
  176. func CopyFile(src, dst string) error {
  177. var err error
  178. var srcfd *os.File
  179. var dstfd *os.File
  180. var srcinfo os.FileInfo
  181. if srcfd, err = os.Open(src); err != nil {
  182. return err
  183. }
  184. defer srcfd.Close()
  185. if dstfd, err = os.Create(dst); err != nil {
  186. return err
  187. }
  188. defer dstfd.Close()
  189. if _, err = io.Copy(dstfd, srcfd); err != nil {
  190. return err
  191. }
  192. if srcinfo, err = os.Stat(src); err != nil {
  193. return err
  194. }
  195. return os.Chmod(dst, srcinfo.Mode())
  196. }
  197. // CopyDir copies a whole directory recursively
  198. func CopyDir(src string, dst string) error {
  199. var err error
  200. var fds []os.FileInfo
  201. var srcinfo os.FileInfo
  202. if srcinfo, err = os.Stat(src); err != nil {
  203. return err
  204. }
  205. if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
  206. return err
  207. }
  208. if fds, err = ioutil.ReadDir(src); err != nil {
  209. return err
  210. }
  211. for _, fd := range fds {
  212. srcfp := filepath.Join(src, fd.Name())
  213. dstfp := filepath.Join(dst, fd.Name())
  214. if fd.IsDir() {
  215. if err = CopyDir(srcfp, dstfp); err != nil {
  216. fmt.Println(err)
  217. }
  218. } else {
  219. if err = CopyFile(srcfp, dstfp); err != nil {
  220. fmt.Println(err)
  221. }
  222. }
  223. }
  224. return nil
  225. }
  226. // CopyTestData 单元测试前把测试的数据 copy 一份出来操作,src 目录中默认应该有一个 org 原始数据文件夹,然后需要复制一份 test 文件夹出来
  227. func CopyTestData(srcDir string) (string, error) {
  228. // 测试数据的文件夹
  229. orgDir := filepath.Join(srcDir, "org")
  230. testDir := filepath.Join(srcDir, "test")
  231. if IsDir(testDir) == true {
  232. err := ClearFolder(testDir)
  233. if err != nil {
  234. return "", err
  235. }
  236. }
  237. err := CopyDir(orgDir, testDir)
  238. if err != nil {
  239. return "", err
  240. }
  241. return testDir, nil
  242. }
  243. // CloseChrome 强行结束没有关闭的 Chrome 进程
  244. func CloseChrome() {
  245. cmdString := ""
  246. var command *exec.Cmd
  247. sysType := runtime.GOOS
  248. if sysType == "linux" {
  249. // LINUX系统
  250. cmdString = "pkill chrome"
  251. command = exec.Command("/bin/sh", "-c", cmdString)
  252. }
  253. if sysType == "windows" {
  254. // windows系统
  255. cmdString = "taskkill /F /im notepad.exe"
  256. command = exec.Command("cmd.exe", "/c", cmdString)
  257. }
  258. if cmdString == "" || command == nil {
  259. log_helper.GetLogger().Errorln("CloseChrome OS:", sysType)
  260. return
  261. }
  262. err := command.Run()
  263. if err != nil {
  264. log_helper.GetLogger().Errorln("CloseChrome", err)
  265. }
  266. }
  267. // OSCheck 强制的系统支持检查
  268. func OSCheck() bool {
  269. sysType := runtime.GOOS
  270. if sysType == "linux" {
  271. return true
  272. }
  273. if sysType == "windows" {
  274. return true
  275. }
  276. return false
  277. }
  278. // FixWindowPathBackSlash 修复 Windows 反斜杠的梗
  279. func FixWindowPathBackSlash(path string) string {
  280. return strings.Replace(path, string(filepath.Separator), "/", -1)
  281. }
  282. func WriteStrings2File(desfilePath string, strings []string) error {
  283. dstFile, err := os.Create(desfilePath)
  284. if err != nil {
  285. return err
  286. }
  287. defer func() {
  288. _ = dstFile.Close()
  289. }()
  290. allString := ""
  291. for _, s := range strings {
  292. allString += s + "\r\n"
  293. }
  294. _, err = dstFile.WriteString(allString)
  295. if err != nil {
  296. return err
  297. }
  298. return nil
  299. }
  300. func Time2SecondNumber(inTime time.Time) float64 {
  301. outSecond := 0.0
  302. outSecond += float64(inTime.Hour() * 60 * 60)
  303. outSecond += float64(inTime.Minute() * 60)
  304. outSecond += float64(inTime.Second())
  305. outSecond += float64(inTime.Nanosecond()) / 1000 / 1000 / 1000
  306. return outSecond
  307. }
  308. func Time2Duration(inTime time.Time) time.Duration {
  309. return time.Duration(Time2SecondNumber(inTime) * math.Pow10(9))
  310. }
  311. // ReplaceSpecString 替换特殊的字符
  312. func ReplaceSpecString(instring string, rep string) string {
  313. return regex_things.RegMatchSpString.ReplaceAllString(instring, rep)
  314. }
  315. func Bool2Int(inBool bool) int {
  316. if inBool == true {
  317. return 1
  318. } else {
  319. return 0
  320. }
  321. }
  322. // Round 取整
  323. func Round(x float64) int64 {
  324. if x-float64(int64(x)) > 0 {
  325. return int64(x) + 1
  326. } else {
  327. return int64(x)
  328. }
  329. //return int64(math.Floor(x + 0.5))
  330. }
  331. // MakePowerOfTwo 2的整次幂数 buffer length is not a power of two
  332. func MakePowerOfTwo(x int64) int64 {
  333. power := math.Log2(float64(x))
  334. tmpRound := Round(power)
  335. return int64(math.Pow(2, float64(tmpRound)))
  336. }
  337. // MakeCeil10msMultipleFromFloat 将传入的秒,规整到 10ms 的倍数,返回依然是 秒,向上取整
  338. func MakeCeil10msMultipleFromFloat(input float64) float64 {
  339. const bb = 100
  340. // 先转到 10 ms 单位,比如传入是 1.912 - > 191.2
  341. t10ms := input * bb
  342. // 191.2 - > 192.0
  343. newT10ms := math.Ceil(t10ms)
  344. // 转换回来
  345. return newT10ms / bb
  346. }
  347. // MakeFloor10msMultipleFromFloat 将传入的秒,规整到 10ms 的倍数,返回依然是 秒,向下取整
  348. func MakeFloor10msMultipleFromFloat(input float64) float64 {
  349. const bb = 100
  350. // 先转到 10 ms 单位,比如传入是 1.912 - > 191.2
  351. t10ms := input * bb
  352. // 191.2 - > 191.0
  353. newT10ms := math.Floor(t10ms)
  354. // 转换回来
  355. return newT10ms / bb
  356. }
  357. // MakeCeil10msMultipleFromTime 向上取整,规整到 10ms 的倍数
  358. func MakeCeil10msMultipleFromTime(input time.Time) time.Time {
  359. nowTime := MakeCeil10msMultipleFromFloat(Time2SecondNumber(input))
  360. newTime := time.Time{}.Add(time.Duration(nowTime * math.Pow10(9)))
  361. return newTime
  362. }
  363. // MakeFloor10msMultipleFromTime 向下取整,规整到 10ms 的倍数
  364. func MakeFloor10msMultipleFromTime(input time.Time) time.Time {
  365. nowTime := MakeFloor10msMultipleFromFloat(Time2SecondNumber(input))
  366. newTime := time.Time{}.Add(time.Duration(nowTime * math.Pow10(9)))
  367. return newTime
  368. }
  369. // Time2SubTimeString 时间转字幕格式的时间字符串
  370. func Time2SubTimeString(inTime time.Time, timeFormat string) string {
  371. /*
  372. 这里进行时间转字符串的时候有一点比较特殊
  373. 正常来说输出的格式是类似 15:04:05.00
  374. 那么有个问题,字幕的时间格式是 0:00:12.00, 小时,是个数,除非有跨度到 20 小时的视频,不然小时就应该是个数
  375. 这就需要一个额外的函数去处理这些情况
  376. */
  377. outTimeString := inTime.Format(timeFormat)
  378. if inTime.Hour() > 9 {
  379. // 小时,两位数
  380. return outTimeString
  381. } else {
  382. // 小时,一位数
  383. items := strings.SplitN(outTimeString, ":", -1)
  384. if len(items) == 3 {
  385. outTimeString = strings.Replace(outTimeString, items[0], fmt.Sprintf("%d", inTime.Hour()), 1)
  386. return outTimeString
  387. }
  388. return outTimeString
  389. }
  390. }
  391. // IsEqual 比较 float64
  392. func IsEqual(f1, f2 float64) bool {
  393. const MIN = 0.000001
  394. if f1 > f2 {
  395. return math.Dim(f1, f2) < MIN
  396. } else {
  397. return math.Dim(f2, f1) < MIN
  398. }
  399. }