jellyfin-server/MediaBrowser.Api/Subtitles/SubtitleService.cs

293 lines
13 KiB
C#
Raw Normal View History

using System;
2014-05-17 04:24:10 +00:00
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
2014-05-17 04:24:10 +00:00
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Subtitles;
using MediaBrowser.Model.Entities;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Providers;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
2014-05-17 04:24:10 +00:00
namespace MediaBrowser.Api.Subtitles
2014-05-17 04:24:10 +00:00
{
[Route("/Videos/{Id}/Subtitles/{Index}", "DELETE", Summary = "Deletes an external subtitle file")]
2014-11-15 02:31:03 +00:00
[Authenticated(Roles = "Admin")]
2014-05-17 04:24:10 +00:00
public class DeleteSubtitle
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
2018-09-12 17:26:21 +00:00
public Guid Id { get; set; }
2014-05-17 04:24:10 +00:00
[ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "DELETE")]
public int Index { get; set; }
}
[Route("/Items/{Id}/RemoteSearch/Subtitles/{Language}", "GET")]
[Authenticated]
2017-08-19 19:43:35 +00:00
public class SearchRemoteSubtitles : IReturn<RemoteSubtitleInfo[]>
2014-05-17 04:24:10 +00:00
{
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
2018-09-12 17:26:21 +00:00
public Guid Id { get; set; }
2014-05-17 04:24:10 +00:00
[ApiMember(Name = "Language", Description = "Language", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Language { get; set; }
public bool? IsPerfectMatch { get; set; }
2014-05-17 04:24:10 +00:00
}
[Route("/Items/{Id}/RemoteSearch/Subtitles/{SubtitleId}", "POST")]
[Authenticated]
2014-05-17 04:24:10 +00:00
public class DownloadRemoteSubtitles : IReturnVoid
{
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
2018-09-12 17:26:21 +00:00
public Guid Id { get; set; }
2014-05-17 04:24:10 +00:00
[ApiMember(Name = "SubtitleId", Description = "SubtitleId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public string SubtitleId { get; set; }
}
[Route("/Providers/Subtitles/Subtitles/{Id}", "GET")]
[Authenticated]
2014-05-17 04:24:10 +00:00
public class GetRemoteSubtitles : IReturnVoid
{
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get; set; }
}
[Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")]
[Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/{StartPositionTicks}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")]
public class GetSubtitle
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
2018-09-12 17:26:21 +00:00
public Guid Id { get; set; }
[ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string MediaSourceId { get; set; }
[ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
public int Index { get; set; }
[ApiMember(Name = "Format", Description = "Format", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Format { get; set; }
[ApiMember(Name = "StartPositionTicks", Description = "StartPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public long StartPositionTicks { get; set; }
[ApiMember(Name = "EndPositionTicks", Description = "EndPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public long? EndPositionTicks { get; set; }
2016-05-27 17:17:57 +00:00
[ApiMember(Name = "CopyTimestamps", Description = "CopyTimestamps", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool CopyTimestamps { get; set; }
2016-06-05 18:51:18 +00:00
public bool AddVttTimeMap { get; set; }
}
[Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/subtitles.m3u8", "GET", Summary = "Gets an HLS subtitle playlist.")]
2015-04-30 14:07:24 +00:00
[Authenticated]
public class GetSubtitlePlaylist
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get; set; }
[ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string MediaSourceId { get; set; }
[ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
public int Index { get; set; }
2018-09-12 17:26:21 +00:00
[ApiMember(Name = "SegmentLength", Description = "The subtitle srgment length", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")]
public int SegmentLength { get; set; }
}
2014-05-17 04:24:10 +00:00
public class SubtitleService : BaseApiService
{
private readonly ILibraryManager _libraryManager;
private readonly ISubtitleManager _subtitleManager;
private readonly ISubtitleEncoder _subtitleEncoder;
2015-03-07 22:43:53 +00:00
private readonly IMediaSourceManager _mediaSourceManager;
2015-03-14 04:50:23 +00:00
private readonly IProviderManager _providerManager;
2015-09-13 23:07:54 +00:00
private readonly IFileSystem _fileSystem;
2016-11-10 14:41:24 +00:00
private readonly IAuthorizationContext _authContext;
2014-05-17 04:24:10 +00:00
2016-11-10 14:41:24 +00:00
public SubtitleService(ILibraryManager libraryManager, ISubtitleManager subtitleManager, ISubtitleEncoder subtitleEncoder, IMediaSourceManager mediaSourceManager, IProviderManager providerManager, IFileSystem fileSystem, IAuthorizationContext authContext)
2014-05-17 04:24:10 +00:00
{
_libraryManager = libraryManager;
_subtitleManager = subtitleManager;
_subtitleEncoder = subtitleEncoder;
2015-03-07 22:43:53 +00:00
_mediaSourceManager = mediaSourceManager;
2015-03-14 04:50:23 +00:00
_providerManager = providerManager;
2015-09-13 23:07:54 +00:00
_fileSystem = fileSystem;
2016-11-10 14:41:24 +00:00
_authContext = authContext;
2014-05-17 04:24:10 +00:00
}
2015-04-09 05:20:23 +00:00
public async Task<object> Get(GetSubtitlePlaylist request)
{
var item = (Video)_libraryManager.GetItemById(new Guid(request.Id));
2016-09-18 20:38:38 +00:00
var mediaSource = await _mediaSourceManager.GetMediaSource(item, request.MediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
var builder = new StringBuilder();
var runtime = mediaSource.RunTimeTicks ?? -1;
if (runtime <= 0)
{
throw new ArgumentException("HLS Subtitles are not supported for this media.");
}
var segmentLengthTicks = TimeSpan.FromSeconds(request.SegmentLength).Ticks;
if (segmentLengthTicks <= 0)
{
throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)");
}
builder.AppendLine("#EXTM3U");
builder.AppendLine("#EXT-X-TARGETDURATION:" + request.SegmentLength.ToString(CultureInfo.InvariantCulture));
builder.AppendLine("#EXT-X-VERSION:3");
builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
2016-05-25 02:06:11 +00:00
builder.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
long positionTicks = 0;
2016-11-10 14:41:24 +00:00
var accessToken = _authContext.GetAuthorizationInfo(Request).Token;
2016-03-07 18:50:58 +00:00
while (positionTicks < runtime)
{
var remaining = runtime - positionTicks;
var lengthTicks = Math.Min(remaining, segmentLengthTicks);
2016-05-25 02:06:11 +00:00
builder.AppendLine("#EXTINF:" + TimeSpan.FromTicks(lengthTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture) + ",");
var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
2016-06-05 18:54:21 +00:00
var url = string.Format("stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}",
positionTicks.ToString(CultureInfo.InvariantCulture),
2016-03-07 18:50:58 +00:00
endPositionTicks.ToString(CultureInfo.InvariantCulture),
accessToken);
builder.AppendLine(url);
positionTicks += segmentLengthTicks;
}
builder.AppendLine("#EXT-X-ENDLIST");
2014-08-22 15:47:44 +00:00
2018-09-12 17:26:21 +00:00
return ResultFactory.GetResult(Request, builder.ToString(), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
}
2016-06-05 18:51:18 +00:00
public async Task<object> Get(GetSubtitle request)
2014-05-17 04:24:10 +00:00
{
2014-08-22 15:47:44 +00:00
if (string.Equals(request.Format, "js", StringComparison.OrdinalIgnoreCase))
{
request.Format = "json";
}
if (string.IsNullOrEmpty(request.Format))
2014-05-17 04:24:10 +00:00
{
2018-09-12 17:26:21 +00:00
var item = (Video)_libraryManager.GetItemById(request.Id);
2014-05-17 04:24:10 +00:00
2018-09-12 17:26:21 +00:00
var idString = request.Id.ToString("N");
2015-03-28 20:22:27 +00:00
var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false, null)
2018-09-12 17:26:21 +00:00
.First(i => string.Equals(i.Id, request.MediaSourceId ?? idString));
2014-05-17 04:24:10 +00:00
var subtitleStream = mediaSource.MediaStreams
.First(i => i.Type == MediaStreamType.Subtitle && i.Index == request.Index);
2014-05-17 04:24:10 +00:00
2016-06-19 06:18:29 +00:00
return await ResultFactory.GetStaticFileResult(Request, subtitleStream.Path).ConfigureAwait(false);
2014-05-17 04:24:10 +00:00
}
2016-10-31 20:00:26 +00:00
if (string.Equals(request.Format, "vtt", StringComparison.OrdinalIgnoreCase) && request.AddVttTimeMap)
2016-06-05 18:51:18 +00:00
{
2016-10-31 20:00:26 +00:00
using (var stream = await GetSubtitles(request).ConfigureAwait(false))
2016-06-05 18:51:18 +00:00
{
2016-10-31 19:38:13 +00:00
using (var reader = new StreamReader(stream))
2016-06-05 18:51:18 +00:00
{
2016-10-31 19:38:13 +00:00
var text = reader.ReadToEnd();
2016-06-06 21:13:00 +00:00
text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000");
2018-09-12 17:26:21 +00:00
return ResultFactory.GetResult(Request, text, MimeTypes.GetMimeType("file." + request.Format));
2016-10-31 19:38:13 +00:00
}
2016-06-05 18:51:18 +00:00
}
}
2016-10-31 20:00:26 +00:00
2018-09-12 17:26:21 +00:00
return ResultFactory.GetResult(Request, await GetSubtitles(request).ConfigureAwait(false), MimeTypes.GetMimeType("file." + request.Format));
}
2016-06-19 06:18:29 +00:00
private Task<Stream> GetSubtitles(GetSubtitle request)
{
2018-09-12 17:26:21 +00:00
var item = _libraryManager.GetItemById(request.Id);
return _subtitleEncoder.GetSubtitles(item,
request.MediaSourceId,
request.Index,
2014-06-11 19:31:33 +00:00
request.Format,
request.StartPositionTicks,
2018-09-12 17:26:21 +00:00
request.EndPositionTicks ?? 0,
2016-05-27 17:17:57 +00:00
request.CopyTimestamps,
2016-06-05 18:51:18 +00:00
CancellationToken.None);
2014-05-17 04:24:10 +00:00
}
public async Task<object> Get(SearchRemoteSubtitles request)
{
var video = (Video)_libraryManager.GetItemById(request.Id);
return await _subtitleManager.SearchSubtitles(video, request.Language, request.IsPerfectMatch, CancellationToken.None).ConfigureAwait(false);
2014-05-17 04:24:10 +00:00
}
2018-09-12 17:26:21 +00:00
public Task Delete(DeleteSubtitle request)
2014-05-17 04:24:10 +00:00
{
2018-09-12 17:26:21 +00:00
var item = _libraryManager.GetItemById(request.Id);
return _subtitleManager.DeleteSubtitles(item, request.Index);
2014-05-17 04:24:10 +00:00
}
2016-06-19 06:18:29 +00:00
public async Task<object> Get(GetRemoteSubtitles request)
2014-05-17 04:24:10 +00:00
{
2016-06-19 06:18:29 +00:00
var result = await _subtitleManager.GetRemoteSubtitles(request.Id, CancellationToken.None).ConfigureAwait(false);
2014-05-17 04:24:10 +00:00
2018-09-12 17:26:21 +00:00
return ResultFactory.GetResult(Request, result.Stream, MimeTypes.GetMimeType("file." + result.Format));
2014-05-17 04:24:10 +00:00
}
public void Post(DownloadRemoteSubtitles request)
{
var video = (Video)_libraryManager.GetItemById(request.Id);
Task.Run(async () =>
{
try
{
await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None)
.ConfigureAwait(false);
2018-12-14 19:17:29 +00:00
_providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(Logger, _fileSystem)), RefreshPriority.High);
2014-05-17 04:24:10 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
Logger.LogError(ex, "Error downloading subtitles");
2014-05-17 04:24:10 +00:00
}
});
}
}
}