BaseItem.cs 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  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. var ownerId = item.Id;
  1231. var tasks = newExtras.Select(i =>
  1232. {
  1233. return RefreshMetadataForOwnedItem(i, true, new MetadataRefreshOptions(options), cancellationToken);
  1234. });
  1235. await Task.WhenAll(tasks).ConfigureAwait(false);
  1236. item.ExtraIds = newExtraIds;
  1237. return extrasChanged;
  1238. }
  1239. private async Task<bool> RefreshThemeVideos(BaseItem item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1240. {
  1241. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1242. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray();
  1243. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  1244. var ownerId = item.Id;
  1245. var tasks = newThemeVideos.Select(i =>
  1246. {
  1247. var subOptions = new MetadataRefreshOptions(options);
  1248. if (!i.ExtraType.HasValue ||
  1249. i.ExtraType.Value != Model.Entities.ExtraType.ThemeVideo ||
  1250. i.OwnerId != ownerId ||
  1251. !i.ParentId.Equals(Guid.Empty))
  1252. {
  1253. i.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1254. i.OwnerId = ownerId;
  1255. i.ParentId = Guid.Empty;
  1256. subOptions.ForceSave = true;
  1257. }
  1258. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1259. });
  1260. await Task.WhenAll(tasks).ConfigureAwait(false);
  1261. item.ThemeVideoIds = newThemeVideoIds;
  1262. return themeVideosChanged;
  1263. }
  1264. /// <summary>
  1265. /// Refreshes the theme songs.
  1266. /// </summary>
  1267. private async Task<bool> RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1268. {
  1269. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1270. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray();
  1271. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  1272. var ownerId = item.Id;
  1273. var tasks = newThemeSongs.Select(i =>
  1274. {
  1275. var subOptions = new MetadataRefreshOptions(options);
  1276. if (!i.ExtraType.HasValue ||
  1277. i.ExtraType.Value != Model.Entities.ExtraType.ThemeSong ||
  1278. i.OwnerId != ownerId ||
  1279. !i.ParentId.Equals(Guid.Empty))
  1280. {
  1281. i.ExtraType = Model.Entities.ExtraType.ThemeSong;
  1282. i.OwnerId = ownerId;
  1283. i.ParentId = Guid.Empty;
  1284. subOptions.ForceSave = true;
  1285. }
  1286. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1287. });
  1288. await Task.WhenAll(tasks).ConfigureAwait(false);
  1289. item.ThemeSongIds = newThemeSongIds;
  1290. return themeSongsChanged;
  1291. }
  1292. /// <summary>
  1293. /// Gets or sets the provider ids.
  1294. /// </summary>
  1295. /// <value>The provider ids.</value>
  1296. [IgnoreDataMember]
  1297. public Dictionary<string, string> ProviderIds { get; set; }
  1298. [IgnoreDataMember]
  1299. public virtual Folder LatestItemsIndexContainer => null;
  1300. public virtual double GetDefaultPrimaryImageAspectRatio()
  1301. {
  1302. return 0;
  1303. }
  1304. public virtual string CreatePresentationUniqueKey()
  1305. {
  1306. return Id.ToString("N");
  1307. }
  1308. [IgnoreDataMember]
  1309. public string PresentationUniqueKey { get; set; }
  1310. public string GetPresentationUniqueKey()
  1311. {
  1312. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1313. }
  1314. public virtual bool RequiresRefresh()
  1315. {
  1316. return false;
  1317. }
  1318. public virtual List<string> GetUserDataKeys()
  1319. {
  1320. var list = new List<string>();
  1321. if (SourceType == SourceType.Channel)
  1322. {
  1323. if (!string.IsNullOrEmpty(ExternalId))
  1324. {
  1325. list.Add(ExternalId);
  1326. }
  1327. }
  1328. list.Add(Id.ToString());
  1329. return list;
  1330. }
  1331. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1332. {
  1333. var updateType = ItemUpdateType.None;
  1334. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1335. {
  1336. IsInMixedFolder = newItem.IsInMixedFolder;
  1337. updateType |= ItemUpdateType.MetadataImport;
  1338. }
  1339. return updateType;
  1340. }
  1341. public void AfterMetadataRefresh()
  1342. {
  1343. _sortName = null;
  1344. }
  1345. /// <summary>
  1346. /// Gets the preferred metadata language.
  1347. /// </summary>
  1348. /// <returns>System.String.</returns>
  1349. public string GetPreferredMetadataLanguage()
  1350. {
  1351. string lang = PreferredMetadataLanguage;
  1352. if (string.IsNullOrEmpty(lang))
  1353. {
  1354. lang = GetParents()
  1355. .Select(i => i.PreferredMetadataLanguage)
  1356. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1357. }
  1358. if (string.IsNullOrEmpty(lang))
  1359. {
  1360. lang = LibraryManager.GetCollectionFolders(this)
  1361. .Select(i => i.PreferredMetadataLanguage)
  1362. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1363. }
  1364. if (string.IsNullOrEmpty(lang))
  1365. {
  1366. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1367. }
  1368. if (string.IsNullOrEmpty(lang))
  1369. {
  1370. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1371. }
  1372. return lang;
  1373. }
  1374. /// <summary>
  1375. /// Gets the preferred metadata language.
  1376. /// </summary>
  1377. /// <returns>System.String.</returns>
  1378. public string GetPreferredMetadataCountryCode()
  1379. {
  1380. string lang = PreferredMetadataCountryCode;
  1381. if (string.IsNullOrEmpty(lang))
  1382. {
  1383. lang = GetParents()
  1384. .Select(i => i.PreferredMetadataCountryCode)
  1385. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1386. }
  1387. if (string.IsNullOrEmpty(lang))
  1388. {
  1389. lang = LibraryManager.GetCollectionFolders(this)
  1390. .Select(i => i.PreferredMetadataCountryCode)
  1391. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1392. }
  1393. if (string.IsNullOrEmpty(lang))
  1394. {
  1395. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1396. }
  1397. if (string.IsNullOrEmpty(lang))
  1398. {
  1399. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1400. }
  1401. return lang;
  1402. }
  1403. public virtual bool IsSaveLocalMetadataEnabled()
  1404. {
  1405. if (SourceType == SourceType.Channel)
  1406. {
  1407. return false;
  1408. }
  1409. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1410. return libraryOptions.SaveLocalMetadata;
  1411. }
  1412. /// <summary>
  1413. /// Determines if a given user has access to this item
  1414. /// </summary>
  1415. /// <param name="user">The user.</param>
  1416. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1417. /// <exception cref="ArgumentNullException">user</exception>
  1418. public bool IsParentalAllowed(User user)
  1419. {
  1420. if (user == null)
  1421. {
  1422. throw new ArgumentNullException(nameof(user));
  1423. }
  1424. if (!IsVisibleViaTags(user))
  1425. {
  1426. return false;
  1427. }
  1428. var maxAllowedRating = user.Policy.MaxParentalRating;
  1429. if (maxAllowedRating == null)
  1430. {
  1431. return true;
  1432. }
  1433. var rating = CustomRatingForComparison;
  1434. if (string.IsNullOrEmpty(rating))
  1435. {
  1436. rating = OfficialRatingForComparison;
  1437. }
  1438. if (string.IsNullOrEmpty(rating))
  1439. {
  1440. return !GetBlockUnratedValue(user.Policy);
  1441. }
  1442. var value = LocalizationManager.GetRatingLevel(rating);
  1443. // Could not determine the integer value
  1444. if (!value.HasValue)
  1445. {
  1446. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1447. if (!isAllowed)
  1448. {
  1449. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1450. }
  1451. return isAllowed;
  1452. }
  1453. return value.Value <= maxAllowedRating.Value;
  1454. }
  1455. public int? GetParentalRatingValue()
  1456. {
  1457. var rating = CustomRating;
  1458. if (string.IsNullOrEmpty(rating))
  1459. {
  1460. rating = OfficialRating;
  1461. }
  1462. if (string.IsNullOrEmpty(rating))
  1463. {
  1464. return null;
  1465. }
  1466. return LocalizationManager.GetRatingLevel(rating);
  1467. }
  1468. public int? GetInheritedParentalRatingValue()
  1469. {
  1470. var rating = CustomRatingForComparison;
  1471. if (string.IsNullOrEmpty(rating))
  1472. {
  1473. rating = OfficialRatingForComparison;
  1474. }
  1475. if (string.IsNullOrEmpty(rating))
  1476. {
  1477. return null;
  1478. }
  1479. return LocalizationManager.GetRatingLevel(rating);
  1480. }
  1481. public List<string> GetInheritedTags()
  1482. {
  1483. var list = new List<string>();
  1484. list.AddRange(Tags);
  1485. foreach (var parent in GetParents())
  1486. {
  1487. list.AddRange(parent.Tags);
  1488. }
  1489. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1490. }
  1491. private bool IsVisibleViaTags(User user)
  1492. {
  1493. var policy = user.Policy;
  1494. if (policy.BlockedTags.Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1495. {
  1496. return false;
  1497. }
  1498. return true;
  1499. }
  1500. protected virtual bool IsAllowTagFilterEnforced()
  1501. {
  1502. return true;
  1503. }
  1504. public virtual UnratedItem GetBlockUnratedType()
  1505. {
  1506. if (SourceType == SourceType.Channel)
  1507. {
  1508. return UnratedItem.ChannelContent;
  1509. }
  1510. return UnratedItem.Other;
  1511. }
  1512. /// <summary>
  1513. /// Gets the block unrated value.
  1514. /// </summary>
  1515. /// <param name="config">The configuration.</param>
  1516. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1517. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1518. {
  1519. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1520. // Special folders like series and albums will override this method.
  1521. if (IsFolder)
  1522. {
  1523. return false;
  1524. }
  1525. if (this is IItemByName)
  1526. {
  1527. return false;
  1528. }
  1529. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1530. }
  1531. /// <summary>
  1532. /// Determines if this folder should be visible to a given user.
  1533. /// Default is just parental allowed. Can be overridden for more functionality.
  1534. /// </summary>
  1535. /// <param name="user">The user.</param>
  1536. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1537. /// <exception cref="ArgumentNullException">user</exception>
  1538. public virtual bool IsVisible(User user)
  1539. {
  1540. if (user == null)
  1541. {
  1542. throw new ArgumentNullException(nameof(user));
  1543. }
  1544. return IsParentalAllowed(user);
  1545. }
  1546. public virtual bool IsVisibleStandalone(User user)
  1547. {
  1548. if (SourceType == SourceType.Channel)
  1549. {
  1550. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1551. }
  1552. return IsVisibleStandaloneInternal(user, true);
  1553. }
  1554. [IgnoreDataMember]
  1555. public virtual bool SupportsInheritedParentImages => false;
  1556. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1557. {
  1558. if (!IsVisible(user))
  1559. {
  1560. return false;
  1561. }
  1562. if (GetParents().Any(i => !i.IsVisible(user)))
  1563. {
  1564. return false;
  1565. }
  1566. if (checkFolders)
  1567. {
  1568. var topParent = GetParents().LastOrDefault() ?? this;
  1569. if (string.IsNullOrEmpty(topParent.Path))
  1570. {
  1571. return true;
  1572. }
  1573. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1574. if (itemCollectionFolders.Count > 0)
  1575. {
  1576. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1577. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1578. {
  1579. return false;
  1580. }
  1581. }
  1582. }
  1583. return true;
  1584. }
  1585. /// <summary>
  1586. /// Gets a value indicating whether this instance is folder.
  1587. /// </summary>
  1588. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1589. [IgnoreDataMember]
  1590. public virtual bool IsFolder => false;
  1591. [IgnoreDataMember]
  1592. public virtual bool IsDisplayedAsFolder => false;
  1593. public virtual string GetClientTypeName()
  1594. {
  1595. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1596. {
  1597. return "ChannelFolderItem";
  1598. }
  1599. return GetType().Name;
  1600. }
  1601. /// <summary>
  1602. /// Gets the linked child.
  1603. /// </summary>
  1604. /// <param name="info">The info.</param>
  1605. /// <returns>BaseItem.</returns>
  1606. protected BaseItem GetLinkedChild(LinkedChild info)
  1607. {
  1608. // First get using the cached Id
  1609. if (info.ItemId.HasValue)
  1610. {
  1611. if (info.ItemId.Value.Equals(Guid.Empty))
  1612. {
  1613. return null;
  1614. }
  1615. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1616. if (itemById != null)
  1617. {
  1618. return itemById;
  1619. }
  1620. }
  1621. var item = FindLinkedChild(info);
  1622. // If still null, log
  1623. if (item == null)
  1624. {
  1625. // Don't keep searching over and over
  1626. info.ItemId = Guid.Empty;
  1627. }
  1628. else
  1629. {
  1630. // Cache the id for next time
  1631. info.ItemId = item.Id;
  1632. }
  1633. return item;
  1634. }
  1635. private BaseItem FindLinkedChild(LinkedChild info)
  1636. {
  1637. var path = info.Path;
  1638. if (!string.IsNullOrEmpty(path))
  1639. {
  1640. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1641. var itemByPath = LibraryManager.FindByPath(path, null);
  1642. if (itemByPath == null)
  1643. {
  1644. //Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1645. }
  1646. return itemByPath;
  1647. }
  1648. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1649. {
  1650. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1651. if (item == null)
  1652. {
  1653. //Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1654. }
  1655. return item;
  1656. }
  1657. return null;
  1658. }
  1659. [IgnoreDataMember]
  1660. public virtual bool EnableRememberingTrackSelections => true;
  1661. /// <summary>
  1662. /// Adds a studio to the item
  1663. /// </summary>
  1664. /// <param name="name">The name.</param>
  1665. /// <exception cref="ArgumentNullException"></exception>
  1666. public void AddStudio(string name)
  1667. {
  1668. if (string.IsNullOrEmpty(name))
  1669. {
  1670. throw new ArgumentNullException(nameof(name));
  1671. }
  1672. var current = Studios;
  1673. if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
  1674. {
  1675. if (current.Length == 0)
  1676. {
  1677. Studios = new[] { name };
  1678. }
  1679. else
  1680. {
  1681. var list =
  1682. Studios = current.Concat(new[] { name }).ToArray();
  1683. }
  1684. }
  1685. }
  1686. public void SetStudios(IEnumerable<string> names)
  1687. {
  1688. Studios = names.Distinct().ToArray();
  1689. }
  1690. /// <summary>
  1691. /// Adds a genre to the item
  1692. /// </summary>
  1693. /// <param name="name">The name.</param>
  1694. /// <exception cref="ArgumentNullException"></exception>
  1695. public void AddGenre(string name)
  1696. {
  1697. if (string.IsNullOrEmpty(name))
  1698. {
  1699. throw new ArgumentNullException(nameof(name));
  1700. }
  1701. var genres = Genres;
  1702. if (!genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1703. {
  1704. var list = genres.ToList();
  1705. list.Add(name);
  1706. Genres = list.ToArray();
  1707. }
  1708. }
  1709. /// <summary>
  1710. /// Marks the played.
  1711. /// </summary>
  1712. /// <param name="user">The user.</param>
  1713. /// <param name="datePlayed">The date played.</param>
  1714. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1715. /// <returns>Task.</returns>
  1716. /// <exception cref="ArgumentNullException"></exception>
  1717. public virtual void MarkPlayed(User user,
  1718. DateTime? datePlayed,
  1719. bool resetPosition)
  1720. {
  1721. if (user == null)
  1722. {
  1723. throw new ArgumentNullException(nameof(user));
  1724. }
  1725. var data = UserDataManager.GetUserData(user, this);
  1726. if (datePlayed.HasValue)
  1727. {
  1728. // Increment
  1729. data.PlayCount++;
  1730. }
  1731. // Ensure it's at least one
  1732. data.PlayCount = Math.Max(data.PlayCount, 1);
  1733. if (resetPosition)
  1734. {
  1735. data.PlaybackPositionTicks = 0;
  1736. }
  1737. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1738. data.Played = true;
  1739. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1740. }
  1741. /// <summary>
  1742. /// Marks the unplayed.
  1743. /// </summary>
  1744. /// <param name="user">The user.</param>
  1745. /// <returns>Task.</returns>
  1746. /// <exception cref="ArgumentNullException"></exception>
  1747. public virtual void MarkUnplayed(User user)
  1748. {
  1749. if (user == null)
  1750. {
  1751. throw new ArgumentNullException(nameof(user));
  1752. }
  1753. var data = UserDataManager.GetUserData(user, this);
  1754. //I think it is okay to do this here.
  1755. // if this is only called when a user is manually forcing something to un-played
  1756. // then it probably is what we want to do...
  1757. data.PlayCount = 0;
  1758. data.PlaybackPositionTicks = 0;
  1759. data.LastPlayedDate = null;
  1760. data.Played = false;
  1761. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1762. }
  1763. /// <summary>
  1764. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1765. /// </summary>
  1766. /// <returns>Task.</returns>
  1767. public virtual void ChangedExternally()
  1768. {
  1769. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem))
  1770. {
  1771. }, RefreshPriority.High);
  1772. }
  1773. /// <summary>
  1774. /// Gets an image
  1775. /// </summary>
  1776. /// <param name="type">The type.</param>
  1777. /// <param name="imageIndex">Index of the image.</param>
  1778. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1779. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1780. public bool HasImage(ImageType type, int imageIndex)
  1781. {
  1782. return GetImageInfo(type, imageIndex) != null;
  1783. }
  1784. public void SetImage(ItemImageInfo image, int index)
  1785. {
  1786. if (image.Type == ImageType.Chapter)
  1787. {
  1788. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1789. }
  1790. var existingImage = GetImageInfo(image.Type, index);
  1791. if (existingImage != null)
  1792. {
  1793. existingImage.Path = image.Path;
  1794. existingImage.DateModified = image.DateModified;
  1795. existingImage.Width = image.Width;
  1796. existingImage.Height = image.Height;
  1797. }
  1798. else
  1799. {
  1800. var currentCount = ImageInfos.Length;
  1801. ImageInfos = ImageInfos.Concat(new[] { image }).ToArray();
  1802. }
  1803. }
  1804. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1805. {
  1806. if (type == ImageType.Chapter)
  1807. {
  1808. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1809. }
  1810. var image = GetImageInfo(type, index);
  1811. if (image == null)
  1812. {
  1813. ImageInfos = ImageInfos.Concat(new[] { GetImageInfo(file, type) }).ToArray();
  1814. }
  1815. else
  1816. {
  1817. var imageInfo = GetImageInfo(file, type);
  1818. image.Path = file.FullName;
  1819. image.DateModified = imageInfo.DateModified;
  1820. // reset these values
  1821. image.Width = 0;
  1822. image.Height = 0;
  1823. }
  1824. }
  1825. /// <summary>
  1826. /// Deletes the image.
  1827. /// </summary>
  1828. /// <param name="type">The type.</param>
  1829. /// <param name="index">The index.</param>
  1830. /// <returns>Task.</returns>
  1831. public void DeleteImage(ImageType type, int index)
  1832. {
  1833. var info = GetImageInfo(type, index);
  1834. if (info == null)
  1835. {
  1836. // Nothing to do
  1837. return;
  1838. }
  1839. // Remove it from the item
  1840. RemoveImage(info);
  1841. if (info.IsLocalFile)
  1842. {
  1843. FileSystem.DeleteFile(info.Path);
  1844. }
  1845. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1846. }
  1847. public void RemoveImage(ItemImageInfo image)
  1848. {
  1849. RemoveImages(new List<ItemImageInfo> { image });
  1850. }
  1851. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1852. {
  1853. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1854. }
  1855. public virtual void UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1856. {
  1857. LibraryManager.UpdateItem(this, GetParent(), updateReason, cancellationToken);
  1858. }
  1859. /// <summary>
  1860. /// Validates that images within the item are still on the file system
  1861. /// </summary>
  1862. public bool ValidateImages(IDirectoryService directoryService)
  1863. {
  1864. var allFiles = ImageInfos
  1865. .Where(i => i.IsLocalFile)
  1866. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1867. .Distinct(StringComparer.OrdinalIgnoreCase)
  1868. .SelectMany(i => directoryService.GetFilePaths(i))
  1869. .ToList();
  1870. var deletedImages = ImageInfos
  1871. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1872. .ToList();
  1873. if (deletedImages.Count > 0)
  1874. {
  1875. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1876. }
  1877. return deletedImages.Count > 0;
  1878. }
  1879. /// <summary>
  1880. /// Gets the image path.
  1881. /// </summary>
  1882. /// <param name="imageType">Type of the image.</param>
  1883. /// <param name="imageIndex">Index of the image.</param>
  1884. /// <returns>System.String.</returns>
  1885. /// <exception cref="InvalidOperationException">
  1886. /// </exception>
  1887. /// <exception cref="ArgumentNullException">item</exception>
  1888. public string GetImagePath(ImageType imageType, int imageIndex)
  1889. => GetImageInfo(imageType, imageIndex)?.Path;
  1890. /// <summary>
  1891. /// Gets the image information.
  1892. /// </summary>
  1893. /// <param name="imageType">Type of the image.</param>
  1894. /// <param name="imageIndex">Index of the image.</param>
  1895. /// <returns>ItemImageInfo.</returns>
  1896. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1897. {
  1898. if (imageType == ImageType.Chapter)
  1899. {
  1900. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1901. if (chapter == null)
  1902. {
  1903. return null;
  1904. }
  1905. var path = chapter.ImagePath;
  1906. if (string.IsNullOrEmpty(path))
  1907. {
  1908. return null;
  1909. }
  1910. return new ItemImageInfo
  1911. {
  1912. Path = path,
  1913. DateModified = chapter.ImageDateModified,
  1914. Type = imageType
  1915. };
  1916. }
  1917. return GetImages(imageType)
  1918. .ElementAtOrDefault(imageIndex);
  1919. }
  1920. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1921. {
  1922. if (imageType == ImageType.Chapter)
  1923. {
  1924. throw new ArgumentException("No image info for chapter images");
  1925. }
  1926. return ImageInfos.Where(i => i.Type == imageType);
  1927. }
  1928. /// <summary>
  1929. /// Adds the images.
  1930. /// </summary>
  1931. /// <param name="imageType">Type of the image.</param>
  1932. /// <param name="images">The images.</param>
  1933. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1934. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
  1935. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1936. {
  1937. if (imageType == ImageType.Chapter)
  1938. {
  1939. throw new ArgumentException("Cannot call AddImages with chapter images");
  1940. }
  1941. var existingImages = GetImages(imageType)
  1942. .ToList();
  1943. var newImageList = new List<FileSystemMetadata>();
  1944. var imageAdded = false;
  1945. var imageUpdated = false;
  1946. foreach (var newImage in images)
  1947. {
  1948. if (newImage == null)
  1949. {
  1950. throw new ArgumentException("null image found in list");
  1951. }
  1952. var existing = existingImages
  1953. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1954. if (existing == null)
  1955. {
  1956. newImageList.Add(newImage);
  1957. imageAdded = true;
  1958. }
  1959. else
  1960. {
  1961. if (existing.IsLocalFile)
  1962. {
  1963. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1964. // If date changed then we need to reset saved image dimensions
  1965. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  1966. {
  1967. existing.Width = 0;
  1968. existing.Height = 0;
  1969. imageUpdated = true;
  1970. }
  1971. existing.DateModified = newDateModified;
  1972. }
  1973. }
  1974. }
  1975. if (imageAdded || images.Count != existingImages.Count)
  1976. {
  1977. var newImagePaths = images.Select(i => i.FullName).ToList();
  1978. var deleted = existingImages
  1979. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
  1980. .ToList();
  1981. if (deleted.Count > 0)
  1982. {
  1983. ImageInfos = ImageInfos.Except(deleted).ToArray();
  1984. }
  1985. }
  1986. if (newImageList.Count > 0)
  1987. {
  1988. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  1989. }
  1990. return imageUpdated || newImageList.Count > 0;
  1991. }
  1992. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1993. {
  1994. return new ItemImageInfo
  1995. {
  1996. Path = file.FullName,
  1997. Type = type,
  1998. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1999. };
  2000. }
  2001. /// <summary>
  2002. /// Gets the file system path to delete when the item is to be deleted
  2003. /// </summary>
  2004. /// <returns></returns>
  2005. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  2006. {
  2007. return new[] {
  2008. new FileSystemMetadata
  2009. {
  2010. FullName = Path,
  2011. IsDirectory = IsFolder
  2012. }
  2013. }.Concat(GetLocalMetadataFilesToDelete());
  2014. }
  2015. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  2016. {
  2017. if (IsFolder || !IsInMixedFolder)
  2018. {
  2019. return new List<FileSystemMetadata>();
  2020. }
  2021. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  2022. var extensions = new List<string> { ".nfo", ".xml", ".srt", ".vtt", ".sub", ".idx", ".txt", ".edl", ".bif", ".smi", ".ttml" };
  2023. extensions.AddRange(SupportedImageExtensions);
  2024. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), extensions.ToArray(), false, false)
  2025. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  2026. .ToList();
  2027. }
  2028. public bool AllowsMultipleImages(ImageType type)
  2029. {
  2030. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  2031. }
  2032. public void SwapImages(ImageType type, int index1, int index2)
  2033. {
  2034. if (!AllowsMultipleImages(type))
  2035. {
  2036. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  2037. }
  2038. var info1 = GetImageInfo(type, index1);
  2039. var info2 = GetImageInfo(type, index2);
  2040. if (info1 == null || info2 == null)
  2041. {
  2042. // Nothing to do
  2043. return;
  2044. }
  2045. if (!info1.IsLocalFile || !info2.IsLocalFile)
  2046. {
  2047. // TODO: Not supported yet
  2048. return;
  2049. }
  2050. var path1 = info1.Path;
  2051. var path2 = info2.Path;
  2052. FileSystem.SwapFiles(path1, path2);
  2053. // Refresh these values
  2054. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  2055. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  2056. info1.Width = 0;
  2057. info1.Height = 0;
  2058. info2.Width = 0;
  2059. info2.Height = 0;
  2060. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2061. }
  2062. public virtual bool IsPlayed(User user)
  2063. {
  2064. var userdata = UserDataManager.GetUserData(user, this);
  2065. return userdata != null && userdata.Played;
  2066. }
  2067. public bool IsFavoriteOrLiked(User user)
  2068. {
  2069. var userdata = UserDataManager.GetUserData(user, this);
  2070. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  2071. }
  2072. public virtual bool IsUnplayed(User user)
  2073. {
  2074. if (user == null)
  2075. {
  2076. throw new ArgumentNullException(nameof(user));
  2077. }
  2078. var userdata = UserDataManager.GetUserData(user, this);
  2079. return userdata == null || !userdata.Played;
  2080. }
  2081. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  2082. {
  2083. return GetItemLookupInfo<ItemLookupInfo>();
  2084. }
  2085. protected T GetItemLookupInfo<T>()
  2086. where T : ItemLookupInfo, new()
  2087. {
  2088. return new T
  2089. {
  2090. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  2091. MetadataLanguage = GetPreferredMetadataLanguage(),
  2092. Name = GetNameForMetadataLookup(),
  2093. ProviderIds = ProviderIds,
  2094. IndexNumber = IndexNumber,
  2095. ParentIndexNumber = ParentIndexNumber,
  2096. Year = ProductionYear,
  2097. PremiereDate = PremiereDate
  2098. };
  2099. }
  2100. protected virtual string GetNameForMetadataLookup()
  2101. {
  2102. return Name;
  2103. }
  2104. /// <summary>
  2105. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  2106. /// </summary>
  2107. public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
  2108. {
  2109. _sortName = null;
  2110. var hasChanges = false;
  2111. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  2112. {
  2113. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  2114. hasChanges = true;
  2115. }
  2116. return hasChanges;
  2117. }
  2118. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  2119. {
  2120. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  2121. {
  2122. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  2123. }
  2124. return path;
  2125. }
  2126. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  2127. {
  2128. if (RunTimeTicks.HasValue)
  2129. {
  2130. double pct = RunTimeTicks.Value;
  2131. if (pct > 0)
  2132. {
  2133. pct = userData.PlaybackPositionTicks / pct;
  2134. if (pct > 0)
  2135. {
  2136. dto.PlayedPercentage = 100 * pct;
  2137. }
  2138. }
  2139. }
  2140. }
  2141. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2142. {
  2143. var newOptions = new MetadataRefreshOptions(options);
  2144. newOptions.SearchResult = null;
  2145. var item = this;
  2146. if (copyTitleMetadata)
  2147. {
  2148. // Take some data from the main item, for querying purposes
  2149. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2150. {
  2151. newOptions.ForceSave = true;
  2152. ownedItem.Genres = item.Genres;
  2153. }
  2154. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2155. {
  2156. newOptions.ForceSave = true;
  2157. ownedItem.Studios = item.Studios;
  2158. }
  2159. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2160. {
  2161. newOptions.ForceSave = true;
  2162. ownedItem.ProductionLocations = item.ProductionLocations;
  2163. }
  2164. if (item.CommunityRating != ownedItem.CommunityRating)
  2165. {
  2166. ownedItem.CommunityRating = item.CommunityRating;
  2167. newOptions.ForceSave = true;
  2168. }
  2169. if (item.CriticRating != ownedItem.CriticRating)
  2170. {
  2171. ownedItem.CriticRating = item.CriticRating;
  2172. newOptions.ForceSave = true;
  2173. }
  2174. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2175. {
  2176. ownedItem.Overview = item.Overview;
  2177. newOptions.ForceSave = true;
  2178. }
  2179. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2180. {
  2181. ownedItem.OfficialRating = item.OfficialRating;
  2182. newOptions.ForceSave = true;
  2183. }
  2184. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2185. {
  2186. ownedItem.CustomRating = item.CustomRating;
  2187. newOptions.ForceSave = true;
  2188. }
  2189. }
  2190. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2191. }
  2192. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2193. {
  2194. var newOptions = new MetadataRefreshOptions(options);
  2195. newOptions.SearchResult = null;
  2196. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2197. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2198. var video = LibraryManager.GetItemById(id) as Video;
  2199. if (video == null)
  2200. {
  2201. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2202. newOptions.ForceSave = true;
  2203. }
  2204. //var parentId = Id;
  2205. //if (!video.IsOwnedItem || video.ParentId != parentId)
  2206. //{
  2207. // video.IsOwnedItem = true;
  2208. // video.ParentId = parentId;
  2209. // newOptions.ForceSave = true;
  2210. //}
  2211. if (video == null)
  2212. {
  2213. return Task.FromResult(true);
  2214. }
  2215. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2216. }
  2217. public string GetEtag(User user)
  2218. {
  2219. var list = GetEtagValues(user);
  2220. return string.Join("|", list.ToArray()).GetMD5().ToString("N");
  2221. }
  2222. protected virtual List<string> GetEtagValues(User user)
  2223. {
  2224. return new List<string>
  2225. {
  2226. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2227. };
  2228. }
  2229. public virtual IEnumerable<Guid> GetAncestorIds()
  2230. {
  2231. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2232. }
  2233. public BaseItem GetTopParent()
  2234. {
  2235. if (IsTopParent)
  2236. {
  2237. return this;
  2238. }
  2239. foreach (var parent in GetParents())
  2240. {
  2241. if (parent.IsTopParent)
  2242. {
  2243. return parent;
  2244. }
  2245. }
  2246. return null;
  2247. }
  2248. [IgnoreDataMember]
  2249. public virtual bool IsTopParent
  2250. {
  2251. get
  2252. {
  2253. if (this is BasePluginFolder || this is Channel)
  2254. {
  2255. return true;
  2256. }
  2257. var view = this as IHasCollectionType;
  2258. if (view != null)
  2259. {
  2260. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2261. {
  2262. return true;
  2263. }
  2264. }
  2265. if (GetParent() is AggregateFolder)
  2266. {
  2267. return true;
  2268. }
  2269. return false;
  2270. }
  2271. }
  2272. [IgnoreDataMember]
  2273. public virtual bool SupportsAncestors => true;
  2274. [IgnoreDataMember]
  2275. public virtual bool StopRefreshIfLocalMetadataFound => true;
  2276. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2277. {
  2278. return new[] { Id };
  2279. }
  2280. public virtual List<ExternalUrl> GetRelatedUrls()
  2281. {
  2282. return new List<ExternalUrl>();
  2283. }
  2284. public virtual double? GetRefreshProgress()
  2285. {
  2286. return null;
  2287. }
  2288. public virtual ItemUpdateType OnMetadataChanged()
  2289. {
  2290. var updateType = ItemUpdateType.None;
  2291. var item = this;
  2292. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2293. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2294. {
  2295. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2296. updateType |= ItemUpdateType.MetadataImport;
  2297. }
  2298. return updateType;
  2299. }
  2300. /// <summary>
  2301. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2302. /// </summary>
  2303. /// <returns></returns>
  2304. public bool UpdateRatingToItems(IList<BaseItem> children)
  2305. {
  2306. var currentOfficialRating = OfficialRating;
  2307. // Gather all possible ratings
  2308. var ratings = children
  2309. .Select(i => i.OfficialRating)
  2310. .Where(i => !string.IsNullOrEmpty(i))
  2311. .Distinct(StringComparer.OrdinalIgnoreCase)
  2312. .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i)))
  2313. .OrderBy(i => i.Item2 ?? 1000)
  2314. .Select(i => i.Item1);
  2315. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2316. return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
  2317. StringComparison.OrdinalIgnoreCase);
  2318. }
  2319. public IEnumerable<BaseItem> GetThemeSongs()
  2320. {
  2321. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeSong)).OrderBy(i => i.SortName);
  2322. }
  2323. public IEnumerable<BaseItem> GetThemeVideos()
  2324. {
  2325. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName);
  2326. }
  2327. /// <summary>
  2328. /// Gets or sets the remote trailers.
  2329. /// </summary>
  2330. /// <value>The remote trailers.</value>
  2331. public MediaUrl[] RemoteTrailers { get; set; }
  2332. public IEnumerable<BaseItem> GetExtras()
  2333. {
  2334. return ExtraIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
  2335. }
  2336. public IEnumerable<BaseItem> GetExtras(ExtraType[] extraTypes)
  2337. {
  2338. return ExtraIds.Select(LibraryManager.GetItemById).Where(i => i != null && extraTypes.Contains(i.ExtraType.Value)).OrderBy(i => i.SortName);
  2339. }
  2340. public IEnumerable<BaseItem> GetDisplayExtras()
  2341. {
  2342. return GetExtras(DisplayExtraTypes);
  2343. }
  2344. public virtual bool IsHD => Height >= 720;
  2345. public bool IsShortcut { get; set; }
  2346. public string ShortcutPath { get; set; }
  2347. public int Width { get; set; }
  2348. public int Height { get; set; }
  2349. public Guid[] ExtraIds { get; set; }
  2350. public virtual long GetRunTimeTicksForPlayState()
  2351. {
  2352. return RunTimeTicks ?? 0;
  2353. }
  2354. // Possible types of extra videos
  2355. 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 };
  2356. public virtual bool SupportsExternalTransfer => false;
  2357. }
  2358. }