util.go 12 KB

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