BaseItem.cs 82 KB

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