OpenSubtitleDownloader.cs 13 KB

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