BaseItem.cs 83 KB

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