| | | 1 | | #pragma warning disable CS1591 |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Linq; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | using Emby.Naming.Common; |
| | | 11 | | using Jellyfin.Extensions; |
| | | 12 | | using MediaBrowser.Common.Extensions; |
| | | 13 | | using MediaBrowser.Controller.Entities; |
| | | 14 | | using MediaBrowser.Controller.Entities.Movies; |
| | | 15 | | using MediaBrowser.Controller.Entities.TV; |
| | | 16 | | using MediaBrowser.Controller.Library; |
| | | 17 | | using MediaBrowser.Controller.Persistence; |
| | | 18 | | using MediaBrowser.Controller.Providers; |
| | | 19 | | using MediaBrowser.Controller.Subtitles; |
| | | 20 | | using MediaBrowser.Model.Configuration; |
| | | 21 | | using MediaBrowser.Model.Entities; |
| | | 22 | | using MediaBrowser.Model.Globalization; |
| | | 23 | | using MediaBrowser.Model.IO; |
| | | 24 | | using MediaBrowser.Model.Providers; |
| | | 25 | | using Microsoft.Extensions.Logging; |
| | | 26 | | |
| | | 27 | | namespace MediaBrowser.Providers.Subtitles |
| | | 28 | | { |
| | | 29 | | public class SubtitleManager : ISubtitleManager |
| | | 30 | | { |
| | | 31 | | private readonly ILogger<SubtitleManager> _logger; |
| | | 32 | | private readonly IFileSystem _fileSystem; |
| | | 33 | | private readonly ILibraryMonitor _monitor; |
| | | 34 | | private readonly IMediaSourceManager _mediaSourceManager; |
| | | 35 | | private readonly ILocalizationManager _localization; |
| | | 36 | | private readonly IDirectoryService _directoryService; |
| | | 37 | | private readonly HashSet<string> _allowedSubtitleFormats; |
| | | 38 | | |
| | | 39 | | private readonly ISubtitleProvider[] _subtitleProviders; |
| | | 40 | | |
| | | 41 | | public SubtitleManager( |
| | | 42 | | ILogger<SubtitleManager> logger, |
| | | 43 | | IFileSystem fileSystem, |
| | | 44 | | ILibraryMonitor monitor, |
| | | 45 | | IMediaSourceManager mediaSourceManager, |
| | | 46 | | ILocalizationManager localizationManager, |
| | | 47 | | IDirectoryService directoryService, |
| | | 48 | | IEnumerable<ISubtitleProvider> subtitleProviders, |
| | | 49 | | NamingOptions namingOptions) |
| | | 50 | | { |
| | 27 | 51 | | _logger = logger; |
| | 27 | 52 | | _fileSystem = fileSystem; |
| | 27 | 53 | | _monitor = monitor; |
| | 27 | 54 | | _mediaSourceManager = mediaSourceManager; |
| | 27 | 55 | | _localization = localizationManager; |
| | 27 | 56 | | _directoryService = directoryService; |
| | 27 | 57 | | _subtitleProviders = subtitleProviders |
| | 27 | 58 | | .OrderBy(i => i is IHasOrder hasOrder ? hasOrder.Order : 0) |
| | 27 | 59 | | .ToArray(); |
| | 27 | 60 | | _allowedSubtitleFormats = new HashSet<string>( |
| | 27 | 61 | | namingOptions.SubtitleFileExtensions.Select(e => e.TrimStart('.')), |
| | 27 | 62 | | StringComparer.OrdinalIgnoreCase); |
| | 27 | 63 | | } |
| | | 64 | | |
| | | 65 | | /// <inheritdoc /> |
| | | 66 | | public event EventHandler<SubtitleDownloadFailureEventArgs>? SubtitleDownloadFailure; |
| | | 67 | | |
| | | 68 | | /// <inheritdoc /> |
| | | 69 | | public async Task<RemoteSubtitleInfo[]> SearchSubtitles(SubtitleSearchRequest request, CancellationToken cancell |
| | | 70 | | { |
| | 0 | 71 | | if (request.Language is not null) |
| | | 72 | | { |
| | 0 | 73 | | var culture = _localization.FindLanguageInfo(request.Language); |
| | | 74 | | |
| | 0 | 75 | | if (culture is not null) |
| | | 76 | | { |
| | 0 | 77 | | request.TwoLetterISOLanguageName = culture.TwoLetterISOLanguageName; |
| | | 78 | | } |
| | | 79 | | } |
| | | 80 | | |
| | 0 | 81 | | var contentType = request.ContentType; |
| | 0 | 82 | | var providers = _subtitleProviders |
| | 0 | 83 | | .Where(i => i.SupportedMediaTypes.Contains(contentType) && !request.DisabledSubtitleFetchers.Contains(i. |
| | 0 | 84 | | .OrderBy(i => |
| | 0 | 85 | | { |
| | 0 | 86 | | var index = request.SubtitleFetcherOrder.IndexOf(i.Name); |
| | 0 | 87 | | return index == -1 ? int.MaxValue : index; |
| | 0 | 88 | | }) |
| | 0 | 89 | | .ToArray(); |
| | | 90 | | |
| | | 91 | | // If not searching all, search one at a time until something is found |
| | 0 | 92 | | if (!request.SearchAllProviders) |
| | | 93 | | { |
| | 0 | 94 | | foreach (var provider in providers) |
| | | 95 | | { |
| | | 96 | | try |
| | | 97 | | { |
| | 0 | 98 | | var searchResults = await provider.Search(request, cancellationToken).ConfigureAwait(false); |
| | | 99 | | |
| | 0 | 100 | | var list = searchResults.ToArray(); |
| | | 101 | | |
| | 0 | 102 | | if (list.Length > 0) |
| | | 103 | | { |
| | 0 | 104 | | Normalize(list); |
| | 0 | 105 | | return list; |
| | | 106 | | } |
| | 0 | 107 | | } |
| | 0 | 108 | | catch (Exception ex) |
| | | 109 | | { |
| | 0 | 110 | | _logger.LogError(ex, "Error downloading subtitles from {Provider}", provider.Name); |
| | 0 | 111 | | } |
| | 0 | 112 | | } |
| | | 113 | | |
| | 0 | 114 | | return Array.Empty<RemoteSubtitleInfo>(); |
| | | 115 | | } |
| | | 116 | | |
| | 0 | 117 | | var tasks = providers.Select(async i => |
| | 0 | 118 | | { |
| | 0 | 119 | | try |
| | 0 | 120 | | { |
| | 0 | 121 | | var searchResults = await i.Search(request, cancellationToken).ConfigureAwait(false); |
| | 0 | 122 | | |
| | 0 | 123 | | var list = searchResults.ToArray(); |
| | 0 | 124 | | Normalize(list); |
| | 0 | 125 | | return list; |
| | 0 | 126 | | } |
| | 0 | 127 | | catch (Exception ex) |
| | 0 | 128 | | { |
| | 0 | 129 | | _logger.LogError(ex, "Error downloading subtitles from {Name}", i.Name); |
| | 0 | 130 | | return Array.Empty<RemoteSubtitleInfo>(); |
| | 0 | 131 | | } |
| | 0 | 132 | | }); |
| | | 133 | | |
| | 0 | 134 | | var results = await Task.WhenAll(tasks).ConfigureAwait(false); |
| | | 135 | | |
| | 0 | 136 | | return results.SelectMany(i => i).ToArray(); |
| | 0 | 137 | | } |
| | | 138 | | |
| | | 139 | | /// <inheritdoc /> |
| | | 140 | | public Task DownloadSubtitles(Video video, string subtitleId, CancellationToken cancellationToken) |
| | | 141 | | { |
| | 0 | 142 | | var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video); |
| | | 143 | | |
| | 0 | 144 | | return DownloadSubtitles(video, libraryOptions, subtitleId, cancellationToken); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <inheritdoc /> |
| | | 148 | | public async Task DownloadSubtitles( |
| | | 149 | | Video video, |
| | | 150 | | LibraryOptions libraryOptions, |
| | | 151 | | string subtitleId, |
| | | 152 | | CancellationToken cancellationToken) |
| | | 153 | | { |
| | 0 | 154 | | var parts = subtitleId.Split('_', 2); |
| | 0 | 155 | | var provider = GetProvider(parts[0]); |
| | | 156 | | |
| | | 157 | | try |
| | | 158 | | { |
| | 0 | 159 | | var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false); |
| | | 160 | | |
| | 0 | 161 | | await TrySaveSubtitle(video, libraryOptions, response).ConfigureAwait(false); |
| | 0 | 162 | | } |
| | 0 | 163 | | catch (RateLimitExceededException) |
| | | 164 | | { |
| | 0 | 165 | | throw; |
| | | 166 | | } |
| | 0 | 167 | | catch (Exception ex) |
| | | 168 | | { |
| | 0 | 169 | | SubtitleDownloadFailure?.Invoke(this, new SubtitleDownloadFailureEventArgs |
| | 0 | 170 | | { |
| | 0 | 171 | | Item = video, |
| | 0 | 172 | | Exception = ex, |
| | 0 | 173 | | Provider = provider.Name |
| | 0 | 174 | | }); |
| | | 175 | | |
| | 0 | 176 | | throw; |
| | | 177 | | } |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <inheritdoc /> |
| | | 181 | | public Task UploadSubtitle(Video video, SubtitleResponse response) |
| | | 182 | | { |
| | 0 | 183 | | var format = response.Format; |
| | 0 | 184 | | if (string.IsNullOrEmpty(format) || !_allowedSubtitleFormats.Contains(format)) |
| | | 185 | | { |
| | 0 | 186 | | throw new ArgumentException($"Unsupported subtitle format: '{format}'"); |
| | | 187 | | } |
| | | 188 | | |
| | 0 | 189 | | var libraryOptions = BaseItem.LibraryManager.GetLibraryOptions(video); |
| | 0 | 190 | | return TrySaveSubtitle(video, libraryOptions, response); |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | private async Task TrySaveSubtitle( |
| | | 194 | | Video video, |
| | | 195 | | LibraryOptions libraryOptions, |
| | | 196 | | SubtitleResponse response) |
| | | 197 | | { |
| | 0 | 198 | | var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia; |
| | | 199 | | |
| | 0 | 200 | | var memoryStream = new MemoryStream(); |
| | 0 | 201 | | await using (memoryStream.ConfigureAwait(false)) |
| | | 202 | | { |
| | 0 | 203 | | var stream = response.Stream; |
| | 0 | 204 | | await using (stream.ConfigureAwait(false)) |
| | | 205 | | { |
| | 0 | 206 | | await stream.CopyToAsync(memoryStream).ConfigureAwait(false); |
| | 0 | 207 | | memoryStream.Position = 0; |
| | | 208 | | } |
| | | 209 | | |
| | 0 | 210 | | var savePaths = new List<string>(); |
| | 0 | 211 | | var language = response.Language.ToLowerInvariant(); |
| | 0 | 212 | | if (language.AsSpan().IndexOfAny(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) >= 0) |
| | | 213 | | { |
| | 0 | 214 | | throw new ArgumentException("Language contains invalid characters."); |
| | | 215 | | } |
| | | 216 | | |
| | 0 | 217 | | var saveFileName = Path.GetFileNameWithoutExtension(video.Path) + "." + language; |
| | | 218 | | |
| | 0 | 219 | | if (response.IsForced) |
| | | 220 | | { |
| | 0 | 221 | | saveFileName += ".forced"; |
| | | 222 | | } |
| | | 223 | | |
| | 0 | 224 | | if (response.IsHearingImpaired) |
| | | 225 | | { |
| | 0 | 226 | | saveFileName += ".sdh"; |
| | | 227 | | } |
| | | 228 | | |
| | 0 | 229 | | if (saveInMediaFolder) |
| | | 230 | | { |
| | 0 | 231 | | var mediaFolderPath = Path.GetFullPath(Path.Combine(video.ContainingFolderPath, saveFileName)); |
| | 0 | 232 | | savePaths.Add(mediaFolderPath); |
| | | 233 | | } |
| | | 234 | | else |
| | | 235 | | { |
| | 0 | 236 | | var internalPath = Path.GetFullPath(Path.Combine(video.GetInternalMetadataPath(), saveFileName)); |
| | 0 | 237 | | savePaths.Add(internalPath); |
| | | 238 | | } |
| | | 239 | | |
| | 0 | 240 | | await TrySaveToFiles(memoryStream, savePaths, video, response.Format.ToLowerInvariant()).ConfigureAwait( |
| | | 241 | | } |
| | 0 | 242 | | } |
| | | 243 | | |
| | | 244 | | private async Task TrySaveToFiles(Stream stream, List<string> savePaths, Video video, string extension) |
| | | 245 | | { |
| | 0 | 246 | | if (!_allowedSubtitleFormats.Contains(extension, StringComparison.OrdinalIgnoreCase)) |
| | | 247 | | { |
| | 0 | 248 | | throw new ArgumentException($"Invalid subtitle format: {extension}"); |
| | | 249 | | } |
| | | 250 | | |
| | 0 | 251 | | List<Exception>? exs = null; |
| | | 252 | | |
| | 0 | 253 | | foreach (var savePath in savePaths) |
| | | 254 | | { |
| | 0 | 255 | | var path = Path.GetFullPath(savePath + "." + extension); |
| | | 256 | | try |
| | | 257 | | { |
| | 0 | 258 | | var containingFolder = video.ContainingFolderPath + Path.DirectorySeparatorChar; |
| | 0 | 259 | | var metadataFolder = video.GetInternalMetadataPath() + Path.DirectorySeparatorChar; |
| | 0 | 260 | | if (path.StartsWith(containingFolder, StringComparison.Ordinal) |
| | 0 | 261 | | || path.StartsWith(metadataFolder, StringComparison.Ordinal)) |
| | | 262 | | { |
| | 0 | 263 | | var fileExists = File.Exists(path); |
| | 0 | 264 | | var counter = 0; |
| | | 265 | | |
| | 0 | 266 | | while (fileExists) |
| | | 267 | | { |
| | 0 | 268 | | path = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}", savePath, counter, extensi |
| | 0 | 269 | | fileExists = File.Exists(path); |
| | 0 | 270 | | counter++; |
| | | 271 | | } |
| | | 272 | | |
| | 0 | 273 | | _logger.LogInformation("Saving subtitles to {SavePath}", path); |
| | 0 | 274 | | _monitor.ReportFileSystemChangeBeginning(path); |
| | | 275 | | |
| | 0 | 276 | | Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException("Pa |
| | | 277 | | |
| | 0 | 278 | | var fileOptions = AsyncFile.WriteOptions; |
| | 0 | 279 | | fileOptions.Mode = FileMode.CreateNew; |
| | 0 | 280 | | fileOptions.PreallocationSize = stream.Length; |
| | 0 | 281 | | var fs = new FileStream(path, fileOptions); |
| | 0 | 282 | | await using (fs.ConfigureAwait(false)) |
| | | 283 | | { |
| | 0 | 284 | | await stream.CopyToAsync(fs).ConfigureAwait(false); |
| | | 285 | | } |
| | | 286 | | |
| | 0 | 287 | | _directoryService.Invalidate(path); |
| | | 288 | | |
| | 0 | 289 | | return; |
| | | 290 | | } |
| | | 291 | | else |
| | | 292 | | { |
| | | 293 | | // TODO: Add some error handling to the API user: return BadRequest("Could not save subtitle, ba |
| | 0 | 294 | | _logger.LogError("An uploaded subtitle could not be saved because the resulting path was invalid |
| | | 295 | | } |
| | 0 | 296 | | } |
| | 0 | 297 | | catch (Exception ex) |
| | | 298 | | { |
| | 0 | 299 | | (exs ??= []).Add(ex); |
| | 0 | 300 | | } |
| | | 301 | | finally |
| | | 302 | | { |
| | 0 | 303 | | _monitor.ReportFileSystemChangeComplete(path, false); |
| | | 304 | | } |
| | | 305 | | |
| | 0 | 306 | | stream.Position = 0; |
| | 0 | 307 | | } |
| | | 308 | | |
| | 0 | 309 | | if (exs is not null) |
| | | 310 | | { |
| | 0 | 311 | | throw new AggregateException(exs); |
| | | 312 | | } |
| | 0 | 313 | | } |
| | | 314 | | |
| | | 315 | | /// <inheritdoc /> |
| | | 316 | | public Task<RemoteSubtitleInfo[]> SearchSubtitles(Video video, string language, bool? isPerfectMatch, bool isAut |
| | | 317 | | { |
| | 0 | 318 | | if (video.VideoType != VideoType.VideoFile) |
| | | 319 | | { |
| | 0 | 320 | | return Task.FromResult(Array.Empty<RemoteSubtitleInfo>()); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | VideoContentType mediaType; |
| | | 324 | | |
| | 0 | 325 | | if (video is Episode) |
| | | 326 | | { |
| | 0 | 327 | | mediaType = VideoContentType.Episode; |
| | | 328 | | } |
| | 0 | 329 | | else if (video is Movie) |
| | | 330 | | { |
| | 0 | 331 | | mediaType = VideoContentType.Movie; |
| | | 332 | | } |
| | | 333 | | else |
| | | 334 | | { |
| | | 335 | | // These are the only supported types |
| | 0 | 336 | | return Task.FromResult(Array.Empty<RemoteSubtitleInfo>()); |
| | | 337 | | } |
| | | 338 | | |
| | 0 | 339 | | var request = new SubtitleSearchRequest |
| | 0 | 340 | | { |
| | 0 | 341 | | ContentType = mediaType, |
| | 0 | 342 | | IndexNumber = video.IndexNumber, |
| | 0 | 343 | | Language = language, |
| | 0 | 344 | | MediaPath = video.Path, |
| | 0 | 345 | | Name = video.Name, |
| | 0 | 346 | | ParentIndexNumber = video.ParentIndexNumber, |
| | 0 | 347 | | ProductionYear = video.ProductionYear, |
| | 0 | 348 | | ProviderIds = video.ProviderIds, |
| | 0 | 349 | | RuntimeTicks = video.RunTimeTicks, |
| | 0 | 350 | | IsPerfectMatch = isPerfectMatch ?? false, |
| | 0 | 351 | | IsAutomated = isAutomated |
| | 0 | 352 | | }; |
| | | 353 | | |
| | 0 | 354 | | if (video is Episode episode) |
| | | 355 | | { |
| | 0 | 356 | | request.IndexNumberEnd = episode.IndexNumberEnd; |
| | 0 | 357 | | request.SeriesName = episode.SeriesName; |
| | | 358 | | } |
| | | 359 | | |
| | 0 | 360 | | return SearchSubtitles(request, cancellationToken); |
| | | 361 | | } |
| | | 362 | | |
| | | 363 | | private void Normalize(IEnumerable<RemoteSubtitleInfo> subtitles) |
| | | 364 | | { |
| | 0 | 365 | | foreach (var sub in subtitles) |
| | | 366 | | { |
| | 0 | 367 | | sub.Id = GetProviderId(sub.ProviderName) + "_" + sub.Id; |
| | | 368 | | } |
| | 0 | 369 | | } |
| | | 370 | | |
| | | 371 | | private string GetProviderId(string name) |
| | | 372 | | { |
| | 0 | 373 | | return name.ToLowerInvariant().GetMD5().ToString("N", CultureInfo.InvariantCulture); |
| | | 374 | | } |
| | | 375 | | |
| | | 376 | | private ISubtitleProvider GetProvider(string id) |
| | | 377 | | { |
| | 0 | 378 | | return _subtitleProviders.First(i => string.Equals(id, GetProviderId(i.Name), StringComparison.Ordinal)); |
| | | 379 | | } |
| | | 380 | | |
| | | 381 | | /// <inheritdoc /> |
| | | 382 | | public Task DeleteSubtitles(BaseItem item, int index) |
| | | 383 | | { |
| | 0 | 384 | | var stream = _mediaSourceManager.GetMediaStreams(new MediaStreamQuery |
| | 0 | 385 | | { |
| | 0 | 386 | | Index = index, |
| | 0 | 387 | | ItemId = item.Id, |
| | 0 | 388 | | Type = MediaStreamType.Subtitle |
| | 0 | 389 | | })[0]; |
| | | 390 | | |
| | 0 | 391 | | var path = stream.Path; |
| | 0 | 392 | | _monitor.ReportFileSystemChangeBeginning(path); |
| | | 393 | | |
| | | 394 | | try |
| | | 395 | | { |
| | 0 | 396 | | _fileSystem.DeleteFile(path); |
| | 0 | 397 | | } |
| | | 398 | | finally |
| | | 399 | | { |
| | 0 | 400 | | _monitor.ReportFileSystemChangeComplete(path, false); |
| | 0 | 401 | | } |
| | | 402 | | |
| | 0 | 403 | | _directoryService.Invalidate(path); |
| | | 404 | | |
| | 0 | 405 | | return item.RefreshMetadata(CancellationToken.None); |
| | | 406 | | } |
| | | 407 | | |
| | | 408 | | /// <inheritdoc /> |
| | | 409 | | public Task<SubtitleResponse> GetRemoteSubtitles(string id, CancellationToken cancellationToken) |
| | | 410 | | { |
| | 0 | 411 | | var parts = id.Split('_', 2); |
| | | 412 | | |
| | 0 | 413 | | var provider = GetProvider(parts[0]); |
| | 0 | 414 | | id = parts[^1]; |
| | | 415 | | |
| | 0 | 416 | | return provider.GetSubtitles(id, cancellationToken); |
| | | 417 | | } |
| | | 418 | | |
| | | 419 | | /// <inheritdoc /> |
| | | 420 | | public SubtitleProviderInfo[] GetSupportedProviders(BaseItem item) |
| | | 421 | | { |
| | | 422 | | VideoContentType mediaType; |
| | | 423 | | |
| | 0 | 424 | | if (item is Episode) |
| | | 425 | | { |
| | 0 | 426 | | mediaType = VideoContentType.Episode; |
| | | 427 | | } |
| | 0 | 428 | | else if (item is Movie) |
| | | 429 | | { |
| | 0 | 430 | | mediaType = VideoContentType.Movie; |
| | | 431 | | } |
| | | 432 | | else |
| | | 433 | | { |
| | | 434 | | // These are the only supported types |
| | 0 | 435 | | return Array.Empty<SubtitleProviderInfo>(); |
| | | 436 | | } |
| | | 437 | | |
| | 0 | 438 | | return _subtitleProviders |
| | 0 | 439 | | .Where(i => i.SupportedMediaTypes.Contains(mediaType)) |
| | 0 | 440 | | .Select(i => new SubtitleProviderInfo |
| | 0 | 441 | | { |
| | 0 | 442 | | Name = i.Name, |
| | 0 | 443 | | Id = GetProviderId(i.Name) |
| | 0 | 444 | | }).ToArray(); |
| | | 445 | | } |
| | | 446 | | } |
| | | 447 | | } |