zimuku.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. package zimuku
  2. import (
  3. "fmt"
  4. "github.com/PuerkitoBio/goquery"
  5. "github.com/Tnze/go.num/v2/zh"
  6. "github.com/allanpk716/ChineseSubFinder/internal/common"
  7. "github.com/allanpk716/ChineseSubFinder/internal/pkg"
  8. "github.com/allanpk716/ChineseSubFinder/internal/pkg/decode"
  9. "github.com/allanpk716/ChineseSubFinder/internal/pkg/language"
  10. "github.com/allanpk716/ChineseSubFinder/internal/pkg/log_helper"
  11. "github.com/allanpk716/ChineseSubFinder/internal/pkg/notify_center"
  12. "github.com/allanpk716/ChineseSubFinder/internal/pkg/sub_parser_hub"
  13. "github.com/allanpk716/ChineseSubFinder/internal/types"
  14. "github.com/allanpk716/ChineseSubFinder/internal/types/series"
  15. "github.com/allanpk716/ChineseSubFinder/internal/types/supplier"
  16. "github.com/sirupsen/logrus"
  17. "path/filepath"
  18. "regexp"
  19. "sort"
  20. "strings"
  21. )
  22. type Supplier struct {
  23. reqParam types.ReqParam
  24. log *logrus.Logger
  25. topic int
  26. }
  27. func NewSupplier(_reqParam ...types.ReqParam) *Supplier {
  28. sup := Supplier{}
  29. sup.log = log_helper.GetLogger()
  30. sup.topic = common.DownloadSubsPerSite
  31. if len(_reqParam) > 0 {
  32. sup.reqParam = _reqParam[0]
  33. if sup.reqParam.Topic > 0 && sup.reqParam.Topic != sup.topic {
  34. sup.topic = sup.reqParam.Topic
  35. }
  36. }
  37. return &sup
  38. }
  39. func (s Supplier) GetSupplierName() string {
  40. return common.SubSiteZiMuKu
  41. }
  42. func (s Supplier) GetReqParam() types.ReqParam {
  43. return s.reqParam
  44. }
  45. func (s Supplier) GetSubListFromFile4Movie(filePath string) ([]supplier.SubInfo, error) {
  46. return s.getSubListFromMovie(filePath)
  47. }
  48. func (s Supplier) GetSubListFromFile4Series(seriesInfo *series.SeriesInfo) ([]supplier.SubInfo, error) {
  49. var err error
  50. /*
  51. 去网站搜索的时候,有个比较由意思的逻辑,有些剧集,哪怕只有一季,sonarr 也会给它命名为 Season 1
  52. 但是在 zimuku 搜索的时候,如果你加上 XXX 第一季 就搜索不出来,那么目前比较可行的办法是查询两次
  53. 第一次优先查询 XXX 第一季 ,如果返回的列表是空的,那么再查询 XXX
  54. */
  55. // 这里打算牺牲效率,提高代码的复用度,不然后续得维护一套电影的查询逻辑,一套剧集的查询逻辑
  56. // 比如,其实可以搜索剧集名称,应该可以得到多个季的列表,然后分析再继续
  57. // 现在粗暴点,直接一季搜索一次,跟电影的搜索一样,在首个影片就停止,然后继续往下
  58. AllSeasonSubResult := SubResult{}
  59. for value := range seriesInfo.SeasonDict {
  60. // 第一级界面,找到影片的详情界面
  61. keyword := seriesInfo.Name + " 第" + zh.Uint64(value).String() + "季"
  62. filmDetailPageUrl, err := s.step0(keyword)
  63. if err != nil {
  64. s.log.Errorln(keyword)
  65. // 如果只是搜索不到,则继续换关键词
  66. if err != common.ZiMuKuSearchKeyWordStep0DetailPageUrlNotFound {
  67. return nil, err
  68. }
  69. keyword := seriesInfo.Name
  70. s.log.Infoln("Retry", keyword)
  71. filmDetailPageUrl, err = s.step0(keyword)
  72. if err != nil {
  73. s.log.Errorln(keyword)
  74. return nil, err
  75. }
  76. }
  77. // 第二级界面,有多少个字幕
  78. subResult, err := s.step1(filmDetailPageUrl)
  79. if err != nil {
  80. s.log.Errorln("step1", filmDetailPageUrl)
  81. return nil, err
  82. }
  83. if AllSeasonSubResult.Title == "" {
  84. AllSeasonSubResult = subResult
  85. } else {
  86. AllSeasonSubResult.SubInfos = append(AllSeasonSubResult.SubInfos, subResult.SubInfos...)
  87. }
  88. }
  89. // 找到最大的优先级的字幕下载
  90. sort.Sort(SortByPriority{AllSeasonSubResult.SubInfos})
  91. // 找到那些 Eps 需要下载字幕的
  92. subInfoNeedDownload := s.whichEpisodeNeedDownloadSub(seriesInfo, AllSeasonSubResult)
  93. // 剩下的部分跟 GetSubListFroKeyword 一样,就是去下载了
  94. outSubInfoList := s.whichSubInfoNeedDownload(subInfoNeedDownload, err)
  95. // 返回前,需要把每一个 Eps 的 Season Episode 信息填充到每个 SubInfo 中
  96. return outSubInfoList, nil
  97. }
  98. func (s Supplier) GetSubListFromFile4Anime(seriesInfo *series.SeriesInfo) ([]supplier.SubInfo, error) {
  99. panic("not implemented")
  100. }
  101. func (s Supplier) getSubListFromMovie(fileFPath string) ([]supplier.SubInfo, error) {
  102. /*
  103. 虽然是传入视频文件路径,但是其实需要读取对应的视频文件目录下的
  104. movie.xml 以及 *.nfo,找到 IMDB id
  105. 优先通过 IMDB id 去查找字幕
  106. 如果找不到,再靠文件名提取影片名称去查找
  107. */
  108. // 得到这个视频文件名中的信息
  109. info, _, err := decode.GetVideoInfoFromFileFullPath(fileFPath)
  110. if err != nil {
  111. return nil, err
  112. }
  113. // 找到这个视频文件,尝试得到 IMDB ID
  114. // 目前测试来看,加入 年 这个关键词去搜索,对 2020 年后的影片有利,因为网站有统一的详细页面了,而之前的,没有,会影响识别
  115. // 所以,year >= 2020 年,则可以多加一个关键词(年)去搜索影片
  116. imdbInfo, err := decode.GetImdbInfo4Movie(fileFPath)
  117. if err != nil {
  118. // 允许的错误,跳过,继续进行文件名的搜索
  119. s.log.Errorln("model.GetImdbInfo", err)
  120. }
  121. var subInfoList []supplier.SubInfo
  122. if imdbInfo.ImdbId != "" {
  123. // 先用 imdb id 找
  124. subInfoList, err = s.getSubListFromKeyword(imdbInfo.ImdbId)
  125. if err != nil {
  126. // 允许的错误,跳过,继续进行文件名的搜索
  127. s.log.Errorln(s.GetSupplierName(), "keyword:", imdbInfo.ImdbId)
  128. s.log.Errorln("getSubListFromKeyword", "IMDBID can not found sub", fileFPath, err)
  129. }
  130. // 如果有就优先返回
  131. if len(subInfoList) > 0 {
  132. return subInfoList, nil
  133. }
  134. }
  135. // 如果没有,那么就用文件名查找
  136. searchKeyword := pkg.VideoNameSearchKeywordMaker(info.Title, imdbInfo.Year)
  137. subInfoList, err = s.getSubListFromKeyword(searchKeyword)
  138. if err != nil {
  139. s.log.Errorln(s.GetSupplierName(), "keyword:", searchKeyword)
  140. return nil, err
  141. }
  142. return subInfoList, nil
  143. }
  144. func (s Supplier) getSubListFromKeyword(keyword string) ([]supplier.SubInfo, error) {
  145. var outSubInfoList []supplier.SubInfo
  146. // 第一级界面,找到影片的详情界面
  147. filmDetailPageUrl, err := s.step0(keyword)
  148. if err != nil {
  149. return nil, err
  150. }
  151. // 第二级界面,有多少个字幕
  152. subResult, err := s.step1(filmDetailPageUrl)
  153. if err != nil {
  154. return nil, err
  155. }
  156. // 第三级界面,单个字幕详情
  157. // 找到最大的优先级的字幕下载
  158. sort.Sort(SortByPriority{subResult.SubInfos})
  159. outSubInfoList = s.whichSubInfoNeedDownload(subResult.SubInfos, err)
  160. return outSubInfoList, nil
  161. }
  162. func (s Supplier) whichEpisodeNeedDownloadSub(seriesInfo *series.SeriesInfo, AllSeasonSubResult SubResult) []SubInfo {
  163. // 字幕很多,考虑效率,需要做成字典
  164. // key SxEx - SubInfos
  165. var allSubDict = make(map[string]SubInfos)
  166. // 全季的字幕列表
  167. var oneSeasonSubDict = make(map[string]SubInfos)
  168. for _, subInfo := range AllSeasonSubResult.SubInfos {
  169. _, season, episode, err := decode.GetSeasonAndEpisodeFromSubFileName(subInfo.Name)
  170. if err != nil {
  171. s.log.Errorln("whichEpisodeNeedDownloadSub.GetVideoInfoFromFileFullPath", subInfo.Name, err)
  172. continue
  173. }
  174. subInfo.Season = season
  175. subInfo.Episode = episode
  176. epsKey := pkg.GetEpisodeKeyName(season, episode)
  177. _, ok := allSubDict[epsKey]
  178. if ok == false {
  179. // 初始化
  180. allSubDict[epsKey] = SubInfos{}
  181. if season != 0 && episode == 0 {
  182. oneSeasonSubDict[epsKey] = SubInfos{}
  183. }
  184. }
  185. // 添加
  186. allSubDict[epsKey] = append(allSubDict[epsKey], subInfo)
  187. if season != 0 && episode == 0 {
  188. oneSeasonSubDict[epsKey] = append(oneSeasonSubDict[epsKey], subInfo)
  189. }
  190. }
  191. // 本地的视频列表,找到没有字幕的
  192. // 需要进行下载字幕的列表
  193. var subInfoNeedDownload = make([]SubInfo, 0)
  194. // 有那些 Eps 需要下载的,按 SxEx 反回 epsKey
  195. for epsKey, epsInfo := range seriesInfo.NeedDlEpsKeyList {
  196. // 从一堆字幕里面找合适的
  197. value, ok := allSubDict[epsKey]
  198. // 是否有
  199. if ok == true && len(value) > 0 {
  200. value[0].Season = epsInfo.Season
  201. value[0].Episode = epsInfo.Episode
  202. subInfoNeedDownload = append(subInfoNeedDownload, value[0])
  203. } else {
  204. s.log.Infoln("ZiMuKu Not Find Sub can be download", epsInfo.Title, epsInfo.Season, epsInfo.Episode)
  205. }
  206. }
  207. // 全季的字幕列表,也拼进去,后面进行下载
  208. for _, infos := range oneSeasonSubDict {
  209. subInfoNeedDownload = append(subInfoNeedDownload, infos[0])
  210. }
  211. // 返回前,需要把每一个 Eps 的 Season Episode 信息填充到每个 SubInfo 中
  212. return subInfoNeedDownload
  213. }
  214. func (s Supplier) whichSubInfoNeedDownload(subInfos SubInfos, err error) []supplier.SubInfo {
  215. var outSubInfoList = make([]supplier.SubInfo, 0)
  216. for i := range subInfos {
  217. err = s.step2(&subInfos[i])
  218. if err != nil {
  219. s.log.Error(err)
  220. continue
  221. }
  222. }
  223. // TODO 这里需要考虑,可以设置为高级选项,不够就用 unknow 来补充
  224. // 首先过滤出中文的字幕,同时需要满足是支持的字幕
  225. var tmpSubInfo = make([]SubInfo, 0)
  226. for _, subInfo := range subInfos {
  227. tmpLang := language.LangConverter(subInfo.Lang)
  228. if language.HasChineseLang(tmpLang) == true && sub_parser_hub.IsSubTypeWanted(subInfo.Ext) == true {
  229. tmpSubInfo = append(tmpSubInfo, subInfo)
  230. }
  231. }
  232. // 看字幕够不够
  233. if len(tmpSubInfo) < s.topic {
  234. for _, subInfo := range subInfos {
  235. if len(tmpSubInfo) >= s.topic {
  236. break
  237. }
  238. tmpLang := language.LangConverter(subInfo.Lang)
  239. if language.HasChineseLang(tmpLang) == false {
  240. tmpSubInfo = append(tmpSubInfo, subInfo)
  241. }
  242. }
  243. }
  244. // 第四级界面,具体字幕下载
  245. for i, subInfo := range tmpSubInfo {
  246. fileName, data, err := s.step3(subInfo.SubDownloadPageUrl)
  247. if err != nil {
  248. s.log.Error(err)
  249. continue
  250. }
  251. // 默认都是包含中文字幕的,然后具体使用的时候再进行区分
  252. oneSubInfo := supplier.NewSubInfo(s.GetSupplierName(), int64(i), fileName, types.ChineseSimple, pkg.AddBaseUrl(common.SubZiMuKuRootUrl, subInfo.SubDownloadPageUrl), 0,
  253. 0, filepath.Ext(fileName), data)
  254. oneSubInfo.Season = subInfo.Season
  255. oneSubInfo.Episode = subInfo.Episode
  256. outSubInfoList = append(outSubInfoList, *oneSubInfo)
  257. }
  258. // 返回前,需要把每一个 Eps 的 Season Episode 信息填充到每个 SubInfo 中
  259. return outSubInfoList
  260. }
  261. // step0 先在查询界面找到字幕对应第一个影片的详情界面,需要解决自定义错误 ZiMuKuSearchKeyWordStep0DetailPageUrlNotFound
  262. func (s Supplier) step0(keyword string) (string, error) {
  263. var err error
  264. defer func() {
  265. if err != nil {
  266. notify_center.Notify.Add("zimuku_step0", err.Error())
  267. }
  268. }()
  269. httpClient := pkg.NewHttpClient(s.reqParam)
  270. // 第一级界面,有多少个字幕
  271. resp, err := httpClient.R().
  272. SetQueryParams(map[string]string{
  273. "q": keyword,
  274. }).
  275. Get(common.SubZiMuKuSearchUrl)
  276. if err != nil {
  277. return "", err
  278. }
  279. // 找到对应影片的详情界面
  280. re := regexp.MustCompile(`<p\s+class="tt\s+clearfix"><a\s+href="(/subs/[\w]+\.html)"\s+target="_blank"><b>(.*?)</b></a></p>`)
  281. matched := re.FindAllStringSubmatch(resp.String(), -1)
  282. if len(matched) < 1 {
  283. return "", common.ZiMuKuSearchKeyWordStep0DetailPageUrlNotFound
  284. }
  285. // 影片的详情界面 url
  286. filmDetailPageUrl := matched[0][1]
  287. return filmDetailPageUrl, nil
  288. }
  289. // step1 分析详情界面,找到有多少个字幕
  290. func (s Supplier) step1(filmDetailPageUrl string) (SubResult, error) {
  291. var err error
  292. defer func() {
  293. if err != nil {
  294. notify_center.Notify.Add("zimuku_step1", err.Error())
  295. }
  296. }()
  297. filmDetailPageUrl = pkg.AddBaseUrl(common.SubZiMuKuRootUrl, filmDetailPageUrl)
  298. httpClient := pkg.NewHttpClient(s.reqParam)
  299. resp, err := httpClient.R().
  300. Get(filmDetailPageUrl)
  301. if err != nil {
  302. return SubResult{}, err
  303. }
  304. doc, err := goquery.NewDocumentFromReader(strings.NewReader(resp.String()))
  305. if err != nil {
  306. return SubResult{}, err
  307. }
  308. var subResult SubResult
  309. subResult.SubInfos = SubInfos{}
  310. counterIndex := 3
  311. // 先找到页面”下载“关键词是第几列,然后下面的下载量才能正确的解析。否则,电影是[3],而在剧集中,因为多了字幕组的筛选,则为[4]
  312. doc.Find("#subtb thead tr th").Each(func(i int, th *goquery.Selection) {
  313. if th.Text() == "下载" {
  314. counterIndex = i
  315. }
  316. })
  317. doc.Find("#subtb tbody tr").Each(func(i int, tr *goquery.Selection) {
  318. // 字幕下载页面地址
  319. href, exists := tr.Find("a").Attr("href")
  320. if !exists {
  321. return
  322. }
  323. // 标题
  324. title, exists := tr.Find("a").Attr("title")
  325. if !exists {
  326. return
  327. }
  328. // 扩展名
  329. ext := tr.Find(".label-info").Text()
  330. // 作者信息
  331. authorInfos := tr.Find(".gray")
  332. authorInfo := ""
  333. authorInfos.Each(func(a_i int, a_lb *goquery.Selection) {
  334. authorInfo += a_lb.Text() + ","
  335. })
  336. authorInfoLen := len(authorInfo)
  337. if authorInfoLen > 0 {
  338. authorInfo = authorInfo[0 : authorInfoLen-3]
  339. }
  340. // 语言
  341. lang, exists := tr.Find("img").First().Attr("alt")
  342. if !exists {
  343. lang = ""
  344. }
  345. // 投票
  346. rate, exists := tr.Find(".rating-star").First().Attr("title")
  347. if !exists {
  348. rate = ""
  349. }
  350. vote, err := decode.GetNumber2Float(rate)
  351. if err != nil {
  352. return
  353. }
  354. // 下载次数统计
  355. downCountNub := 0
  356. downCount := tr.Find("td").Eq(counterIndex).Text()
  357. if strings.Contains(downCount, "万") {
  358. fNumb, err := decode.GetNumber2Float(downCount)
  359. if err != nil {
  360. return
  361. }
  362. downCountNub = int(fNumb * 10000)
  363. } else {
  364. downCountNub, err = decode.GetNumber2int(downCount)
  365. if err != nil {
  366. return
  367. }
  368. }
  369. var subInfo SubInfo
  370. subResult.Title = title
  371. subInfo.Name = title
  372. subInfo.DetailUrl = href
  373. subInfo.Ext = ext
  374. subInfo.AuthorInfo = authorInfo
  375. subInfo.Lang = lang
  376. subInfo.DownloadTimes = downCountNub
  377. subInfo.Score = vote
  378. // 计算优先级
  379. subInfo.Priority = subInfo.Score * float32(subInfo.DownloadTimes)
  380. subResult.SubInfos = append(subResult.SubInfos, subInfo)
  381. })
  382. return subResult, nil
  383. }
  384. // step2 第二级界面,单个字幕详情,需要判断 ZiMuKuDownloadUrlStep2NotFound 这个自定义错误
  385. func (s Supplier) step2(subInfo *SubInfo) error {
  386. var err error
  387. defer func() {
  388. if err != nil {
  389. notify_center.Notify.Add("zimuku_step2", err.Error())
  390. }
  391. }()
  392. detailUrl := pkg.AddBaseUrl(common.SubZiMuKuRootUrl, subInfo.DetailUrl)
  393. httpClient := pkg.NewHttpClient(s.reqParam)
  394. resp, err := httpClient.R().
  395. Get(detailUrl)
  396. if err != nil {
  397. return err
  398. }
  399. // 找到下载地址
  400. re := regexp.MustCompile(`<a\s+id="down1"\s+href="([^"]*/dld/[\w]+\.html)"`)
  401. matched := re.FindAllStringSubmatch(resp.String(), -1)
  402. if matched == nil || len(matched) == 0 || len(matched[0]) == 0 {
  403. s.log.Debug(detailUrl)
  404. return common.ZiMuKuDownloadUrlStep2NotFound
  405. }
  406. if strings.Contains(matched[0][1], "://") {
  407. subInfo.SubDownloadPageUrl = matched[0][1]
  408. } else {
  409. subInfo.SubDownloadPageUrl = fmt.Sprintf("%s%s", common.SubZiMuKuRootUrl, matched[0][1])
  410. }
  411. return nil
  412. }
  413. // step3 第三级界面,具体字幕下载 ZiMuKuDownloadUrlStep3NotFound ZiMuKuDownloadUrlStep3AllFailed
  414. func (s Supplier) step3(subDownloadPageUrl string) (string, []byte, error) {
  415. var err error
  416. defer func() {
  417. if err != nil {
  418. notify_center.Notify.Add("zimuku_step3", err.Error())
  419. }
  420. }()
  421. subDownloadPageUrl = pkg.AddBaseUrl(common.SubZiMuKuRootUrl, subDownloadPageUrl)
  422. httpClient := pkg.NewHttpClient(s.reqParam)
  423. resp, err := httpClient.R().
  424. Get(subDownloadPageUrl)
  425. if err != nil {
  426. return "", nil, err
  427. }
  428. re := regexp.MustCompile(`<li><a\s+rel="nofollow"\s+href="([^"]*/download/[^"]+)"`)
  429. matched := re.FindAllStringSubmatch(resp.String(), -1)
  430. if matched == nil || len(matched) == 0 || len(matched[0]) == 0 {
  431. s.log.Debug(subDownloadPageUrl)
  432. return "", nil, common.ZiMuKuDownloadUrlStep3NotFound
  433. }
  434. var filename string
  435. var data []byte
  436. s.reqParam.Referer = subDownloadPageUrl
  437. for i := 0; i < len(matched); i++ {
  438. data, filename, err = pkg.DownFile(pkg.AddBaseUrl(common.SubZiMuKuRootUrl, matched[i][1]), s.reqParam)
  439. if err != nil {
  440. s.log.Errorln("ZiMuKu step3 DownloadFile", err)
  441. continue
  442. }
  443. return filename, data, nil
  444. }
  445. s.log.Debug(subDownloadPageUrl)
  446. return "", nil, common.ZiMuKuDownloadUrlStep3AllFailed
  447. }
  448. type SubResult struct {
  449. Title string // 字幕的标题
  450. OtherName string // 影片又名
  451. SubInfos SubInfos // 字幕的列表
  452. }
  453. type SubInfo struct {
  454. Name string // 字幕的名称
  455. Lang string // 语言
  456. AuthorInfo string // 作者
  457. Ext string // 后缀名
  458. Score float32 // 评分
  459. DownloadTimes int // 下载的次数
  460. Priority float32 // 优先级,使用评分和次数乘积而来,类似于 Score 投票
  461. DetailUrl string // 字幕的详情界面,需要再次分析具体的下载地址,地址需要拼接网站的根地址上去
  462. SubDownloadPageUrl string // 字幕的具体的下载页面,会有多个下载可用的链接
  463. DownloadUrl string // 字幕的下载地址
  464. Season int // 第几季,默认-1
  465. Episode int // 第几集,默认-1
  466. }
  467. // SubInfos 实现自定义排序
  468. type SubInfos []SubInfo
  469. func (s SubInfos) Len() int {
  470. return len(s)
  471. }
  472. func (s SubInfos) Less(i, j int) bool {
  473. return s[i].Priority > s[j].Priority
  474. }
  475. func (s SubInfos) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  476. type SortByPriority struct{ SubInfos }
  477. // Less 根据元素的优先级降序排序
  478. func (s SortByPriority) Less(i, j int) bool {
  479. return s.SubInfos[i].Priority > s.SubInfos[j].Priority
  480. }