BaseItem.cs 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665
  1. #nullable disable
  2. #pragma warning disable CS1591, SA1401
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.Json.Serialization;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Diacritics.Extensions;
  13. using Jellyfin.Data.Entities;
  14. using Jellyfin.Data.Enums;
  15. using Jellyfin.Extensions;
  16. using MediaBrowser.Common.Extensions;
  17. using MediaBrowser.Controller.Channels;
  18. using MediaBrowser.Controller.Configuration;
  19. using MediaBrowser.Controller.Dto;
  20. using MediaBrowser.Controller.Entities.Audio;
  21. using MediaBrowser.Controller.Library;
  22. using MediaBrowser.Controller.Persistence;
  23. using MediaBrowser.Controller.Providers;
  24. using MediaBrowser.Model.Dto;
  25. using MediaBrowser.Model.Entities;
  26. using MediaBrowser.Model.Globalization;
  27. using MediaBrowser.Model.IO;
  28. using MediaBrowser.Model.Library;
  29. using MediaBrowser.Model.LiveTv;
  30. using MediaBrowser.Model.MediaInfo;
  31. using MediaBrowser.Model.Providers;
  32. using Microsoft.Extensions.Logging;
  33. namespace MediaBrowser.Controller.Entities
  34. {
  35. /// <summary>
  36. /// Class BaseItem.
  37. /// </summary>
  38. public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>, IEquatable<BaseItem>
  39. {
  40. private BaseItemKind? _baseItemKind;
  41. public const string ThemeSongFileName = "theme";
  42. /// <summary>
  43. /// The supported image extensions.
  44. /// </summary>
  45. public static readonly string[] SupportedImageExtensions
  46. = new[] { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  47. private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
  48. {
  49. ".nfo",
  50. ".xml",
  51. ".srt",
  52. ".vtt",
  53. ".sub",
  54. ".idx",
  55. ".txt",
  56. ".edl",
  57. ".bif",
  58. ".smi",
  59. ".ttml"
  60. };
  61. /// <summary>
  62. /// Extra types that should be counted and displayed as "Special Features" in the UI.
  63. /// </summary>
  64. public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
  65. {
  66. Model.Entities.ExtraType.Unknown,
  67. Model.Entities.ExtraType.BehindTheScenes,
  68. Model.Entities.ExtraType.Clip,
  69. Model.Entities.ExtraType.DeletedScene,
  70. Model.Entities.ExtraType.Interview,
  71. Model.Entities.ExtraType.Sample,
  72. Model.Entities.ExtraType.Scene
  73. };
  74. private string _sortName;
  75. private string _forcedSortName;
  76. private string _name;
  77. public const char SlugChar = '-';
  78. protected BaseItem()
  79. {
  80. Tags = Array.Empty<string>();
  81. Genres = Array.Empty<string>();
  82. Studios = Array.Empty<string>();
  83. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  84. LockedFields = Array.Empty<MetadataField>();
  85. ImageInfos = Array.Empty<ItemImageInfo>();
  86. ProductionLocations = Array.Empty<string>();
  87. RemoteTrailers = Array.Empty<MediaUrl>();
  88. ExtraIds = Array.Empty<Guid>();
  89. }
  90. [JsonIgnore]
  91. public string PreferredMetadataCountryCode { get; set; }
  92. [JsonIgnore]
  93. public string PreferredMetadataLanguage { get; set; }
  94. public long? Size { get; set; }
  95. public string Container { get; set; }
  96. [JsonIgnore]
  97. public string Tagline { get; set; }
  98. [JsonIgnore]
  99. public virtual ItemImageInfo[] ImageInfos { get; set; }
  100. [JsonIgnore]
  101. public bool IsVirtualItem { get; set; }
  102. /// <summary>
  103. /// Gets or sets the album.
  104. /// </summary>
  105. /// <value>The album.</value>
  106. [JsonIgnore]
  107. public string Album { get; set; }
  108. /// <summary>
  109. /// Gets or sets the channel identifier.
  110. /// </summary>
  111. /// <value>The channel identifier.</value>
  112. [JsonIgnore]
  113. public Guid ChannelId { get; set; }
  114. [JsonIgnore]
  115. public virtual bool SupportsAddingToPlaylist => false;
  116. [JsonIgnore]
  117. public virtual bool AlwaysScanInternalMetadataPath => false;
  118. /// <summary>
  119. /// Gets or sets a value indicating whether this instance is in mixed folder.
  120. /// </summary>
  121. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  122. [JsonIgnore]
  123. public bool IsInMixedFolder { get; set; }
  124. [JsonIgnore]
  125. public virtual bool SupportsPlayedStatus => false;
  126. [JsonIgnore]
  127. public virtual bool SupportsPositionTicksResume => false;
  128. [JsonIgnore]
  129. public virtual bool SupportsRemoteImageDownloading => true;
  130. /// <summary>
  131. /// Gets or sets the name.
  132. /// </summary>
  133. /// <value>The name.</value>
  134. [JsonIgnore]
  135. public virtual string Name
  136. {
  137. get => _name;
  138. set
  139. {
  140. _name = value;
  141. // lazy load this again
  142. _sortName = null;
  143. }
  144. }
  145. [JsonIgnore]
  146. public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
  147. [JsonIgnore]
  148. public int? TotalBitrate { get; set; }
  149. [JsonIgnore]
  150. public ExtraType? ExtraType { get; set; }
  151. [JsonIgnore]
  152. public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo);
  153. [JsonIgnore]
  154. public string OriginalTitle { get; set; }
  155. /// <summary>
  156. /// Gets or sets the id.
  157. /// </summary>
  158. /// <value>The id.</value>
  159. [JsonIgnore]
  160. public Guid Id { get; set; }
  161. [JsonIgnore]
  162. public Guid OwnerId { get; set; }
  163. /// <summary>
  164. /// Gets or sets the audio.
  165. /// </summary>
  166. /// <value>The audio.</value>
  167. [JsonIgnore]
  168. public ProgramAudio? Audio { get; set; }
  169. /// <summary>
  170. /// Gets the id that should be used to key display prefs for this item.
  171. /// Default is based on the type for everything except actual generic folders.
  172. /// </summary>
  173. /// <value>The display prefs id.</value>
  174. [JsonIgnore]
  175. public virtual Guid DisplayPreferencesId
  176. {
  177. get
  178. {
  179. var thisType = GetType();
  180. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  181. }
  182. }
  183. /// <summary>
  184. /// Gets or sets the path.
  185. /// </summary>
  186. /// <value>The path.</value>
  187. [JsonIgnore]
  188. public virtual string Path { get; set; }
  189. [JsonIgnore]
  190. public virtual SourceType SourceType
  191. {
  192. get
  193. {
  194. if (!ChannelId.Equals(default))
  195. {
  196. return SourceType.Channel;
  197. }
  198. return SourceType.Library;
  199. }
  200. }
  201. /// <summary>
  202. /// Gets the folder containing the item.
  203. /// If the item is a folder, it returns the folder itself.
  204. /// </summary>
  205. [JsonIgnore]
  206. public virtual string ContainingFolderPath
  207. {
  208. get
  209. {
  210. if (IsFolder)
  211. {
  212. return Path;
  213. }
  214. return System.IO.Path.GetDirectoryName(Path);
  215. }
  216. }
  217. /// <summary>
  218. /// Gets or sets the name of the service.
  219. /// </summary>
  220. /// <value>The name of the service.</value>
  221. [JsonIgnore]
  222. public string ServiceName { get; set; }
  223. /// <summary>
  224. /// Gets or sets the external id.
  225. /// </summary>
  226. /// <remarks>
  227. /// If this content came from an external service, the id of the content on that service.
  228. /// </remarks>
  229. [JsonIgnore]
  230. public string ExternalId { get; set; }
  231. [JsonIgnore]
  232. public string ExternalSeriesId { get; set; }
  233. [JsonIgnore]
  234. public virtual bool IsHidden => false;
  235. /// <summary>
  236. /// Gets the type of the location.
  237. /// </summary>
  238. /// <value>The type of the location.</value>
  239. [JsonIgnore]
  240. public virtual LocationType LocationType
  241. {
  242. get
  243. {
  244. var path = Path;
  245. if (string.IsNullOrEmpty(path))
  246. {
  247. if (SourceType == SourceType.Channel)
  248. {
  249. return LocationType.Remote;
  250. }
  251. return LocationType.Virtual;
  252. }
  253. return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
  254. }
  255. }
  256. [JsonIgnore]
  257. public MediaProtocol? PathProtocol
  258. {
  259. get
  260. {
  261. var path = Path;
  262. if (string.IsNullOrEmpty(path))
  263. {
  264. return null;
  265. }
  266. return MediaSourceManager.GetPathProtocol(path);
  267. }
  268. }
  269. [JsonIgnore]
  270. public bool IsFileProtocol => PathProtocol == MediaProtocol.File;
  271. [JsonIgnore]
  272. public bool HasPathProtocol => PathProtocol.HasValue;
  273. [JsonIgnore]
  274. public virtual bool SupportsLocalMetadata
  275. {
  276. get
  277. {
  278. if (SourceType == SourceType.Channel)
  279. {
  280. return false;
  281. }
  282. return IsFileProtocol;
  283. }
  284. }
  285. [JsonIgnore]
  286. public virtual string FileNameWithoutExtension
  287. {
  288. get
  289. {
  290. if (IsFileProtocol)
  291. {
  292. return System.IO.Path.GetFileNameWithoutExtension(Path);
  293. }
  294. return null;
  295. }
  296. }
  297. [JsonIgnore]
  298. public virtual bool EnableAlphaNumericSorting => true;
  299. public virtual bool IsHD => Height >= 720;
  300. public bool IsShortcut { get; set; }
  301. public string ShortcutPath { get; set; }
  302. public int Width { get; set; }
  303. public int Height { get; set; }
  304. public Guid[] ExtraIds { get; set; }
  305. /// <summary>
  306. /// Gets the primary image path.
  307. /// </summary>
  308. /// <remarks>
  309. /// This is just a helper for convenience.
  310. /// </remarks>
  311. /// <value>The primary image path.</value>
  312. [JsonIgnore]
  313. public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
  314. /// <summary>
  315. /// Gets or sets the date created.
  316. /// </summary>
  317. /// <value>The date created.</value>
  318. [JsonIgnore]
  319. public DateTime DateCreated { get; set; }
  320. /// <summary>
  321. /// Gets or sets the date modified.
  322. /// </summary>
  323. /// <value>The date modified.</value>
  324. [JsonIgnore]
  325. public DateTime DateModified { get; set; }
  326. public DateTime DateLastSaved { get; set; }
  327. [JsonIgnore]
  328. public DateTime DateLastRefreshed { get; set; }
  329. [JsonIgnore]
  330. public bool IsLocked { get; set; }
  331. /// <summary>
  332. /// Gets or sets the locked fields.
  333. /// </summary>
  334. /// <value>The locked fields.</value>
  335. [JsonIgnore]
  336. public MetadataField[] LockedFields { get; set; }
  337. /// <summary>
  338. /// Gets the type of the media.
  339. /// </summary>
  340. /// <value>The type of the media.</value>
  341. [JsonIgnore]
  342. public virtual string MediaType => null;
  343. [JsonIgnore]
  344. public virtual string[] PhysicalLocations
  345. {
  346. get
  347. {
  348. if (!IsFileProtocol)
  349. {
  350. return Array.Empty<string>();
  351. }
  352. return new[] { Path };
  353. }
  354. }
  355. [JsonIgnore]
  356. public bool EnableMediaSourceDisplay
  357. {
  358. get
  359. {
  360. if (SourceType == SourceType.Channel)
  361. {
  362. return ChannelManager.EnableMediaSourceDisplay(this);
  363. }
  364. return true;
  365. }
  366. }
  367. [JsonIgnore]
  368. public Guid ParentId { get; set; }
  369. /// <summary>
  370. /// Gets or sets the logger.
  371. /// </summary>
  372. public static ILogger<BaseItem> Logger { get; set; }
  373. public static ILibraryManager LibraryManager { get; set; }
  374. public static IServerConfigurationManager ConfigurationManager { get; set; }
  375. public static IProviderManager ProviderManager { get; set; }
  376. public static ILocalizationManager LocalizationManager { get; set; }
  377. public static IItemRepository ItemRepository { get; set; }
  378. public static IFileSystem FileSystem { get; set; }
  379. public static IUserDataManager UserDataManager { get; set; }
  380. public static IChannelManager ChannelManager { get; set; }
  381. public static IMediaSourceManager MediaSourceManager { get; set; }
  382. /// <summary>
  383. /// Gets or sets the name of the forced sort.
  384. /// </summary>
  385. /// <value>The name of the forced sort.</value>
  386. [JsonIgnore]
  387. public string ForcedSortName
  388. {
  389. get => _forcedSortName;
  390. set
  391. {
  392. _forcedSortName = value;
  393. _sortName = null;
  394. }
  395. }
  396. /// <summary>
  397. /// Gets or sets the name of the sort.
  398. /// </summary>
  399. /// <value>The name of the sort.</value>
  400. [JsonIgnore]
  401. public string SortName
  402. {
  403. get
  404. {
  405. if (_sortName == null)
  406. {
  407. if (!string.IsNullOrEmpty(ForcedSortName))
  408. {
  409. // Need the ToLower because that's what CreateSortName does
  410. _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
  411. }
  412. else
  413. {
  414. _sortName = CreateSortName();
  415. }
  416. }
  417. return _sortName;
  418. }
  419. set => _sortName = value;
  420. }
  421. [JsonIgnore]
  422. public virtual Guid DisplayParentId => ParentId;
  423. [JsonIgnore]
  424. public BaseItem DisplayParent
  425. {
  426. get
  427. {
  428. var id = DisplayParentId;
  429. if (id.Equals(default))
  430. {
  431. return null;
  432. }
  433. return LibraryManager.GetItemById(id);
  434. }
  435. }
  436. /// <summary>
  437. /// Gets or sets the date that the item first debuted. For movies this could be premiere date, episodes would be first aired.
  438. /// </summary>
  439. /// <value>The premiere date.</value>
  440. [JsonIgnore]
  441. public DateTime? PremiereDate { get; set; }
  442. /// <summary>
  443. /// Gets or sets the end date.
  444. /// </summary>
  445. /// <value>The end date.</value>
  446. [JsonIgnore]
  447. public DateTime? EndDate { get; set; }
  448. /// <summary>
  449. /// Gets or sets the official rating.
  450. /// </summary>
  451. /// <value>The official rating.</value>
  452. [JsonIgnore]
  453. public string OfficialRating { get; set; }
  454. [JsonIgnore]
  455. public int InheritedParentalRatingValue { get; set; }
  456. /// <summary>
  457. /// Gets or sets the critic rating.
  458. /// </summary>
  459. /// <value>The critic rating.</value>
  460. [JsonIgnore]
  461. public float? CriticRating { get; set; }
  462. /// <summary>
  463. /// Gets or sets the custom rating.
  464. /// </summary>
  465. /// <value>The custom rating.</value>
  466. [JsonIgnore]
  467. public string CustomRating { get; set; }
  468. /// <summary>
  469. /// Gets or sets the overview.
  470. /// </summary>
  471. /// <value>The overview.</value>
  472. [JsonIgnore]
  473. public string Overview { get; set; }
  474. /// <summary>
  475. /// Gets or sets the studios.
  476. /// </summary>
  477. /// <value>The studios.</value>
  478. [JsonIgnore]
  479. public string[] Studios { get; set; }
  480. /// <summary>
  481. /// Gets or sets the genres.
  482. /// </summary>
  483. /// <value>The genres.</value>
  484. [JsonIgnore]
  485. public string[] Genres { get; set; }
  486. /// <summary>
  487. /// Gets or sets the tags.
  488. /// </summary>
  489. /// <value>The tags.</value>
  490. [JsonIgnore]
  491. public string[] Tags { get; set; }
  492. [JsonIgnore]
  493. public string[] ProductionLocations { get; set; }
  494. /// <summary>
  495. /// Gets or sets the home page URL.
  496. /// </summary>
  497. /// <value>The home page URL.</value>
  498. [JsonIgnore]
  499. public string HomePageUrl { get; set; }
  500. /// <summary>
  501. /// Gets or sets the community rating.
  502. /// </summary>
  503. /// <value>The community rating.</value>
  504. [JsonIgnore]
  505. public float? CommunityRating { get; set; }
  506. /// <summary>
  507. /// Gets or sets the run time ticks.
  508. /// </summary>
  509. /// <value>The run time ticks.</value>
  510. [JsonIgnore]
  511. public long? RunTimeTicks { get; set; }
  512. /// <summary>
  513. /// Gets or sets the production year.
  514. /// </summary>
  515. /// <value>The production year.</value>
  516. [JsonIgnore]
  517. public int? ProductionYear { get; set; }
  518. /// <summary>
  519. /// Gets or sets the index number. If the item is part of a series, this is it's number in the series.
  520. /// This could be episode number, album track number, etc.
  521. /// </summary>
  522. /// <value>The index number.</value>
  523. [JsonIgnore]
  524. public int? IndexNumber { get; set; }
  525. /// <summary>
  526. /// Gets or sets the parent index number. For an episode this could be the season number, or for a song this could be the disc number.
  527. /// </summary>
  528. /// <value>The parent index number.</value>
  529. [JsonIgnore]
  530. public int? ParentIndexNumber { get; set; }
  531. [JsonIgnore]
  532. public virtual bool HasLocalAlternateVersions => false;
  533. [JsonIgnore]
  534. public string OfficialRatingForComparison
  535. {
  536. get
  537. {
  538. var officialRating = OfficialRating;
  539. if (!string.IsNullOrEmpty(officialRating))
  540. {
  541. return officialRating;
  542. }
  543. var parent = DisplayParent;
  544. if (parent != null)
  545. {
  546. return parent.OfficialRatingForComparison;
  547. }
  548. return null;
  549. }
  550. }
  551. [JsonIgnore]
  552. public string CustomRatingForComparison
  553. {
  554. get
  555. {
  556. var customRating = CustomRating;
  557. if (!string.IsNullOrEmpty(customRating))
  558. {
  559. return customRating;
  560. }
  561. var parent = DisplayParent;
  562. if (parent != null)
  563. {
  564. return parent.CustomRatingForComparison;
  565. }
  566. return null;
  567. }
  568. }
  569. /// <summary>
  570. /// Gets or sets the provider ids.
  571. /// </summary>
  572. /// <value>The provider ids.</value>
  573. [JsonIgnore]
  574. public Dictionary<string, string> ProviderIds { get; set; }
  575. [JsonIgnore]
  576. public virtual Folder LatestItemsIndexContainer => null;
  577. [JsonIgnore]
  578. public string PresentationUniqueKey { get; set; }
  579. [JsonIgnore]
  580. public virtual bool EnableRememberingTrackSelections => true;
  581. [JsonIgnore]
  582. public virtual bool IsTopParent
  583. {
  584. get
  585. {
  586. if (this is BasePluginFolder || this is Channel)
  587. {
  588. return true;
  589. }
  590. if (this is IHasCollectionType view)
  591. {
  592. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  593. {
  594. return true;
  595. }
  596. }
  597. if (GetParent() is AggregateFolder)
  598. {
  599. return true;
  600. }
  601. return false;
  602. }
  603. }
  604. [JsonIgnore]
  605. public virtual bool SupportsAncestors => true;
  606. [JsonIgnore]
  607. public virtual bool StopRefreshIfLocalMetadataFound => true;
  608. [JsonIgnore]
  609. protected virtual bool SupportsOwnedItems => !ParentId.Equals(default) && IsFileProtocol;
  610. [JsonIgnore]
  611. public virtual bool SupportsPeople => false;
  612. [JsonIgnore]
  613. public virtual bool SupportsThemeMedia => false;
  614. [JsonIgnore]
  615. public virtual bool SupportsInheritedParentImages => false;
  616. /// <summary>
  617. /// Gets a value indicating whether this instance is folder.
  618. /// </summary>
  619. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  620. [JsonIgnore]
  621. public virtual bool IsFolder => false;
  622. [JsonIgnore]
  623. public virtual bool IsDisplayedAsFolder => false;
  624. /// <summary>
  625. /// Gets or sets the remote trailers.
  626. /// </summary>
  627. /// <value>The remote trailers.</value>
  628. public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
  629. public virtual bool SupportsExternalTransfer => false;
  630. public virtual double GetDefaultPrimaryImageAspectRatio()
  631. {
  632. return 0;
  633. }
  634. public virtual string CreatePresentationUniqueKey()
  635. {
  636. return Id.ToString("N", CultureInfo.InvariantCulture);
  637. }
  638. private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
  639. {
  640. var list = new List<Tuple<StringBuilder, bool>>();
  641. int thisMarker = 0;
  642. while (thisMarker < s1.Length)
  643. {
  644. char thisCh = s1[thisMarker];
  645. var thisChunk = new StringBuilder();
  646. bool isNumeric = char.IsDigit(thisCh);
  647. while (thisMarker < s1.Length && char.IsDigit(thisCh) == isNumeric)
  648. {
  649. thisChunk.Append(thisCh);
  650. thisMarker++;
  651. if (thisMarker < s1.Length)
  652. {
  653. thisCh = s1[thisMarker];
  654. }
  655. }
  656. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  657. }
  658. return list;
  659. }
  660. public virtual bool CanDelete()
  661. {
  662. if (SourceType == SourceType.Channel)
  663. {
  664. return ChannelManager.CanDelete(this);
  665. }
  666. return IsFileProtocol;
  667. }
  668. public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
  669. {
  670. if (user.HasPermission(PermissionKind.EnableContentDeletion))
  671. {
  672. return true;
  673. }
  674. var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
  675. if (SourceType == SourceType.Channel)
  676. {
  677. return allowed.Contains(ChannelId);
  678. }
  679. else
  680. {
  681. var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
  682. foreach (var folder in collectionFolders)
  683. {
  684. if (allowed.Contains(folder.Id))
  685. {
  686. return true;
  687. }
  688. }
  689. }
  690. return false;
  691. }
  692. public BaseItem GetOwner()
  693. {
  694. var ownerId = OwnerId;
  695. return ownerId.Equals(default) ? null : LibraryManager.GetItemById(ownerId);
  696. }
  697. public bool CanDelete(User user, List<Folder> allCollectionFolders)
  698. {
  699. return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
  700. }
  701. public bool CanDelete(User user)
  702. {
  703. var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
  704. return CanDelete(user, allCollectionFolders);
  705. }
  706. public virtual bool CanDownload()
  707. {
  708. return false;
  709. }
  710. public virtual bool IsAuthorizedToDownload(User user)
  711. {
  712. return user.HasPermission(PermissionKind.EnableContentDownloading);
  713. }
  714. public bool CanDownload(User user)
  715. {
  716. return CanDownload() && IsAuthorizedToDownload(user);
  717. }
  718. /// <summary>
  719. /// Returns a <see cref="string" /> that represents this instance.
  720. /// </summary>
  721. /// <returns>A <see cref="string" /> that represents this instance.</returns>
  722. public override string ToString()
  723. {
  724. return Name;
  725. }
  726. public string GetInternalMetadataPath()
  727. {
  728. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  729. return GetInternalMetadataPath(basePath);
  730. }
  731. protected virtual string GetInternalMetadataPath(string basePath)
  732. {
  733. if (SourceType == SourceType.Channel)
  734. {
  735. return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture));
  736. }
  737. ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
  738. return System.IO.Path.Join(basePath, "library", idString[..2], idString);
  739. }
  740. /// <summary>
  741. /// Creates the name of the sort.
  742. /// </summary>
  743. /// <returns>System.String.</returns>
  744. protected virtual string CreateSortName()
  745. {
  746. if (Name == null)
  747. {
  748. return null; // some items may not have name filled in properly
  749. }
  750. if (!EnableAlphaNumericSorting)
  751. {
  752. return Name.TrimStart();
  753. }
  754. var sortable = Name.Trim().ToLowerInvariant();
  755. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  756. {
  757. sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
  758. }
  759. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  760. {
  761. sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
  762. }
  763. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  764. {
  765. // Remove from beginning if a space follows
  766. if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
  767. {
  768. sortable = sortable.Remove(0, search.Length + 1);
  769. }
  770. // Remove from middle if surrounded by spaces
  771. sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
  772. // Remove from end if followed by a space
  773. if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
  774. {
  775. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  776. }
  777. }
  778. return ModifySortChunks(sortable);
  779. }
  780. private string ModifySortChunks(string name)
  781. {
  782. var chunks = GetSortChunks(name);
  783. var builder = new StringBuilder();
  784. foreach (var chunk in chunks)
  785. {
  786. var chunkBuilder = chunk.Item1;
  787. // This chunk is numeric
  788. if (chunk.Item2)
  789. {
  790. while (chunkBuilder.Length < 10)
  791. {
  792. chunkBuilder.Insert(0, '0');
  793. }
  794. }
  795. builder.Append(chunkBuilder);
  796. }
  797. // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  798. return builder.ToString().RemoveDiacritics();
  799. }
  800. public BaseItem GetParent()
  801. {
  802. var parentId = ParentId;
  803. if (parentId.Equals(default))
  804. {
  805. return null;
  806. }
  807. return LibraryManager.GetItemById(parentId);
  808. }
  809. public IEnumerable<BaseItem> GetParents()
  810. {
  811. var parent = GetParent();
  812. while (parent != null)
  813. {
  814. yield return parent;
  815. parent = parent.GetParent();
  816. }
  817. }
  818. /// <summary>
  819. /// Finds a parent of a given type.
  820. /// </summary>
  821. /// <typeparam name="T">Type of parent.</typeparam>
  822. /// <returns>``0.</returns>
  823. public T FindParent<T>()
  824. where T : Folder
  825. {
  826. foreach (var parent in GetParents())
  827. {
  828. if (parent is T item)
  829. {
  830. return item;
  831. }
  832. }
  833. return null;
  834. }
  835. /// <summary>
  836. /// Gets the play access.
  837. /// </summary>
  838. /// <param name="user">The user.</param>
  839. /// <returns>PlayAccess.</returns>
  840. public PlayAccess GetPlayAccess(User user)
  841. {
  842. if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
  843. {
  844. return PlayAccess.None;
  845. }
  846. // if (!user.IsParentalScheduleAllowed())
  847. // {
  848. // return PlayAccess.None;
  849. // }
  850. return PlayAccess.Full;
  851. }
  852. public virtual List<MediaStream> GetMediaStreams()
  853. {
  854. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  855. {
  856. ItemId = Id
  857. });
  858. }
  859. protected virtual bool IsActiveRecording()
  860. {
  861. return false;
  862. }
  863. public virtual List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  864. {
  865. if (SourceType == SourceType.Channel)
  866. {
  867. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  868. .ToList();
  869. if (sources.Count > 0)
  870. {
  871. return sources;
  872. }
  873. }
  874. var list = GetAllItemsForMediaSources();
  875. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item, i.MediaSourceType)).ToList();
  876. if (IsActiveRecording())
  877. {
  878. foreach (var mediaSource in result)
  879. {
  880. mediaSource.Type = MediaSourceType.Placeholder;
  881. }
  882. }
  883. return result.OrderBy(i =>
  884. {
  885. if (i.VideoType == VideoType.VideoFile)
  886. {
  887. return 0;
  888. }
  889. return 1;
  890. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  891. .ThenByDescending(i =>
  892. {
  893. var stream = i.VideoStream;
  894. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  895. })
  896. .ToList();
  897. }
  898. protected virtual IEnumerable<(BaseItem Item, MediaSourceType MediaSourceType)> GetAllItemsForMediaSources()
  899. {
  900. return Enumerable.Empty<(BaseItem, MediaSourceType)>();
  901. }
  902. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  903. {
  904. if (item == null)
  905. {
  906. throw new ArgumentNullException(nameof(item));
  907. }
  908. var protocol = item.PathProtocol;
  909. var info = new MediaSourceInfo
  910. {
  911. Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
  912. Protocol = protocol ?? MediaProtocol.File,
  913. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  914. MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
  915. Name = GetMediaSourceName(item),
  916. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  917. RunTimeTicks = item.RunTimeTicks,
  918. Container = item.Container,
  919. Size = item.Size,
  920. Type = type
  921. };
  922. if (string.IsNullOrEmpty(info.Path))
  923. {
  924. info.Type = MediaSourceType.Placeholder;
  925. }
  926. if (info.Protocol == MediaProtocol.File)
  927. {
  928. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  929. }
  930. var video = item as Video;
  931. if (video != null)
  932. {
  933. info.IsoType = video.IsoType;
  934. info.VideoType = video.VideoType;
  935. info.Video3DFormat = video.Video3DFormat;
  936. info.Timestamp = video.Timestamp;
  937. if (video.IsShortcut)
  938. {
  939. info.IsRemote = true;
  940. info.Path = video.ShortcutPath;
  941. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  942. }
  943. if (string.IsNullOrEmpty(info.Container))
  944. {
  945. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  946. {
  947. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  948. {
  949. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  950. }
  951. }
  952. }
  953. }
  954. if (string.IsNullOrEmpty(info.Container))
  955. {
  956. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  957. {
  958. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  959. }
  960. }
  961. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  962. {
  963. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  964. }
  965. if (video != null && video.VideoType != VideoType.VideoFile)
  966. {
  967. info.SupportsDirectStream = false;
  968. }
  969. info.Bitrate = item.TotalBitrate;
  970. info.InferTotalBitrate();
  971. return info;
  972. }
  973. private string GetMediaSourceName(BaseItem item)
  974. {
  975. var terms = new List<string>();
  976. var path = item.Path;
  977. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  978. {
  979. if (HasLocalAlternateVersions)
  980. {
  981. var displayName = System.IO.Path.GetFileNameWithoutExtension(path)
  982. .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase)
  983. .TrimStart(new char[] { ' ', '-' });
  984. if (!string.IsNullOrEmpty(displayName))
  985. {
  986. terms.Add(displayName);
  987. }
  988. }
  989. if (terms.Count == 0)
  990. {
  991. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  992. terms.Add(displayName);
  993. }
  994. }
  995. if (terms.Count == 0)
  996. {
  997. terms.Add(item.Name);
  998. }
  999. if (item is Video video)
  1000. {
  1001. if (video.Video3DFormat.HasValue)
  1002. {
  1003. terms.Add("3D");
  1004. }
  1005. if (video.VideoType == VideoType.BluRay)
  1006. {
  1007. terms.Add("Bluray");
  1008. }
  1009. else if (video.VideoType == VideoType.Dvd)
  1010. {
  1011. terms.Add("DVD");
  1012. }
  1013. else if (video.VideoType == VideoType.Iso)
  1014. {
  1015. if (video.IsoType.HasValue)
  1016. {
  1017. if (video.IsoType.Value == IsoType.BluRay)
  1018. {
  1019. terms.Add("Bluray");
  1020. }
  1021. else if (video.IsoType.Value == IsoType.Dvd)
  1022. {
  1023. terms.Add("DVD");
  1024. }
  1025. }
  1026. else
  1027. {
  1028. terms.Add("ISO");
  1029. }
  1030. }
  1031. }
  1032. return string.Join('/', terms);
  1033. }
  1034. public Task RefreshMetadata(CancellationToken cancellationToken)
  1035. {
  1036. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  1037. }
  1038. protected virtual void TriggerOnRefreshStart()
  1039. {
  1040. }
  1041. protected virtual void TriggerOnRefreshComplete()
  1042. {
  1043. }
  1044. /// <summary>
  1045. /// Overrides the base implementation to refresh metadata for local trailers.
  1046. /// </summary>
  1047. /// <param name="options">The options.</param>
  1048. /// <param name="cancellationToken">The cancellation token.</param>
  1049. /// <returns>true if a provider reports we changed.</returns>
  1050. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1051. {
  1052. TriggerOnRefreshStart();
  1053. var requiresSave = false;
  1054. if (SupportsOwnedItems)
  1055. {
  1056. try
  1057. {
  1058. if (IsFileProtocol)
  1059. {
  1060. requiresSave = await RefreshedOwnedItems(options, GetFileSystemChildren(options.DirectoryService), cancellationToken).ConfigureAwait(false);
  1061. }
  1062. await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh
  1063. }
  1064. catch (Exception ex)
  1065. {
  1066. Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name);
  1067. }
  1068. }
  1069. try
  1070. {
  1071. var refreshOptions = requiresSave
  1072. ? new MetadataRefreshOptions(options)
  1073. {
  1074. ForceSave = true
  1075. }
  1076. : options;
  1077. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1078. }
  1079. finally
  1080. {
  1081. TriggerOnRefreshComplete();
  1082. }
  1083. }
  1084. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1085. {
  1086. if (!IsVisible(user))
  1087. {
  1088. return false;
  1089. }
  1090. if (GetParents().Any(i => !i.IsVisible(user)))
  1091. {
  1092. return false;
  1093. }
  1094. if (checkFolders)
  1095. {
  1096. var topParent = GetParents().LastOrDefault() ?? this;
  1097. if (string.IsNullOrEmpty(topParent.Path))
  1098. {
  1099. return true;
  1100. }
  1101. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1102. if (itemCollectionFolders.Count > 0)
  1103. {
  1104. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1105. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1106. {
  1107. return false;
  1108. }
  1109. }
  1110. }
  1111. return true;
  1112. }
  1113. public void SetParent(Folder parent)
  1114. {
  1115. ParentId = parent == null ? Guid.Empty : parent.Id;
  1116. }
  1117. /// <summary>
  1118. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1119. /// Returns true or false indicating if changes were found.
  1120. /// </summary>
  1121. /// <param name="options">The metadata refresh options.</param>
  1122. /// <param name="fileSystemChildren">The list of filesystem children.</param>
  1123. /// <param name="cancellationToken">The cancellation token.</param>
  1124. /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
  1125. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1126. {
  1127. if (!IsFileProtocol || !SupportsOwnedItems || IsInMixedFolder || this is ICollectionFolder or UserRootFolder or AggregateFolder || this.GetType() == typeof(Folder))
  1128. {
  1129. return false;
  1130. }
  1131. return await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1132. }
  1133. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1134. {
  1135. var path = ContainingFolderPath;
  1136. return directoryService.GetFileSystemEntries(path);
  1137. }
  1138. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1139. {
  1140. var extras = LibraryManager.FindExtras(item, fileSystemChildren, options.DirectoryService).ToArray();
  1141. var newExtraIds = extras.Select(i => i.Id).ToArray();
  1142. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1143. if (!extrasChanged && !options.ReplaceAllMetadata && options.MetadataRefreshMode != MetadataRefreshMode.FullRefresh)
  1144. {
  1145. return false;
  1146. }
  1147. var ownerId = item.Id;
  1148. var tasks = extras.Select(i =>
  1149. {
  1150. var subOptions = new MetadataRefreshOptions(options);
  1151. if (!i.OwnerId.Equals(ownerId) || !i.ParentId.Equals(default))
  1152. {
  1153. i.OwnerId = ownerId;
  1154. i.ParentId = Guid.Empty;
  1155. subOptions.ForceSave = true;
  1156. }
  1157. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1158. });
  1159. await Task.WhenAll(tasks).ConfigureAwait(false);
  1160. item.ExtraIds = newExtraIds;
  1161. return true;
  1162. }
  1163. public string GetPresentationUniqueKey()
  1164. {
  1165. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1166. }
  1167. public virtual bool RequiresRefresh()
  1168. {
  1169. return false;
  1170. }
  1171. public virtual List<string> GetUserDataKeys()
  1172. {
  1173. var list = new List<string>();
  1174. if (SourceType == SourceType.Channel)
  1175. {
  1176. if (!string.IsNullOrEmpty(ExternalId))
  1177. {
  1178. list.Add(ExternalId);
  1179. }
  1180. }
  1181. list.Add(Id.ToString());
  1182. return list;
  1183. }
  1184. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1185. {
  1186. var updateType = ItemUpdateType.None;
  1187. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1188. {
  1189. IsInMixedFolder = newItem.IsInMixedFolder;
  1190. updateType |= ItemUpdateType.MetadataImport;
  1191. }
  1192. return updateType;
  1193. }
  1194. public void AfterMetadataRefresh()
  1195. {
  1196. _sortName = null;
  1197. }
  1198. /// <summary>
  1199. /// Gets the preferred metadata language.
  1200. /// </summary>
  1201. /// <returns>System.String.</returns>
  1202. public string GetPreferredMetadataLanguage()
  1203. {
  1204. string lang = PreferredMetadataLanguage;
  1205. if (string.IsNullOrEmpty(lang))
  1206. {
  1207. lang = GetParents()
  1208. .Select(i => i.PreferredMetadataLanguage)
  1209. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1210. }
  1211. if (string.IsNullOrEmpty(lang))
  1212. {
  1213. lang = LibraryManager.GetCollectionFolders(this)
  1214. .Select(i => i.PreferredMetadataLanguage)
  1215. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1216. }
  1217. if (string.IsNullOrEmpty(lang))
  1218. {
  1219. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1220. }
  1221. if (string.IsNullOrEmpty(lang))
  1222. {
  1223. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1224. }
  1225. return lang;
  1226. }
  1227. /// <summary>
  1228. /// Gets the preferred metadata language.
  1229. /// </summary>
  1230. /// <returns>System.String.</returns>
  1231. public string GetPreferredMetadataCountryCode()
  1232. {
  1233. string lang = PreferredMetadataCountryCode;
  1234. if (string.IsNullOrEmpty(lang))
  1235. {
  1236. lang = GetParents()
  1237. .Select(i => i.PreferredMetadataCountryCode)
  1238. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1239. }
  1240. if (string.IsNullOrEmpty(lang))
  1241. {
  1242. lang = LibraryManager.GetCollectionFolders(this)
  1243. .Select(i => i.PreferredMetadataCountryCode)
  1244. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1245. }
  1246. if (string.IsNullOrEmpty(lang))
  1247. {
  1248. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1249. }
  1250. if (string.IsNullOrEmpty(lang))
  1251. {
  1252. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1253. }
  1254. return lang;
  1255. }
  1256. public virtual bool IsSaveLocalMetadataEnabled()
  1257. {
  1258. if (SourceType == SourceType.Channel)
  1259. {
  1260. return false;
  1261. }
  1262. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1263. return libraryOptions.SaveLocalMetadata;
  1264. }
  1265. /// <summary>
  1266. /// Determines if a given user has access to this item.
  1267. /// </summary>
  1268. /// <param name="user">The user.</param>
  1269. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1270. /// <exception cref="ArgumentNullException">If user is null.</exception>
  1271. public bool IsParentalAllowed(User user)
  1272. {
  1273. if (user == null)
  1274. {
  1275. throw new ArgumentNullException(nameof(user));
  1276. }
  1277. if (!IsVisibleViaTags(user))
  1278. {
  1279. return false;
  1280. }
  1281. var maxAllowedRating = user.MaxParentalAgeRating;
  1282. if (maxAllowedRating == null)
  1283. {
  1284. return true;
  1285. }
  1286. var rating = CustomRatingForComparison;
  1287. if (string.IsNullOrEmpty(rating))
  1288. {
  1289. rating = OfficialRatingForComparison;
  1290. }
  1291. if (string.IsNullOrEmpty(rating))
  1292. {
  1293. return !GetBlockUnratedValue(user);
  1294. }
  1295. var value = LocalizationManager.GetRatingLevel(rating);
  1296. // Could not determine the integer value
  1297. if (!value.HasValue)
  1298. {
  1299. var isAllowed = !GetBlockUnratedValue(user);
  1300. if (!isAllowed)
  1301. {
  1302. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1303. }
  1304. return isAllowed;
  1305. }
  1306. return value.Value <= maxAllowedRating.Value;
  1307. }
  1308. public int? GetParentalRatingValue()
  1309. {
  1310. var rating = CustomRating;
  1311. if (string.IsNullOrEmpty(rating))
  1312. {
  1313. rating = OfficialRating;
  1314. }
  1315. if (string.IsNullOrEmpty(rating))
  1316. {
  1317. return null;
  1318. }
  1319. return LocalizationManager.GetRatingLevel(rating);
  1320. }
  1321. public int? GetInheritedParentalRatingValue()
  1322. {
  1323. var rating = CustomRatingForComparison;
  1324. if (string.IsNullOrEmpty(rating))
  1325. {
  1326. rating = OfficialRatingForComparison;
  1327. }
  1328. if (string.IsNullOrEmpty(rating))
  1329. {
  1330. return null;
  1331. }
  1332. return LocalizationManager.GetRatingLevel(rating);
  1333. }
  1334. public List<string> GetInheritedTags()
  1335. {
  1336. var list = new List<string>();
  1337. list.AddRange(Tags);
  1338. foreach (var parent in GetParents())
  1339. {
  1340. list.AddRange(parent.Tags);
  1341. }
  1342. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1343. }
  1344. private bool IsVisibleViaTags(User user)
  1345. {
  1346. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparison.OrdinalIgnoreCase)))
  1347. {
  1348. return false;
  1349. }
  1350. return true;
  1351. }
  1352. protected virtual bool IsAllowTagFilterEnforced()
  1353. {
  1354. return true;
  1355. }
  1356. public virtual UnratedItem GetBlockUnratedType()
  1357. {
  1358. if (SourceType == SourceType.Channel)
  1359. {
  1360. return UnratedItem.ChannelContent;
  1361. }
  1362. return UnratedItem.Other;
  1363. }
  1364. /// <summary>
  1365. /// Gets the block unrated value.
  1366. /// </summary>
  1367. /// <param name="user">The configuration.</param>
  1368. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1369. protected virtual bool GetBlockUnratedValue(User user)
  1370. {
  1371. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1372. // Special folders like series and albums will override this method.
  1373. if (IsFolder || this is IItemByName)
  1374. {
  1375. return false;
  1376. }
  1377. return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType());
  1378. }
  1379. /// <summary>
  1380. /// Determines if this folder should be visible to a given user.
  1381. /// Default is just parental allowed. Can be overridden for more functionality.
  1382. /// </summary>
  1383. /// <param name="user">The user.</param>
  1384. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1385. /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
  1386. public virtual bool IsVisible(User user)
  1387. {
  1388. if (user == null)
  1389. {
  1390. throw new ArgumentNullException(nameof(user));
  1391. }
  1392. return IsParentalAllowed(user);
  1393. }
  1394. public virtual bool IsVisibleStandalone(User user)
  1395. {
  1396. if (SourceType == SourceType.Channel)
  1397. {
  1398. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1399. }
  1400. return IsVisibleStandaloneInternal(user, true);
  1401. }
  1402. public virtual string GetClientTypeName()
  1403. {
  1404. if (IsFolder && SourceType == SourceType.Channel && this is not Channel)
  1405. {
  1406. return "ChannelFolderItem";
  1407. }
  1408. return GetType().Name;
  1409. }
  1410. public BaseItemKind GetBaseItemKind()
  1411. {
  1412. return _baseItemKind ??= Enum.Parse<BaseItemKind>(GetClientTypeName());
  1413. }
  1414. /// <summary>
  1415. /// Gets the linked child.
  1416. /// </summary>
  1417. /// <param name="info">The info.</param>
  1418. /// <returns>BaseItem.</returns>
  1419. protected BaseItem GetLinkedChild(LinkedChild info)
  1420. {
  1421. // First get using the cached Id
  1422. if (info.ItemId.HasValue)
  1423. {
  1424. if (info.ItemId.Value.Equals(default))
  1425. {
  1426. return null;
  1427. }
  1428. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1429. if (itemById != null)
  1430. {
  1431. return itemById;
  1432. }
  1433. }
  1434. var item = FindLinkedChild(info);
  1435. // If still null, log
  1436. if (item == null)
  1437. {
  1438. // Don't keep searching over and over
  1439. info.ItemId = Guid.Empty;
  1440. }
  1441. else
  1442. {
  1443. // Cache the id for next time
  1444. info.ItemId = item.Id;
  1445. }
  1446. return item;
  1447. }
  1448. private BaseItem FindLinkedChild(LinkedChild info)
  1449. {
  1450. var path = info.Path;
  1451. if (!string.IsNullOrEmpty(path))
  1452. {
  1453. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1454. var itemByPath = LibraryManager.FindByPath(path, null);
  1455. if (itemByPath == null)
  1456. {
  1457. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1458. }
  1459. return itemByPath;
  1460. }
  1461. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1462. {
  1463. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1464. if (item == null)
  1465. {
  1466. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1467. }
  1468. return item;
  1469. }
  1470. return null;
  1471. }
  1472. /// <summary>
  1473. /// Adds a studio to the item.
  1474. /// </summary>
  1475. /// <param name="name">The name.</param>
  1476. /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
  1477. public void AddStudio(string name)
  1478. {
  1479. if (string.IsNullOrEmpty(name))
  1480. {
  1481. throw new ArgumentNullException(nameof(name));
  1482. }
  1483. var current = Studios;
  1484. if (!current.Contains(name, StringComparison.OrdinalIgnoreCase))
  1485. {
  1486. int curLen = current.Length;
  1487. if (curLen == 0)
  1488. {
  1489. Studios = new[] { name };
  1490. }
  1491. else
  1492. {
  1493. var newArr = new string[curLen + 1];
  1494. current.CopyTo(newArr, 0);
  1495. newArr[curLen] = name;
  1496. Studios = newArr;
  1497. }
  1498. }
  1499. }
  1500. public void SetStudios(IEnumerable<string> names)
  1501. {
  1502. Studios = names.Distinct().ToArray();
  1503. }
  1504. /// <summary>
  1505. /// Adds a genre to the item.
  1506. /// </summary>
  1507. /// <param name="name">The name.</param>
  1508. /// <exception cref="ArgumentNullException">Throwns if name is null.</exception>
  1509. public void AddGenre(string name)
  1510. {
  1511. if (string.IsNullOrEmpty(name))
  1512. {
  1513. throw new ArgumentNullException(nameof(name));
  1514. }
  1515. var genres = Genres;
  1516. if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
  1517. {
  1518. var list = genres.ToList();
  1519. list.Add(name);
  1520. Genres = list.ToArray();
  1521. }
  1522. }
  1523. /// <summary>
  1524. /// Marks the played.
  1525. /// </summary>
  1526. /// <param name="user">The user.</param>
  1527. /// <param name="datePlayed">The date played.</param>
  1528. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1529. /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
  1530. public virtual void MarkPlayed(
  1531. User user,
  1532. DateTime? datePlayed,
  1533. bool resetPosition)
  1534. {
  1535. if (user == null)
  1536. {
  1537. throw new ArgumentNullException(nameof(user));
  1538. }
  1539. var data = UserDataManager.GetUserData(user, this);
  1540. if (datePlayed.HasValue)
  1541. {
  1542. // Increment
  1543. data.PlayCount++;
  1544. }
  1545. // Ensure it's at least one
  1546. data.PlayCount = Math.Max(data.PlayCount, 1);
  1547. if (resetPosition)
  1548. {
  1549. data.PlaybackPositionTicks = 0;
  1550. }
  1551. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1552. data.Played = true;
  1553. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1554. }
  1555. /// <summary>
  1556. /// Marks the unplayed.
  1557. /// </summary>
  1558. /// <param name="user">The user.</param>
  1559. /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
  1560. public virtual void MarkUnplayed(User user)
  1561. {
  1562. if (user == null)
  1563. {
  1564. throw new ArgumentNullException(nameof(user));
  1565. }
  1566. var data = UserDataManager.GetUserData(user, this);
  1567. // I think it is okay to do this here.
  1568. // if this is only called when a user is manually forcing something to un-played
  1569. // then it probably is what we want to do...
  1570. data.PlayCount = 0;
  1571. data.PlaybackPositionTicks = 0;
  1572. data.LastPlayedDate = null;
  1573. data.Played = false;
  1574. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1575. }
  1576. /// <summary>
  1577. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1578. /// </summary>
  1579. public virtual void ChangedExternally()
  1580. {
  1581. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1582. }
  1583. /// <summary>
  1584. /// Gets an image.
  1585. /// </summary>
  1586. /// <param name="type">The type.</param>
  1587. /// <param name="imageIndex">Index of the image.</param>
  1588. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1589. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
  1590. public bool HasImage(ImageType type, int imageIndex)
  1591. {
  1592. return GetImageInfo(type, imageIndex) != null;
  1593. }
  1594. public void SetImage(ItemImageInfo image, int index)
  1595. {
  1596. if (image.Type == ImageType.Chapter)
  1597. {
  1598. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1599. }
  1600. var existingImage = GetImageInfo(image.Type, index);
  1601. if (existingImage == null)
  1602. {
  1603. AddImage(image);
  1604. }
  1605. else
  1606. {
  1607. existingImage.Path = image.Path;
  1608. existingImage.DateModified = image.DateModified;
  1609. existingImage.Width = image.Width;
  1610. existingImage.Height = image.Height;
  1611. existingImage.BlurHash = image.BlurHash;
  1612. }
  1613. }
  1614. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1615. {
  1616. if (type == ImageType.Chapter)
  1617. {
  1618. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1619. }
  1620. var image = GetImageInfo(type, index);
  1621. if (image == null)
  1622. {
  1623. AddImage(GetImageInfo(file, type));
  1624. }
  1625. else
  1626. {
  1627. var imageInfo = GetImageInfo(file, type);
  1628. image.Path = file.FullName;
  1629. image.DateModified = imageInfo.DateModified;
  1630. // reset these values
  1631. image.Width = 0;
  1632. image.Height = 0;
  1633. }
  1634. }
  1635. /// <summary>
  1636. /// Deletes the image.
  1637. /// </summary>
  1638. /// <param name="type">The type.</param>
  1639. /// <param name="index">The index.</param>
  1640. /// <returns>A task.</returns>
  1641. public async Task DeleteImageAsync(ImageType type, int index)
  1642. {
  1643. var info = GetImageInfo(type, index);
  1644. if (info == null)
  1645. {
  1646. // Nothing to do
  1647. return;
  1648. }
  1649. // Remove it from the item
  1650. RemoveImage(info);
  1651. if (info.IsLocalFile)
  1652. {
  1653. FileSystem.DeleteFile(info.Path);
  1654. }
  1655. await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  1656. }
  1657. public void RemoveImage(ItemImageInfo image)
  1658. {
  1659. RemoveImages(new[] { image });
  1660. }
  1661. public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
  1662. {
  1663. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1664. }
  1665. public void AddImage(ItemImageInfo image)
  1666. {
  1667. var current = ImageInfos;
  1668. var currentCount = current.Length;
  1669. var newArr = new ItemImageInfo[currentCount + 1];
  1670. current.CopyTo(newArr, 0);
  1671. newArr[currentCount] = image;
  1672. ImageInfos = newArr;
  1673. }
  1674. public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1675. => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken);
  1676. /// <summary>
  1677. /// Validates that images within the item are still on the filesystem.
  1678. /// </summary>
  1679. /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
  1680. public bool ValidateImages()
  1681. {
  1682. List<ItemImageInfo> deletedImages = null;
  1683. foreach (var imageInfo in ImageInfos)
  1684. {
  1685. if (!imageInfo.IsLocalFile)
  1686. {
  1687. continue;
  1688. }
  1689. if (File.Exists(imageInfo.Path))
  1690. {
  1691. continue;
  1692. }
  1693. (deletedImages ??= new List<ItemImageInfo>()).Add(imageInfo);
  1694. }
  1695. var anyImagesRemoved = deletedImages?.Count > 0;
  1696. if (anyImagesRemoved)
  1697. {
  1698. RemoveImages(deletedImages);
  1699. }
  1700. return anyImagesRemoved;
  1701. }
  1702. /// <summary>
  1703. /// Gets the image path.
  1704. /// </summary>
  1705. /// <param name="imageType">Type of the image.</param>
  1706. /// <param name="imageIndex">Index of the image.</param>
  1707. /// <returns>System.String.</returns>
  1708. /// <exception cref="ArgumentNullException">Item is null.</exception>
  1709. public string GetImagePath(ImageType imageType, int imageIndex)
  1710. => GetImageInfo(imageType, imageIndex)?.Path;
  1711. /// <summary>
  1712. /// Gets the image information.
  1713. /// </summary>
  1714. /// <param name="imageType">Type of the image.</param>
  1715. /// <param name="imageIndex">Index of the image.</param>
  1716. /// <returns>ItemImageInfo.</returns>
  1717. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1718. {
  1719. if (imageType == ImageType.Chapter)
  1720. {
  1721. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1722. if (chapter == null)
  1723. {
  1724. return null;
  1725. }
  1726. var path = chapter.ImagePath;
  1727. if (string.IsNullOrEmpty(path))
  1728. {
  1729. return null;
  1730. }
  1731. return new ItemImageInfo
  1732. {
  1733. Path = path,
  1734. DateModified = chapter.ImageDateModified,
  1735. Type = imageType
  1736. };
  1737. }
  1738. // Music albums usually don't have dedicated backdrops, so return one from the artist instead
  1739. if (GetType() == typeof(MusicAlbum) && imageType == ImageType.Backdrop)
  1740. {
  1741. var artist = FindParent<MusicArtist>();
  1742. if (artist != null)
  1743. {
  1744. return artist.GetImages(imageType).ElementAtOrDefault(imageIndex);
  1745. }
  1746. }
  1747. return GetImages(imageType)
  1748. .ElementAtOrDefault(imageIndex);
  1749. }
  1750. /// <summary>
  1751. /// Computes image index for given image or raises if no matching image found.
  1752. /// </summary>
  1753. /// <param name="image">Image to compute index for.</param>
  1754. /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
  1755. /// </exception>
  1756. /// <returns>Image index.</returns>
  1757. public int GetImageIndex(ItemImageInfo image)
  1758. {
  1759. if (image == null)
  1760. {
  1761. throw new ArgumentNullException(nameof(image));
  1762. }
  1763. if (image.Type == ImageType.Chapter)
  1764. {
  1765. var chapters = ItemRepository.GetChapters(this);
  1766. for (var i = 0; i < chapters.Count; i++)
  1767. {
  1768. if (chapters[i].ImagePath == image.Path)
  1769. {
  1770. return i;
  1771. }
  1772. }
  1773. throw new ArgumentException("No chapter index found for image path", image.Path);
  1774. }
  1775. var images = GetImages(image.Type).ToArray();
  1776. for (var i = 0; i < images.Length; i++)
  1777. {
  1778. if (images[i].Path == image.Path)
  1779. {
  1780. return i;
  1781. }
  1782. }
  1783. throw new ArgumentException("No image index found for image path", image.Path);
  1784. }
  1785. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1786. {
  1787. if (imageType == ImageType.Chapter)
  1788. {
  1789. throw new ArgumentException("No image info for chapter images");
  1790. }
  1791. // Yield return is more performant than LINQ Where on an Array
  1792. for (var i = 0; i < ImageInfos.Length; i++)
  1793. {
  1794. var imageInfo = ImageInfos[i];
  1795. if (imageInfo.Type == imageType)
  1796. {
  1797. yield return imageInfo;
  1798. }
  1799. }
  1800. }
  1801. /// <summary>
  1802. /// Adds the images, updating metadata if they already are part of this item.
  1803. /// </summary>
  1804. /// <param name="imageType">Type of the image.</param>
  1805. /// <param name="images">The images.</param>
  1806. /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns>
  1807. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
  1808. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1809. {
  1810. if (imageType == ImageType.Chapter)
  1811. {
  1812. throw new ArgumentException("Cannot call AddImages with chapter images");
  1813. }
  1814. var existingImages = GetImages(imageType)
  1815. .ToList();
  1816. var newImageList = new List<FileSystemMetadata>();
  1817. var imageUpdated = false;
  1818. foreach (var newImage in images)
  1819. {
  1820. if (newImage == null)
  1821. {
  1822. throw new ArgumentException("null image found in list");
  1823. }
  1824. var existing = existingImages
  1825. .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1826. if (existing == null)
  1827. {
  1828. newImageList.Add(newImage);
  1829. }
  1830. else
  1831. {
  1832. if (existing.IsLocalFile)
  1833. {
  1834. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1835. // If date changed then we need to reset saved image dimensions
  1836. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  1837. {
  1838. existing.Width = 0;
  1839. existing.Height = 0;
  1840. imageUpdated = true;
  1841. }
  1842. existing.DateModified = newDateModified;
  1843. }
  1844. }
  1845. }
  1846. if (newImageList.Count > 0)
  1847. {
  1848. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  1849. }
  1850. return imageUpdated || newImageList.Count > 0;
  1851. }
  1852. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1853. {
  1854. return new ItemImageInfo
  1855. {
  1856. Path = file.FullName,
  1857. Type = type,
  1858. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1859. };
  1860. }
  1861. /// <summary>
  1862. /// Gets the file system path to delete when the item is to be deleted.
  1863. /// </summary>
  1864. /// <returns>The metadata for the deleted paths.</returns>
  1865. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1866. {
  1867. return new[]
  1868. {
  1869. new FileSystemMetadata
  1870. {
  1871. FullName = Path,
  1872. IsDirectory = IsFolder
  1873. }
  1874. }.Concat(GetLocalMetadataFilesToDelete());
  1875. }
  1876. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1877. {
  1878. if (IsFolder || !IsInMixedFolder)
  1879. {
  1880. return new List<FileSystemMetadata>();
  1881. }
  1882. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1883. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  1884. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1885. .ToList();
  1886. }
  1887. public bool AllowsMultipleImages(ImageType type)
  1888. {
  1889. return type == ImageType.Backdrop || type == ImageType.Chapter;
  1890. }
  1891. public Task SwapImagesAsync(ImageType type, int index1, int index2)
  1892. {
  1893. if (!AllowsMultipleImages(type))
  1894. {
  1895. throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots");
  1896. }
  1897. var info1 = GetImageInfo(type, index1);
  1898. var info2 = GetImageInfo(type, index2);
  1899. if (info1 == null || info2 == null)
  1900. {
  1901. // Nothing to do
  1902. return Task.CompletedTask;
  1903. }
  1904. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1905. {
  1906. // TODO: Not supported yet
  1907. return Task.CompletedTask;
  1908. }
  1909. var path1 = info1.Path;
  1910. var path2 = info2.Path;
  1911. FileSystem.SwapFiles(path1, path2);
  1912. // Refresh these values
  1913. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1914. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1915. info1.Width = 0;
  1916. info1.Height = 0;
  1917. info2.Width = 0;
  1918. info2.Height = 0;
  1919. return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1920. }
  1921. public virtual bool IsPlayed(User user)
  1922. {
  1923. var userdata = UserDataManager.GetUserData(user, this);
  1924. return userdata != null && userdata.Played;
  1925. }
  1926. public bool IsFavoriteOrLiked(User user)
  1927. {
  1928. var userdata = UserDataManager.GetUserData(user, this);
  1929. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1930. }
  1931. public virtual bool IsUnplayed(User user)
  1932. {
  1933. if (user == null)
  1934. {
  1935. throw new ArgumentNullException(nameof(user));
  1936. }
  1937. var userdata = UserDataManager.GetUserData(user, this);
  1938. return userdata == null || !userdata.Played;
  1939. }
  1940. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1941. {
  1942. return GetItemLookupInfo<ItemLookupInfo>();
  1943. }
  1944. protected T GetItemLookupInfo<T>()
  1945. where T : ItemLookupInfo, new()
  1946. {
  1947. return new T
  1948. {
  1949. Path = Path,
  1950. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1951. MetadataLanguage = GetPreferredMetadataLanguage(),
  1952. Name = GetNameForMetadataLookup(),
  1953. OriginalTitle = OriginalTitle,
  1954. ProviderIds = ProviderIds,
  1955. IndexNumber = IndexNumber,
  1956. ParentIndexNumber = ParentIndexNumber,
  1957. Year = ProductionYear,
  1958. PremiereDate = PremiereDate
  1959. };
  1960. }
  1961. protected virtual string GetNameForMetadataLookup()
  1962. {
  1963. return Name;
  1964. }
  1965. /// <summary>
  1966. /// This is called before any metadata refresh and returns true if changes were made.
  1967. /// </summary>
  1968. /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
  1969. /// <returns>true if the item has change, else false.</returns>
  1970. public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
  1971. {
  1972. _sortName = null;
  1973. var hasChanges = false;
  1974. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1975. {
  1976. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  1977. hasChanges = true;
  1978. }
  1979. return hasChanges;
  1980. }
  1981. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  1982. {
  1983. if (protocol == MediaProtocol.File)
  1984. {
  1985. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1986. }
  1987. return path;
  1988. }
  1989. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1990. {
  1991. if (RunTimeTicks.HasValue)
  1992. {
  1993. double pct = RunTimeTicks.Value;
  1994. if (pct > 0)
  1995. {
  1996. pct = userData.PlaybackPositionTicks / pct;
  1997. if (pct > 0)
  1998. {
  1999. dto.PlayedPercentage = 100 * pct;
  2000. }
  2001. }
  2002. }
  2003. }
  2004. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2005. {
  2006. var newOptions = new MetadataRefreshOptions(options)
  2007. {
  2008. SearchResult = null
  2009. };
  2010. var item = this;
  2011. if (copyTitleMetadata)
  2012. {
  2013. // Take some data from the main item, for querying purposes
  2014. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2015. {
  2016. newOptions.ForceSave = true;
  2017. ownedItem.Genres = item.Genres;
  2018. }
  2019. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2020. {
  2021. newOptions.ForceSave = true;
  2022. ownedItem.Studios = item.Studios;
  2023. }
  2024. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2025. {
  2026. newOptions.ForceSave = true;
  2027. ownedItem.ProductionLocations = item.ProductionLocations;
  2028. }
  2029. if (item.CommunityRating != ownedItem.CommunityRating)
  2030. {
  2031. ownedItem.CommunityRating = item.CommunityRating;
  2032. newOptions.ForceSave = true;
  2033. }
  2034. if (item.CriticRating != ownedItem.CriticRating)
  2035. {
  2036. ownedItem.CriticRating = item.CriticRating;
  2037. newOptions.ForceSave = true;
  2038. }
  2039. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2040. {
  2041. ownedItem.Overview = item.Overview;
  2042. newOptions.ForceSave = true;
  2043. }
  2044. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2045. {
  2046. ownedItem.OfficialRating = item.OfficialRating;
  2047. newOptions.ForceSave = true;
  2048. }
  2049. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2050. {
  2051. ownedItem.CustomRating = item.CustomRating;
  2052. newOptions.ForceSave = true;
  2053. }
  2054. }
  2055. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2056. }
  2057. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2058. {
  2059. var newOptions = new MetadataRefreshOptions(options)
  2060. {
  2061. SearchResult = null
  2062. };
  2063. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2064. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2065. var video = LibraryManager.GetItemById(id) as Video;
  2066. if (video == null)
  2067. {
  2068. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2069. newOptions.ForceSave = true;
  2070. }
  2071. if (video == null)
  2072. {
  2073. return Task.FromResult(true);
  2074. }
  2075. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2076. }
  2077. public string GetEtag(User user)
  2078. {
  2079. var list = GetEtagValues(user);
  2080. return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2081. }
  2082. protected virtual List<string> GetEtagValues(User user)
  2083. {
  2084. return new List<string>
  2085. {
  2086. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2087. };
  2088. }
  2089. public virtual IEnumerable<Guid> GetAncestorIds()
  2090. {
  2091. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2092. }
  2093. public BaseItem GetTopParent()
  2094. {
  2095. if (IsTopParent)
  2096. {
  2097. return this;
  2098. }
  2099. return GetParents().FirstOrDefault(parent => parent.IsTopParent);
  2100. }
  2101. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2102. {
  2103. return new[] { Id };
  2104. }
  2105. public virtual List<ExternalUrl> GetRelatedUrls()
  2106. {
  2107. return new List<ExternalUrl>();
  2108. }
  2109. public virtual double? GetRefreshProgress()
  2110. {
  2111. return null;
  2112. }
  2113. public virtual ItemUpdateType OnMetadataChanged()
  2114. {
  2115. var updateType = ItemUpdateType.None;
  2116. var item = this;
  2117. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2118. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2119. {
  2120. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2121. updateType |= ItemUpdateType.MetadataImport;
  2122. }
  2123. return updateType;
  2124. }
  2125. /// <summary>
  2126. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2127. /// </summary>
  2128. /// <param name="children">Media children.</param>
  2129. /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
  2130. public bool UpdateRatingToItems(IList<BaseItem> children)
  2131. {
  2132. var currentOfficialRating = OfficialRating;
  2133. // Gather all possible ratings
  2134. var ratings = children
  2135. .Select(i => i.OfficialRating)
  2136. .Where(i => !string.IsNullOrEmpty(i))
  2137. .Distinct(StringComparer.OrdinalIgnoreCase)
  2138. .Select(rating => (rating, LocalizationManager.GetRatingLevel(rating)))
  2139. .OrderBy(i => i.Item2 ?? 1000)
  2140. .Select(i => i.rating);
  2141. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2142. return !string.Equals(
  2143. currentOfficialRating ?? string.Empty,
  2144. OfficialRating ?? string.Empty,
  2145. StringComparison.OrdinalIgnoreCase);
  2146. }
  2147. public IReadOnlyList<BaseItem> GetThemeSongs()
  2148. {
  2149. return GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeSong).ToArray();
  2150. }
  2151. public IReadOnlyList<BaseItem> GetThemeVideos()
  2152. {
  2153. return GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeVideo).ToArray();
  2154. }
  2155. /// <summary>
  2156. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2157. /// </summary>
  2158. /// <returns>An enumerable containing the items.</returns>
  2159. public IEnumerable<BaseItem> GetExtras()
  2160. {
  2161. return ExtraIds
  2162. .Select(LibraryManager.GetItemById)
  2163. .Where(i => i != null)
  2164. .OrderBy(i => i.SortName);
  2165. }
  2166. /// <summary>
  2167. /// Get all extras with specific types that are associated with this item.
  2168. /// </summary>
  2169. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2170. /// <returns>An enumerable containing the extras.</returns>
  2171. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2172. {
  2173. return ExtraIds
  2174. .Select(LibraryManager.GetItemById)
  2175. .Where(i => i != null)
  2176. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
  2177. }
  2178. public virtual long GetRunTimeTicksForPlayState()
  2179. {
  2180. return RunTimeTicks ?? 0;
  2181. }
  2182. /// <inheritdoc />
  2183. public override bool Equals(object obj)
  2184. {
  2185. return obj is BaseItem baseItem && this.Equals(baseItem);
  2186. }
  2187. /// <inheritdoc />
  2188. public bool Equals(BaseItem other) => other is not null && other.Id.Equals(Id);
  2189. /// <inheritdoc />
  2190. public override int GetHashCode() => HashCode.Combine(Id);
  2191. }
  2192. }