2
0

BaseItem.cs 96 KB

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