SubtitleService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.MediaEncoding;
  14. using MediaBrowser.Controller.Net;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Controller.Subtitles;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Providers;
  20. using MediaBrowser.Model.Services;
  21. using Microsoft.Extensions.Logging;
  22. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  23. namespace MediaBrowser.Api.Subtitles
  24. {
  25. [Route("/Videos/{Id}/Subtitles/{Index}", "DELETE", Summary = "Deletes an external subtitle file")]
  26. [Authenticated(Roles = "Admin")]
  27. public class DeleteSubtitle
  28. {
  29. /// <summary>
  30. /// Gets or sets the id.
  31. /// </summary>
  32. /// <value>The id.</value>
  33. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
  34. public Guid Id { get; set; }
  35. [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "DELETE")]
  36. public int Index { get; set; }
  37. }
  38. [Route("/Items/{Id}/RemoteSearch/Subtitles/{Language}", "GET")]
  39. [Authenticated]
  40. public class SearchRemoteSubtitles : IReturn<RemoteSubtitleInfo[]>
  41. {
  42. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  43. public Guid Id { get; set; }
  44. [ApiMember(Name = "Language", Description = "Language", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  45. public string Language { get; set; }
  46. public bool? IsPerfectMatch { get; set; }
  47. }
  48. [Route("/Items/{Id}/RemoteSearch/Subtitles/{SubtitleId}", "POST")]
  49. [Authenticated]
  50. public class DownloadRemoteSubtitles : IReturnVoid
  51. {
  52. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  53. public Guid Id { get; set; }
  54. [ApiMember(Name = "SubtitleId", Description = "SubtitleId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  55. public string SubtitleId { get; set; }
  56. }
  57. [Route("/Providers/Subtitles/Subtitles/{Id}", "GET")]
  58. [Authenticated]
  59. public class GetRemoteSubtitles : IReturnVoid
  60. {
  61. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  62. public string Id { get; set; }
  63. }
  64. [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")]
  65. [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/{StartPositionTicks}/Stream.{Format}", "GET", Summary = "Gets subtitles in a specified format.")]
  66. public class GetSubtitle
  67. {
  68. /// <summary>
  69. /// Gets or sets the id.
  70. /// </summary>
  71. /// <value>The id.</value>
  72. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  73. public Guid Id { get; set; }
  74. [ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  75. public string MediaSourceId { get; set; }
  76. [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
  77. public int Index { get; set; }
  78. [ApiMember(Name = "Format", Description = "Format", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  79. public string Format { get; set; }
  80. [ApiMember(Name = "StartPositionTicks", Description = "StartPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  81. public long StartPositionTicks { get; set; }
  82. [ApiMember(Name = "EndPositionTicks", Description = "EndPositionTicks", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  83. public long? EndPositionTicks { get; set; }
  84. [ApiMember(Name = "CopyTimestamps", Description = "CopyTimestamps", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  85. public bool CopyTimestamps { get; set; }
  86. public bool AddVttTimeMap { get; set; }
  87. }
  88. [Route("/Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/subtitles.m3u8", "GET", Summary = "Gets an HLS subtitle playlist.")]
  89. [Authenticated]
  90. public class GetSubtitlePlaylist
  91. {
  92. /// <summary>
  93. /// Gets or sets the id.
  94. /// </summary>
  95. /// <value>The id.</value>
  96. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  97. public string Id { get; set; }
  98. [ApiMember(Name = "MediaSourceId", Description = "MediaSourceId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  99. public string MediaSourceId { get; set; }
  100. [ApiMember(Name = "Index", Description = "The subtitle stream index", IsRequired = true, DataType = "int", ParameterType = "path", Verb = "GET")]
  101. public int Index { get; set; }
  102. [ApiMember(Name = "SegmentLength", Description = "The subtitle srgment length", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")]
  103. public int SegmentLength { get; set; }
  104. }
  105. [Route("/FallbackFont/Font", "GET", Summary = "Gets the fallback font file")]
  106. [Authenticated]
  107. public class GetFallbackFont
  108. {
  109. }
  110. public class SubtitleService : BaseApiService
  111. {
  112. private readonly IServerConfigurationManager _serverConfigurationManager;
  113. private readonly ILibraryManager _libraryManager;
  114. private readonly ISubtitleManager _subtitleManager;
  115. private readonly ISubtitleEncoder _subtitleEncoder;
  116. private readonly IMediaSourceManager _mediaSourceManager;
  117. private readonly IProviderManager _providerManager;
  118. private readonly IFileSystem _fileSystem;
  119. private readonly IAuthorizationContext _authContext;
  120. public SubtitleService(
  121. ILogger<SubtitleService> logger,
  122. IServerConfigurationManager serverConfigurationManager,
  123. IHttpResultFactory httpResultFactory,
  124. ILibraryManager libraryManager,
  125. ISubtitleManager subtitleManager,
  126. ISubtitleEncoder subtitleEncoder,
  127. IMediaSourceManager mediaSourceManager,
  128. IProviderManager providerManager,
  129. IFileSystem fileSystem,
  130. IAuthorizationContext authContext)
  131. : base(logger, serverConfigurationManager, httpResultFactory)
  132. {
  133. _serverConfigurationManager = serverConfigurationManager;
  134. _libraryManager = libraryManager;
  135. _subtitleManager = subtitleManager;
  136. _subtitleEncoder = subtitleEncoder;
  137. _mediaSourceManager = mediaSourceManager;
  138. _providerManager = providerManager;
  139. _fileSystem = fileSystem;
  140. _authContext = authContext;
  141. }
  142. public async Task<object> Get(GetSubtitlePlaylist request)
  143. {
  144. var item = (Video)_libraryManager.GetItemById(new Guid(request.Id));
  145. var mediaSource = await _mediaSourceManager.GetMediaSource(item, request.MediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
  146. var builder = new StringBuilder();
  147. var runtime = mediaSource.RunTimeTicks ?? -1;
  148. if (runtime <= 0)
  149. {
  150. throw new ArgumentException("HLS Subtitles are not supported for this media.");
  151. }
  152. var segmentLengthTicks = TimeSpan.FromSeconds(request.SegmentLength).Ticks;
  153. if (segmentLengthTicks <= 0)
  154. {
  155. throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)");
  156. }
  157. builder.AppendLine("#EXTM3U");
  158. builder.AppendLine("#EXT-X-TARGETDURATION:" + request.SegmentLength.ToString(CultureInfo.InvariantCulture));
  159. builder.AppendLine("#EXT-X-VERSION:3");
  160. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  161. builder.AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
  162. long positionTicks = 0;
  163. var accessToken = _authContext.GetAuthorizationInfo(Request).Token;
  164. while (positionTicks < runtime)
  165. {
  166. var remaining = runtime - positionTicks;
  167. var lengthTicks = Math.Min(remaining, segmentLengthTicks);
  168. builder.AppendLine("#EXTINF:" + TimeSpan.FromTicks(lengthTicks).TotalSeconds.ToString(CultureInfo.InvariantCulture) + ",");
  169. var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
  170. var url = string.Format("stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}",
  171. positionTicks.ToString(CultureInfo.InvariantCulture),
  172. endPositionTicks.ToString(CultureInfo.InvariantCulture),
  173. accessToken);
  174. builder.AppendLine(url);
  175. positionTicks += segmentLengthTicks;
  176. }
  177. builder.AppendLine("#EXT-X-ENDLIST");
  178. return ResultFactory.GetResult(Request, builder.ToString(), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  179. }
  180. public async Task<object> Get(GetSubtitle request)
  181. {
  182. if (string.Equals(request.Format, "js", StringComparison.OrdinalIgnoreCase))
  183. {
  184. request.Format = "json";
  185. }
  186. if (string.IsNullOrEmpty(request.Format))
  187. {
  188. var item = (Video)_libraryManager.GetItemById(request.Id);
  189. var idString = request.Id.ToString("N", CultureInfo.InvariantCulture);
  190. var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false, null)
  191. .First(i => string.Equals(i.Id, request.MediaSourceId ?? idString));
  192. var subtitleStream = mediaSource.MediaStreams
  193. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == request.Index);
  194. return await ResultFactory.GetStaticFileResult(Request, subtitleStream.Path).ConfigureAwait(false);
  195. }
  196. if (string.Equals(request.Format, "vtt", StringComparison.OrdinalIgnoreCase) && request.AddVttTimeMap)
  197. {
  198. using var stream = await GetSubtitles(request).ConfigureAwait(false);
  199. using var reader = new StreamReader(stream);
  200. var text = reader.ReadToEnd();
  201. text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000");
  202. return ResultFactory.GetResult(Request, text, MimeTypes.GetMimeType("file." + request.Format));
  203. }
  204. return ResultFactory.GetResult(Request, await GetSubtitles(request).ConfigureAwait(false), MimeTypes.GetMimeType("file." + request.Format));
  205. }
  206. private Task<Stream> GetSubtitles(GetSubtitle request)
  207. {
  208. var item = _libraryManager.GetItemById(request.Id);
  209. return _subtitleEncoder.GetSubtitles(item,
  210. request.MediaSourceId,
  211. request.Index,
  212. request.Format,
  213. request.StartPositionTicks,
  214. request.EndPositionTicks ?? 0,
  215. request.CopyTimestamps,
  216. CancellationToken.None);
  217. }
  218. public async Task<object> Get(SearchRemoteSubtitles request)
  219. {
  220. var video = (Video)_libraryManager.GetItemById(request.Id);
  221. return await _subtitleManager.SearchSubtitles(video, request.Language, request.IsPerfectMatch, CancellationToken.None).ConfigureAwait(false);
  222. }
  223. public Task Delete(DeleteSubtitle request)
  224. {
  225. var item = _libraryManager.GetItemById(request.Id);
  226. return _subtitleManager.DeleteSubtitles(item, request.Index);
  227. }
  228. public async Task<object> Get(GetRemoteSubtitles request)
  229. {
  230. var result = await _subtitleManager.GetRemoteSubtitles(request.Id, CancellationToken.None).ConfigureAwait(false);
  231. return ResultFactory.GetResult(Request, result.Stream, MimeTypes.GetMimeType("file." + result.Format));
  232. }
  233. public void Post(DownloadRemoteSubtitles request)
  234. {
  235. var video = (Video)_libraryManager.GetItemById(request.Id);
  236. Task.Run(async () =>
  237. {
  238. try
  239. {
  240. await _subtitleManager.DownloadSubtitles(video, request.SubtitleId, CancellationToken.None)
  241. .ConfigureAwait(false);
  242. _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  243. }
  244. catch (Exception ex)
  245. {
  246. Logger.LogError(ex, "Error downloading subtitles");
  247. }
  248. });
  249. }
  250. public async Task<object> Get(GetFallbackFont request)
  251. {
  252. var fallbackFontPath = EncodingConfigurationExtensions.GetEncodingOptions(_serverConfigurationManager).FallbackFontPath;
  253. if (!string.IsNullOrEmpty(fallbackFontPath))
  254. {
  255. var directoryService = new DirectoryService(_fileSystem);
  256. try
  257. {
  258. // 10 Megabytes
  259. var maxSize = 10485760;
  260. var fontFile = directoryService.GetFile(fallbackFontPath);
  261. var fileSize = fontFile?.Length;
  262. if (fileSize != null && fileSize > 0)
  263. {
  264. Logger.LogDebug("Fallback font size is {0} Bytes", fileSize);
  265. if (fileSize <= maxSize)
  266. {
  267. return await ResultFactory.GetStaticFileResult(Request, fontFile.FullName);
  268. }
  269. Logger.LogWarning("The selected font is too large. Maximum allowed size is 10 Megabytes");
  270. }
  271. else
  272. {
  273. Logger.LogWarning("The selected font is null or empty");
  274. }
  275. }
  276. catch (Exception ex)
  277. {
  278. Logger.LogError(ex, "Error reading fallback font file");
  279. }
  280. }
  281. else
  282. {
  283. Logger.LogWarning("The path of fallback font has not been set");
  284. }
  285. return string.Empty;
  286. }
  287. }
  288. }