SubtitleController.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Mime;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Jellyfin.Api.Attributes;
  13. using Jellyfin.Api.Constants;
  14. using Jellyfin.Api.Extensions;
  15. using Jellyfin.Api.Models.SubtitleDtos;
  16. using MediaBrowser.Common.Configuration;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.Entities;
  19. using MediaBrowser.Controller.Library;
  20. using MediaBrowser.Controller.MediaEncoding;
  21. using MediaBrowser.Controller.Providers;
  22. using MediaBrowser.Controller.Subtitles;
  23. using MediaBrowser.Model.Entities;
  24. using MediaBrowser.Model.IO;
  25. using MediaBrowser.Model.Net;
  26. using MediaBrowser.Model.Providers;
  27. using MediaBrowser.Model.Subtitles;
  28. using Microsoft.AspNetCore.Authorization;
  29. using Microsoft.AspNetCore.Http;
  30. using Microsoft.AspNetCore.Mvc;
  31. using Microsoft.Extensions.Logging;
  32. namespace Jellyfin.Api.Controllers;
  33. /// <summary>
  34. /// Subtitle controller.
  35. /// </summary>
  36. [Route("")]
  37. public class SubtitleController : BaseJellyfinApiController
  38. {
  39. private readonly IServerConfigurationManager _serverConfigurationManager;
  40. private readonly ILibraryManager _libraryManager;
  41. private readonly ISubtitleManager _subtitleManager;
  42. private readonly ISubtitleEncoder _subtitleEncoder;
  43. private readonly IMediaSourceManager _mediaSourceManager;
  44. private readonly IProviderManager _providerManager;
  45. private readonly IFileSystem _fileSystem;
  46. private readonly ILogger<SubtitleController> _logger;
  47. /// <summary>
  48. /// Initializes a new instance of the <see cref="SubtitleController"/> class.
  49. /// </summary>
  50. /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
  51. /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
  52. /// <param name="subtitleManager">Instance of <see cref="ISubtitleManager"/> interface.</param>
  53. /// <param name="subtitleEncoder">Instance of <see cref="ISubtitleEncoder"/> interface.</param>
  54. /// <param name="mediaSourceManager">Instance of <see cref="IMediaSourceManager"/> interface.</param>
  55. /// <param name="providerManager">Instance of <see cref="IProviderManager"/> interface.</param>
  56. /// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
  57. /// <param name="logger">Instance of <see cref="ILogger{SubtitleController}"/> interface.</param>
  58. public SubtitleController(
  59. IServerConfigurationManager serverConfigurationManager,
  60. ILibraryManager libraryManager,
  61. ISubtitleManager subtitleManager,
  62. ISubtitleEncoder subtitleEncoder,
  63. IMediaSourceManager mediaSourceManager,
  64. IProviderManager providerManager,
  65. IFileSystem fileSystem,
  66. ILogger<SubtitleController> logger)
  67. {
  68. _serverConfigurationManager = serverConfigurationManager;
  69. _libraryManager = libraryManager;
  70. _subtitleManager = subtitleManager;
  71. _subtitleEncoder = subtitleEncoder;
  72. _mediaSourceManager = mediaSourceManager;
  73. _providerManager = providerManager;
  74. _fileSystem = fileSystem;
  75. _logger = logger;
  76. }
  77. /// <summary>
  78. /// Deletes an external subtitle file.
  79. /// </summary>
  80. /// <param name="itemId">The item id.</param>
  81. /// <param name="index">The index of the subtitle file.</param>
  82. /// <response code="204">Subtitle deleted.</response>
  83. /// <response code="404">Item not found.</response>
  84. /// <returns>A <see cref="NoContentResult"/>.</returns>
  85. [HttpDelete("Videos/{itemId}/Subtitles/{index}")]
  86. [Authorize(Policy = Policies.RequiresElevation)]
  87. [ProducesResponseType(StatusCodes.Status204NoContent)]
  88. [ProducesResponseType(StatusCodes.Status404NotFound)]
  89. public ActionResult<Task> DeleteSubtitle(
  90. [FromRoute, Required] Guid itemId,
  91. [FromRoute, Required] int index)
  92. {
  93. var item = _libraryManager.GetItemById(itemId);
  94. if (item is null)
  95. {
  96. return NotFound();
  97. }
  98. _subtitleManager.DeleteSubtitles(item, index);
  99. return NoContent();
  100. }
  101. /// <summary>
  102. /// Search remote subtitles.
  103. /// </summary>
  104. /// <param name="itemId">The item id.</param>
  105. /// <param name="language">The language of the subtitles.</param>
  106. /// <param name="isPerfectMatch">Optional. Only show subtitles which are a perfect match.</param>
  107. /// <response code="200">Subtitles retrieved.</response>
  108. /// <returns>An array of <see cref="RemoteSubtitleInfo"/>.</returns>
  109. [HttpGet("Items/{itemId}/RemoteSearch/Subtitles/{language}")]
  110. [Authorize(Policy = Policies.DefaultAuthorization)]
  111. [ProducesResponseType(StatusCodes.Status200OK)]
  112. public async Task<ActionResult<IEnumerable<RemoteSubtitleInfo>>> SearchRemoteSubtitles(
  113. [FromRoute, Required] Guid itemId,
  114. [FromRoute, Required] string language,
  115. [FromQuery] bool? isPerfectMatch)
  116. {
  117. var video = (Video)_libraryManager.GetItemById(itemId);
  118. return await _subtitleManager.SearchSubtitles(video, language, isPerfectMatch, false, CancellationToken.None).ConfigureAwait(false);
  119. }
  120. /// <summary>
  121. /// Downloads a remote subtitle.
  122. /// </summary>
  123. /// <param name="itemId">The item id.</param>
  124. /// <param name="subtitleId">The subtitle id.</param>
  125. /// <response code="204">Subtitle downloaded.</response>
  126. /// <returns>A <see cref="NoContentResult"/>.</returns>
  127. [HttpPost("Items/{itemId}/RemoteSearch/Subtitles/{subtitleId}")]
  128. [Authorize(Policy = Policies.DefaultAuthorization)]
  129. [ProducesResponseType(StatusCodes.Status204NoContent)]
  130. public async Task<ActionResult> DownloadRemoteSubtitles(
  131. [FromRoute, Required] Guid itemId,
  132. [FromRoute, Required] string subtitleId)
  133. {
  134. var video = (Video)_libraryManager.GetItemById(itemId);
  135. try
  136. {
  137. await _subtitleManager.DownloadSubtitles(video, subtitleId, CancellationToken.None)
  138. .ConfigureAwait(false);
  139. _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  140. }
  141. catch (Exception ex)
  142. {
  143. _logger.LogError(ex, "Error downloading subtitles");
  144. }
  145. return NoContent();
  146. }
  147. /// <summary>
  148. /// Gets the remote subtitles.
  149. /// </summary>
  150. /// <param name="id">The item id.</param>
  151. /// <response code="200">File returned.</response>
  152. /// <returns>A <see cref="FileStreamResult"/> with the subtitle file.</returns>
  153. [HttpGet("Providers/Subtitles/Subtitles/{id}")]
  154. [Authorize(Policy = Policies.DefaultAuthorization)]
  155. [ProducesResponseType(StatusCodes.Status200OK)]
  156. [Produces(MediaTypeNames.Application.Octet)]
  157. [ProducesFile("text/*")]
  158. public async Task<ActionResult> GetRemoteSubtitles([FromRoute, Required] string id)
  159. {
  160. var result = await _subtitleManager.GetRemoteSubtitles(id, CancellationToken.None).ConfigureAwait(false);
  161. return File(result.Stream, MimeTypes.GetMimeType("file." + result.Format));
  162. }
  163. /// <summary>
  164. /// Gets subtitles in a specified format.
  165. /// </summary>
  166. /// <param name="routeItemId">The (route) item id.</param>
  167. /// <param name="routeMediaSourceId">The (route) media source id.</param>
  168. /// <param name="routeIndex">The (route) subtitle stream index.</param>
  169. /// <param name="routeFormat">The (route) format of the returned subtitle.</param>
  170. /// <param name="itemId">The item id.</param>
  171. /// <param name="mediaSourceId">The media source id.</param>
  172. /// <param name="index">The subtitle stream index.</param>
  173. /// <param name="format">The format of the returned subtitle.</param>
  174. /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
  175. /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
  176. /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
  177. /// <param name="startPositionTicks">The start position of the subtitle in ticks.</param>
  178. /// <response code="200">File returned.</response>
  179. /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
  180. [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/Stream.{routeFormat}")]
  181. [ProducesResponseType(StatusCodes.Status200OK)]
  182. [ProducesFile("text/*")]
  183. public async Task<ActionResult> GetSubtitle(
  184. [FromRoute, Required] Guid routeItemId,
  185. [FromRoute, Required] string routeMediaSourceId,
  186. [FromRoute, Required] int routeIndex,
  187. [FromRoute, Required] string routeFormat,
  188. [FromQuery, ParameterObsolete] Guid? itemId,
  189. [FromQuery, ParameterObsolete] string? mediaSourceId,
  190. [FromQuery, ParameterObsolete] int? index,
  191. [FromQuery, ParameterObsolete] string? format,
  192. [FromQuery] long? endPositionTicks,
  193. [FromQuery] bool copyTimestamps = false,
  194. [FromQuery] bool addVttTimeMap = false,
  195. [FromQuery] long startPositionTicks = 0)
  196. {
  197. // Set parameters to route value if not provided via query.
  198. itemId ??= routeItemId;
  199. mediaSourceId ??= routeMediaSourceId;
  200. index ??= routeIndex;
  201. format ??= routeFormat;
  202. if (string.Equals(format, "js", StringComparison.OrdinalIgnoreCase))
  203. {
  204. format = "json";
  205. }
  206. if (string.IsNullOrEmpty(format))
  207. {
  208. var item = (Video)_libraryManager.GetItemById(itemId.Value);
  209. var idString = itemId.Value.ToString("N", CultureInfo.InvariantCulture);
  210. var mediaSource = _mediaSourceManager.GetStaticMediaSources(item, false)
  211. .First(i => string.Equals(i.Id, mediaSourceId ?? idString, StringComparison.Ordinal));
  212. var subtitleStream = mediaSource.MediaStreams
  213. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == index);
  214. return PhysicalFile(subtitleStream.Path, MimeTypes.GetMimeType(subtitleStream.Path));
  215. }
  216. if (string.Equals(format, "vtt", StringComparison.OrdinalIgnoreCase) && addVttTimeMap)
  217. {
  218. Stream stream = await EncodeSubtitles(itemId.Value, mediaSourceId, index.Value, format, startPositionTicks, endPositionTicks, copyTimestamps).ConfigureAwait(false);
  219. await using (stream.ConfigureAwait(false))
  220. {
  221. using var reader = new StreamReader(stream);
  222. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  223. text = text.Replace("WEBVTT", "WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000", StringComparison.Ordinal);
  224. return File(Encoding.UTF8.GetBytes(text), MimeTypes.GetMimeType("file." + format));
  225. }
  226. }
  227. return File(
  228. await EncodeSubtitles(
  229. itemId.Value,
  230. mediaSourceId,
  231. index.Value,
  232. format,
  233. startPositionTicks,
  234. endPositionTicks,
  235. copyTimestamps).ConfigureAwait(false),
  236. MimeTypes.GetMimeType("file." + format));
  237. }
  238. /// <summary>
  239. /// Gets subtitles in a specified format.
  240. /// </summary>
  241. /// <param name="routeItemId">The (route) item id.</param>
  242. /// <param name="routeMediaSourceId">The (route) media source id.</param>
  243. /// <param name="routeIndex">The (route) subtitle stream index.</param>
  244. /// <param name="routeStartPositionTicks">The (route) start position of the subtitle in ticks.</param>
  245. /// <param name="routeFormat">The (route) format of the returned subtitle.</param>
  246. /// <param name="itemId">The item id.</param>
  247. /// <param name="mediaSourceId">The media source id.</param>
  248. /// <param name="index">The subtitle stream index.</param>
  249. /// <param name="startPositionTicks">The start position of the subtitle in ticks.</param>
  250. /// <param name="format">The format of the returned subtitle.</param>
  251. /// <param name="endPositionTicks">Optional. The end position of the subtitle in ticks.</param>
  252. /// <param name="copyTimestamps">Optional. Whether to copy the timestamps.</param>
  253. /// <param name="addVttTimeMap">Optional. Whether to add a VTT time map.</param>
  254. /// <response code="200">File returned.</response>
  255. /// <returns>A <see cref="FileContentResult"/> with the subtitle file.</returns>
  256. [HttpGet("Videos/{routeItemId}/{routeMediaSourceId}/Subtitles/{routeIndex}/{routeStartPositionTicks}/Stream.{routeFormat}")]
  257. [ProducesResponseType(StatusCodes.Status200OK)]
  258. [ProducesFile("text/*")]
  259. public Task<ActionResult> GetSubtitleWithTicks(
  260. [FromRoute, Required] Guid routeItemId,
  261. [FromRoute, Required] string routeMediaSourceId,
  262. [FromRoute, Required] int routeIndex,
  263. [FromRoute, Required] long routeStartPositionTicks,
  264. [FromRoute, Required] string routeFormat,
  265. [FromQuery, ParameterObsolete] Guid? itemId,
  266. [FromQuery, ParameterObsolete] string? mediaSourceId,
  267. [FromQuery, ParameterObsolete] int? index,
  268. [FromQuery, ParameterObsolete] long? startPositionTicks,
  269. [FromQuery, ParameterObsolete] string? format,
  270. [FromQuery] long? endPositionTicks,
  271. [FromQuery] bool copyTimestamps = false,
  272. [FromQuery] bool addVttTimeMap = false)
  273. {
  274. return GetSubtitle(
  275. routeItemId,
  276. routeMediaSourceId,
  277. routeIndex,
  278. routeFormat,
  279. itemId,
  280. mediaSourceId,
  281. index,
  282. format,
  283. endPositionTicks,
  284. copyTimestamps,
  285. addVttTimeMap,
  286. startPositionTicks ?? routeStartPositionTicks);
  287. }
  288. /// <summary>
  289. /// Gets an HLS subtitle playlist.
  290. /// </summary>
  291. /// <param name="itemId">The item id.</param>
  292. /// <param name="index">The subtitle stream index.</param>
  293. /// <param name="mediaSourceId">The media source id.</param>
  294. /// <param name="segmentLength">The subtitle segment length.</param>
  295. /// <response code="200">Subtitle playlist retrieved.</response>
  296. /// <returns>A <see cref="FileContentResult"/> with the HLS subtitle playlist.</returns>
  297. [HttpGet("Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/subtitles.m3u8")]
  298. [Authorize(Policy = Policies.DefaultAuthorization)]
  299. [ProducesResponseType(StatusCodes.Status200OK)]
  300. [ProducesPlaylistFile]
  301. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "index", Justification = "Imported from ServiceStack")]
  302. public async Task<ActionResult> GetSubtitlePlaylist(
  303. [FromRoute, Required] Guid itemId,
  304. [FromRoute, Required] int index,
  305. [FromRoute, Required] string mediaSourceId,
  306. [FromQuery, Required] int segmentLength)
  307. {
  308. var item = (Video)_libraryManager.GetItemById(itemId);
  309. var mediaSource = await _mediaSourceManager.GetMediaSource(item, mediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false);
  310. var runtime = mediaSource.RunTimeTicks ?? -1;
  311. if (runtime <= 0)
  312. {
  313. throw new ArgumentException("HLS Subtitles are not supported for this media.");
  314. }
  315. var segmentLengthTicks = TimeSpan.FromSeconds(segmentLength).Ticks;
  316. if (segmentLengthTicks <= 0)
  317. {
  318. throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)");
  319. }
  320. var builder = new StringBuilder();
  321. builder.AppendLine("#EXTM3U")
  322. .Append("#EXT-X-TARGETDURATION:")
  323. .Append(segmentLength)
  324. .AppendLine()
  325. .AppendLine("#EXT-X-VERSION:3")
  326. .AppendLine("#EXT-X-MEDIA-SEQUENCE:0")
  327. .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD");
  328. long positionTicks = 0;
  329. var accessToken = User.GetToken();
  330. while (positionTicks < runtime)
  331. {
  332. var remaining = runtime - positionTicks;
  333. var lengthTicks = Math.Min(remaining, segmentLengthTicks);
  334. builder.Append("#EXTINF:")
  335. .Append(TimeSpan.FromTicks(lengthTicks).TotalSeconds)
  336. .Append(',')
  337. .AppendLine();
  338. var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks);
  339. var url = string.Format(
  340. CultureInfo.InvariantCulture,
  341. "stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}",
  342. positionTicks.ToString(CultureInfo.InvariantCulture),
  343. endPositionTicks.ToString(CultureInfo.InvariantCulture),
  344. accessToken);
  345. builder.AppendLine(url);
  346. positionTicks += segmentLengthTicks;
  347. }
  348. builder.AppendLine("#EXT-X-ENDLIST");
  349. return File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
  350. }
  351. /// <summary>
  352. /// Upload an external subtitle file.
  353. /// </summary>
  354. /// <param name="itemId">The item the subtitle belongs to.</param>
  355. /// <param name="body">The request body.</param>
  356. /// <response code="204">Subtitle uploaded.</response>
  357. /// <returns>A <see cref="NoContentResult"/>.</returns>
  358. [HttpPost("Videos/{itemId}/Subtitles")]
  359. [Authorize(Policy = Policies.RequiresElevation)]
  360. [ProducesResponseType(StatusCodes.Status204NoContent)]
  361. public async Task<ActionResult> UploadSubtitle(
  362. [FromRoute, Required] Guid itemId,
  363. [FromBody, Required] UploadSubtitleDto body)
  364. {
  365. var video = (Video)_libraryManager.GetItemById(itemId);
  366. var data = Convert.FromBase64String(body.Data);
  367. var memoryStream = new MemoryStream(data, 0, data.Length, false, true);
  368. await using (memoryStream.ConfigureAwait(false))
  369. {
  370. await _subtitleManager.UploadSubtitle(
  371. video,
  372. new SubtitleResponse
  373. {
  374. Format = body.Format,
  375. Language = body.Language,
  376. IsForced = body.IsForced,
  377. Stream = memoryStream
  378. }).ConfigureAwait(false);
  379. _providerManager.QueueRefresh(video.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  380. return NoContent();
  381. }
  382. }
  383. /// <summary>
  384. /// Encodes a subtitle in the specified format.
  385. /// </summary>
  386. /// <param name="id">The media id.</param>
  387. /// <param name="mediaSourceId">The source media id.</param>
  388. /// <param name="index">The subtitle index.</param>
  389. /// <param name="format">The format to convert to.</param>
  390. /// <param name="startPositionTicks">The start position in ticks.</param>
  391. /// <param name="endPositionTicks">The end position in ticks.</param>
  392. /// <param name="copyTimestamps">Whether to copy the timestamps.</param>
  393. /// <returns>A <see cref="Task{Stream}"/> with the new subtitle file.</returns>
  394. private Task<Stream> EncodeSubtitles(
  395. Guid id,
  396. string? mediaSourceId,
  397. int index,
  398. string format,
  399. long startPositionTicks,
  400. long? endPositionTicks,
  401. bool copyTimestamps)
  402. {
  403. var item = _libraryManager.GetItemById(id);
  404. return _subtitleEncoder.GetSubtitles(
  405. item,
  406. mediaSourceId,
  407. index,
  408. format,
  409. startPositionTicks,
  410. endPositionTicks ?? 0,
  411. copyTimestamps,
  412. CancellationToken.None);
  413. }
  414. /// <summary>
  415. /// Gets a list of available fallback font files.
  416. /// </summary>
  417. /// <response code="200">Information retrieved.</response>
  418. /// <returns>An array of <see cref="FontFile"/> with the available font files.</returns>
  419. [HttpGet("FallbackFont/Fonts")]
  420. [Authorize(Policy = Policies.DefaultAuthorization)]
  421. [ProducesResponseType(StatusCodes.Status200OK)]
  422. public IEnumerable<FontFile> GetFallbackFontList()
  423. {
  424. var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
  425. var fallbackFontPath = encodingOptions.FallbackFontPath;
  426. if (!string.IsNullOrEmpty(fallbackFontPath))
  427. {
  428. var files = _fileSystem.GetFiles(fallbackFontPath, new[] { ".woff", ".woff2", ".ttf", ".otf" }, false, false);
  429. var fontFiles = files
  430. .Select(i => new FontFile
  431. {
  432. Name = i.Name,
  433. Size = i.Length,
  434. DateCreated = _fileSystem.GetCreationTimeUtc(i),
  435. DateModified = _fileSystem.GetLastWriteTimeUtc(i)
  436. })
  437. .OrderBy(i => i.Size)
  438. .ThenBy(i => i.Name)
  439. .ThenByDescending(i => i.DateModified)
  440. .ThenByDescending(i => i.DateCreated);
  441. // max total size 20M
  442. const int MaxSize = 20971520;
  443. var sizeCounter = 0L;
  444. foreach (var fontFile in fontFiles)
  445. {
  446. sizeCounter += fontFile.Size;
  447. if (sizeCounter >= MaxSize)
  448. {
  449. _logger.LogWarning("Some fonts will not be sent due to size limitations");
  450. yield break;
  451. }
  452. yield return fontFile;
  453. }
  454. }
  455. else
  456. {
  457. _logger.LogWarning("The path of fallback font folder has not been set");
  458. encodingOptions.EnableFallbackFont = false;
  459. }
  460. }
  461. /// <summary>
  462. /// Gets a fallback font file.
  463. /// </summary>
  464. /// <param name="name">The name of the fallback font file to get.</param>
  465. /// <response code="200">Fallback font file retrieved.</response>
  466. /// <returns>The fallback font file.</returns>
  467. [HttpGet("FallbackFont/Fonts/{name}")]
  468. [Authorize(Policy = Policies.DefaultAuthorization)]
  469. [ProducesResponseType(StatusCodes.Status200OK)]
  470. [ProducesFile("font/*")]
  471. public ActionResult GetFallbackFont([FromRoute, Required] string name)
  472. {
  473. var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
  474. var fallbackFontPath = encodingOptions.FallbackFontPath;
  475. if (!string.IsNullOrEmpty(fallbackFontPath))
  476. {
  477. var fontFile = _fileSystem.GetFiles(fallbackFontPath)
  478. .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  479. var fileSize = fontFile?.Length;
  480. if (fontFile is not null && fileSize is not null && fileSize > 0)
  481. {
  482. _logger.LogDebug("Fallback font size is {FileSize} Bytes", fileSize);
  483. return PhysicalFile(fontFile.FullName, MimeTypes.GetMimeType(fontFile.FullName));
  484. }
  485. else
  486. {
  487. _logger.LogWarning("The selected font is null or empty");
  488. }
  489. }
  490. else
  491. {
  492. _logger.LogWarning("The path of fallback font folder has not been set");
  493. encodingOptions.EnableFallbackFont = false;
  494. }
  495. // returning HTTP 204 will break the SubtitlesOctopus
  496. return Ok();
  497. }
  498. }