BaseItem.cs 81 KB

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