2
0

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