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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
|
#pragma warning disable CS1591
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.Extensions;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
using Microsoft.Extensions.Logging;
using static MediaBrowser.Model.IO.IODefaults;
namespace MediaBrowser.Providers.Subtitles
{
public class SubtitleManager : ISubtitleManager
{
private readonly ILogger<SubtitleManager> _logger;
private readonly IFileSystem _fileSystem;
private readonly ILibraryMonitor _monitor;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly ILocalizationManager _localization;
private ISubtitleProvider[] _subtitleProviders;
public SubtitleManager(
ILogger<SubtitleManager> logger,
IFileSystem fileSystem,
ILibraryMonitor monitor,
IMediaSourceManager mediaSourceManager,
ILocalizationManager localizationManager)
{
_logger = logger;
_fileSystem = fileSystem;
_monitor = monitor;
_mediaSourceManager = mediaSourceManager;
_localization = localizationManager;
}
/// <inheritdoc />
public event EventHandler<SubtitleDownloadFailureEventArgs> SubtitleDownloadFailure;
/// <inheritdoc />
public void AddParts(IEnumerable<ISubtitleProvider> subtitleProviders)
{
_subtitleProviders = subtitleProviders
.OrderBy(i => i is IHasOrder hasOrder ? hasOrder.Order : 0)
.ToArray();
}
/// <inheritdoc />
public async Task<RemoteSubtitleInfo[]> SearchSubtitles(SubtitleSearchRequest request, CancellationToken cancellationToken)
{
if (request.Language != null)
{
var culture = _localization.FindLanguageInfo(request.Language);
if (culture != null)
{
request.TwoLetterISOLanguageName = culture.TwoLetterISOLanguageName;
}
}
var contentType = request.ContentType;
var providers = _subtitleProviders
.Where(i => i.SupportedMediaTypes.Contains(contentType))
.Where(i => !request.DisabledSubtitleFetchers.Contains(i.Name, StringComparer.OrdinalIgnoreCase))
.OrderBy(i =>
{
var index = request.SubtitleFetcherOrder.ToList().IndexOf(i.Name);
return index == -1 ? int.MaxValue : index;
})
.ToArray();
// If not searching all, search one at a time until something is found
if (!request.SearchAllProviders)
{
foreach (var provider in providers)
{
try
{
var searchResults = await provider.Search(request, cancellationToken).ConfigureAwait(false);
var list = searchResults.ToArray();
if (list.Length > 0)
{
Normalize(list);
return list;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading subtitles from {Provider}", provider.Name);
}
}
return Array.Empty<RemoteSubtitleInfo>();
}
var tasks = providers.Select(async i =>
{
try
{
var searchResults = await i.Search(request, cancellationToken).ConfigureAwait(false);
var list = searchResults.ToArray();
Normalize(list);
return list;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading subtitles from {0}", i.Name);
return Array.Empty<RemoteSubtitleInfo>();
}
});
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return results.SelectMany(i => i).ToArray();
}
/// <inheritdoc />
public Task DownloadSubtitles(Video video, string subtitleId, CancellationToken cancellationToken)
{
var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video);
return DownloadSubtitles(video, libraryOptions, subtitleId, cancellationToken);
}
/// <inheritdoc />
public async Task DownloadSubtitles(
Video video,
LibraryOptions libraryOptions,
string subtitleId,
CancellationToken cancellationToken)
{
var parts = subtitleId.Split('_', 2);
var provider = GetProvider(parts[0]);
try
{
var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false);
await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false);
}
catch (RateLimitExceededException)
{
throw;
}
catch (Exception ex)
{
SubtitleDownloadFailure?.Invoke(this, new SubtitleDownloadFailureEventArgs
{
Item = video,
Exception = ex,
Provider = provider.Name
});
throw;
}
}
/// <inheritdoc />
public Task UploadSubtitle(Video video, SubtitleResponse response)
{
var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video);
return TrySaveSubtitle(video, libraryOptions, response);
}
private async Task TrySaveSubtitle(
Video video,
LibraryOptions libraryOptions,
SubtitleResponse response)
{
var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;
using (var stream = response.Stream)
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
memoryStream.Position = 0;
var savePaths = new List<string>();
var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLowerInvariant();
if (response.IsForced)
{
saveFileName += ".forced";
}
saveFileName += "." + response.Format.ToLowerInvariant();
if (saveInMediaFolder)
{
savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName));
}
savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName));
await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);
}
}
private async Task TrySaveToFiles(Stream stream, List<string> savePaths)
{
Exception exceptionToThrow = null;
foreach (var savePath in savePaths)
{
_logger.LogInformation("Saving subtitles to {0}", savePath);
_monitor.ReportFileSystemChangeBeginning(savePath);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
// use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, FileStreamBufferSize, true))
{
await stream.CopyToAsync(fs).ConfigureAwait(false);
}
return;
}
catch (Exception ex)
{
if (exceptionToThrow == null)
{
exceptionToThrow = ex;
}
}
finally
{
_monitor.ReportFileSystemChangeComplete(savePath, false);
}
stream.Position = 0;
}
if (exceptionToThrow != null)
{
throw exceptionToThrow;
}
}
/// <inheritdoc />
public Task<RemoteSubtitleInfo[]> SearchSubtitles(Video video, string language, bool? isPerfectMatch, CancellationToken cancellationToken)
{
if (video.VideoType != VideoType.VideoFile)
{
return Task.FromResult(Array.Empty<RemoteSubtitleInfo>());
}
VideoContentType mediaType;
if (video is Episode)
{
mediaType = VideoContentType.Episode;
}
else if (video is Movie)
{
mediaType = VideoContentType.Movie;
}
else
{
// These are the only supported types
return Task.FromResult(Array.Empty<RemoteSubtitleInfo>());
}
var request = new SubtitleSearchRequest
{
ContentType = mediaType,
IndexNumber = video.IndexNumber,
Language = language,
MediaPath = video.Path,
Name = video.Name,
ParentIndexNumber = video.ParentIndexNumber,
ProductionYear = video.ProductionYear,
ProviderIds = video.ProviderIds,
RuntimeTicks = video.RunTimeTicks,
IsPerfectMatch = isPerfectMatch ?? false
};
if (video is Episode episode)
{
request.IndexNumberEnd = episode.IndexNumberEnd;
request.SeriesName = episode.SeriesName;
}
return SearchSubtitles(request, cancellationToken);
}
private void Normalize(IEnumerable<RemoteSubtitleInfo> subtitles)
{
foreach (var sub in subtitles)
{
sub.Id = GetProviderId(sub.ProviderName) + "_" + sub.Id;
}
}
private string GetProviderId(string name)
{
return name.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture);
}
private ISubtitleProvider GetProvider(string id)
{
return _subtitleProviders.First(i => string.Equals(id, GetProviderId(i.Name), StringComparison.Ordinal));
}
/// <inheritdoc />
public Task DeleteSubtitles(BaseItem item, int index)
{
var stream = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery
{
Index = index,
ItemId = item.Id,
Type = MediaStreamType.Subtitle
})[0];
var path = stream.Path;
_monitor.ReportFileSystemChangeBeginning(path);
try
{
_fileSystem.DeleteFile(path);
}
finally
{
_monitor.ReportFileSystemChangeComplete(path, false);
}
return item.RefreshMetadata(CancellationToken.None);
}
/// <inheritdoc />
public Task<SubtitleResponse> GetRemoteSubtitles(string id, CancellationToken cancellationToken)
{
var parts = id.Split('_', 2);
var provider = GetProvider(parts[0]);
id = parts[^1];
return provider.GetSubtitles(id, cancellationToken);
}
/// <inheritdoc />
public SubtitleProviderInfo[] GetSupportedProviders(BaseItem video)
{
VideoContentType mediaType;
if (video is Episode)
{
mediaType = VideoContentType.Episode;
}
else if (video is Movie)
{
mediaType = VideoContentType.Movie;
}
else
{
// These are the only supported types
return Array.Empty<SubtitleProviderInfo>();
}
return _subtitleProviders
.Where(i => i.SupportedMediaTypes.Contains(mediaType))
.Select(i => new SubtitleProviderInfo
{
Name = i.Name,
Id = GetProviderId(i.Name)
}).ToArray();
}
}
}
|