jellyfin-server/Jellyfin.Api/Controllers/SubtitleController.cs

351 lines
16 KiB
C#
Raw Normal View History

2020-06-11 10:29:56 +00:00
using System;
using System.Collections.Generic;
2020-06-10 16:20:54 +00:00
using System.ComponentModel.DataAnnotations;
2020-06-19 14:49:42 +00:00
using System.Diagnostics.CodeAnalysis;
2020-06-10 16:20:54 +00:00
using System.Globalization;
using System.IO;
using System.Linq;
2020-06-11 10:29:56 +00:00
using System.Net.Mime;
2020-06-10 16:20:54 +00:00
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
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;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.Controllers
{
/// <summary>
/// Subtitle controller.
/// </summary>
2020-08-04 18:48:53 +00:00
[Route("")]
2020-06-10 16:20:54 +00:00
public class SubtitleController : BaseJellyfinApiController
{
private readonly ILibraryManager _libraryManager;
private readonly ISubtitleManager _subtitleManager;
private readonly ISubtitleEncoder _subtitleEncoder;
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IProviderManager _providerManager;
private readonly IFileSystem _fileSystem;
private readonly IAuthorizationContext _authContext;
private readonly ILogger<SubtitleController> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="SubtitleController"/> class.
/// </summary>
/// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
/// <param name="subtitleManager">Instance of <see cref="ISubtitleManager"/> interface.</param>
/// <param name="subtitleEncoder">Instance of <see cref="ISubtitleEncoder"/> interface.</param>
/// <param name="mediaSourceManager">Instance of <see cref="IMediaSourceManager"/> interface.</param>
/// <param name="providerManager">Instance of <see cref="IProviderManager"/> interface.</param>
/// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
/// <param name="authContext">Instance of <see cref="IAuthorizationContext"/> interface.</param>
/// <param name="logger">Instance of <see cref="ILogger{SubtitleController}"/> interface.</param>
public SubtitleController(
ILibraryManager libraryManager,
ISubtitleManager subtitleManager,
ISubtitleEncoder subtitleEncoder,
IMediaSourceManager mediaSourceManager,
IProviderManager providerManager,
IFileSystem fileSystem,
IAuthorizationContext authContext,
ILogger<SubtitleController> logger)
{
_libraryManager = libraryManager;
_subtitleManager = subtitleManager;
_subtitleEncoder = subtitleEncoder;
_mediaSourceManager = mediaSourceManager;
_providerManager = providerManager;
_fileSystem = fileSystem;
_authContext = authContext;
_logger = logger;
}
/// <summary>
/// Deletes an external subtitle file.
/// </summary>
/// <param name="itemId">The item id.</param>
2020-06-10 16:20:54 +00:00
/// <param name="index">The index of the subtitle file.</param>
/// <response code="204">Subtitle deleted.</response>
/// <response code="404">Item not found.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 18:48:53 +00:00
[HttpDelete("Videos/{itemId}/Subtitles/{index}")]
2020-06-10 16:20:54 +00:00
[Authorize(Policy = Policies.RequiresElevation)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<Task> DeleteSubtitle(
2020-09-05 23:07:25 +00:00
[FromRoute][Required] Guid itemId,
[FromRoute][Required] int index)
2020-06-10 16:20:54 +00:00
{
var item = _libraryManager.GetItemById(itemId);
2020-06-10 16:20:54 +00:00
if (item == null)
{
return NotFound();
}
_subtitleManager.DeleteSubtitles(item, index);
return NoContent();
}
/// <summary>
/// Search remote subtitles.
/// </summary>
/// <param name="itemId">The item id.</param>
2020-06-10 16:20:54 +00:00
/// <param name="language">The language of the subtitles.</param>
/// <param name="isPerfectMatch">Optional. Only show subtitles which are a perfect match.</param>
/// <response code="200">Subtitles retrieved.</response>
/// <returns>An array of <see cref="RemoteSubtitleInfo"/>.</returns>
2020-08-04 18:48:53 +00:00
[HttpGet("Items/{itemId}/RemoteSearch/Subtitles/{language}")]
2020-06-16 20:15:58 +00:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-10 16:20:54 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-11 10:29:56 +00:00
public async Task<ActionResult<IEnumerable<RemoteSubtitleInfo>>> SearchRemoteSubtitles(
2020-09-05 23:07:25 +00:00
[FromRoute][Required] Guid itemId,
2020-08-06 14:17:45 +00:00
[FromRoute, Required] string? language,
2020-06-11 10:29:56 +00:00
[FromQuery] bool? isPerfectMatch)
2020-06-10 16:20:54 +00:00
{
var video = (Video)_libraryManager.GetItemById(itemId);
2020-06-10 16:20:54 +00:00
return await _subtitleManager.SearchSubtitles(video, language, isPerfectMatch, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// Downloads a remote subtitle.
/// </summary>
/// <param name="itemId">The item id.</param>
2020-06-10 16:20:54 +00:00
/// <param name="subtitleId">The subtitle id.</param>
/// <response code="204">Subtitle downloaded.</response>
/// <returns>A <see cref="NoContentResult"/>.</returns>
2020-08-04 18:48:53 +00:00
[HttpPost("Items/{itemId}/RemoteSearch/Subtitles/{subtitleId}")]
2020-06-16 20:15:58 +00:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-10 16:20:54 +00:00
[ProducesResponseType(StatusCodes.Status204NoContent)]
2020-06-11 10:29:56 +00:00
public async Task<ActionResult> DownloadRemoteSubtitles(
2020-09-05 23:07:25 +00:00
[FromRoute][Required] Guid itemId,
2020-08-06 14:17:45 +00:00
[FromRoute, Required] string? subtitleId)
2020-06-10 16:20:54 +00:00
{
var video = (Video)_libraryManager.GetItemById(itemId);
2020-06-10 16:20:54 +00:00
2020-06-11 10:29:56 +00:00
try
{
await _subtitleManager.DownloadSubtitles(video, subtitleId, CancellationToken.None)
.ConfigureAwait(false);
_providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
}
catch (Exception ex)
2020-06-10 16:20:54 +00:00
{
2020-06-11 10:29:56 +00:00
_logger.LogError(ex, "Error downloading subtitles");
}
2020-06-10 16:20:54 +00:00
return NoContent();
}
/// <summary>
/// Gets the remote subtitles.
/// </summary>
/// <param name="id">The item id.</param>
/// <response code="200">File returned.</response>
/// <returns>A <see cref="FileStreamResult"/> with the subtitle file.</returns>
2020-08-04 18:48:53 +00:00
[HttpGet("Providers/Subtitles/Subtitles/{id}")]
2020-06-16 20:15:58 +00:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-10 16:20:54 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-11 10:29:56 +00:00
[Produces(MediaTypeNames.Application.Octet)]
2020-08-06 14:17:45 +00:00
public async Task<ActionResult> GetRemoteSubtitles([FromRoute, Required] string? id)
2020-06-10 16:20:54 +00:00
{
var result = await _subtitleManager.GetRemoteSubtitles(id, CancellationToken.None).ConfigureAwait(false);
return File(result.Stream, MimeTypes.GetMimeType("file." + result.Format));
}
/// <summary>
/// Gets subtitles in a specified format.
/// </summary>
/// <param name="itemId">The item id.</param>
2020-06-10 16:20:54 +00:00
/// <param name="mediaSourceId">The media source id.</param>
/// <param name="index">The subtitle stream index.</param>
/// <param name="format">The format of the returned subtitle.</param>
/// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
/// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
/// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
/// <param name="startPositionTicks">Optional. The start position of the subtitle in ticks.</param>
2020-06-10 16:20:54 +00:00
/// <response code="200">File returned.</response>
/// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
2020-08-04 18:48:53 +00:00
[HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{format}")]
[HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/{startPositionTicks?}/Stream.{format}", Name = "GetSubtitle_2")]
2020-06-10 16:20:54 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult> GetSubtitle(
[FromRoute, Required] Guid itemId,
2020-06-27 16:50:44 +00:00
[FromRoute, Required] string? mediaSourceId,
2020-06-10 16:20:54 +00:00
[FromRoute, Required] int index,
2020-06-27 16:50:44 +00:00
[FromRoute, Required] string? format,
2020-06-10 16:20:54 +00:00
[FromQuery] long? endPositionTicks,
[FromQuery] bool copyTimestamps = false,
[FromQuery] bool addVttTimeMap = false,
2020-09-05 23:07:25 +00:00
[FromRoute][Required] long startPositionTicks = 0)
2020-06-10 16:20:54 +00:00
{
if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase))
{
format = "json";
}
if (string.IsNullOrEmpty(format))
{
var item = (Video)_libraryManager.GetItemById(itemId);
2020-06-10 16:20:54 +00:00
var idString = itemId.ToString("N", CultureInfo.InvariantCulture);
2020-06-10 16:20:54 +00:00
var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false)
.First(i => string.Equals(i.Id, mediaSourceId ?? idString, StringComparison.Ordinal));
var subtitleStream = mediaSource.MediaStreams
.First(i => i.Type == MediaStreamType.Subtitle && i.Index == index);
FileStream stream = new FileStream(subtitleStream.Path, FileMode.Open, FileAccess.Read);
return File(stream, MimeTypes.GetMimeType(subtitleStream.Path));
}
if (string.Equals(format, "vtt", StringComparison.OrdinalIgnoreCase) && addVttTimeMap)
{
await using Stream stream = await EncodeSubtitles(itemId, mediaSourceId, index, format, startPositionTicks, endPositionTicks, copyTimestamps).ConfigureAwait(false);
2020-06-10 16:20:54 +00:00
using var reader = new StreamReader(stream);
2020-06-11 10:29:56 +00:00
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
2020-06-10 16:20:54 +00:00
text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000", StringComparison.Ordinal);
2020-06-11 10:29:56 +00:00
return File(Encoding.UTF8.GetBytes(text), MimeTypes.GetMimeType("file." + format));
2020-06-10 16:20:54 +00:00
}
return File(
await EncodeSubtitles(
itemId,
2020-06-10 16:20:54 +00:00
mediaSourceId,
index,
format,
startPositionTicks,
endPositionTicks,
copyTimestamps).ConfigureAwait(false),
MimeTypes.GetMimeType("file." + format));
}
/// <summary>
/// Gets an HLS subtitle playlist.
/// </summary>
/// <param name="itemId">The item id.</param>
2020-06-10 16:20:54 +00:00
/// <param name="index">The subtitle stream index.</param>
/// <param name="mediaSourceId">The media source id.</param>
/// <param name="segmentLength">The subtitle segment length.</param>
/// <response code="200">Subtitle playlist retrieved.</response>
/// <returns>A <see cref="FileContentResult"/> with the HLS subtitle playlist.</returns>
2020-08-04 18:48:53 +00:00
[HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/subtitles.m3u8")]
2020-06-16 20:15:58 +00:00
[Authorize(Policy = Policies.DefaultAuthorization)]
2020-06-10 16:20:54 +00:00
[ProducesResponseType(StatusCodes.Status200OK)]
2020-06-19 14:49:42 +00:00
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
2020-06-10 16:20:54 +00:00
public async Task<ActionResult> GetSubtitlePlaylist(
2020-09-05 23:07:25 +00:00
[FromRoute][Required] Guid itemId,
[FromRoute][Required] int index,
[FromRoute][Required] string? mediaSourceId,
2020-06-10 16:20:54 +00:00
[FromQuery, Required] int segmentLength)
{
var item = (Video)_libraryManager.GetItemById(itemId);
2020-06-10 16:20:54 +00:00
var mediaSource = await _mediaSourceManager.GetMediaSource(item, mediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
var runtime = mediaSource.RunTimeTicks ?? -1;
if (runtime <= 0)
{
throw new ArgumentException("HLS Subtitles are not supported for this media.");
}
var segmentLengthTicks = TimeSpan.FromSeconds(segmentLength).Ticks;
if (segmentLengthTicks <= 0)
{
throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)");
}
2020-08-05 02:30:45 +00:00
var builder = new StringBuilder();
2020-08-03 18:01:24 +00:00
builder.AppendLine("#EXTM3U")
.Append("#EXT-X-TARGETDURATION:")
.AppendLine(segmentLength.ToString(CultureInfo.InvariantCulture))
.AppendLine("#EXT-X-VERSION:3")
.AppendLine("#EXT-X-MEDIA-SEQUENCE:0")
.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
2020-06-10 16:20:54 +00:00
long positionTicks = 0;
var accessToken = _authContext.GetAuthorizationInfo(Request).Token;
while (positionTicks < runtime)
{
var remaining = runtime - positionTicks;
var lengthTicks = Math.Min(remaining, segmentLengthTicks);
2020-08-03 18:01:24 +00:00
builder.Append("#EXTINF:")
.Append(TimeSpan.FromTicks(lengthTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture))
.AppendLine(",");
2020-06-10 16:20:54 +00:00
var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
var url = string.Format(
CultureInfo.CurrentCulture,
"stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}",
positionTicks.ToString(CultureInfo.InvariantCulture),
endPositionTicks.ToString(CultureInfo.InvariantCulture),
accessToken);
builder.AppendLine(url);
positionTicks += segmentLengthTicks;
}
builder.AppendLine("#EXT-X-ENDLIST");
2020-06-11 10:29:56 +00:00
return File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
2020-06-10 16:20:54 +00:00
}
/// <summary>
/// Encodes a subtitle in the specified format.
/// </summary>
/// <param name="id">The media id.</param>
/// <param name="mediaSourceId">The source media id.</param>
/// <param name="index">The subtitle index.</param>
/// <param name="format">The format to convert to.</param>
/// <param name="startPositionTicks">The start position in ticks.</param>
/// <param name="endPositionTicks">The end position in ticks.</param>
/// <param name="copyTimestamps">Whether to copy the timestamps.</param>
/// <returns>A <see cref="Task{Stream}"/> with the new subtitle file.</returns>
private Task<Stream> EncodeSubtitles(
Guid id,
2020-06-27 16:50:44 +00:00
string? mediaSourceId,
2020-06-10 16:20:54 +00:00
int index,
string format,
long startPositionTicks,
long? endPositionTicks,
bool copyTimestamps)
{
var item = _libraryManager.GetItemById(id);
return _subtitleEncoder.GetSubtitles(
item,
mediaSourceId,
index,
format,
startPositionTicks,
endPositionTicks ?? 0,
copyTimestamps,
CancellationToken.None);
}
}
}