BaseItem.cs 81 KB

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