BaseItem.cs 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.Json.Serialization;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Data.Entities;
  11. using Jellyfin.Data.Enums;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Controller.Channels;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Dto;
  16. using MediaBrowser.Controller.Extensions;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.Persistence;
  19. using MediaBrowser.Controller.Providers;
  20. using MediaBrowser.Model.Configuration;
  21. using MediaBrowser.Model.Dto;
  22. using MediaBrowser.Model.Entities;
  23. using MediaBrowser.Model.Globalization;
  24. using MediaBrowser.Model.IO;
  25. using MediaBrowser.Model.Library;
  26. using MediaBrowser.Model.LiveTv;
  27. using MediaBrowser.Model.MediaInfo;
  28. using MediaBrowser.Model.Providers;
  29. using MediaBrowser.Model.Users;
  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<MetadataFields>();
  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 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 MetadataFields[] 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 new 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. var idString = Id.ToString("N", CultureInfo.InvariantCulture);
  560. basePath = System.IO.Path.Combine(basePath, "library");
  561. return System.IO.Path.Combine(basePath, idString.Substring(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) return null; //some items may not have name filled in properly
  570. if (!EnableAlphaNumericSorting)
  571. {
  572. return Name.TrimStart();
  573. }
  574. var sortable = Name.Trim().ToLowerInvariant();
  575. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  576. {
  577. sortable = sortable.Replace(removeChar, string.Empty);
  578. }
  579. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  580. {
  581. sortable = sortable.Replace(replaceChar, " ");
  582. }
  583. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  584. {
  585. // Remove from beginning if a space follows
  586. if (sortable.StartsWith(search + " "))
  587. {
  588. sortable = sortable.Remove(0, search.Length + 1);
  589. }
  590. // Remove from middle if surrounded by spaces
  591. sortable = sortable.Replace(" " + search + " ", " ");
  592. // Remove from end if followed by a space
  593. if (sortable.EndsWith(" " + search))
  594. {
  595. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  596. }
  597. }
  598. return ModifySortChunks(sortable);
  599. }
  600. private string ModifySortChunks(string name)
  601. {
  602. var chunks = GetSortChunks(name);
  603. var builder = new StringBuilder();
  604. foreach (var chunk in chunks)
  605. {
  606. var chunkBuilder = chunk.Item1;
  607. // This chunk is numeric
  608. if (chunk.Item2)
  609. {
  610. while (chunkBuilder.Length < 10)
  611. {
  612. chunkBuilder.Insert(0, '0');
  613. }
  614. }
  615. builder.Append(chunkBuilder);
  616. }
  617. //logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  618. return builder.ToString().RemoveDiacritics();
  619. }
  620. [JsonIgnore]
  621. public bool EnableMediaSourceDisplay
  622. {
  623. get
  624. {
  625. if (SourceType == SourceType.Channel)
  626. {
  627. return ChannelManager.EnableMediaSourceDisplay(this);
  628. }
  629. return true;
  630. }
  631. }
  632. [JsonIgnore]
  633. public Guid ParentId { get; set; }
  634. /// <summary>
  635. /// Gets or sets the parent.
  636. /// </summary>
  637. /// <value>The parent.</value>
  638. [JsonIgnore]
  639. public Folder Parent
  640. {
  641. get => GetParent() as Folder;
  642. set
  643. {
  644. }
  645. }
  646. public void SetParent(Folder parent)
  647. {
  648. ParentId = parent == null ? Guid.Empty : parent.Id;
  649. }
  650. public BaseItem GetParent()
  651. {
  652. var parentId = ParentId;
  653. if (!parentId.Equals(Guid.Empty))
  654. {
  655. return LibraryManager.GetItemById(parentId);
  656. }
  657. return null;
  658. }
  659. public IEnumerable<BaseItem> GetParents()
  660. {
  661. var parent = GetParent();
  662. while (parent != null)
  663. {
  664. yield return parent;
  665. parent = parent.GetParent();
  666. }
  667. }
  668. /// <summary>
  669. /// Finds a parent of a given type
  670. /// </summary>
  671. /// <typeparam name="T"></typeparam>
  672. /// <returns>``0.</returns>
  673. public T FindParent<T>()
  674. where T : Folder
  675. {
  676. foreach (var parent in GetParents())
  677. {
  678. var item = parent as T;
  679. if (item != null)
  680. {
  681. return item;
  682. }
  683. }
  684. return null;
  685. }
  686. [JsonIgnore]
  687. public virtual Guid DisplayParentId
  688. {
  689. get
  690. {
  691. var parentId = ParentId;
  692. return parentId;
  693. }
  694. }
  695. [JsonIgnore]
  696. public BaseItem DisplayParent
  697. {
  698. get
  699. {
  700. var id = DisplayParentId;
  701. if (id.Equals(Guid.Empty))
  702. {
  703. return null;
  704. }
  705. return LibraryManager.GetItemById(id);
  706. }
  707. }
  708. /// <summary>
  709. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  710. /// </summary>
  711. /// <value>The premiere date.</value>
  712. [JsonIgnore]
  713. public DateTime? PremiereDate { get; set; }
  714. /// <summary>
  715. /// Gets or sets the end date.
  716. /// </summary>
  717. /// <value>The end date.</value>
  718. [JsonIgnore]
  719. public DateTime? EndDate { get; set; }
  720. /// <summary>
  721. /// Gets or sets the official rating.
  722. /// </summary>
  723. /// <value>The official rating.</value>
  724. [JsonIgnore]
  725. public string OfficialRating { get; set; }
  726. [JsonIgnore]
  727. public int InheritedParentalRatingValue { get; set; }
  728. /// <summary>
  729. /// Gets or sets the critic rating.
  730. /// </summary>
  731. /// <value>The critic rating.</value>
  732. [JsonIgnore]
  733. public float? CriticRating { get; set; }
  734. /// <summary>
  735. /// Gets or sets the custom rating.
  736. /// </summary>
  737. /// <value>The custom rating.</value>
  738. [JsonIgnore]
  739. public string CustomRating { get; set; }
  740. /// <summary>
  741. /// Gets or sets the overview.
  742. /// </summary>
  743. /// <value>The overview.</value>
  744. [JsonIgnore]
  745. public string Overview { get; set; }
  746. /// <summary>
  747. /// Gets or sets the studios.
  748. /// </summary>
  749. /// <value>The studios.</value>
  750. [JsonIgnore]
  751. public string[] Studios { get; set; }
  752. /// <summary>
  753. /// Gets or sets the genres.
  754. /// </summary>
  755. /// <value>The genres.</value>
  756. [JsonIgnore]
  757. public string[] Genres { get; set; }
  758. /// <summary>
  759. /// Gets or sets the tags.
  760. /// </summary>
  761. /// <value>The tags.</value>
  762. [JsonIgnore]
  763. public string[] Tags { get; set; }
  764. [JsonIgnore]
  765. public string[] ProductionLocations { get; set; }
  766. /// <summary>
  767. /// Gets or sets the home page URL.
  768. /// </summary>
  769. /// <value>The home page URL.</value>
  770. [JsonIgnore]
  771. public string HomePageUrl { get; set; }
  772. /// <summary>
  773. /// Gets or sets the community rating.
  774. /// </summary>
  775. /// <value>The community rating.</value>
  776. [JsonIgnore]
  777. public float? CommunityRating { get; set; }
  778. /// <summary>
  779. /// Gets or sets the run time ticks.
  780. /// </summary>
  781. /// <value>The run time ticks.</value>
  782. [JsonIgnore]
  783. public long? RunTimeTicks { get; set; }
  784. /// <summary>
  785. /// Gets or sets the production year.
  786. /// </summary>
  787. /// <value>The production year.</value>
  788. [JsonIgnore]
  789. public int? ProductionYear { get; set; }
  790. /// <summary>
  791. /// If the item is part of a series, this is it's number in the series.
  792. /// This could be episode number, album track number, etc.
  793. /// </summary>
  794. /// <value>The index number.</value>
  795. [JsonIgnore]
  796. public int? IndexNumber { get; set; }
  797. /// <summary>
  798. /// For an episode this could be the season number, or for a song this could be the disc number.
  799. /// </summary>
  800. /// <value>The parent index number.</value>
  801. [JsonIgnore]
  802. public int? ParentIndexNumber { get; set; }
  803. [JsonIgnore]
  804. public virtual bool HasLocalAlternateVersions => false;
  805. [JsonIgnore]
  806. public string OfficialRatingForComparison
  807. {
  808. get
  809. {
  810. var officialRating = OfficialRating;
  811. if (!string.IsNullOrEmpty(officialRating))
  812. {
  813. return officialRating;
  814. }
  815. var parent = DisplayParent;
  816. if (parent != null)
  817. {
  818. return parent.OfficialRatingForComparison;
  819. }
  820. return null;
  821. }
  822. }
  823. [JsonIgnore]
  824. public string CustomRatingForComparison
  825. {
  826. get
  827. {
  828. var customRating = CustomRating;
  829. if (!string.IsNullOrEmpty(customRating))
  830. {
  831. return customRating;
  832. }
  833. var parent = DisplayParent;
  834. if (parent != null)
  835. {
  836. return parent.CustomRatingForComparison;
  837. }
  838. return null;
  839. }
  840. }
  841. /// <summary>
  842. /// Gets the play access.
  843. /// </summary>
  844. /// <param name="user">The user.</param>
  845. /// <returns>PlayAccess.</returns>
  846. public PlayAccess GetPlayAccess(User user)
  847. {
  848. if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
  849. {
  850. return PlayAccess.None;
  851. }
  852. //if (!user.IsParentalScheduleAllowed())
  853. //{
  854. // return PlayAccess.None;
  855. //}
  856. return PlayAccess.Full;
  857. }
  858. public virtual List<MediaStream> GetMediaStreams()
  859. {
  860. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  861. {
  862. ItemId = Id
  863. });
  864. }
  865. protected virtual bool IsActiveRecording()
  866. {
  867. return false;
  868. }
  869. public virtual List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  870. {
  871. if (SourceType == SourceType.Channel)
  872. {
  873. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  874. .ToList();
  875. if (sources.Count > 0)
  876. {
  877. return sources;
  878. }
  879. }
  880. var list = GetAllItemsForMediaSources();
  881. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item1, i.Item2)).ToList();
  882. if (IsActiveRecording())
  883. {
  884. foreach (var mediaSource in result)
  885. {
  886. mediaSource.Type = MediaSourceType.Placeholder;
  887. }
  888. }
  889. return result.OrderBy(i =>
  890. {
  891. if (i.VideoType == VideoType.VideoFile)
  892. {
  893. return 0;
  894. }
  895. return 1;
  896. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  897. .ThenByDescending(i =>
  898. {
  899. var stream = i.VideoStream;
  900. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  901. })
  902. .ToList();
  903. }
  904. protected virtual List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources()
  905. {
  906. return new List<Tuple<BaseItem, MediaSourceType>>();
  907. }
  908. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  909. {
  910. if (item == null)
  911. {
  912. throw new ArgumentNullException(nameof(item));
  913. }
  914. var protocol = item.PathProtocol;
  915. var info = new MediaSourceInfo
  916. {
  917. Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
  918. Protocol = protocol ?? MediaProtocol.File,
  919. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  920. MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
  921. Name = GetMediaSourceName(item),
  922. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  923. RunTimeTicks = item.RunTimeTicks,
  924. Container = item.Container,
  925. Size = item.Size,
  926. Type = type
  927. };
  928. if (string.IsNullOrEmpty(info.Path))
  929. {
  930. info.Type = MediaSourceType.Placeholder;
  931. }
  932. if (info.Protocol == MediaProtocol.File)
  933. {
  934. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  935. }
  936. var video = item as Video;
  937. if (video != null)
  938. {
  939. info.IsoType = video.IsoType;
  940. info.VideoType = video.VideoType;
  941. info.Video3DFormat = video.Video3DFormat;
  942. info.Timestamp = video.Timestamp;
  943. if (video.IsShortcut)
  944. {
  945. info.IsRemote = true;
  946. info.Path = video.ShortcutPath;
  947. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  948. }
  949. if (string.IsNullOrEmpty(info.Container))
  950. {
  951. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  952. {
  953. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  954. {
  955. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  956. }
  957. }
  958. }
  959. }
  960. if (string.IsNullOrEmpty(info.Container))
  961. {
  962. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  963. {
  964. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  965. }
  966. }
  967. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  968. {
  969. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  970. }
  971. if (video != null && video.VideoType != VideoType.VideoFile)
  972. {
  973. info.SupportsDirectStream = false;
  974. }
  975. info.Bitrate = item.TotalBitrate;
  976. info.InferTotalBitrate();
  977. return info;
  978. }
  979. private string GetMediaSourceName(BaseItem item)
  980. {
  981. var terms = new List<string>();
  982. var path = item.Path;
  983. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  984. {
  985. if (HasLocalAlternateVersions)
  986. {
  987. var displayName = System.IO.Path.GetFileNameWithoutExtension(path)
  988. .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase)
  989. .TrimStart(new char[] { ' ', '-' });
  990. if (!string.IsNullOrEmpty(displayName))
  991. {
  992. terms.Add(displayName);
  993. }
  994. }
  995. if (terms.Count == 0)
  996. {
  997. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  998. terms.Add(displayName);
  999. }
  1000. }
  1001. if (terms.Count == 0)
  1002. {
  1003. terms.Add(item.Name);
  1004. }
  1005. var video = item as Video;
  1006. if (video != null)
  1007. {
  1008. if (video.Video3DFormat.HasValue)
  1009. {
  1010. terms.Add("3D");
  1011. }
  1012. if (video.VideoType == VideoType.BluRay)
  1013. {
  1014. terms.Add("Bluray");
  1015. }
  1016. else if (video.VideoType == VideoType.Dvd)
  1017. {
  1018. terms.Add("DVD");
  1019. }
  1020. else if (video.VideoType == VideoType.Iso)
  1021. {
  1022. if (video.IsoType.HasValue)
  1023. {
  1024. if (video.IsoType.Value == IsoType.BluRay)
  1025. {
  1026. terms.Add("Bluray");
  1027. }
  1028. else if (video.IsoType.Value == IsoType.Dvd)
  1029. {
  1030. terms.Add("DVD");
  1031. }
  1032. }
  1033. else
  1034. {
  1035. terms.Add("ISO");
  1036. }
  1037. }
  1038. }
  1039. return string.Join("/", terms.ToArray());
  1040. }
  1041. /// <summary>
  1042. /// Loads the theme songs.
  1043. /// </summary>
  1044. /// <returns>List{Audio.Audio}.</returns>
  1045. private static Audio.Audio[] LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1046. {
  1047. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1048. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  1049. .SelectMany(i => FileSystem.GetFiles(i.FullName))
  1050. .ToList();
  1051. // Support plex/xbmc convention
  1052. files.AddRange(fileSystemChildren
  1053. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  1054. );
  1055. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1056. .OfType<Audio.Audio>()
  1057. .Select(audio =>
  1058. {
  1059. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1060. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  1061. if (dbItem != null)
  1062. {
  1063. audio = dbItem;
  1064. }
  1065. else
  1066. {
  1067. // item is new
  1068. audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong;
  1069. }
  1070. return audio;
  1071. // Sort them so that the list can be easily compared for changes
  1072. }).OrderBy(i => i.Path).ToArray();
  1073. }
  1074. /// <summary>
  1075. /// Loads the video backdrops.
  1076. /// </summary>
  1077. /// <returns>List{Video}.</returns>
  1078. private static Video[] LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1079. {
  1080. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1081. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  1082. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1083. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1084. .OfType<Video>()
  1085. .Select(item =>
  1086. {
  1087. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1088. if (LibraryManager.GetItemById(item.Id) is Video dbItem)
  1089. {
  1090. item = dbItem;
  1091. }
  1092. else
  1093. {
  1094. // item is new
  1095. item.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1096. }
  1097. return item;
  1098. // Sort them so that the list can be easily compared for changes
  1099. }).OrderBy(i => i.Path).ToArray();
  1100. }
  1101. protected virtual BaseItem[] LoadExtras(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1102. {
  1103. var extras = new List<Video>();
  1104. var folders = fileSystemChildren.Where(i => i.IsDirectory).ToArray();
  1105. foreach (var extraFolderName in AllExtrasTypesFolderNames)
  1106. {
  1107. var files = folders
  1108. .Where(i => string.Equals(i.Name, extraFolderName, StringComparison.OrdinalIgnoreCase))
  1109. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1110. extras.AddRange(LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1111. .OfType<Video>()
  1112. .Select(item =>
  1113. {
  1114. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1115. if (LibraryManager.GetItemById(item.Id) is Video dbItem)
  1116. {
  1117. item = dbItem;
  1118. }
  1119. // Use some hackery to get the extra type based on foldername
  1120. item.ExtraType = Enum.TryParse(extraFolderName.Replace(" ", string.Empty), true, out ExtraType extraType)
  1121. ? extraType
  1122. : Model.Entities.ExtraType.Unknown;
  1123. return item;
  1124. // Sort them so that the list can be easily compared for changes
  1125. }).OrderBy(i => i.Path));
  1126. }
  1127. return extras.ToArray();
  1128. }
  1129. public Task RefreshMetadata(CancellationToken cancellationToken)
  1130. {
  1131. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  1132. }
  1133. protected virtual void TriggerOnRefreshStart()
  1134. {
  1135. }
  1136. protected virtual void TriggerOnRefreshComplete()
  1137. {
  1138. }
  1139. /// <summary>
  1140. /// Overrides the base implementation to refresh metadata for local trailers
  1141. /// </summary>
  1142. /// <param name="options">The options.</param>
  1143. /// <param name="cancellationToken">The cancellation token.</param>
  1144. /// <returns>true if a provider reports we changed</returns>
  1145. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1146. {
  1147. TriggerOnRefreshStart();
  1148. var requiresSave = false;
  1149. if (SupportsOwnedItems)
  1150. {
  1151. try
  1152. {
  1153. var files = IsFileProtocol ?
  1154. GetFileSystemChildren(options.DirectoryService).ToList() :
  1155. new List<FileSystemMetadata>();
  1156. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  1157. if (ownedItemsChanged)
  1158. {
  1159. requiresSave = true;
  1160. }
  1161. }
  1162. catch (Exception ex)
  1163. {
  1164. Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name);
  1165. }
  1166. }
  1167. try
  1168. {
  1169. var refreshOptions = requiresSave
  1170. ? new MetadataRefreshOptions(options)
  1171. {
  1172. ForceSave = true
  1173. }
  1174. : options;
  1175. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1176. }
  1177. finally
  1178. {
  1179. TriggerOnRefreshComplete();
  1180. }
  1181. }
  1182. [JsonIgnore]
  1183. protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
  1184. [JsonIgnore]
  1185. public virtual bool SupportsPeople => false;
  1186. [JsonIgnore]
  1187. public virtual bool SupportsThemeMedia => false;
  1188. /// <summary>
  1189. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1190. /// Returns true or false indicating if changes were found.
  1191. /// </summary>
  1192. /// <param name="options"></param>
  1193. /// <param name="fileSystemChildren"></param>
  1194. /// <param name="cancellationToken"></param>
  1195. /// <returns></returns>
  1196. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1197. {
  1198. var themeSongsChanged = false;
  1199. var themeVideosChanged = false;
  1200. var extrasChanged = false;
  1201. var localTrailersChanged = false;
  1202. if (IsFileProtocol && SupportsOwnedItems)
  1203. {
  1204. if (SupportsThemeMedia)
  1205. {
  1206. if (!IsInMixedFolder)
  1207. {
  1208. themeSongsChanged = await RefreshThemeSongs(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1209. themeVideosChanged = await RefreshThemeVideos(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1210. extrasChanged = await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1211. }
  1212. }
  1213. var hasTrailers = this as IHasTrailers;
  1214. if (hasTrailers != null)
  1215. {
  1216. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1217. }
  1218. }
  1219. return themeSongsChanged || themeVideosChanged || extrasChanged || localTrailersChanged;
  1220. }
  1221. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1222. {
  1223. var path = ContainingFolderPath;
  1224. return directoryService.GetFileSystemEntries(path);
  1225. }
  1226. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1227. {
  1228. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService);
  1229. var newItemIds = newItems.Select(i => i.Id);
  1230. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  1231. var ownerId = item.Id;
  1232. var tasks = newItems.Select(i =>
  1233. {
  1234. var subOptions = new MetadataRefreshOptions(options);
  1235. if (i.ExtraType != Model.Entities.ExtraType.Trailer ||
  1236. i.OwnerId != ownerId ||
  1237. !i.ParentId.Equals(Guid.Empty))
  1238. {
  1239. i.ExtraType = Model.Entities.ExtraType.Trailer;
  1240. i.OwnerId = ownerId;
  1241. i.ParentId = Guid.Empty;
  1242. subOptions.ForceSave = true;
  1243. }
  1244. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1245. });
  1246. await Task.WhenAll(tasks).ConfigureAwait(false);
  1247. item.LocalTrailerIds = newItemIds.ToArray();
  1248. return itemsChanged;
  1249. }
  1250. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1251. {
  1252. var extras = LoadExtras(fileSystemChildren, options.DirectoryService);
  1253. var themeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1254. var themeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1255. var newExtras = new BaseItem[extras.Length + themeVideos.Length + themeSongs.Length];
  1256. extras.CopyTo(newExtras, 0);
  1257. themeVideos.CopyTo(newExtras, extras.Length);
  1258. themeSongs.CopyTo(newExtras, extras.Length + themeVideos.Length);
  1259. var newExtraIds = newExtras.Select(i => i.Id).ToArray();
  1260. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1261. if (extrasChanged)
  1262. {
  1263. var ownerId = item.Id;
  1264. var tasks = newExtras.Select(i =>
  1265. {
  1266. var subOptions = new MetadataRefreshOptions(options);
  1267. if (i.OwnerId != ownerId || i.ParentId != Guid.Empty)
  1268. {
  1269. i.OwnerId = ownerId;
  1270. i.ParentId = Guid.Empty;
  1271. subOptions.ForceSave = true;
  1272. }
  1273. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1274. });
  1275. await Task.WhenAll(tasks).ConfigureAwait(false);
  1276. item.ExtraIds = newExtraIds;
  1277. }
  1278. return extrasChanged;
  1279. }
  1280. private async Task<bool> RefreshThemeVideos(BaseItem item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1281. {
  1282. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1283. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray();
  1284. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  1285. var ownerId = item.Id;
  1286. var tasks = newThemeVideos.Select(i =>
  1287. {
  1288. var subOptions = new MetadataRefreshOptions(options);
  1289. if (!i.ExtraType.HasValue ||
  1290. i.ExtraType.Value != Model.Entities.ExtraType.ThemeVideo ||
  1291. i.OwnerId != ownerId ||
  1292. !i.ParentId.Equals(Guid.Empty))
  1293. {
  1294. i.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1295. i.OwnerId = ownerId;
  1296. i.ParentId = Guid.Empty;
  1297. subOptions.ForceSave = true;
  1298. }
  1299. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1300. });
  1301. await Task.WhenAll(tasks).ConfigureAwait(false);
  1302. item.ThemeVideoIds = newThemeVideoIds;
  1303. return themeVideosChanged;
  1304. }
  1305. /// <summary>
  1306. /// Refreshes the theme songs.
  1307. /// </summary>
  1308. private async Task<bool> RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1309. {
  1310. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1311. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray();
  1312. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  1313. var ownerId = item.Id;
  1314. var tasks = newThemeSongs.Select(i =>
  1315. {
  1316. var subOptions = new MetadataRefreshOptions(options);
  1317. if (!i.ExtraType.HasValue ||
  1318. i.ExtraType.Value != Model.Entities.ExtraType.ThemeSong ||
  1319. i.OwnerId != ownerId ||
  1320. !i.ParentId.Equals(Guid.Empty))
  1321. {
  1322. i.ExtraType = Model.Entities.ExtraType.ThemeSong;
  1323. i.OwnerId = ownerId;
  1324. i.ParentId = Guid.Empty;
  1325. subOptions.ForceSave = true;
  1326. }
  1327. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1328. });
  1329. await Task.WhenAll(tasks).ConfigureAwait(false);
  1330. item.ThemeSongIds = newThemeSongIds;
  1331. return themeSongsChanged;
  1332. }
  1333. /// <summary>
  1334. /// Gets or sets the provider ids.
  1335. /// </summary>
  1336. /// <value>The provider ids.</value>
  1337. [JsonIgnore]
  1338. public Dictionary<string, string> ProviderIds { get; set; }
  1339. [JsonIgnore]
  1340. public virtual Folder LatestItemsIndexContainer => null;
  1341. public virtual double GetDefaultPrimaryImageAspectRatio()
  1342. {
  1343. return 0;
  1344. }
  1345. public virtual string CreatePresentationUniqueKey()
  1346. {
  1347. return Id.ToString("N", CultureInfo.InvariantCulture);
  1348. }
  1349. [JsonIgnore]
  1350. public string PresentationUniqueKey { get; set; }
  1351. public string GetPresentationUniqueKey()
  1352. {
  1353. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1354. }
  1355. public virtual bool RequiresRefresh()
  1356. {
  1357. return false;
  1358. }
  1359. public virtual List<string> GetUserDataKeys()
  1360. {
  1361. var list = new List<string>();
  1362. if (SourceType == SourceType.Channel)
  1363. {
  1364. if (!string.IsNullOrEmpty(ExternalId))
  1365. {
  1366. list.Add(ExternalId);
  1367. }
  1368. }
  1369. list.Add(Id.ToString());
  1370. return list;
  1371. }
  1372. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1373. {
  1374. var updateType = ItemUpdateType.None;
  1375. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1376. {
  1377. IsInMixedFolder = newItem.IsInMixedFolder;
  1378. updateType |= ItemUpdateType.MetadataImport;
  1379. }
  1380. return updateType;
  1381. }
  1382. public void AfterMetadataRefresh()
  1383. {
  1384. _sortName = null;
  1385. }
  1386. /// <summary>
  1387. /// Gets the preferred metadata language.
  1388. /// </summary>
  1389. /// <returns>System.String.</returns>
  1390. public string GetPreferredMetadataLanguage()
  1391. {
  1392. string lang = PreferredMetadataLanguage;
  1393. if (string.IsNullOrEmpty(lang))
  1394. {
  1395. lang = GetParents()
  1396. .Select(i => i.PreferredMetadataLanguage)
  1397. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1398. }
  1399. if (string.IsNullOrEmpty(lang))
  1400. {
  1401. lang = LibraryManager.GetCollectionFolders(this)
  1402. .Select(i => i.PreferredMetadataLanguage)
  1403. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1404. }
  1405. if (string.IsNullOrEmpty(lang))
  1406. {
  1407. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1408. }
  1409. if (string.IsNullOrEmpty(lang))
  1410. {
  1411. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1412. }
  1413. return lang;
  1414. }
  1415. /// <summary>
  1416. /// Gets the preferred metadata language.
  1417. /// </summary>
  1418. /// <returns>System.String.</returns>
  1419. public string GetPreferredMetadataCountryCode()
  1420. {
  1421. string lang = PreferredMetadataCountryCode;
  1422. if (string.IsNullOrEmpty(lang))
  1423. {
  1424. lang = GetParents()
  1425. .Select(i => i.PreferredMetadataCountryCode)
  1426. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1427. }
  1428. if (string.IsNullOrEmpty(lang))
  1429. {
  1430. lang = LibraryManager.GetCollectionFolders(this)
  1431. .Select(i => i.PreferredMetadataCountryCode)
  1432. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1433. }
  1434. if (string.IsNullOrEmpty(lang))
  1435. {
  1436. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1437. }
  1438. if (string.IsNullOrEmpty(lang))
  1439. {
  1440. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1441. }
  1442. return lang;
  1443. }
  1444. public virtual bool IsSaveLocalMetadataEnabled()
  1445. {
  1446. if (SourceType == SourceType.Channel)
  1447. {
  1448. return false;
  1449. }
  1450. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1451. return libraryOptions.SaveLocalMetadata;
  1452. }
  1453. /// <summary>
  1454. /// Determines if a given user has access to this item
  1455. /// </summary>
  1456. /// <param name="user">The user.</param>
  1457. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1458. /// <exception cref="ArgumentNullException">user</exception>
  1459. public bool IsParentalAllowed(User user)
  1460. {
  1461. if (user == null)
  1462. {
  1463. throw new ArgumentNullException(nameof(user));
  1464. }
  1465. if (!IsVisibleViaTags(user))
  1466. {
  1467. return false;
  1468. }
  1469. var maxAllowedRating = user.MaxParentalAgeRating;
  1470. if (maxAllowedRating == null)
  1471. {
  1472. return true;
  1473. }
  1474. var rating = CustomRatingForComparison;
  1475. if (string.IsNullOrEmpty(rating))
  1476. {
  1477. rating = OfficialRatingForComparison;
  1478. }
  1479. if (string.IsNullOrEmpty(rating))
  1480. {
  1481. return !GetBlockUnratedValue(user);
  1482. }
  1483. var value = LocalizationManager.GetRatingLevel(rating);
  1484. // Could not determine the integer value
  1485. if (!value.HasValue)
  1486. {
  1487. var isAllowed = !GetBlockUnratedValue(user);
  1488. if (!isAllowed)
  1489. {
  1490. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1491. }
  1492. return isAllowed;
  1493. }
  1494. return value.Value <= maxAllowedRating.Value;
  1495. }
  1496. public int? GetParentalRatingValue()
  1497. {
  1498. var rating = CustomRating;
  1499. if (string.IsNullOrEmpty(rating))
  1500. {
  1501. rating = OfficialRating;
  1502. }
  1503. if (string.IsNullOrEmpty(rating))
  1504. {
  1505. return null;
  1506. }
  1507. return LocalizationManager.GetRatingLevel(rating);
  1508. }
  1509. public int? GetInheritedParentalRatingValue()
  1510. {
  1511. var rating = CustomRatingForComparison;
  1512. if (string.IsNullOrEmpty(rating))
  1513. {
  1514. rating = OfficialRatingForComparison;
  1515. }
  1516. if (string.IsNullOrEmpty(rating))
  1517. {
  1518. return null;
  1519. }
  1520. return LocalizationManager.GetRatingLevel(rating);
  1521. }
  1522. public List<string> GetInheritedTags()
  1523. {
  1524. var list = new List<string>();
  1525. list.AddRange(Tags);
  1526. foreach (var parent in GetParents())
  1527. {
  1528. list.AddRange(parent.Tags);
  1529. }
  1530. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1531. }
  1532. private bool IsVisibleViaTags(User user)
  1533. {
  1534. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1535. {
  1536. return false;
  1537. }
  1538. return true;
  1539. }
  1540. protected virtual bool IsAllowTagFilterEnforced()
  1541. {
  1542. return true;
  1543. }
  1544. public virtual UnratedItem GetBlockUnratedType()
  1545. {
  1546. if (SourceType == SourceType.Channel)
  1547. {
  1548. return UnratedItem.ChannelContent;
  1549. }
  1550. return UnratedItem.Other;
  1551. }
  1552. /// <summary>
  1553. /// Gets the block unrated value.
  1554. /// </summary>
  1555. /// <param name="user">The configuration.</param>
  1556. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1557. protected virtual bool GetBlockUnratedValue(User user)
  1558. {
  1559. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1560. // Special folders like series and albums will override this method.
  1561. if (IsFolder || this is IItemByName)
  1562. {
  1563. return false;
  1564. }
  1565. return user.GetPreference(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType().ToString());
  1566. }
  1567. /// <summary>
  1568. /// Determines if this folder should be visible to a given user.
  1569. /// Default is just parental allowed. Can be overridden for more functionality.
  1570. /// </summary>
  1571. /// <param name="user">The user.</param>
  1572. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1573. /// <exception cref="ArgumentNullException">user</exception>
  1574. public virtual bool IsVisible(User user)
  1575. {
  1576. if (user == null)
  1577. {
  1578. throw new ArgumentNullException(nameof(user));
  1579. }
  1580. return IsParentalAllowed(user);
  1581. }
  1582. public virtual bool IsVisibleStandalone(User user)
  1583. {
  1584. if (SourceType == SourceType.Channel)
  1585. {
  1586. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1587. }
  1588. return IsVisibleStandaloneInternal(user, true);
  1589. }
  1590. [JsonIgnore]
  1591. public virtual bool SupportsInheritedParentImages => false;
  1592. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1593. {
  1594. if (!IsVisible(user))
  1595. {
  1596. return false;
  1597. }
  1598. if (GetParents().Any(i => !i.IsVisible(user)))
  1599. {
  1600. return false;
  1601. }
  1602. if (checkFolders)
  1603. {
  1604. var topParent = GetParents().LastOrDefault() ?? this;
  1605. if (string.IsNullOrEmpty(topParent.Path))
  1606. {
  1607. return true;
  1608. }
  1609. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1610. if (itemCollectionFolders.Count > 0)
  1611. {
  1612. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1613. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1614. {
  1615. return false;
  1616. }
  1617. }
  1618. }
  1619. return true;
  1620. }
  1621. /// <summary>
  1622. /// Gets a value indicating whether this instance is folder.
  1623. /// </summary>
  1624. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1625. [JsonIgnore]
  1626. public virtual bool IsFolder => false;
  1627. [JsonIgnore]
  1628. public virtual bool IsDisplayedAsFolder => false;
  1629. public virtual string GetClientTypeName()
  1630. {
  1631. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1632. {
  1633. return "ChannelFolderItem";
  1634. }
  1635. return GetType().Name;
  1636. }
  1637. /// <summary>
  1638. /// Gets the linked child.
  1639. /// </summary>
  1640. /// <param name="info">The info.</param>
  1641. /// <returns>BaseItem.</returns>
  1642. protected BaseItem GetLinkedChild(LinkedChild info)
  1643. {
  1644. // First get using the cached Id
  1645. if (info.ItemId.HasValue)
  1646. {
  1647. if (info.ItemId.Value.Equals(Guid.Empty))
  1648. {
  1649. return null;
  1650. }
  1651. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1652. if (itemById != null)
  1653. {
  1654. return itemById;
  1655. }
  1656. }
  1657. var item = FindLinkedChild(info);
  1658. // If still null, log
  1659. if (item == null)
  1660. {
  1661. // Don't keep searching over and over
  1662. info.ItemId = Guid.Empty;
  1663. }
  1664. else
  1665. {
  1666. // Cache the id for next time
  1667. info.ItemId = item.Id;
  1668. }
  1669. return item;
  1670. }
  1671. private BaseItem FindLinkedChild(LinkedChild info)
  1672. {
  1673. var path = info.Path;
  1674. if (!string.IsNullOrEmpty(path))
  1675. {
  1676. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1677. var itemByPath = LibraryManager.FindByPath(path, null);
  1678. if (itemByPath == null)
  1679. {
  1680. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1681. }
  1682. return itemByPath;
  1683. }
  1684. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1685. {
  1686. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1687. if (item == null)
  1688. {
  1689. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1690. }
  1691. return item;
  1692. }
  1693. return null;
  1694. }
  1695. [JsonIgnore]
  1696. public virtual bool EnableRememberingTrackSelections => true;
  1697. /// <summary>
  1698. /// Adds a studio to the item
  1699. /// </summary>
  1700. /// <param name="name">The name.</param>
  1701. /// <exception cref="ArgumentNullException"></exception>
  1702. public void AddStudio(string name)
  1703. {
  1704. if (string.IsNullOrEmpty(name))
  1705. {
  1706. throw new ArgumentNullException(nameof(name));
  1707. }
  1708. var current = Studios;
  1709. if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
  1710. {
  1711. int curLen = current.Length;
  1712. if (curLen == 0)
  1713. {
  1714. Studios = new[] { name };
  1715. }
  1716. else
  1717. {
  1718. var newArr = new string[curLen + 1];
  1719. current.CopyTo(newArr, 0);
  1720. newArr[curLen] = name;
  1721. Studios = newArr;
  1722. }
  1723. }
  1724. }
  1725. public void SetStudios(IEnumerable<string> names)
  1726. {
  1727. Studios = names.Distinct().ToArray();
  1728. }
  1729. /// <summary>
  1730. /// Adds a genre to the item
  1731. /// </summary>
  1732. /// <param name="name">The name.</param>
  1733. /// <exception cref="ArgumentNullException"></exception>
  1734. public void AddGenre(string name)
  1735. {
  1736. if (string.IsNullOrEmpty(name))
  1737. {
  1738. throw new ArgumentNullException(nameof(name));
  1739. }
  1740. var genres = Genres;
  1741. if (!genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1742. {
  1743. var list = genres.ToList();
  1744. list.Add(name);
  1745. Genres = list.ToArray();
  1746. }
  1747. }
  1748. /// <summary>
  1749. /// Marks the played.
  1750. /// </summary>
  1751. /// <param name="user">The user.</param>
  1752. /// <param name="datePlayed">The date played.</param>
  1753. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1754. /// <returns>Task.</returns>
  1755. /// <exception cref="ArgumentNullException"></exception>
  1756. public virtual void MarkPlayed(
  1757. User user,
  1758. DateTime? datePlayed,
  1759. bool resetPosition)
  1760. {
  1761. if (user == null)
  1762. {
  1763. throw new ArgumentNullException(nameof(user));
  1764. }
  1765. var data = UserDataManager.GetUserData(user, this);
  1766. if (datePlayed.HasValue)
  1767. {
  1768. // Increment
  1769. data.PlayCount++;
  1770. }
  1771. // Ensure it's at least one
  1772. data.PlayCount = Math.Max(data.PlayCount, 1);
  1773. if (resetPosition)
  1774. {
  1775. data.PlaybackPositionTicks = 0;
  1776. }
  1777. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1778. data.Played = true;
  1779. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1780. }
  1781. /// <summary>
  1782. /// Marks the unplayed.
  1783. /// </summary>
  1784. /// <param name="user">The user.</param>
  1785. /// <returns>Task.</returns>
  1786. /// <exception cref="ArgumentNullException"></exception>
  1787. public virtual void MarkUnplayed(User user)
  1788. {
  1789. if (user == null)
  1790. {
  1791. throw new ArgumentNullException(nameof(user));
  1792. }
  1793. var data = UserDataManager.GetUserData(user, this);
  1794. //I think it is okay to do this here.
  1795. // if this is only called when a user is manually forcing something to un-played
  1796. // then it probably is what we want to do...
  1797. data.PlayCount = 0;
  1798. data.PlaybackPositionTicks = 0;
  1799. data.LastPlayedDate = null;
  1800. data.Played = false;
  1801. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1802. }
  1803. /// <summary>
  1804. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1805. /// </summary>
  1806. public virtual void ChangedExternally()
  1807. {
  1808. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1809. }
  1810. /// <summary>
  1811. /// Gets an image
  1812. /// </summary>
  1813. /// <param name="type">The type.</param>
  1814. /// <param name="imageIndex">Index of the image.</param>
  1815. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1816. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1817. public bool HasImage(ImageType type, int imageIndex)
  1818. {
  1819. return GetImageInfo(type, imageIndex) != null;
  1820. }
  1821. public void SetImage(ItemImageInfo image, int index)
  1822. {
  1823. if (image.Type == ImageType.Chapter)
  1824. {
  1825. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1826. }
  1827. var existingImage = GetImageInfo(image.Type, index);
  1828. if (existingImage != null)
  1829. {
  1830. existingImage.Path = image.Path;
  1831. existingImage.DateModified = image.DateModified;
  1832. existingImage.Width = image.Width;
  1833. existingImage.Height = image.Height;
  1834. }
  1835. else
  1836. {
  1837. var current = ImageInfos;
  1838. var currentCount = current.Length;
  1839. var newArr = new ItemImageInfo[currentCount + 1];
  1840. current.CopyTo(newArr, 0);
  1841. newArr[currentCount] = image;
  1842. ImageInfos = newArr;
  1843. }
  1844. }
  1845. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1846. {
  1847. if (type == ImageType.Chapter)
  1848. {
  1849. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1850. }
  1851. var image = GetImageInfo(type, index);
  1852. if (image == null)
  1853. {
  1854. ImageInfos = ImageInfos.Concat(new[] { GetImageInfo(file, type) }).ToArray();
  1855. }
  1856. else
  1857. {
  1858. var imageInfo = GetImageInfo(file, type);
  1859. image.Path = file.FullName;
  1860. image.DateModified = imageInfo.DateModified;
  1861. // reset these values
  1862. image.Width = 0;
  1863. image.Height = 0;
  1864. }
  1865. }
  1866. /// <summary>
  1867. /// Deletes the image.
  1868. /// </summary>
  1869. /// <param name="type">The type.</param>
  1870. /// <param name="index">The index.</param>
  1871. public void DeleteImage(ImageType type, int index)
  1872. {
  1873. var info = GetImageInfo(type, index);
  1874. if (info == null)
  1875. {
  1876. // Nothing to do
  1877. return;
  1878. }
  1879. // Remove it from the item
  1880. RemoveImage(info);
  1881. if (info.IsLocalFile)
  1882. {
  1883. FileSystem.DeleteFile(info.Path);
  1884. }
  1885. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1886. }
  1887. public void RemoveImage(ItemImageInfo image)
  1888. {
  1889. RemoveImages(new List<ItemImageInfo> { image });
  1890. }
  1891. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1892. {
  1893. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1894. }
  1895. public virtual void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1896. {
  1897. LibraryManager.UpdateItem(this, GetParent(), updateReason, cancellationToken);
  1898. }
  1899. /// <summary>
  1900. /// Validates that images within the item are still on the filesystem.
  1901. /// </summary>
  1902. public bool ValidateImages(IDirectoryService directoryService)
  1903. {
  1904. var allFiles = ImageInfos
  1905. .Where(i => i.IsLocalFile)
  1906. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1907. .Distinct(StringComparer.OrdinalIgnoreCase)
  1908. .SelectMany(i => directoryService.GetFilePaths(i))
  1909. .ToList();
  1910. var deletedImages = ImageInfos
  1911. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1912. .ToList();
  1913. if (deletedImages.Count > 0)
  1914. {
  1915. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1916. }
  1917. return deletedImages.Count > 0;
  1918. }
  1919. /// <summary>
  1920. /// Gets the image path.
  1921. /// </summary>
  1922. /// <param name="imageType">Type of the image.</param>
  1923. /// <param name="imageIndex">Index of the image.</param>
  1924. /// <returns>System.String.</returns>
  1925. /// <exception cref="InvalidOperationException">
  1926. /// </exception>
  1927. /// <exception cref="ArgumentNullException">item</exception>
  1928. public string GetImagePath(ImageType imageType, int imageIndex)
  1929. => GetImageInfo(imageType, imageIndex)?.Path;
  1930. /// <summary>
  1931. /// Gets the image information.
  1932. /// </summary>
  1933. /// <param name="imageType">Type of the image.</param>
  1934. /// <param name="imageIndex">Index of the image.</param>
  1935. /// <returns>ItemImageInfo.</returns>
  1936. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1937. {
  1938. if (imageType == ImageType.Chapter)
  1939. {
  1940. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1941. if (chapter == null)
  1942. {
  1943. return null;
  1944. }
  1945. var path = chapter.ImagePath;
  1946. if (string.IsNullOrEmpty(path))
  1947. {
  1948. return null;
  1949. }
  1950. return new ItemImageInfo
  1951. {
  1952. Path = path,
  1953. DateModified = chapter.ImageDateModified,
  1954. Type = imageType
  1955. };
  1956. }
  1957. return GetImages(imageType)
  1958. .ElementAtOrDefault(imageIndex);
  1959. }
  1960. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1961. {
  1962. if (imageType == ImageType.Chapter)
  1963. {
  1964. throw new ArgumentException("No image info for chapter images");
  1965. }
  1966. return ImageInfos.Where(i => i.Type == imageType);
  1967. }
  1968. /// <summary>
  1969. /// Adds the images.
  1970. /// </summary>
  1971. /// <param name="imageType">Type of the image.</param>
  1972. /// <param name="images">The images.</param>
  1973. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1974. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
  1975. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1976. {
  1977. if (imageType == ImageType.Chapter)
  1978. {
  1979. throw new ArgumentException("Cannot call AddImages with chapter images");
  1980. }
  1981. var existingImages = GetImages(imageType)
  1982. .ToList();
  1983. var newImageList = new List<FileSystemMetadata>();
  1984. var imageAdded = false;
  1985. var imageUpdated = false;
  1986. foreach (var newImage in images)
  1987. {
  1988. if (newImage == null)
  1989. {
  1990. throw new ArgumentException("null image found in list");
  1991. }
  1992. var existing = existingImages
  1993. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1994. if (existing == null)
  1995. {
  1996. newImageList.Add(newImage);
  1997. imageAdded = true;
  1998. }
  1999. else
  2000. {
  2001. if (existing.IsLocalFile)
  2002. {
  2003. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  2004. // If date changed then we need to reset saved image dimensions
  2005. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  2006. {
  2007. existing.Width = 0;
  2008. existing.Height = 0;
  2009. imageUpdated = true;
  2010. }
  2011. existing.DateModified = newDateModified;
  2012. }
  2013. }
  2014. }
  2015. if (imageAdded || images.Count != existingImages.Count)
  2016. {
  2017. var newImagePaths = images.Select(i => i.FullName).ToList();
  2018. var deleted = existingImages
  2019. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
  2020. .ToList();
  2021. if (deleted.Count > 0)
  2022. {
  2023. ImageInfos = ImageInfos.Except(deleted).ToArray();
  2024. }
  2025. }
  2026. if (newImageList.Count > 0)
  2027. {
  2028. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  2029. }
  2030. return imageUpdated || newImageList.Count > 0;
  2031. }
  2032. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  2033. {
  2034. return new ItemImageInfo
  2035. {
  2036. Path = file.FullName,
  2037. Type = type,
  2038. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  2039. };
  2040. }
  2041. /// <summary>
  2042. /// Gets the file system path to delete when the item is to be deleted
  2043. /// </summary>
  2044. /// <returns></returns>
  2045. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  2046. {
  2047. return new[] {
  2048. new FileSystemMetadata
  2049. {
  2050. FullName = Path,
  2051. IsDirectory = IsFolder
  2052. }
  2053. }.Concat(GetLocalMetadataFilesToDelete());
  2054. }
  2055. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  2056. {
  2057. if (IsFolder || !IsInMixedFolder)
  2058. {
  2059. return new List<FileSystemMetadata>();
  2060. }
  2061. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  2062. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  2063. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  2064. .ToList();
  2065. }
  2066. public bool AllowsMultipleImages(ImageType type)
  2067. {
  2068. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  2069. }
  2070. public void SwapImages(ImageType type, int index1, int index2)
  2071. {
  2072. if (!AllowsMultipleImages(type))
  2073. {
  2074. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  2075. }
  2076. var info1 = GetImageInfo(type, index1);
  2077. var info2 = GetImageInfo(type, index2);
  2078. if (info1 == null || info2 == null)
  2079. {
  2080. // Nothing to do
  2081. return;
  2082. }
  2083. if (!info1.IsLocalFile || !info2.IsLocalFile)
  2084. {
  2085. // TODO: Not supported yet
  2086. return;
  2087. }
  2088. var path1 = info1.Path;
  2089. var path2 = info2.Path;
  2090. FileSystem.SwapFiles(path1, path2);
  2091. // Refresh these values
  2092. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  2093. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  2094. info1.Width = 0;
  2095. info1.Height = 0;
  2096. info2.Width = 0;
  2097. info2.Height = 0;
  2098. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2099. }
  2100. public virtual bool IsPlayed(User user)
  2101. {
  2102. var userdata = UserDataManager.GetUserData(user, this);
  2103. return userdata != null && userdata.Played;
  2104. }
  2105. public bool IsFavoriteOrLiked(User user)
  2106. {
  2107. var userdata = UserDataManager.GetUserData(user, this);
  2108. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  2109. }
  2110. public virtual bool IsUnplayed(User user)
  2111. {
  2112. if (user == null)
  2113. {
  2114. throw new ArgumentNullException(nameof(user));
  2115. }
  2116. var userdata = UserDataManager.GetUserData(user, this);
  2117. return userdata == null || !userdata.Played;
  2118. }
  2119. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  2120. {
  2121. return GetItemLookupInfo<ItemLookupInfo>();
  2122. }
  2123. protected T GetItemLookupInfo<T>()
  2124. where T : ItemLookupInfo, new()
  2125. {
  2126. return new T
  2127. {
  2128. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  2129. MetadataLanguage = GetPreferredMetadataLanguage(),
  2130. Name = GetNameForMetadataLookup(),
  2131. ProviderIds = ProviderIds,
  2132. IndexNumber = IndexNumber,
  2133. ParentIndexNumber = ParentIndexNumber,
  2134. Year = ProductionYear,
  2135. PremiereDate = PremiereDate
  2136. };
  2137. }
  2138. protected virtual string GetNameForMetadataLookup()
  2139. {
  2140. return Name;
  2141. }
  2142. /// <summary>
  2143. /// This is called before any metadata refresh and returns true if changes were made.
  2144. /// </summary>
  2145. public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
  2146. {
  2147. _sortName = null;
  2148. var hasChanges = false;
  2149. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  2150. {
  2151. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  2152. hasChanges = true;
  2153. }
  2154. return hasChanges;
  2155. }
  2156. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  2157. {
  2158. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  2159. {
  2160. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  2161. }
  2162. return path;
  2163. }
  2164. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  2165. {
  2166. if (RunTimeTicks.HasValue)
  2167. {
  2168. double pct = RunTimeTicks.Value;
  2169. if (pct > 0)
  2170. {
  2171. pct = userData.PlaybackPositionTicks / pct;
  2172. if (pct > 0)
  2173. {
  2174. dto.PlayedPercentage = 100 * pct;
  2175. }
  2176. }
  2177. }
  2178. }
  2179. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2180. {
  2181. var newOptions = new MetadataRefreshOptions(options);
  2182. newOptions.SearchResult = null;
  2183. var item = this;
  2184. if (copyTitleMetadata)
  2185. {
  2186. // Take some data from the main item, for querying purposes
  2187. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2188. {
  2189. newOptions.ForceSave = true;
  2190. ownedItem.Genres = item.Genres;
  2191. }
  2192. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2193. {
  2194. newOptions.ForceSave = true;
  2195. ownedItem.Studios = item.Studios;
  2196. }
  2197. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2198. {
  2199. newOptions.ForceSave = true;
  2200. ownedItem.ProductionLocations = item.ProductionLocations;
  2201. }
  2202. if (item.CommunityRating != ownedItem.CommunityRating)
  2203. {
  2204. ownedItem.CommunityRating = item.CommunityRating;
  2205. newOptions.ForceSave = true;
  2206. }
  2207. if (item.CriticRating != ownedItem.CriticRating)
  2208. {
  2209. ownedItem.CriticRating = item.CriticRating;
  2210. newOptions.ForceSave = true;
  2211. }
  2212. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2213. {
  2214. ownedItem.Overview = item.Overview;
  2215. newOptions.ForceSave = true;
  2216. }
  2217. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2218. {
  2219. ownedItem.OfficialRating = item.OfficialRating;
  2220. newOptions.ForceSave = true;
  2221. }
  2222. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2223. {
  2224. ownedItem.CustomRating = item.CustomRating;
  2225. newOptions.ForceSave = true;
  2226. }
  2227. }
  2228. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2229. }
  2230. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2231. {
  2232. var newOptions = new MetadataRefreshOptions(options);
  2233. newOptions.SearchResult = null;
  2234. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2235. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2236. var video = LibraryManager.GetItemById(id) as Video;
  2237. if (video == null)
  2238. {
  2239. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2240. newOptions.ForceSave = true;
  2241. }
  2242. //var parentId = Id;
  2243. //if (!video.IsOwnedItem || video.ParentId != parentId)
  2244. //{
  2245. // video.IsOwnedItem = true;
  2246. // video.ParentId = parentId;
  2247. // newOptions.ForceSave = true;
  2248. //}
  2249. if (video == null)
  2250. {
  2251. return Task.FromResult(true);
  2252. }
  2253. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2254. }
  2255. public string GetEtag(User user)
  2256. {
  2257. var list = GetEtagValues(user);
  2258. return string.Join("|", list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2259. }
  2260. protected virtual List<string> GetEtagValues(User user)
  2261. {
  2262. return new List<string>
  2263. {
  2264. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2265. };
  2266. }
  2267. public virtual IEnumerable<Guid> GetAncestorIds()
  2268. {
  2269. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2270. }
  2271. public BaseItem GetTopParent()
  2272. {
  2273. if (IsTopParent)
  2274. {
  2275. return this;
  2276. }
  2277. foreach (var parent in GetParents())
  2278. {
  2279. if (parent.IsTopParent)
  2280. {
  2281. return parent;
  2282. }
  2283. }
  2284. return null;
  2285. }
  2286. [JsonIgnore]
  2287. public virtual bool IsTopParent
  2288. {
  2289. get
  2290. {
  2291. if (this is BasePluginFolder || this is Channel)
  2292. {
  2293. return true;
  2294. }
  2295. if (this is IHasCollectionType view)
  2296. {
  2297. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2298. {
  2299. return true;
  2300. }
  2301. }
  2302. if (GetParent() is AggregateFolder)
  2303. {
  2304. return true;
  2305. }
  2306. return false;
  2307. }
  2308. }
  2309. [JsonIgnore]
  2310. public virtual bool SupportsAncestors => true;
  2311. [JsonIgnore]
  2312. public virtual bool StopRefreshIfLocalMetadataFound => true;
  2313. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2314. {
  2315. return new[] { Id };
  2316. }
  2317. public virtual List<ExternalUrl> GetRelatedUrls()
  2318. {
  2319. return new List<ExternalUrl>();
  2320. }
  2321. public virtual double? GetRefreshProgress()
  2322. {
  2323. return null;
  2324. }
  2325. public virtual ItemUpdateType OnMetadataChanged()
  2326. {
  2327. var updateType = ItemUpdateType.None;
  2328. var item = this;
  2329. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2330. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2331. {
  2332. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2333. updateType |= ItemUpdateType.MetadataImport;
  2334. }
  2335. return updateType;
  2336. }
  2337. /// <summary>
  2338. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2339. /// </summary>
  2340. /// <returns></returns>
  2341. public bool UpdateRatingToItems(IList<BaseItem> children)
  2342. {
  2343. var currentOfficialRating = OfficialRating;
  2344. // Gather all possible ratings
  2345. var ratings = children
  2346. .Select(i => i.OfficialRating)
  2347. .Where(i => !string.IsNullOrEmpty(i))
  2348. .Distinct(StringComparer.OrdinalIgnoreCase)
  2349. .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i)))
  2350. .OrderBy(i => i.Item2 ?? 1000)
  2351. .Select(i => i.Item1);
  2352. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2353. return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
  2354. StringComparison.OrdinalIgnoreCase);
  2355. }
  2356. public IEnumerable<BaseItem> GetThemeSongs()
  2357. {
  2358. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeSong)).OrderBy(i => i.SortName);
  2359. }
  2360. public IEnumerable<BaseItem> GetThemeVideos()
  2361. {
  2362. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName);
  2363. }
  2364. /// <summary>
  2365. /// Gets or sets the remote trailers.
  2366. /// </summary>
  2367. /// <value>The remote trailers.</value>
  2368. public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
  2369. /// <summary>
  2370. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2371. /// </summary>
  2372. /// <returns>An enumerable containing the items.</returns>
  2373. public IEnumerable<BaseItem> GetExtras()
  2374. {
  2375. return ExtraIds
  2376. .Select(LibraryManager.GetItemById)
  2377. .Where(i => i != null)
  2378. .OrderBy(i => i.SortName);
  2379. }
  2380. /// <summary>
  2381. /// Get all extras with specific types that are associated with this item.
  2382. /// </summary>
  2383. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2384. /// <returns>An enumerable containing the extras.</returns>
  2385. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2386. {
  2387. return ExtraIds
  2388. .Select(LibraryManager.GetItemById)
  2389. .Where(i => i != null)
  2390. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
  2391. }
  2392. public IEnumerable<BaseItem> GetTrailers()
  2393. {
  2394. if (this is IHasTrailers)
  2395. return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
  2396. else
  2397. return Array.Empty<BaseItem>();
  2398. }
  2399. public virtual bool IsHD => Height >= 720;
  2400. public bool IsShortcut { get; set; }
  2401. public string ShortcutPath { get; set; }
  2402. public int Width { get; set; }
  2403. public int Height { get; set; }
  2404. public Guid[] ExtraIds { get; set; }
  2405. public virtual long GetRunTimeTicksForPlayState()
  2406. {
  2407. return RunTimeTicks ?? 0;
  2408. }
  2409. /// <summary>
  2410. /// Extra types that should be counted and displayed as "Special Features" in the UI.
  2411. /// </summary>
  2412. public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
  2413. {
  2414. Model.Entities.ExtraType.Unknown,
  2415. Model.Entities.ExtraType.BehindTheScenes,
  2416. Model.Entities.ExtraType.Clip,
  2417. Model.Entities.ExtraType.DeletedScene,
  2418. Model.Entities.ExtraType.Interview,
  2419. Model.Entities.ExtraType.Sample,
  2420. Model.Entities.ExtraType.Scene
  2421. };
  2422. public virtual bool SupportsExternalTransfer => false;
  2423. /// <inheritdoc />
  2424. public override bool Equals(object obj)
  2425. {
  2426. return obj is BaseItem baseItem && this.Equals(baseItem);
  2427. }
  2428. /// <inheritdoc />
  2429. public bool Equals(BaseItem item) => Object.Equals(Id, item?.Id);
  2430. /// <inheritdoc />
  2431. public override int GetHashCode() => HashCode.Combine(Id);
  2432. }
  2433. }