ItemUpdateController.cs 16 KB

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