SubtitleController.cs 23 KB

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