BaseItem.cs 84 KB

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