BaseItem.cs 81 KB

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