BaseItem.cs 96 KB

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