BaseItem.cs 85 KB

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