BaseItem.cs 85 KB

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