BaseItem.cs 95 KB

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