BaseItem.cs 94 KB

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