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