util.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package pkg
  2. import (
  3. "fmt"
  4. "github.com/allanpk716/ChineseSubFinder/internal/common"
  5. "github.com/allanpk716/ChineseSubFinder/internal/pkg/log_helper"
  6. "github.com/allanpk716/ChineseSubFinder/internal/pkg/rod_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"
  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. 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 defDebugFolder == "" {
  98. nowProcessRoot, _ := os.Getwd()
  99. nowProcessRoot = path.Join(nowProcessRoot, common.DebugFolder)
  100. err := os.MkdirAll(nowProcessRoot, os.ModePerm)
  101. if err != nil {
  102. return "", err
  103. }
  104. defDebugFolder = nowProcessRoot
  105. return nowProcessRoot, err
  106. }
  107. return defDebugFolder, nil
  108. }
  109. // GetRootTmpFolder 获取缓存的根目录,每一个视频的缓存将在其中额外新建子集文件夹
  110. func GetRootTmpFolder() (string, error) {
  111. if defTmpFolder == "" {
  112. nowProcessRoot, _ := os.Getwd()
  113. nowProcessRoot = path.Join(nowProcessRoot, common.TmpFolder)
  114. err := os.MkdirAll(nowProcessRoot, os.ModePerm)
  115. if err != nil {
  116. return "", err
  117. }
  118. defTmpFolder = nowProcessRoot
  119. return nowProcessRoot, err
  120. }
  121. return 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 := path.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(wantedExtMap) < 1 {
  254. defExtMap[common.VideoExtMp4] = common.VideoExtMp4
  255. defExtMap[common.VideoExtMkv] = common.VideoExtMkv
  256. defExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  257. defExtMap[common.VideoExtIso] = common.VideoExtIso
  258. wantedExtMap[common.VideoExtMp4] = common.VideoExtMp4
  259. wantedExtMap[common.VideoExtMkv] = common.VideoExtMkv
  260. wantedExtMap[common.VideoExtRmvb] = common.VideoExtRmvb
  261. wantedExtMap[common.VideoExtIso] = common.VideoExtIso
  262. for _, videoExt := range customVideoExts {
  263. wantedExtMap[videoExt] = videoExt
  264. }
  265. }
  266. fileExt := strings.ToLower(filepath.Ext(fileName))
  267. _, bFound := 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. // ReloadBrowser 提前把浏览器下载好
  274. func ReloadBrowser() {
  275. page, err := rod_helper.NewBrowserLoadPage("https://www.baidu.com", "", 300*time.Second, 2)
  276. if err != nil {
  277. return
  278. }
  279. defer page.Close()
  280. }
  281. // CopyFile copies a single file from src to dst
  282. func CopyFile(src, dst string) error {
  283. var err error
  284. var srcfd *os.File
  285. var dstfd *os.File
  286. var srcinfo os.FileInfo
  287. if srcfd, err = os.Open(src); err != nil {
  288. return err
  289. }
  290. defer srcfd.Close()
  291. if dstfd, err = os.Create(dst); err != nil {
  292. return err
  293. }
  294. defer dstfd.Close()
  295. if _, err = io.Copy(dstfd, srcfd); err != nil {
  296. return err
  297. }
  298. if srcinfo, err = os.Stat(src); err != nil {
  299. return err
  300. }
  301. return os.Chmod(dst, srcinfo.Mode())
  302. }
  303. // CopyDir copies a whole directory recursively
  304. func CopyDir(src string, dst string) error {
  305. var err error
  306. var fds []os.FileInfo
  307. var srcinfo os.FileInfo
  308. if srcinfo, err = os.Stat(src); err != nil {
  309. return err
  310. }
  311. if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
  312. return err
  313. }
  314. if fds, err = ioutil.ReadDir(src); err != nil {
  315. return err
  316. }
  317. for _, fd := range fds {
  318. srcfp := path.Join(src, fd.Name())
  319. dstfp := path.Join(dst, fd.Name())
  320. if fd.IsDir() {
  321. if err = CopyDir(srcfp, dstfp); err != nil {
  322. fmt.Println(err)
  323. }
  324. } else {
  325. if err = CopyFile(srcfp, dstfp); err != nil {
  326. fmt.Println(err)
  327. }
  328. }
  329. }
  330. return nil
  331. }
  332. // CopyTestData 单元测试前把测试的数据 copy 一份出来操作,src 目录中默认应该有一个 org 原始数据文件夹,然后需要复制一份 test 文件夹出来
  333. func CopyTestData(srcDir string) (string, error) {
  334. // 测试数据的文件夹
  335. orgDir := path.Join(srcDir, "org")
  336. testDir := path.Join(srcDir, "test")
  337. if IsDir(testDir) == true {
  338. err := ClearFolder(testDir)
  339. if err != nil {
  340. return "", err
  341. }
  342. }
  343. err := CopyDir(orgDir, testDir)
  344. if err != nil {
  345. return "", err
  346. }
  347. return testDir, nil
  348. }
  349. // CloseChrome 强行结束没有关闭的 Chrome 进程
  350. func CloseChrome() {
  351. cmdString := ""
  352. sysType := runtime.GOOS
  353. if sysType == "linux" {
  354. // LINUX系统
  355. cmdString = "pkill chrome"
  356. }
  357. if sysType == "windows" {
  358. // windows系统
  359. cmdString = "taskkill /F /im chromedriver.exe"
  360. }
  361. if cmdString == "" {
  362. log_helper.GetLogger().Errorln("CloseChrome OS:", sysType)
  363. return
  364. }
  365. command := exec.Command(cmdString)
  366. err := command.Run()
  367. if err != nil {
  368. log_helper.GetLogger().Errorln("CloseChrome", err)
  369. }
  370. }