BaseItem.cs 93 KB

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