util.go 11 KB

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