BaseItem.cs 86 KB

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