OpenSubtitleDownloader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Controller.Security;
  7. using MediaBrowser.Controller.Subtitles;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Providers;
  12. using MediaBrowser.Model.Serialization;
  13. using OpenSubtitlesHandler;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Providers.Subtitles
  22. {
  23. public class OpenSubtitleDownloader : ISubtitleProvider, IDisposable
  24. {
  25. private readonly ILogger _logger;
  26. private readonly IHttpClient _httpClient;
  27. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  28. private readonly IServerConfigurationManager _config;
  29. private readonly IEncryptionManager _encryption;
  30. private Timer _dailyTimer;
  31. // This is limited to 200 per day
  32. private int _dailyDownloadCount;
  33. // It's 200 but this will be in-exact so buffer a little
  34. // And the user may restart the server
  35. private const int MaxDownloadsPerDay = 150;
  36. private readonly IJsonSerializer _json;
  37. public OpenSubtitleDownloader(ILogManager logManager, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json)
  38. {
  39. _logger = logManager.GetLogger(GetType().Name);
  40. _httpClient = httpClient;
  41. _config = config;
  42. _encryption = encryption;
  43. _json = json;
  44. _config.NamedConfigurationUpdating += _config_NamedConfigurationUpdating;
  45. // Reset the count every 24 hours
  46. _dailyTimer = new Timer(state => _dailyDownloadCount = 0, null, TimeSpan.FromHours(24), TimeSpan.FromHours(24));
  47. Utilities.HttpClient = httpClient;
  48. OpenSubtitles.SetUserAgent("mediabrowser.tv");
  49. }
  50. private const string PasswordHashPrefix = "h:";
  51. void _config_NamedConfigurationUpdating(object sender, ConfigurationUpdateEventArgs e)
  52. {
  53. if (!string.Equals(e.Key, "subtitles", StringComparison.OrdinalIgnoreCase))
  54. {
  55. return;
  56. }
  57. var options = (SubtitleOptions)e.NewConfiguration;
  58. if (options != null &&
  59. !string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash) &&
  60. !options.OpenSubtitlesPasswordHash.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
  61. {
  62. options.OpenSubtitlesPasswordHash = EncryptPassword(options.OpenSubtitlesPasswordHash);
  63. }
  64. }
  65. private string EncryptPassword(string password)
  66. {
  67. return PasswordHashPrefix + _encryption.EncryptString(password);
  68. }
  69. private string DecryptPassword(string password)
  70. {
  71. if (password == null ||
  72. !password.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
  73. {
  74. return string.Empty;
  75. }
  76. return _encryption.DecryptString(password.Substring(2));
  77. }
  78. public string Name
  79. {
  80. get { return "Open Subtitles"; }
  81. }
  82. private SubtitleOptions GetOptions()
  83. {
  84. return _config.GetSubtitleConfiguration();
  85. }
  86. public IEnumerable<VideoContentType> SupportedMediaTypes
  87. {
  88. get
  89. {
  90. var options = GetOptions();
  91. if (string.IsNullOrWhiteSpace(options.OpenSubtitlesUsername) ||
  92. string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash))
  93. {
  94. return new VideoContentType[] { };
  95. }
  96. return new[] { VideoContentType.Episode, VideoContentType.Movie };
  97. }
  98. }
  99. public Task<SubtitleResponse> GetSubtitles(string id, CancellationToken cancellationToken)
  100. {
  101. return GetSubtitlesInternal(id, GetOptions(), cancellationToken);
  102. }
  103. private async Task<SubtitleResponse> GetSubtitlesInternal(string id,
  104. SubtitleOptions options,
  105. CancellationToken cancellationToken)
  106. {
  107. if (string.IsNullOrWhiteSpace(id))
  108. {
  109. throw new ArgumentNullException("id");
  110. }
  111. if (_dailyDownloadCount >= MaxDownloadsPerDay &&
  112. !options.IsOpenSubtitleVipAccount)
  113. {
  114. throw new InvalidOperationException("Open Subtitle's daily download limit has been exceeded. Please try again tomorrow.");
  115. }
  116. var idParts = id.Split(new[] { '-' }, 3);
  117. var format = idParts[0];
  118. var language = idParts[1];
  119. var ossId = idParts[2];
  120. var downloadsList = new[] { int.Parse(ossId, _usCulture) };
  121. await Login(cancellationToken).ConfigureAwait(false);
  122. var resultDownLoad = await OpenSubtitles.DownloadSubtitlesAsync(downloadsList, cancellationToken).ConfigureAwait(false);
  123. if (!(resultDownLoad is MethodResponseSubtitleDownload))
  124. {
  125. throw new ApplicationException("Invalid response type");
  126. }
  127. var results = ((MethodResponseSubtitleDownload)resultDownLoad).Results;
  128. if (results.Count == 0)
  129. {
  130. var msg = string.Format("Subtitle with Id {0} was not found. Name: {1}. Status: {2}. Message: {3}",
  131. ossId,
  132. resultDownLoad.Name ?? string.Empty,
  133. resultDownLoad.Message ?? string.Empty,
  134. resultDownLoad.Status ?? string.Empty);
  135. throw new ResourceNotFoundException(msg);
  136. }
  137. var data = Convert.FromBase64String(results.First().Data);
  138. return new SubtitleResponse
  139. {
  140. Format = format,
  141. Language = language,
  142. Stream = new MemoryStream(Utilities.Decompress(new MemoryStream(data)))
  143. };
  144. }
  145. private DateTime _lastLogin;
  146. private async Task Login(CancellationToken cancellationToken)
  147. {
  148. if ((DateTime.UtcNow - _lastLogin).TotalSeconds < 60)
  149. {
  150. return;
  151. }
  152. var options = GetOptions();
  153. var user = options.OpenSubtitlesUsername ?? string.Empty;
  154. var password = DecryptPassword(options.OpenSubtitlesPasswordHash);
  155. var loginResponse = await OpenSubtitles.LogInAsync(user, password, "en", cancellationToken).ConfigureAwait(false);
  156. if (!(loginResponse is MethodResponseLogIn))
  157. {
  158. throw new UnauthorizedAccessException("Authentication to OpenSubtitles failed.");
  159. }
  160. _lastLogin = DateTime.UtcNow;
  161. }
  162. public async Task<IEnumerable<NameIdPair>> GetSupportedLanguages(CancellationToken cancellationToken)
  163. {
  164. await Login(cancellationToken).ConfigureAwait(false);
  165. var result = OpenSubtitles.GetSubLanguages("en");
  166. if (!(result is MethodResponseGetSubLanguages))
  167. {
  168. _logger.Error("Invalid response type");
  169. return new List<NameIdPair>();
  170. }
  171. var results = ((MethodResponseGetSubLanguages)result).Languages;
  172. return results.Select(i => new NameIdPair
  173. {
  174. Name = i.LanguageName,
  175. Id = i.SubLanguageID
  176. });
  177. }
  178. public async Task<IEnumerable<RemoteSubtitleInfo>> Search(SubtitleSearchRequest request, CancellationToken cancellationToken)
  179. {
  180. var imdbIdText = request.GetProviderId(MetadataProviders.Imdb);
  181. long imdbId = 0;
  182. switch (request.ContentType)
  183. {
  184. case VideoContentType.Episode:
  185. if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName))
  186. {
  187. _logger.Debug("Episode information missing");
  188. return new List<RemoteSubtitleInfo>();
  189. }
  190. break;
  191. case VideoContentType.Movie:
  192. if (string.IsNullOrEmpty(request.Name))
  193. {
  194. _logger.Debug("Movie name missing");
  195. return new List<RemoteSubtitleInfo>();
  196. }
  197. if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId))
  198. {
  199. _logger.Debug("Imdb id missing");
  200. return new List<RemoteSubtitleInfo>();
  201. }
  202. break;
  203. }
  204. if (string.IsNullOrEmpty(request.MediaPath))
  205. {
  206. _logger.Debug("Path Missing");
  207. return new List<RemoteSubtitleInfo>();
  208. }
  209. await Login(cancellationToken).ConfigureAwait(false);
  210. var subLanguageId = request.Language;
  211. var hash = Utilities.ComputeHash(request.MediaPath);
  212. var fileInfo = new FileInfo(request.MediaPath);
  213. var movieByteSize = fileInfo.Length;
  214. var searchImdbId = request.ContentType == VideoContentType.Movie ? imdbId.ToString(_usCulture) : "";
  215. var subtitleSearchParameters = request.ContentType == VideoContentType.Episode
  216. ? new List<SubtitleSearchParameters> {
  217. new SubtitleSearchParameters(subLanguageId,
  218. query: request.SeriesName,
  219. season: request.ParentIndexNumber.Value.ToString(_usCulture),
  220. episode: request.IndexNumber.Value.ToString(_usCulture))
  221. }
  222. : new List<SubtitleSearchParameters> {
  223. new SubtitleSearchParameters(subLanguageId, imdbid: searchImdbId),
  224. new SubtitleSearchParameters(subLanguageId, query: request.Name, imdbid: searchImdbId)
  225. };
  226. var parms = new List<SubtitleSearchParameters> {
  227. new SubtitleSearchParameters( subLanguageId,
  228. movieHash: hash,
  229. movieByteSize: movieByteSize,
  230. imdbid: searchImdbId ),
  231. };
  232. parms.AddRange(subtitleSearchParameters);
  233. var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false);
  234. if (!(result is MethodResponseSubtitleSearch))
  235. {
  236. _logger.Error("Invalid response type");
  237. return new List<RemoteSubtitleInfo>();
  238. }
  239. Predicate<SubtitleSearchResult> mediaFilter =
  240. x =>
  241. request.ContentType == VideoContentType.Episode
  242. ? !string.IsNullOrEmpty(x.SeriesSeason) && !string.IsNullOrEmpty(x.SeriesEpisode) &&
  243. int.Parse(x.SeriesSeason, _usCulture) == request.ParentIndexNumber &&
  244. int.Parse(x.SeriesEpisode, _usCulture) == request.IndexNumber
  245. : !string.IsNullOrEmpty(x.IDMovieImdb) && long.Parse(x.IDMovieImdb, _usCulture) == imdbId;
  246. var results = ((MethodResponseSubtitleSearch)result).Results;
  247. // Avoid implicitly captured closure
  248. var hasCopy = hash;
  249. return results.Where(x => x.SubBad == "0" && mediaFilter(x))
  250. .OrderBy(x => (x.MovieHash == hash ? 0 : 1))
  251. .ThenBy(x => Math.Abs(long.Parse(x.MovieByteSize, _usCulture) - movieByteSize))
  252. .ThenByDescending(x => int.Parse(x.SubDownloadsCnt, _usCulture))
  253. .ThenByDescending(x => double.Parse(x.SubRating, _usCulture))
  254. .Select(i => new RemoteSubtitleInfo
  255. {
  256. Author = i.UserNickName,
  257. Comment = i.SubAuthorComment,
  258. CommunityRating = float.Parse(i.SubRating, _usCulture),
  259. DownloadCount = int.Parse(i.SubDownloadsCnt, _usCulture),
  260. Format = i.SubFormat,
  261. ProviderName = Name,
  262. ThreeLetterISOLanguageName = i.SubLanguageID,
  263. Id = i.SubFormat + "-" + i.SubLanguageID + "-" + i.IDSubtitleFile,
  264. Name = i.SubFileName,
  265. DateCreated = DateTime.Parse(i.SubAddDate, _usCulture),
  266. IsHashMatch = i.MovieHash == hasCopy
  267. });
  268. }
  269. public void Dispose()
  270. {
  271. _config.NamedConfigurationUpdating -= _config_NamedConfigurationUpdating;
  272. if (_dailyTimer != null)
  273. {
  274. _dailyTimer.Dispose();
  275. _dailyTimer = null;
  276. }
  277. }
  278. }
  279. }