BaseItem.cs 81 KB

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