1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Security;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using OpenSubtitlesHandler;
namespace MediaBrowser.MediaEncoding.Subtitles
{
public class OpenSubtitleDownloader : ISubtitleProvider, IDisposable
{
private readonly ILogger _logger;
private readonly IHttpClient _httpClient;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly IServerConfigurationManager _config;
private readonly IEncryptionManager _encryption;
private readonly IJsonSerializer _json;
private readonly IFileSystem _fileSystem;
public OpenSubtitleDownloader(ILoggerFactory loggerFactory, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem)
{
_logger = loggerFactory.CreateLogger(GetType().Name);
_httpClient = httpClient;
_config = config;
_encryption = encryption;
_json = json;
_fileSystem = fileSystem;
_config.NamedConfigurationUpdating += _config_NamedConfigurationUpdating;
Utilities.HttpClient = httpClient;
OpenSubtitles.SetUserAgent("mediabrowser.tv");
}
private const string PasswordHashPrefix = "h:";
void _config_NamedConfigurationUpdating(object sender, ConfigurationUpdateEventArgs e)
{
if (!string.Equals(e.Key, "subtitles", StringComparison.OrdinalIgnoreCase))
{
return;
}
var options = (SubtitleOptions)e.NewConfiguration;
if (options != null &&
!string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash) &&
!options.OpenSubtitlesPasswordHash.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
{
options.OpenSubtitlesPasswordHash = EncryptPassword(options.OpenSubtitlesPasswordHash);
}
}
private string EncryptPassword(string password)
{
return PasswordHashPrefix + _encryption.EncryptString(password);
}
private string DecryptPassword(string password)
{
if (password == null ||
!password.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
{
return string.Empty;
}
return _encryption.DecryptString(password.Substring(2));
}
public string Name
{
get { return "Open Subtitles"; }
}
private SubtitleOptions GetOptions()
{
return _config.GetSubtitleConfiguration();
}
public IEnumerable<VideoContentType> SupportedMediaTypes
{
get
{
var options = GetOptions();
if (string.IsNullOrWhiteSpace(options.OpenSubtitlesUsername) ||
string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash))
{
return new VideoContentType[] { };
}
return new[] { VideoContentType.Episode, VideoContentType.Movie };
}
}
public Task<SubtitleResponse> GetSubtitles(string id, CancellationToken cancellationToken)
{
return GetSubtitlesInternal(id, GetOptions(), cancellationToken);
}
private DateTime _lastRateLimitException;
private async Task<SubtitleResponse> GetSubtitlesInternal(string id,
SubtitleOptions options,
CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentNullException("id");
}
var idParts = id.Split(new[] { '-' }, 3);
var format = idParts[0];
var language = idParts[1];
var ossId = idParts[2];
var downloadsList = new[] { int.Parse(ossId, _usCulture) };
await Login(cancellationToken).ConfigureAwait(false);
if ((DateTime.UtcNow - _lastRateLimitException).TotalHours < 1)
{
throw new RateLimitExceededException("OpenSubtitles rate limit reached");
}
var resultDownLoad = await OpenSubtitles.DownloadSubtitlesAsync(downloadsList, cancellationToken).ConfigureAwait(false);
if ((resultDownLoad.Status ?? string.Empty).IndexOf("407", StringComparison.OrdinalIgnoreCase) != -1)
{
_lastRateLimitException = DateTime.UtcNow;
throw new RateLimitExceededException("OpenSubtitles rate limit reached");
}
if (!(resultDownLoad is MethodResponseSubtitleDownload))
{
throw new Exception("Invalid response type");
}
var results = ((MethodResponseSubtitleDownload)resultDownLoad).Results;
_lastRateLimitException = DateTime.MinValue;
if (results.Count == 0)
{
var msg = string.Format("Subtitle with Id {0} was not found. Name: {1}. Status: {2}. Message: {3}",
ossId,
resultDownLoad.Name ?? string.Empty,
resultDownLoad.Status ?? string.Empty,
resultDownLoad.Message ?? string.Empty);
throw new ResourceNotFoundException(msg);
}
var data = Convert.FromBase64String(results.First().Data);
return new SubtitleResponse
{
Format = format,
Language = language,
Stream = new MemoryStream(Utilities.Decompress(new MemoryStream(data)))
};
}
private DateTime _lastLogin;
private async Task Login(CancellationToken cancellationToken)
{
if ((DateTime.UtcNow - _lastLogin).TotalSeconds < 60)
{
return;
}
var options = GetOptions();
var user = options.OpenSubtitlesUsername ?? string.Empty;
var password = DecryptPassword(options.OpenSubtitlesPasswordHash);
var loginResponse = await OpenSubtitles.LogInAsync(user, password, "en", cancellationToken).ConfigureAwait(false);
if (!(loginResponse is MethodResponseLogIn))
{
throw new Exception("Authentication to OpenSubtitles failed.");
}
_lastLogin = DateTime.UtcNow;
}
public async Task<IEnumerable<NameIdPair>> GetSupportedLanguages(CancellationToken cancellationToken)
{
await Login(cancellationToken).ConfigureAwait(false);
var result = OpenSubtitles.GetSubLanguages("en");
if (!(result is MethodResponseGetSubLanguages))
{
_logger.LogError("Invalid response type");
return new List<NameIdPair>();
}
var results = ((MethodResponseGetSubLanguages)result).Languages;
return results.Select(i => new NameIdPair
{
Name = i.LanguageName,
Id = i.SubLanguageID
});
}
private string NormalizeLanguage(string language)
{
// Problem with Greek subtitle download #1349
if (string.Equals(language, "gre", StringComparison.OrdinalIgnoreCase))
{
return "ell";
}
return language;
}
public async Task<IEnumerable<RemoteSubtitleInfo>> Search(SubtitleSearchRequest request, CancellationToken cancellationToken)
{
var imdbIdText = request.GetProviderId(MetadataProviders.Imdb);
long imdbId = 0;
switch (request.ContentType)
{
case VideoContentType.Episode:
if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName))
{
_logger.LogDebug("Episode information missing");
return new List<RemoteSubtitleInfo>();
}
break;
case VideoContentType.Movie:
if (string.IsNullOrEmpty(request.Name))
{
_logger.LogDebug("Movie name missing");
return new List<RemoteSubtitleInfo>();
}
if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId))
{
_logger.LogDebug("Imdb id missing");
return new List<RemoteSubtitleInfo>();
}
break;
}
if (string.IsNullOrEmpty(request.MediaPath))
{
_logger.LogDebug("Path Missing");
return new List<RemoteSubtitleInfo>();
}
await Login(cancellationToken).ConfigureAwait(false);
var subLanguageId = NormalizeLanguage(request.Language);
string hash;
using (var fileStream = _fileSystem.OpenRead(request.MediaPath))
{
hash = Utilities.ComputeHash(fileStream);
}
var fileInfo = _fileSystem.GetFileInfo(request.MediaPath);
var movieByteSize = fileInfo.Length;
var searchImdbId = request.ContentType == VideoContentType.Movie ? imdbId.ToString(_usCulture) : "";
var subtitleSearchParameters = request.ContentType == VideoContentType.Episode
? new List<SubtitleSearchParameters> {
new SubtitleSearchParameters(subLanguageId,
query: request.SeriesName,
season: request.ParentIndexNumber.Value.ToString(_usCulture),
episode: request.IndexNumber.Value.ToString(_usCulture))
}
: new List<SubtitleSearchParameters> {
new SubtitleSearchParameters(subLanguageId, imdbid: searchImdbId),
new SubtitleSearchParameters(subLanguageId, query: request.Name, imdbid: searchImdbId)
};
var parms = new List<SubtitleSearchParameters> {
new SubtitleSearchParameters( subLanguageId,
movieHash: hash,
movieByteSize: movieByteSize,
imdbid: searchImdbId ),
};
parms.AddRange(subtitleSearchParameters);
var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false);
if (!(result is MethodResponseSubtitleSearch))
{
_logger.LogError("Invalid response type");
return new List<RemoteSubtitleInfo>();
}
Predicate<SubtitleSearchResult> mediaFilter =
x =>
request.ContentType == VideoContentType.Episode
? !string.IsNullOrEmpty(x.SeriesSeason) && !string.IsNullOrEmpty(x.SeriesEpisode) &&
int.Parse(x.SeriesSeason, _usCulture) == request.ParentIndexNumber &&
int.Parse(x.SeriesEpisode, _usCulture) == request.IndexNumber
: !string.IsNullOrEmpty(x.IDMovieImdb) && long.Parse(x.IDMovieImdb, _usCulture) == imdbId;
var results = ((MethodResponseSubtitleSearch)result).Results;
// Avoid implicitly captured closure
var hasCopy = hash;
return results.Where(x => x.SubBad == "0" && mediaFilter(x) && (!request.IsPerfectMatch || string.Equals(x.MovieHash, hash, StringComparison.OrdinalIgnoreCase)))
.OrderBy(x => (string.Equals(x.MovieHash, hash, StringComparison.OrdinalIgnoreCase) ? 0 : 1))
.ThenBy(x => Math.Abs(long.Parse(x.MovieByteSize, _usCulture) - movieByteSize))
.ThenByDescending(x => int.Parse(x.SubDownloadsCnt, _usCulture))
.ThenByDescending(x => double.Parse(x.SubRating, _usCulture))
.Select(i => new RemoteSubtitleInfo
{
Author = i.UserNickName,
Comment = i.SubAuthorComment,
CommunityRating = float.Parse(i.SubRating, _usCulture),
DownloadCount = int.Parse(i.SubDownloadsCnt, _usCulture),
Format = i.SubFormat,
ProviderName = Name,
ThreeLetterISOLanguageName = i.SubLanguageID,
Id = i.SubFormat + "-" + i.SubLanguageID + "-" + i.IDSubtitleFile,
Name = i.SubFileName,
DateCreated = DateTime.Parse(i.SubAddDate, _usCulture),
IsHashMatch = i.MovieHash == hasCopy
}).Where(i => !string.Equals(i.Format, "sub", StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Format, "idx", StringComparison.OrdinalIgnoreCase));
}
public void Dispose()
{
_config.NamedConfigurationUpdating -= _config_NamedConfigurationUpdating;
}
}
}
|