2
0

BaseItem.cs 82 KB

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