BaseItem.cs 91 KB

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