2
0

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