LyricsController.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Net.Mime;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Attributes;
  9. using Jellyfin.Api.Extensions;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common.Api;
  12. using MediaBrowser.Controller.Entities.Audio;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.Lyrics;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Lyrics;
  18. using MediaBrowser.Model.Providers;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Http;
  21. using Microsoft.AspNetCore.Mvc;
  22. namespace Jellyfin.Api.Controllers;
  23. /// <summary>
  24. /// Lyrics controller.
  25. /// </summary>
  26. [Route("")]
  27. public class LyricsController : BaseJellyfinApiController
  28. {
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly ILyricManager _lyricManager;
  31. private readonly IProviderManager _providerManager;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IUserManager _userManager;
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="LyricsController"/> class.
  36. /// </summary>
  37. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  38. /// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
  39. /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
  40. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  41. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  42. public LyricsController(
  43. ILibraryManager libraryManager,
  44. ILyricManager lyricManager,
  45. IProviderManager providerManager,
  46. IFileSystem fileSystem,
  47. IUserManager userManager)
  48. {
  49. _libraryManager = libraryManager;
  50. _lyricManager = lyricManager;
  51. _providerManager = providerManager;
  52. _fileSystem = fileSystem;
  53. _userManager = userManager;
  54. }
  55. /// <summary>
  56. /// Gets an item's lyrics.
  57. /// </summary>
  58. /// <param name="itemId">Item id.</param>
  59. /// <response code="200">Lyrics returned.</response>
  60. /// <response code="404">Something went wrong. No Lyrics will be returned.</response>
  61. /// <returns>An <see cref="OkResult"/> containing the item's lyrics.</returns>
  62. [HttpGet("Audio/{itemId}/Lyrics")]
  63. [Authorize]
  64. [ProducesResponseType(StatusCodes.Status200OK)]
  65. public async Task<ActionResult<LyricDto>> GetLyrics([FromRoute, Required] Guid itemId)
  66. {
  67. var isApiKey = User.GetIsApiKey();
  68. var userId = User.GetUserId();
  69. if (!isApiKey && userId.IsEmpty())
  70. {
  71. return BadRequest();
  72. }
  73. var audio = _libraryManager.GetItemById<Audio>(itemId);
  74. if (audio is null)
  75. {
  76. return NotFound();
  77. }
  78. if (!isApiKey)
  79. {
  80. var user = _userManager.GetUserById(userId);
  81. if (user is null)
  82. {
  83. return NotFound();
  84. }
  85. // Check the item is visible for the user
  86. if (!audio.IsVisible(user))
  87. {
  88. return Unauthorized($"{user.Username} is not permitted to access item {audio.Name}.");
  89. }
  90. }
  91. var result = await _lyricManager.GetLyricsAsync(audio, CancellationToken.None).ConfigureAwait(false);
  92. if (result is not null)
  93. {
  94. return Ok(result);
  95. }
  96. return NotFound();
  97. }
  98. /// <summary>
  99. /// Upload an external lyric file.
  100. /// </summary>
  101. /// <param name="itemId">The item the lyric belongs to.</param>
  102. /// <param name="fileName">Name of the file being uploaded.</param>
  103. /// <response code="200">Lyrics uploaded.</response>
  104. /// <response code="400">Error processing upload.</response>
  105. /// <response code="404">Item not found.</response>
  106. /// <returns>The uploaded lyric.</returns>
  107. [HttpPost("Audio/{itemId}/Lyrics")]
  108. [Authorize(Policy = Policies.LyricManagement)]
  109. [AcceptsFile(MediaTypeNames.Text.Plain)]
  110. [ProducesResponseType(StatusCodes.Status200OK)]
  111. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  112. [ProducesResponseType(StatusCodes.Status404NotFound)]
  113. public async Task<ActionResult<LyricDto>> UploadLyrics(
  114. [FromRoute, Required] Guid itemId,
  115. [FromQuery, Required] string fileName)
  116. {
  117. var audio = _libraryManager.GetItemById<Audio>(itemId);
  118. if (audio is null)
  119. {
  120. return NotFound();
  121. }
  122. if (Request.ContentLength.GetValueOrDefault(0) == 0)
  123. {
  124. return BadRequest("No lyrics uploaded");
  125. }
  126. // Utilize Path.GetExtension as it provides extra path validation.
  127. var format = Path.GetExtension(fileName.AsSpan()).RightPart('.').ToString();
  128. if (string.IsNullOrEmpty(format))
  129. {
  130. return BadRequest("Extension is required on filename");
  131. }
  132. var stream = new MemoryStream();
  133. await using (stream.ConfigureAwait(false))
  134. {
  135. await Request.Body.CopyToAsync(stream).ConfigureAwait(false);
  136. var uploadedLyric = await _lyricManager.UploadLyricAsync(
  137. audio,
  138. new LyricResponse
  139. {
  140. Format = format,
  141. Stream = stream
  142. }).ConfigureAwait(false);
  143. if (uploadedLyric is null)
  144. {
  145. return BadRequest();
  146. }
  147. _providerManager.QueueRefresh(audio.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  148. return Ok(uploadedLyric);
  149. }
  150. }
  151. /// <summary>
  152. /// Deletes an external lyric file.
  153. /// </summary>
  154. /// <param name="itemId">The item id.</param>
  155. /// <response code="204">Lyric deleted.</response>
  156. /// <response code="404">Item not found.</response>
  157. /// <returns>A <see cref="NoContentResult"/>.</returns>
  158. [HttpDelete("Audio/{itemId}/Lyrics")]
  159. [Authorize(Policy = Policies.LyricManagement)]
  160. [ProducesResponseType(StatusCodes.Status204NoContent)]
  161. [ProducesResponseType(StatusCodes.Status404NotFound)]
  162. public async Task<ActionResult> DeleteLyrics(
  163. [FromRoute, Required] Guid itemId)
  164. {
  165. var audio = _libraryManager.GetItemById<Audio>(itemId);
  166. if (audio is null)
  167. {
  168. return NotFound();
  169. }
  170. await _lyricManager.DeleteLyricsAsync(audio).ConfigureAwait(false);
  171. return NoContent();
  172. }
  173. /// <summary>
  174. /// Search remote lyrics.
  175. /// </summary>
  176. /// <param name="itemId">The item id.</param>
  177. /// <response code="200">Lyrics retrieved.</response>
  178. /// <response code="404">Item not found.</response>
  179. /// <returns>An array of <see cref="RemoteLyricInfo"/>.</returns>
  180. [HttpGet("Audio/{itemId}/RemoteSearch/Lyrics")]
  181. [Authorize(Policy = Policies.LyricManagement)]
  182. [ProducesResponseType(StatusCodes.Status200OK)]
  183. [ProducesResponseType(StatusCodes.Status404NotFound)]
  184. public async Task<ActionResult<IReadOnlyList<RemoteLyricInfoDto>>> SearchRemoteLyrics([FromRoute, Required] Guid itemId)
  185. {
  186. var audio = _libraryManager.GetItemById<Audio>(itemId);
  187. if (audio is null)
  188. {
  189. return NotFound();
  190. }
  191. var results = await _lyricManager.SearchLyricsAsync(audio, false, CancellationToken.None).ConfigureAwait(false);
  192. return Ok(results);
  193. }
  194. /// <summary>
  195. /// Downloads a remote lyric.
  196. /// </summary>
  197. /// <param name="itemId">The item id.</param>
  198. /// <param name="lyricId">The lyric id.</param>
  199. /// <response code="200">Lyric downloaded.</response>
  200. /// <response code="404">Item not found.</response>
  201. /// <returns>A <see cref="NoContentResult"/>.</returns>
  202. [HttpPost("Audio/{itemId}/RemoteSearch/Lyrics/{lyricId}")]
  203. [Authorize(Policy = Policies.LyricManagement)]
  204. [ProducesResponseType(StatusCodes.Status200OK)]
  205. [ProducesResponseType(StatusCodes.Status404NotFound)]
  206. public async Task<ActionResult<LyricDto>> DownloadRemoteLyrics(
  207. [FromRoute, Required] Guid itemId,
  208. [FromRoute, Required] string lyricId)
  209. {
  210. var audio = _libraryManager.GetItemById<Audio>(itemId);
  211. if (audio is null)
  212. {
  213. return NotFound();
  214. }
  215. var downloadedLyrics = await _lyricManager.DownloadLyricsAsync(audio, lyricId, CancellationToken.None).ConfigureAwait(false);
  216. if (downloadedLyrics is null)
  217. {
  218. return NotFound();
  219. }
  220. _providerManager.QueueRefresh(audio.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.High);
  221. return Ok(downloadedLyrics);
  222. }
  223. /// <summary>
  224. /// Gets the remote lyrics.
  225. /// </summary>
  226. /// <param name="lyricId">The remote provider item id.</param>
  227. /// <response code="200">File returned.</response>
  228. /// <response code="404">Lyric not found.</response>
  229. /// <returns>A <see cref="FileStreamResult"/> with the lyric file.</returns>
  230. [HttpGet("Providers/Lyrics/{lyricId}")]
  231. [Authorize(Policy = Policies.LyricManagement)]
  232. [ProducesResponseType(StatusCodes.Status200OK)]
  233. [ProducesResponseType(StatusCodes.Status404NotFound)]
  234. public async Task<ActionResult<LyricDto>> GetRemoteLyrics([FromRoute, Required] string lyricId)
  235. {
  236. var result = await _lyricManager.GetRemoteLyricsAsync(lyricId, CancellationToken.None).ConfigureAwait(false);
  237. if (result is null)
  238. {
  239. return NotFound();
  240. }
  241. return Ok(result);
  242. }
  243. }