SubtitleController.cs 24 KB

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