ItemUpdateController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Api.Constants;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Entities.Audio;
  11. using MediaBrowser.Controller.Entities.TV;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.LiveTv;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Globalization;
  18. using MediaBrowser.Model.IO;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Http;
  21. using Microsoft.AspNetCore.Mvc;
  22. namespace Jellyfin.Api.Controllers;
  23. /// <summary>
  24. /// Item update controller.
  25. /// </summary>
  26. [Route("")]
  27. [Authorize(Policy = Policies.RequiresElevation)]
  28. public class ItemUpdateController : BaseJellyfinApiController
  29. {
  30. private readonly ILibraryManager _libraryManager;
  31. private readonly IProviderManager _providerManager;
  32. private readonly ILocalizationManager _localizationManager;
  33. private readonly IFileSystem _fileSystem;
  34. private readonly IServerConfigurationManager _serverConfigurationManager;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="ItemUpdateController"/> class.
  37. /// </summary>
  38. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  39. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  40. /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
  41. /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  42. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  43. public ItemUpdateController(
  44. IFileSystem fileSystem,
  45. ILibraryManager libraryManager,
  46. IProviderManager providerManager,
  47. ILocalizationManager localizationManager,
  48. IServerConfigurationManager serverConfigurationManager)
  49. {
  50. _libraryManager = libraryManager;
  51. _providerManager = providerManager;
  52. _localizationManager = localizationManager;
  53. _fileSystem = fileSystem;
  54. _serverConfigurationManager = serverConfigurationManager;
  55. }
  56. /// <summary>
  57. /// Updates an item.
  58. /// </summary>
  59. /// <param name="itemId">The item id.</param>
  60. /// <param name="request">The new item properties.</param>
  61. /// <response code="204">Item updated.</response>
  62. /// <response code="404">Item not found.</response>
  63. /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
  64. [HttpPost("Items/{itemId}")]
  65. [ProducesResponseType(StatusCodes.Status204NoContent)]
  66. [ProducesResponseType(StatusCodes.Status404NotFound)]
  67. public async Task<ActionResult> UpdateItem([FromRoute, Required] Guid itemId, [FromBody, Required] BaseItemDto request)
  68. {
  69. var item = _libraryManager.GetItemById(itemId);
  70. if (item is null)
  71. {
  72. return NotFound();
  73. }
  74. var newLockData = request.LockData ?? false;
  75. var isLockedChanged = item.IsLocked != newLockData;
  76. var series = item as Series;
  77. var displayOrderChanged = series is not null && !string.Equals(
  78. series.DisplayOrder ?? string.Empty,
  79. request.DisplayOrder ?? string.Empty,
  80. StringComparison.OrdinalIgnoreCase);
  81. // Do this first so that metadata savers can pull the updates from the database.
  82. if (request.People is not null)
  83. {
  84. _libraryManager.UpdatePeople(
  85. item,
  86. request.People.Select(x => new PersonInfo
  87. {
  88. Name = x.Name,
  89. Role = x.Role,
  90. Type = x.Type
  91. }).ToList());
  92. }
  93. UpdateItem(request, item);
  94. item.OnMetadataChanged();
  95. await item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  96. if (isLockedChanged && item.IsFolder)
  97. {
  98. var folder = (Folder)item;
  99. foreach (var child in folder.GetRecursiveChildren())
  100. {
  101. child.IsLocked = newLockData;
  102. await child.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  103. }
  104. }
  105. if (displayOrderChanged)
  106. {
  107. _providerManager.QueueRefresh(
  108. series!.Id,
  109. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  110. {
  111. MetadataRefreshMode = MetadataRefreshMode.FullRefresh,
  112. ImageRefreshMode = MetadataRefreshMode.FullRefresh,
  113. ReplaceAllMetadata = true
  114. },
  115. RefreshPriority.High);
  116. }
  117. return NoContent();
  118. }
  119. /// <summary>
  120. /// Gets metadata editor info for an item.
  121. /// </summary>
  122. /// <param name="itemId">The item id.</param>
  123. /// <response code="200">Item metadata editor returned.</response>
  124. /// <response code="404">Item not found.</response>
  125. /// <returns>An <see cref="OkResult"/> on success containing the metadata editor, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
  126. [HttpGet("Items/{itemId}/MetadataEditor")]
  127. [ProducesResponseType(StatusCodes.Status200OK)]
  128. [ProducesResponseType(StatusCodes.Status404NotFound)]
  129. public ActionResult<MetadataEditorInfo> GetMetadataEditorInfo([FromRoute, Required] Guid itemId)
  130. {
  131. var item = _libraryManager.GetItemById(itemId);
  132. var info = new MetadataEditorInfo
  133. {
  134. ParentalRatingOptions = _localizationManager.GetParentalRatings().ToArray(),
  135. ExternalIdInfos = _providerManager.GetExternalIdInfos(item).ToArray(),
  136. Countries = _localizationManager.GetCountries().ToArray(),
  137. Cultures = _localizationManager.GetCultures().ToArray()
  138. };
  139. if (!item.IsVirtualItem
  140. && item is not ICollectionFolder
  141. && item is not UserView
  142. && item is not AggregateFolder
  143. && item is not LiveTvChannel
  144. && item is not IItemByName
  145. && item.SourceType == SourceType.Library)
  146. {
  147. var inheritedContentType = _libraryManager.GetInheritedContentType(item);
  148. var configuredContentType = _libraryManager.GetConfiguredContentType(item);
  149. if (string.IsNullOrWhiteSpace(inheritedContentType) ||
  150. !string.IsNullOrWhiteSpace(configuredContentType))
  151. {
  152. info.ContentTypeOptions = GetContentTypeOptions(true).ToArray();
  153. info.ContentType = configuredContentType;
  154. if (string.IsNullOrWhiteSpace(inheritedContentType)
  155. || string.Equals(inheritedContentType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
  156. {
  157. info.ContentTypeOptions = info.ContentTypeOptions
  158. .Where(i => string.IsNullOrWhiteSpace(i.Value)
  159. || string.Equals(i.Value, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
  160. .ToArray();
  161. }
  162. }
  163. }
  164. return info;
  165. }
  166. /// <summary>
  167. /// Updates an item's content type.
  168. /// </summary>
  169. /// <param name="itemId">The item id.</param>
  170. /// <param name="contentType">The content type of the item.</param>
  171. /// <response code="204">Item content type updated.</response>
  172. /// <response code="404">Item not found.</response>
  173. /// <returns>An <see cref="NoContentResult"/> on success, or a <see cref="NotFoundResult"/> if the item could not be found.</returns>
  174. [HttpPost("Items/{itemId}/ContentType")]
  175. [ProducesResponseType(StatusCodes.Status204NoContent)]
  176. [ProducesResponseType(StatusCodes.Status404NotFound)]
  177. public ActionResult UpdateItemContentType([FromRoute, Required] Guid itemId, [FromQuery] string? contentType)
  178. {
  179. var item = _libraryManager.GetItemById(itemId);
  180. if (item is null)
  181. {
  182. return NotFound();
  183. }
  184. var path = item.ContainingFolderPath;
  185. var types = _serverConfigurationManager.Configuration.ContentTypes
  186. .Where(i => !string.IsNullOrWhiteSpace(i.Name))
  187. .Where(i => !string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase))
  188. .ToList();
  189. if (!string.IsNullOrWhiteSpace(contentType))
  190. {
  191. types.Add(new NameValuePair
  192. {
  193. Name = path,
  194. Value = contentType
  195. });
  196. }
  197. _serverConfigurationManager.Configuration.ContentTypes = types.ToArray();
  198. _serverConfigurationManager.SaveConfiguration();
  199. return NoContent();
  200. }
  201. private void UpdateItem(BaseItemDto request, BaseItem item)
  202. {
  203. item.Name = request.Name;
  204. item.ForcedSortName = request.ForcedSortName;
  205. item.OriginalTitle = string.IsNullOrWhiteSpace(request.OriginalTitle) ? null : request.OriginalTitle;
  206. item.CriticRating = request.CriticRating;
  207. item.CommunityRating = request.CommunityRating;
  208. item.IndexNumber = request.IndexNumber;
  209. item.ParentIndexNumber = request.ParentIndexNumber;
  210. item.Overview = request.Overview;
  211. item.Genres = request.Genres;
  212. if (item is Episode episode)
  213. {
  214. episode.AirsAfterSeasonNumber = request.AirsAfterSeasonNumber;
  215. episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
  216. episode.AirsBeforeSeasonNumber = request.AirsBeforeSeasonNumber;
  217. }
  218. item.Tags = request.Tags;
  219. if (request.Taglines is not null)
  220. {
  221. item.Tagline = request.Taglines.FirstOrDefault();
  222. }
  223. if (request.Studios is not null)
  224. {
  225. item.Studios = request.Studios.Select(x => x.Name).ToArray();
  226. }
  227. if (request.DateCreated.HasValue)
  228. {
  229. item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
  230. }
  231. item.EndDate = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : null;
  232. item.PremiereDate = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : null;
  233. item.ProductionYear = request.ProductionYear;
  234. item.OfficialRating = string.IsNullOrWhiteSpace(request.OfficialRating) ? null : request.OfficialRating;
  235. item.CustomRating = request.CustomRating;
  236. if (request.ProductionLocations is not null)
  237. {
  238. item.ProductionLocations = request.ProductionLocations;
  239. }
  240. item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
  241. item.PreferredMetadataLanguage = request.PreferredMetadataLanguage;
  242. if (item is IHasDisplayOrder hasDisplayOrder)
  243. {
  244. hasDisplayOrder.DisplayOrder = request.DisplayOrder;
  245. }
  246. if (item is IHasAspectRatio hasAspectRatio)
  247. {
  248. hasAspectRatio.AspectRatio = request.AspectRatio;
  249. }
  250. item.IsLocked = request.LockData ?? false;
  251. if (request.LockedFields is not null)
  252. {
  253. item.LockedFields = request.LockedFields;
  254. }
  255. // Only allow this for series. Runtimes for media comes from ffprobe.
  256. if (item is Series)
  257. {
  258. item.RunTimeTicks = request.RunTimeTicks;
  259. }
  260. foreach (var pair in request.ProviderIds.ToList())
  261. {
  262. if (string.IsNullOrEmpty(pair.Value))
  263. {
  264. request.ProviderIds.Remove(pair.Key);
  265. }
  266. }
  267. item.ProviderIds = request.ProviderIds;
  268. if (item is Video video)
  269. {
  270. video.Video3DFormat = request.Video3DFormat;
  271. }
  272. if (request.AlbumArtists is not null)
  273. {
  274. if (item is IHasAlbumArtist hasAlbumArtists)
  275. {
  276. hasAlbumArtists.AlbumArtists = request
  277. .AlbumArtists
  278. .Select(i => i.Name)
  279. .ToArray();
  280. }
  281. }
  282. if (request.ArtistItems is not null)
  283. {
  284. if (item is IHasArtist hasArtists)
  285. {
  286. hasArtists.Artists = request
  287. .ArtistItems
  288. .Select(i => i.Name)
  289. .ToArray();
  290. }
  291. }
  292. switch (item)
  293. {
  294. case Audio song:
  295. song.Album = request.Album;
  296. break;
  297. case MusicVideo musicVideo:
  298. musicVideo.Album = request.Album;
  299. break;
  300. case Series series:
  301. {
  302. series.Status = GetSeriesStatus(request);
  303. if (request.AirDays is not null)
  304. {
  305. series.AirDays = request.AirDays;
  306. series.AirTime = request.AirTime;
  307. }
  308. break;
  309. }
  310. }
  311. }
  312. private SeriesStatus? GetSeriesStatus(BaseItemDto item)
  313. {
  314. if (string.IsNullOrEmpty(item.Status))
  315. {
  316. return null;
  317. }
  318. return (SeriesStatus)Enum.Parse(typeof(SeriesStatus), item.Status, true);
  319. }
  320. private DateTime NormalizeDateTime(DateTime val)
  321. {
  322. return DateTime.SpecifyKind(val, DateTimeKind.Utc);
  323. }
  324. private List<NameValuePair> GetContentTypeOptions(bool isForItem)
  325. {
  326. var list = new List<NameValuePair>();
  327. if (isForItem)
  328. {
  329. list.Add(new NameValuePair
  330. {
  331. Name = "Inherit",
  332. Value = string.Empty
  333. });
  334. }
  335. list.Add(new NameValuePair
  336. {
  337. Name = "Movies",
  338. Value = "movies"
  339. });
  340. list.Add(new NameValuePair
  341. {
  342. Name = "Music",
  343. Value = "music"
  344. });
  345. list.Add(new NameValuePair
  346. {
  347. Name = "Shows",
  348. Value = "tvshows"
  349. });
  350. if (!isForItem)
  351. {
  352. list.Add(new NameValuePair
  353. {
  354. Name = "Books",
  355. Value = "books"
  356. });
  357. }
  358. list.Add(new NameValuePair
  359. {
  360. Name = "HomeVideos",
  361. Value = "homevideos"
  362. });
  363. list.Add(new NameValuePair
  364. {
  365. Name = "MusicVideos",
  366. Value = "musicvideos"
  367. });
  368. list.Add(new NameValuePair
  369. {
  370. Name = "Photos",
  371. Value = "photos"
  372. });
  373. if (!isForItem)
  374. {
  375. list.Add(new NameValuePair
  376. {
  377. Name = "MixedContent",
  378. Value = string.Empty
  379. });
  380. }
  381. foreach (var val in list)
  382. {
  383. val.Name = _localizationManager.GetLocalizedString(val.Name);
  384. }
  385. return list;
  386. }
  387. }