BaseItem.cs 84 KB

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