BaseItem.cs 81 KB

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