assrt.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package assrt
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/allanpk716/ChineseSubFinder/internal/logic/file_downloader"
  7. "github.com/allanpk716/ChineseSubFinder/internal/pkg/decode"
  8. "github.com/allanpk716/ChineseSubFinder/internal/pkg/imdb_helper"
  9. "github.com/allanpk716/ChineseSubFinder/internal/pkg/my_folder"
  10. "github.com/allanpk716/ChineseSubFinder/internal/pkg/my_util"
  11. "github.com/allanpk716/ChineseSubFinder/internal/pkg/notify_center"
  12. "github.com/allanpk716/ChineseSubFinder/internal/pkg/settings"
  13. common2 "github.com/allanpk716/ChineseSubFinder/internal/types/common"
  14. "github.com/allanpk716/ChineseSubFinder/internal/types/series"
  15. "github.com/allanpk716/ChineseSubFinder/internal/types/supplier"
  16. "github.com/sirupsen/logrus"
  17. "net/url"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. type Supplier struct {
  25. settings *settings.Settings
  26. log *logrus.Logger
  27. fileDownloader *file_downloader.FileDownloader
  28. topic int
  29. isAlive bool
  30. theSearchInterval time.Duration
  31. }
  32. func NewSupplier(fileDownloader *file_downloader.FileDownloader) *Supplier {
  33. sup := Supplier{}
  34. sup.log = fileDownloader.Log
  35. sup.fileDownloader = fileDownloader
  36. sup.topic = common2.DownloadSubsPerSite
  37. sup.isAlive = true // 默认是可以使用的,如果 check 后,再调整状态
  38. sup.settings = fileDownloader.Settings
  39. if sup.settings.AdvancedSettings.Topic > 0 && sup.settings.AdvancedSettings.Topic != sup.topic {
  40. sup.topic = sup.settings.AdvancedSettings.Topic
  41. }
  42. sup.theSearchInterval = 20 * time.Second
  43. return &sup
  44. }
  45. func (s *Supplier) CheckAlive() (bool, int64) {
  46. // 如果没有设置这个 API 接口,那么就任务是不可用的
  47. if s.settings.SubtitleSources.AssrtSettings.Token == "" {
  48. s.isAlive = false
  49. return false, 0
  50. }
  51. // 计算当前时间
  52. startT := time.Now()
  53. userInfo, err := s.getUserInfo()
  54. if err != nil {
  55. s.log.Errorln(s.GetSupplierName(), "CheckAlive", "Error", err)
  56. s.isAlive = false
  57. return false, 0
  58. }
  59. s.log.Infoln(s.GetSupplierName(), "CheckAlive", "UserInfo.Status:", userInfo.Status, "UserInfo.Quota:", userInfo.User.Quota)
  60. // 计算耗时
  61. s.isAlive = true
  62. return true, time.Since(startT).Milliseconds()
  63. }
  64. func (s *Supplier) IsAlive() bool {
  65. return s.isAlive
  66. }
  67. func (s *Supplier) OverDailyDownloadLimit() bool {
  68. // 对于这个接口暂时没有限制
  69. return false
  70. }
  71. func (s *Supplier) GetLogger() *logrus.Logger {
  72. return s.log
  73. }
  74. func (s *Supplier) GetSettings() *settings.Settings {
  75. return s.settings
  76. }
  77. func (s *Supplier) GetSupplierName() string {
  78. return common2.SubSiteAssrt
  79. }
  80. func (s *Supplier) GetSubListFromFile4Movie(filePath string) ([]supplier.SubInfo, error) {
  81. outSubInfos := make([]supplier.SubInfo, 0)
  82. if s.settings.SubtitleSources.AssrtSettings.Enabled == false {
  83. return outSubInfos, nil
  84. }
  85. if s.settings.SubtitleSources.AssrtSettings.Token == "" {
  86. return nil, errors.New("Token is empty")
  87. }
  88. return s.getSubListFromFile(filePath, true)
  89. }
  90. func (s *Supplier) GetSubListFromFile4Series(seriesInfo *series.SeriesInfo) ([]supplier.SubInfo, error) {
  91. outSubInfos := make([]supplier.SubInfo, 0)
  92. if s.settings.SubtitleSources.AssrtSettings.Enabled == false {
  93. return outSubInfos, nil
  94. }
  95. if s.settings.SubtitleSources.AssrtSettings.Token == "" {
  96. return nil, errors.New("Token is empty")
  97. }
  98. return s.downloadSub4Series(seriesInfo)
  99. }
  100. func (s *Supplier) GetSubListFromFile4Anime(seriesInfo *series.SeriesInfo) ([]supplier.SubInfo, error) {
  101. outSubInfos := make([]supplier.SubInfo, 0)
  102. if s.settings.SubtitleSources.AssrtSettings.Enabled == false {
  103. return outSubInfos, nil
  104. }
  105. if s.settings.SubtitleSources.AssrtSettings.Token == "" {
  106. return nil, errors.New("Token is empty")
  107. }
  108. return s.downloadSub4Series(seriesInfo)
  109. }
  110. func (s *Supplier) getSubListFromFile(videoFPath string, isMovie bool) ([]supplier.SubInfo, error) {
  111. defer func() {
  112. s.log.Debugln(s.GetSupplierName(), videoFPath, "End...")
  113. }()
  114. s.log.Debugln(s.GetSupplierName(), videoFPath, "Start...")
  115. outSubInfoList := make([]supplier.SubInfo, 0)
  116. imdbInfo, err := imdb_helper.GetIMDBInfo(s.log, videoFPath, isMovie, s.settings.AdvancedSettings.ProxySettings)
  117. if err != nil {
  118. s.log.Errorln(s.GetSupplierName(), videoFPath, "GetIMDBInfo", err)
  119. return nil, err
  120. }
  121. // 需要找到中文名称去搜索
  122. keyWord := imdbInfo.GetChineseNameFromAKA()
  123. if keyWord == "" {
  124. return nil, errors.New("No Chinese name")
  125. }
  126. if isMovie == false {
  127. // 连续剧需要额外补充 S01E01 这样的信息
  128. infoFromFileName, err := decode.GetVideoInfoFromFileName(videoFPath)
  129. if err != nil {
  130. return nil, err
  131. }
  132. keyWord += " " + my_util.GetEpisodeKeyName(infoFromFileName.Season, infoFromFileName.Episode, true)
  133. }
  134. var searchSubResult SearchSubResult
  135. searchSubResult, err = s.getSubByKeyWord(keyWord)
  136. if err != nil {
  137. s.log.Errorln("getSubByKeyWord", err)
  138. return nil, err
  139. }
  140. videoFileName := filepath.Base(videoFPath)
  141. if searchSubResult.Sub.Subs == nil || len(searchSubResult.Sub.Subs) == 0 {
  142. s.log.Infoln(s.GetSupplierName(), videoFileName, "No subtitle found")
  143. return outSubInfoList, nil
  144. }
  145. for index, subInfo := range searchSubResult.Sub.Subs {
  146. // 获取具体的下载地址
  147. oneSubDetail, err := s.getSubDetail(subInfo.Id)
  148. if err != nil {
  149. s.log.Errorln("getSubDetail", err)
  150. continue
  151. }
  152. if len(oneSubDetail.Sub.Subs) < 1 {
  153. continue
  154. }
  155. // 这里需要注意的是 ASSRT 说明了,下载的地址是有时效性的,那么如果缓存整个地址则不是正确的
  156. // 需要缓存的应该是这个字幕的 ID
  157. nowSubDownloadUrl := oneSubDetail.Sub.Subs[0].Url
  158. subInfo, err := s.fileDownloader.Get(s.GetSupplierName(), int64(index), videoFileName, nowSubDownloadUrl,
  159. 0, 0,
  160. // 得到一个特殊的替代 FileDownloadUrl 的特征字符串
  161. fmt.Sprintf("%s-%s-%d", s.GetSupplierName(), subInfo.NativeName, subInfo.Id),
  162. )
  163. if err != nil {
  164. s.log.Error("FileDownloader.Get", err)
  165. continue
  166. }
  167. outSubInfoList = append(outSubInfoList, *subInfo)
  168. // 如果够了那么多个字幕就返回
  169. if len(outSubInfoList) >= s.topic {
  170. return outSubInfoList, nil
  171. }
  172. }
  173. return outSubInfoList, nil
  174. }
  175. func (s *Supplier) downloadSub4Series(seriesInfo *series.SeriesInfo) ([]supplier.SubInfo, error) {
  176. var allSupplierSubInfo = make([]supplier.SubInfo, 0)
  177. index := 0
  178. // 这里拿到的 seriesInfo ,里面包含了,需要下载字幕的 Eps 信息
  179. for _, episodeInfo := range seriesInfo.NeedDlEpsKeyList {
  180. index++
  181. one, err := s.getSubListFromFile(episodeInfo.FileFullPath, false)
  182. if err != nil {
  183. s.log.Errorln(s.GetSupplierName(), "getSubListFromFile", episodeInfo.FileFullPath, err)
  184. continue
  185. }
  186. if one == nil {
  187. // 没有搜索到字幕
  188. s.log.Infoln(s.GetSupplierName(), "Not Find Sub can be download",
  189. episodeInfo.Title, episodeInfo.Season, episodeInfo.Episode)
  190. continue
  191. }
  192. // 需要赋值给字幕结构
  193. for i := range one {
  194. one[i].Season = episodeInfo.Season
  195. one[i].Episode = episodeInfo.Episode
  196. }
  197. allSupplierSubInfo = append(allSupplierSubInfo, one...)
  198. }
  199. // 返回前,需要把每一个 Eps 的 Season Episode 信息填充到每个 SubInfo 中
  200. return allSupplierSubInfo, nil
  201. }
  202. func (s *Supplier) getSubByKeyWord(keyword string) (SearchSubResult, error) {
  203. defer func() {
  204. time.Sleep(s.theSearchInterval)
  205. }()
  206. var searchSubResult SearchSubResult
  207. s.log.Infoln("Search KeyWord:", keyword)
  208. tt := url.QueryEscape(keyword)
  209. httpClient, err := my_util.NewHttpClient(s.settings.AdvancedSettings.ProxySettings)
  210. if err != nil {
  211. return searchSubResult, err
  212. }
  213. resp, err := httpClient.R().
  214. SetHeader("Content-Type", "application/x-www-form-urlencoded").
  215. Get(s.settings.AdvancedSettings.SuppliersSettings.Assrt.RootUrl +
  216. "/sub/search?q=" + tt +
  217. "&cnt=15&pos=0" +
  218. "&token=" + s.settings.SubtitleSources.AssrtSettings.Token)
  219. if err != nil {
  220. if resp != nil {
  221. s.log.Errorln(s.GetSupplierName(), "NewHttpClient:", keyword, err.Error())
  222. notify_center.Notify.Add(s.GetSupplierName()+" NewHttpClient", fmt.Sprintf("keyword: %s, resp: %s, error: %s", keyword, resp.String(), err.Error()))
  223. // 输出调试文件
  224. cacheCenterFolder, err := my_folder.GetRootCacheCenterFolder()
  225. if err != nil {
  226. s.log.Errorln(s.GetSupplierName(), "GetRootCacheCenterFolder", err)
  227. }
  228. desJsonInfo := filepath.Join(cacheCenterFolder, strings.ReplaceAll(keyword, " ", "")+"--assrt_search_error_getSubByKeyWord.json")
  229. // 写字符串到文件种
  230. file, _ := os.Create(desJsonInfo)
  231. defer func() {
  232. _ = file.Close()
  233. }()
  234. file.WriteString(resp.String())
  235. }
  236. /*
  237. 这里有个梗, Sub 有值的时候是一个列表,但是如果为空的时候,又是一个空的结构体
  238. 所以出现两个结构体需要去尝试解析
  239. SearchSubResultEmpty
  240. SearchSubResult
  241. 比如这个情况:
  242. jsonString := "{\"sub\":{\"action\":\"search\",\"subs\":{},\"result\":\"succeed\",\"keyword\":\"追杀夏娃 S04E07\"},\"status\":0}"
  243. */
  244. err = json.Unmarshal([]byte(resp.String()), &searchSubResult)
  245. if err != nil {
  246. // 再此尝试解析空列表
  247. var searchSubResultEmpty SearchSubResultEmpty
  248. err = json.Unmarshal([]byte(resp.String()), &searchSubResultEmpty)
  249. if err != nil {
  250. s.log.Errorln(s.GetSupplierName(), "json.Unmarshal", err)
  251. return searchSubResult, err
  252. }
  253. // 赋值过去
  254. searchSubResult.Sub.Action = searchSubResultEmpty.Sub.Action
  255. searchSubResult.Sub.Result = searchSubResultEmpty.Sub.Result
  256. searchSubResult.Sub.Keyword = searchSubResultEmpty.Sub.Keyword
  257. searchSubResult.Status = searchSubResultEmpty.Status
  258. return searchSubResult, err
  259. }
  260. return searchSubResult, err
  261. }
  262. return searchSubResult, nil
  263. }
  264. func (s *Supplier) getSubDetail(subID int) (OneSubDetail, error) {
  265. defer func() {
  266. time.Sleep(s.theSearchInterval)
  267. }()
  268. var subDetail OneSubDetail
  269. httpClient, err := my_util.NewHttpClient(s.settings.AdvancedSettings.ProxySettings)
  270. if err != nil {
  271. return subDetail, err
  272. }
  273. resp, err := httpClient.R().
  274. SetQueryParams(map[string]string{
  275. "token": s.settings.SubtitleSources.AssrtSettings.Token,
  276. "id": strconv.Itoa(subID),
  277. }).
  278. SetResult(&subDetail).
  279. Get(s.settings.AdvancedSettings.SuppliersSettings.Assrt.RootUrl + "/sub/detail")
  280. if err != nil {
  281. if resp != nil {
  282. s.log.Errorln(s.GetSupplierName(), "NewHttpClient:", subID, err.Error())
  283. notify_center.Notify.Add(s.GetSupplierName()+" NewHttpClient", fmt.Sprintf("subID: %d, resp: %s, error: %s", subID, resp.String(), err.Error()))
  284. // 输出调试文件
  285. cacheCenterFolder, err := my_folder.GetRootCacheCenterFolder()
  286. if err != nil {
  287. s.log.Errorln(s.GetSupplierName(), "GetRootCacheCenterFolder", err)
  288. }
  289. desJsonInfo := filepath.Join(cacheCenterFolder, strconv.Itoa(subID)+"--assrt_search_error_getSubDetail.json")
  290. // 写字符串到文件种
  291. file, _ := os.Create(desJsonInfo)
  292. defer func() {
  293. _ = file.Close()
  294. }()
  295. file.WriteString(resp.String())
  296. }
  297. return subDetail, err
  298. }
  299. return subDetail, nil
  300. }
  301. func (s *Supplier) getUserInfo() (UserInfo, error) {
  302. var userInfo UserInfo
  303. httpClient, err := my_util.NewHttpClient(s.settings.AdvancedSettings.ProxySettings)
  304. if err != nil {
  305. return userInfo, err
  306. }
  307. resp, err := httpClient.R().
  308. SetQueryParams(map[string]string{
  309. "token": s.settings.SubtitleSources.AssrtSettings.Token,
  310. }).
  311. SetResult(&userInfo).
  312. Get(s.settings.AdvancedSettings.SuppliersSettings.Assrt.RootUrl + "/user/quota")
  313. if err != nil {
  314. if resp != nil {
  315. s.log.Errorln(s.GetSupplierName(), "NewHttpClient:", err.Error())
  316. notify_center.Notify.Add(s.GetSupplierName()+" NewHttpClient", fmt.Sprintf("resp: %s, error: %s", resp.String(), err.Error()))
  317. }
  318. return userInfo, err
  319. }
  320. return userInfo, nil
  321. }
  322. type SearchSubResultEmpty struct {
  323. Sub struct {
  324. Action string `json:"action"`
  325. Subs struct {
  326. } `json:"subs"`
  327. Result string `json:"result"`
  328. Keyword string `json:"keyword"`
  329. } `json:"sub"`
  330. Status int `json:"status"`
  331. }
  332. type SearchSubResult struct {
  333. Sub struct {
  334. Action string `json:"action"`
  335. Subs []struct {
  336. Lang struct {
  337. Desc string `json:"desc,omitempty"`
  338. Langlist struct {
  339. Langcht bool `json:"langcht,omitempty"`
  340. Langdou bool `json:"langdou,omitempty"`
  341. Langeng bool `json:"langeng,omitempty"`
  342. Langchs bool `json:"langchs,omitempty"`
  343. } `json:"langlist,omitempty"`
  344. } `json:"lang,omitempty"`
  345. Id int `json:"id,omitempty"`
  346. VoteScore int `json:"vote_score,omitempty"`
  347. Videoname string `json:"videoname,omitempty"`
  348. ReleaseSite string `json:"release_site,omitempty"`
  349. Revision int `json:"revision,omitempty"`
  350. Subtype string `json:"subtype,omitempty"`
  351. NativeName string `json:"native_name,omitempty"`
  352. UploadTime string `json:"upload_time,omitempty"`
  353. } `json:"subs,omitempty"`
  354. Result string `json:"result,omitempty"`
  355. Keyword string `json:"keyword,omitempty"`
  356. } `json:"sub,omitempty"`
  357. Status int `json:"status,omitempty"`
  358. }
  359. type OneSubDetail struct {
  360. Sub struct {
  361. Action string `json:"action"`
  362. Subs []struct {
  363. DownCount int `json:"down_count,omitempty"`
  364. ViewCount int `json:"view_count,omitempty"`
  365. Lang struct {
  366. Desc string `json:"desc,omitempty"`
  367. Langlist struct {
  368. Langcht bool `json:"langcht,omitempty"`
  369. Langdou bool `json:"langdou,omitempty"`
  370. Langeng bool `json:"langeng,omitempty"`
  371. Langchs bool `json:"langchs,omitempty"`
  372. } `json:"langlist,omitempty"`
  373. } `json:"lang,omitempty"`
  374. Size int `json:"size,omitempty"`
  375. Title string `json:"title,omitempty"`
  376. Videoname string `json:"videoname,omitempty"`
  377. Revision int `json:"revision,omitempty"`
  378. NativeName string `json:"native_name,omitempty"`
  379. UploadTime string `json:"upload_time,omitempty"`
  380. Producer struct {
  381. Producer string `json:"producer,omitempty"`
  382. Verifier string `json:"verifier,omitempty"`
  383. Uploader string `json:"uploader,omitempty"`
  384. Source string `json:"source,omitempty"`
  385. } `json:"producer,omitempty"`
  386. Subtype string `json:"subtype,omitempty"`
  387. VoteScore int `json:"vote_score,omitempty"`
  388. ReleaseSite string `json:"release_site,omitempty"`
  389. Filelist []struct {
  390. S string `json:"s,omitempty"`
  391. F string `json:"f,omitempty"`
  392. Url string `json:"url,omitempty"`
  393. } `json:"filelist,omitempty"`
  394. Id int `json:"id,omitempty"`
  395. Filename string `json:"filename,omitempty"`
  396. Url string `json:"url,omitempty"`
  397. } `json:"subs,omitempty"`
  398. Result string `json:"result,omitempty"`
  399. } `json:"sub,omitempty"`
  400. Status int `json:"status,omitempty"`
  401. }
  402. type UserInfo struct {
  403. User struct {
  404. Action string `json:"action,omitempty"`
  405. Result string `json:"result,omitempty"`
  406. Quota int `json:"quota,omitempty"`
  407. } `json:"user,omitempty"`
  408. Status int `json:"status,omitempty"`
  409. }