BaseItem.cs 82 KB

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