util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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/types"
  8. browser "github.com/allanpk716/fake-useragent"
  9. "github.com/go-resty/resty/v2"
  10. "io"
  11. "io/ioutil"
  12. "net/http"
  13. "os"
  14. "os/exec"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. // NewHttpClient 新建一个 resty 的对象
  23. func NewHttpClient(_reqParam ...types.ReqParam) *resty.Client {
  24. //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"
  25. //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"
  26. // 随机的 Browser
  27. defUserAgent := browser.Random()
  28. var reqParam types.ReqParam
  29. var HttpProxy, UserAgent, Referer string
  30. if len(_reqParam) > 0 {
  31. reqParam = _reqParam[0]
  32. }
  33. if len(reqParam.HttpProxy) > 0 {
  34. HttpProxy = reqParam.HttpProxy
  35. }
  36. if len(reqParam.UserAgent) > 0 {
  37. UserAgent = reqParam.UserAgent
  38. } else {
  39. UserAgent = defUserAgent
  40. }
  41. if len(reqParam.Referer) > 0 {
  42. Referer = reqParam.Referer
  43. }
  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. httpClient.SetHeaders(map[string]string{
  53. "Content-Type": "application/json",
  54. "User-Agent": UserAgent,
  55. })
  56. if len(Referer) > 0 {
  57. httpClient.SetHeader("Referer", Referer)
  58. }
  59. return httpClient
  60. }
  61. // DownFile 从指定的 url 下载文件
  62. func DownFile(urlStr string, _reqParam ...types.ReqParam) ([]byte, string, error) {
  63. var reqParam types.ReqParam
  64. if len(_reqParam) > 0 {
  65. reqParam = _reqParam[0]
  66. }
  67. httpClient := NewHttpClient(reqParam)
  68. resp, err := httpClient.R().Get(urlStr)
  69. if err != nil {
  70. return nil, "", err
  71. }
  72. filename := GetFileName(resp.RawResponse)
  73. return resp.Body(), filename, nil
  74. }
  75. // GetFileName 获取下载文件的文件名
  76. func GetFileName(resp *http.Response) string {
  77. contentDisposition := resp.Header.Get("Content-Disposition")
  78. if len(contentDisposition) == 0 {
  79. return ""
  80. }
  81. re := regexp.MustCompile(`filename=["]*([^"]+)["]*`)
  82. matched := re.FindStringSubmatch(contentDisposition)
  83. if matched == nil || len(matched) == 0 || len(matched[0]) == 0 {
  84. //fmt.Println("######")
  85. return ""
  86. }
  87. return matched[1]
  88. }
  89. // AddBaseUrl 判断传入的 url 是否需要拼接 baseUrl
  90. func AddBaseUrl(baseUrl, url string) string {
  91. if strings.Contains(url, "://") {
  92. return url
  93. }
  94. return fmt.Sprintf("%s%s", baseUrl, url)
  95. }
  96. func GetDebugFolder() (string, error) {
  97. if global_value.DefDebugFolder == "" {
  98. nowProcessRoot, _ := os.Getwd()
  99. nowProcessRoot = filepath.Join(nowProcessRoot, common.DebugFolder)
  100. err := os.MkdirAll(nowProcessRoot, os.ModePerm)
  101. if err != nil {
  102. return "", err
  103. }
  104. global_value.DefDebugFolder = nowProcessRoot
  105. return nowProcessRoot, err
  106. }
  107. return global_value.DefDebugFolder, nil
  108. }
  109. // GetRootTmpFolder 获取缓存的根目录,每一个视频的缓存将在其中额外新建子集文件夹
  110. func GetRootTmpFolder() (string, error) {
  111. if global_value.DefTmpFolder == "" {
  112. nowProcessRoot, _ := os.Getwd()
  113. nowProcessRoot = filepath.Join(nowProcessRoot, common.TmpFolder)
  114. err := os.MkdirAll(nowProcessRoot, os.ModePerm)
  115. if err != nil {
  116. return "", err
  117. }
  118. global_value.DefTmpFolder = nowProcessRoot
  119. return nowProcessRoot, err
  120. }
  121. return global_value.DefTmpFolder, nil
  122. }
  123. // ClearRootTmpFolder 清理缓存的根目录,将里面的子文件夹一并清理
  124. func ClearRootTmpFolder() error {
  125. nowTmpFolder, err := GetRootTmpFolder()
  126. if err != nil {
  127. return err
  128. }
  129. pathSep := string(os.PathSeparator)
  130. files, err := ioutil.ReadDir(nowTmpFolder)
  131. if err != nil {
  132. return err
  133. }
  134. for _, curFile := range files {
  135. fullPath := nowTmpFolder + pathSep + curFile.Name()
  136. if curFile.IsDir() {
  137. err = os.RemoveAll(fullPath)
  138. if err != nil {
  139. return err
  140. }
  141. } else {
  142. // 这里就是文件了
  143. err = os.Remove(fullPath)
  144. if err != nil {
  145. return err
  146. }
  147. }
  148. }
  149. return nil
  150. }
  151. // GetTmpFolder 获取缓存的文件夹,没有则新建
  152. func GetTmpFolder(folderName string) (string, error) {
  153. rootPath, err := GetRootTmpFolder()
  154. if err != nil {
  155. return "", err
  156. }
  157. tmpFolderFullPath := filepath.Join(rootPath, folderName)
  158. err = os.MkdirAll(tmpFolderFullPath, os.ModePerm)
  159. if err != nil {
  160. return "", err
  161. }
  162. return tmpFolderFullPath, nil
  163. }
  164. // ClearFolder 清空文件夹
  165. func ClearFolder(folderName string) error {
  166. pathSep := string(os.PathSeparator)
  167. files, err := ioutil.ReadDir(folderName)
  168. if err != nil {
  169. return err
  170. }
  171. for _, curFile := range files {
  172. fullPath := folderName + pathSep + curFile.Name()
  173. if curFile.IsDir() {
  174. err = os.RemoveAll(fullPath)
  175. if err != nil {
  176. return err
  177. }
  178. } else {
  179. // 这里就是文件了
  180. err = os.Remove(fullPath)
  181. if err != nil {
  182. return err
  183. }
  184. }
  185. }
  186. return nil
  187. }
  188. // ClearTmpFolder 清理指定的缓存文件夹
  189. func ClearTmpFolder(folderName string) error {
  190. nowTmpFolder, err := GetTmpFolder(folderName)
  191. if err != nil {
  192. return err
  193. }
  194. return ClearFolder(nowTmpFolder)
  195. }
  196. // IsDir 存在且是文件夹
  197. func IsDir(path string) bool {
  198. s, err := os.Stat(path)
  199. if err != nil {
  200. return false
  201. }
  202. return s.IsDir()
  203. }
  204. // IsFile 存在且是文件
  205. func IsFile(filePath string) bool {
  206. s, err := os.Stat(filePath)
  207. if err != nil {
  208. return false
  209. }
  210. return !s.IsDir()
  211. }
  212. // VideoNameSearchKeywordMaker 拼接视频搜索的 title 和 年份
  213. func VideoNameSearchKeywordMaker(title string, year string) string {
  214. iYear, err := strconv.Atoi(year)
  215. if err != nil {
  216. // 允许的错误
  217. log_helper.GetLogger().Errorln("VideoNameSearchKeywordMaker", "year to int", err)
  218. iYear = 0
  219. }
  220. searchKeyword := title
  221. if iYear >= 2020 {
  222. searchKeyword = searchKeyword + " " + year
  223. }
  224. return searchKeyword
  225. }
  226. // SearchMatchedVideoFile 搜索符合后缀名的视频文件
  227. func SearchMatchedVideoFile(dir string) ([]string, error) {
  228. var fileFullPathList = make([]string, 0)
  229. pathSep := string(os.PathSeparator)
  230. files, err := ioutil.ReadDir(dir)
  231. if err != nil {
  232. return nil, err
  233. }
  234. for _, curFile := range files {
  235. fullPath := dir + pathSep + curFile.Name()
  236. if curFile.IsDir() {
  237. // 内层的错误就无视了
  238. oneList, _ := SearchMatchedVideoFile(fullPath)
  239. if oneList != nil {
  240. fileFullPathList = append(fileFullPathList, oneList...)
  241. }
  242. } else {
  243. // 这里就是文件了
  244. if IsWantedVideoExtDef(curFile.Name()) == true {
  245. fileFullPathList = append(fileFullPathList, fullPath)
  246. }
  247. }
  248. }
  249. return fileFullPathList, nil
  250. }
  251. // IsWantedVideoExtDef 后缀名是否符合规则
  252. func IsWantedVideoExtDef(fileName string) bool {
  253. if len(global_value.WantedExtMap) < 1 {
  254. global_value.DefExtMap[common.VideoExtMp4] = common.VideoExtMp4
  255. global_value.DefExtMap[common.VideoExtMkv] = common.VideoExtMkv
  256. global_value.DefExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  257. global_value.DefExtMap[common.VideoExtIso] = common.VideoExtIso
  258. global_value.WantedExtMap[common.VideoExtMp4] = common.VideoExtMp4
  259. global_value.WantedExtMap[common.VideoExtMkv] = common.VideoExtMkv
  260. global_value.WantedExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  261. global_value.WantedExtMap[common.VideoExtIso] = common.VideoExtIso
  262. for _, videoExt := range global_value.CustomVideoExts {
  263. global_value.WantedExtMap[videoExt] = videoExt
  264. }
  265. }
  266. fileExt := strings.ToLower(filepath.Ext(fileName))
  267. _, bFound := global_value.WantedExtMap[fileExt]
  268. return bFound
  269. }
  270. func GetEpisodeKeyName(season, eps int) string {
  271. return "S" + strconv.Itoa(season) + "E" + strconv.Itoa(eps)
  272. }
  273. // CopyFile copies a single file from src to dst
  274. func CopyFile(src, dst string) error {
  275. var err error
  276. var srcfd *os.File
  277. var dstfd *os.File
  278. var srcinfo os.FileInfo
  279. if srcfd, err = os.Open(src); err != nil {
  280. return err
  281. }
  282. defer srcfd.Close()
  283. if dstfd, err = os.Create(dst); err != nil {
  284. return err
  285. }
  286. defer dstfd.Close()
  287. if _, err = io.Copy(dstfd, srcfd); err != nil {
  288. return err
  289. }
  290. if srcinfo, err = os.Stat(src); err != nil {
  291. return err
  292. }
  293. return os.Chmod(dst, srcinfo.Mode())
  294. }
  295. // CopyDir copies a whole directory recursively
  296. func CopyDir(src string, dst string) error {
  297. var err error
  298. var fds []os.FileInfo
  299. var srcinfo os.FileInfo
  300. if srcinfo, err = os.Stat(src); err != nil {
  301. return err
  302. }
  303. if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
  304. return err
  305. }
  306. if fds, err = ioutil.ReadDir(src); err != nil {
  307. return err
  308. }
  309. for _, fd := range fds {
  310. srcfp := filepath.Join(src, fd.Name())
  311. dstfp := filepath.Join(dst, fd.Name())
  312. if fd.IsDir() {
  313. if err = CopyDir(srcfp, dstfp); err != nil {
  314. fmt.Println(err)
  315. }
  316. } else {
  317. if err = CopyFile(srcfp, dstfp); err != nil {
  318. fmt.Println(err)
  319. }
  320. }
  321. }
  322. return nil
  323. }
  324. // CopyTestData 单元测试前把测试的数据 copy 一份出来操作,src 目录中默认应该有一个 org 原始数据文件夹,然后需要复制一份 test 文件夹出来
  325. func CopyTestData(srcDir string) (string, error) {
  326. // 测试数据的文件夹
  327. orgDir := filepath.Join(srcDir, "org")
  328. testDir := filepath.Join(srcDir, "test")
  329. if IsDir(testDir) == true {
  330. err := ClearFolder(testDir)
  331. if err != nil {
  332. return "", err
  333. }
  334. }
  335. err := CopyDir(orgDir, testDir)
  336. if err != nil {
  337. return "", err
  338. }
  339. return testDir, nil
  340. }
  341. // CloseChrome 强行结束没有关闭的 Chrome 进程
  342. func CloseChrome() {
  343. cmdString := ""
  344. var command *exec.Cmd
  345. sysType := runtime.GOOS
  346. if sysType == "linux" {
  347. // LINUX系统
  348. cmdString = "pkill chrome"
  349. command = exec.Command("/bin/sh", "-c", cmdString)
  350. }
  351. if sysType == "windows" {
  352. // windows系统
  353. cmdString = "taskkill /F /im notepad.exe"
  354. command = exec.Command("cmd.exe", "/c", cmdString)
  355. }
  356. if cmdString == "" || command == nil {
  357. log_helper.GetLogger().Errorln("CloseChrome OS:", sysType)
  358. return
  359. }
  360. err := command.Run()
  361. if err != nil {
  362. log_helper.GetLogger().Errorln("CloseChrome", err)
  363. }
  364. }
  365. // OSCheck 强制的系统支持检查
  366. func OSCheck() bool {
  367. sysType := runtime.GOOS
  368. if sysType == "linux" {
  369. return true
  370. }
  371. if sysType == "windows" {
  372. return true
  373. }
  374. return false
  375. }
  376. // FixWindowPathBackSlash 修复 Windows 反斜杠的梗
  377. func FixWindowPathBackSlash(path string) string {
  378. return strings.Replace(path, string(filepath.Separator), "/", -1)
  379. }
  380. func WriteStrings2File(desfilePath string, strings []string) error {
  381. dstFile, err := os.Create(desfilePath)
  382. if err != nil {
  383. return err
  384. }
  385. defer func() {
  386. _ = dstFile.Close()
  387. }()
  388. allString := ""
  389. for _, s := range strings {
  390. allString += s + "\r\n"
  391. }
  392. _, err = dstFile.WriteString(allString)
  393. if err != nil {
  394. return err
  395. }
  396. return nil
  397. }
  398. func Time2SecendNumber(inTime time.Time) float64 {
  399. outSecend := 0.0
  400. outSecend += float64(inTime.Hour() * 60 * 60)
  401. outSecend += float64(inTime.Minute() * 60)
  402. outSecend += float64(inTime.Second())
  403. outSecend += float64(inTime.Nanosecond()) / 1000 / 1000 / 1000
  404. return outSecend
  405. }
  406. func Time2Duration(inTime time.Time) time.Duration {
  407. return time.Duration(Time2SecendNumber(inTime))
  408. }