BaseItem.cs 91 KB

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