assrt.go 15 KB

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