BaseItem.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Localization;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Controller.Resolvers;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Logging;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Runtime.Serialization;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Class BaseItem
  23. /// </summary>
  24. public abstract class BaseItem : IHasProviderIds, ILibraryItem
  25. {
  26. protected BaseItem()
  27. {
  28. Genres = new List<string>();
  29. Studios = new List<string>();
  30. People = new List<PersonInfo>();
  31. BackdropImagePaths = new List<string>();
  32. Images = new Dictionary<ImageType, string>();
  33. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  34. LockedFields = new List<MetadataFields>();
  35. ImageSources = new List<ImageSourceInfo>();
  36. }
  37. /// <summary>
  38. /// The supported image extensions
  39. /// </summary>
  40. public static readonly string[] SupportedImageExtensions = new[] { ".png", ".jpg", ".jpeg", ".tbn" };
  41. /// <summary>
  42. /// The trailer folder name
  43. /// </summary>
  44. public const string TrailerFolderName = "trailers";
  45. public const string ThemeSongsFolderName = "theme-music";
  46. public const string ThemeSongFilename = "theme";
  47. public const string ThemeVideosFolderName = "backdrops";
  48. public const string XbmcTrailerFileSuffix = "-trailer";
  49. public bool IsInMixedFolder { get; set; }
  50. private string _name;
  51. /// <summary>
  52. /// Gets or sets the name.
  53. /// </summary>
  54. /// <value>The name.</value>
  55. public string Name
  56. {
  57. get
  58. {
  59. return _name;
  60. }
  61. set
  62. {
  63. _name = value;
  64. // lazy load this again
  65. _sortName = null;
  66. }
  67. }
  68. /// <summary>
  69. /// Gets or sets the id.
  70. /// </summary>
  71. /// <value>The id.</value>
  72. public Guid Id { get; set; }
  73. /// <summary>
  74. /// Return the id that should be used to key display prefs for this item.
  75. /// Default is based on the type for everything except actual generic folders.
  76. /// </summary>
  77. /// <value>The display prefs id.</value>
  78. [IgnoreDataMember]
  79. public virtual Guid DisplayPreferencesId
  80. {
  81. get
  82. {
  83. var thisType = GetType();
  84. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  85. }
  86. }
  87. /// <summary>
  88. /// Gets or sets the path.
  89. /// </summary>
  90. /// <value>The path.</value>
  91. public virtual string Path { get; set; }
  92. [IgnoreDataMember]
  93. protected internal bool IsOffline { get; set; }
  94. /// <summary>
  95. /// Gets or sets the type of the location.
  96. /// </summary>
  97. /// <value>The type of the location.</value>
  98. [IgnoreDataMember]
  99. public virtual LocationType LocationType
  100. {
  101. get
  102. {
  103. if (IsOffline)
  104. {
  105. return LocationType.Offline;
  106. }
  107. if (string.IsNullOrEmpty(Path))
  108. {
  109. return LocationType.Virtual;
  110. }
  111. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  112. }
  113. }
  114. /// <summary>
  115. /// This is just a helper for convenience
  116. /// </summary>
  117. /// <value>The primary image path.</value>
  118. [IgnoreDataMember]
  119. public string PrimaryImagePath
  120. {
  121. get { return GetImage(ImageType.Primary); }
  122. set { SetImage(ImageType.Primary, value); }
  123. }
  124. /// <summary>
  125. /// Gets or sets the images.
  126. /// </summary>
  127. /// <value>The images.</value>
  128. public Dictionary<ImageType, string> Images { get; set; }
  129. /// <summary>
  130. /// Gets or sets the date created.
  131. /// </summary>
  132. /// <value>The date created.</value>
  133. public DateTime DateCreated { get; set; }
  134. /// <summary>
  135. /// Gets or sets the date modified.
  136. /// </summary>
  137. /// <value>The date modified.</value>
  138. public DateTime DateModified { get; set; }
  139. /// <summary>
  140. /// The logger
  141. /// </summary>
  142. public static ILogger Logger { get; set; }
  143. public static ILibraryManager LibraryManager { get; set; }
  144. public static IServerConfigurationManager ConfigurationManager { get; set; }
  145. public static IProviderManager ProviderManager { get; set; }
  146. public static ILocalizationManager LocalizationManager { get; set; }
  147. public static IItemRepository ItemRepository { get; set; }
  148. public static IFileSystem FileSystem { get; set; }
  149. /// <summary>
  150. /// Returns a <see cref="System.String" /> that represents this instance.
  151. /// </summary>
  152. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  153. public override string ToString()
  154. {
  155. return Name;
  156. }
  157. /// <summary>
  158. /// Returns true if this item should not attempt to fetch metadata
  159. /// </summary>
  160. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  161. public bool DontFetchMeta { get; set; }
  162. /// <summary>
  163. /// Gets or sets the locked fields.
  164. /// </summary>
  165. /// <value>The locked fields.</value>
  166. public List<MetadataFields> LockedFields { get; set; }
  167. /// <summary>
  168. /// Should be overridden to return the proper folder where metadata lives
  169. /// </summary>
  170. /// <value>The meta location.</value>
  171. [IgnoreDataMember]
  172. public virtual string MetaLocation
  173. {
  174. get
  175. {
  176. return Path ?? "";
  177. }
  178. }
  179. /// <summary>
  180. /// The _provider data
  181. /// </summary>
  182. private Dictionary<Guid, BaseProviderInfo> _providerData;
  183. /// <summary>
  184. /// Holds persistent data for providers like last refresh date.
  185. /// Providers can use this to determine if they need to refresh.
  186. /// The BaseProviderInfo class can be extended to hold anything a provider may need.
  187. /// Keyed by a unique provider ID.
  188. /// </summary>
  189. /// <value>The provider data.</value>
  190. public Dictionary<Guid, BaseProviderInfo> ProviderData
  191. {
  192. get
  193. {
  194. return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>());
  195. }
  196. set
  197. {
  198. _providerData = value;
  199. }
  200. }
  201. /// <summary>
  202. /// Gets the type of the media.
  203. /// </summary>
  204. /// <value>The type of the media.</value>
  205. [IgnoreDataMember]
  206. public virtual string MediaType
  207. {
  208. get
  209. {
  210. return null;
  211. }
  212. }
  213. /// <summary>
  214. /// The _resolve args
  215. /// </summary>
  216. private ItemResolveArgs _resolveArgs;
  217. /// <summary>
  218. /// We attach these to the item so that we only ever have to hit the file system once
  219. /// (this includes the children of the containing folder)
  220. /// </summary>
  221. /// <value>The resolve args.</value>
  222. [IgnoreDataMember]
  223. public ItemResolveArgs ResolveArgs
  224. {
  225. get
  226. {
  227. if (_resolveArgs == null)
  228. {
  229. try
  230. {
  231. _resolveArgs = CreateResolveArgs();
  232. }
  233. catch (IOException ex)
  234. {
  235. Logger.ErrorException("Error creating resolve args for {0}", ex, Path);
  236. IsOffline = true;
  237. throw;
  238. }
  239. }
  240. return _resolveArgs;
  241. }
  242. set
  243. {
  244. _resolveArgs = value;
  245. }
  246. }
  247. /// <summary>
  248. /// Resets the resolve args.
  249. /// </summary>
  250. /// <param name="pathInfo">The path info.</param>
  251. public void ResetResolveArgs(FileSystemInfo pathInfo)
  252. {
  253. ResetResolveArgs(CreateResolveArgs(pathInfo));
  254. }
  255. /// <summary>
  256. /// Resets the resolve args.
  257. /// </summary>
  258. public void ResetResolveArgs()
  259. {
  260. _resolveArgs = null;
  261. }
  262. /// <summary>
  263. /// Resets the resolve args.
  264. /// </summary>
  265. /// <param name="args">The args.</param>
  266. public void ResetResolveArgs(ItemResolveArgs args)
  267. {
  268. _resolveArgs = args;
  269. }
  270. /// <summary>
  271. /// Creates ResolveArgs on demand
  272. /// </summary>
  273. /// <param name="pathInfo">The path info.</param>
  274. /// <returns>ItemResolveArgs.</returns>
  275. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  276. protected internal virtual ItemResolveArgs CreateResolveArgs(FileSystemInfo pathInfo = null)
  277. {
  278. var path = Path;
  279. var locationType = LocationType;
  280. if (locationType == LocationType.Remote ||
  281. locationType == LocationType.Virtual)
  282. {
  283. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager);
  284. }
  285. var isDirectory = false;
  286. if (UseParentPathToCreateResolveArgs)
  287. {
  288. path = System.IO.Path.GetDirectoryName(path);
  289. isDirectory = true;
  290. }
  291. pathInfo = pathInfo ?? (isDirectory ? new DirectoryInfo(path) : FileSystem.GetFileSystemInfo(path));
  292. if (pathInfo == null || !pathInfo.Exists)
  293. {
  294. throw new IOException("Unable to retrieve file system info for " + path);
  295. }
  296. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager)
  297. {
  298. FileInfo = pathInfo,
  299. Path = path,
  300. Parent = Parent
  301. };
  302. // Gather child folder and files
  303. if (args.IsDirectory)
  304. {
  305. var isPhysicalRoot = args.IsPhysicalRoot;
  306. // When resolving the root, we need it's grandchildren (children of user views)
  307. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  308. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, FileSystem, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  309. // Need to remove subpaths that may have been resolved from shortcuts
  310. // Example: if \\server\movies exists, then strip out \\server\movies\action
  311. if (isPhysicalRoot)
  312. {
  313. var paths = args.FileSystemDictionary.Keys.ToList();
  314. foreach (var subPath in paths
  315. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  316. {
  317. Logger.Info("Ignoring duplicate path: {0}", subPath);
  318. args.FileSystemDictionary.Remove(subPath);
  319. }
  320. }
  321. }
  322. //update our dates
  323. EntityResolutionHelper.EnsureDates(FileSystem, this, args, false);
  324. IsOffline = false;
  325. return args;
  326. }
  327. /// <summary>
  328. /// Some subclasses will stop resolving at a directory and point their Path to a file within. This will help ensure the on-demand resolve args are identical to the
  329. /// original ones.
  330. /// </summary>
  331. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  332. [IgnoreDataMember]
  333. protected virtual bool UseParentPathToCreateResolveArgs
  334. {
  335. get
  336. {
  337. return false;
  338. }
  339. }
  340. /// <summary>
  341. /// Gets or sets the name of the forced sort.
  342. /// </summary>
  343. /// <value>The name of the forced sort.</value>
  344. public string ForcedSortName { get; set; }
  345. private string _sortName;
  346. /// <summary>
  347. /// Gets or sets the name of the sort.
  348. /// </summary>
  349. /// <value>The name of the sort.</value>
  350. [IgnoreDataMember]
  351. public string SortName
  352. {
  353. get
  354. {
  355. if (!string.IsNullOrEmpty(ForcedSortName))
  356. {
  357. return ForcedSortName;
  358. }
  359. return _sortName ?? (_sortName = CreateSortName());
  360. }
  361. }
  362. /// <summary>
  363. /// Creates the name of the sort.
  364. /// </summary>
  365. /// <returns>System.String.</returns>
  366. protected virtual string CreateSortName()
  367. {
  368. if (Name == null) return null; //some items may not have name filled in properly
  369. var sortable = Name.Trim().ToLower();
  370. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  371. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  372. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  373. {
  374. var searchLower = search.ToLower();
  375. // Remove from beginning if a space follows
  376. if (sortable.StartsWith(searchLower + " "))
  377. {
  378. sortable = sortable.Remove(0, searchLower.Length + 1);
  379. }
  380. // Remove from middle if surrounded by spaces
  381. sortable = sortable.Replace(" " + searchLower + " ", " ");
  382. // Remove from end if followed by a space
  383. if (sortable.EndsWith(" " + searchLower))
  384. {
  385. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  386. }
  387. }
  388. return sortable;
  389. }
  390. /// <summary>
  391. /// Gets or sets the parent.
  392. /// </summary>
  393. /// <value>The parent.</value>
  394. [IgnoreDataMember]
  395. public Folder Parent { get; set; }
  396. [IgnoreDataMember]
  397. public IEnumerable<Folder> Parents
  398. {
  399. get
  400. {
  401. var parent = Parent;
  402. while (parent != null)
  403. {
  404. yield return parent;
  405. parent = parent.Parent;
  406. }
  407. }
  408. }
  409. /// <summary>
  410. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  411. /// </summary>
  412. /// <value>The premiere date.</value>
  413. public DateTime? PremiereDate { get; set; }
  414. /// <summary>
  415. /// Gets or sets the end date.
  416. /// </summary>
  417. /// <value>The end date.</value>
  418. public DateTime? EndDate { get; set; }
  419. /// <summary>
  420. /// Gets or sets the display type of the media.
  421. /// </summary>
  422. /// <value>The display type of the media.</value>
  423. public string DisplayMediaType { get; set; }
  424. /// <summary>
  425. /// Gets or sets the backdrop image paths.
  426. /// </summary>
  427. /// <value>The backdrop image paths.</value>
  428. public List<string> BackdropImagePaths { get; set; }
  429. /// <summary>
  430. /// Gets or sets the backdrop image sources.
  431. /// </summary>
  432. /// <value>The backdrop image sources.</value>
  433. public List<ImageSourceInfo> ImageSources { get; set; }
  434. /// <summary>
  435. /// Gets or sets the official rating.
  436. /// </summary>
  437. /// <value>The official rating.</value>
  438. public string OfficialRating { get; set; }
  439. /// <summary>
  440. /// Gets or sets the official rating description.
  441. /// </summary>
  442. /// <value>The official rating description.</value>
  443. public string OfficialRatingDescription { get; set; }
  444. /// <summary>
  445. /// Gets or sets the custom rating.
  446. /// </summary>
  447. /// <value>The custom rating.</value>
  448. public string CustomRating { get; set; }
  449. /// <summary>
  450. /// Gets or sets the overview.
  451. /// </summary>
  452. /// <value>The overview.</value>
  453. public string Overview { get; set; }
  454. /// <summary>
  455. /// Gets or sets the people.
  456. /// </summary>
  457. /// <value>The people.</value>
  458. public List<PersonInfo> People { get; set; }
  459. /// <summary>
  460. /// Override this if you need to combine/collapse person information
  461. /// </summary>
  462. /// <value>All people.</value>
  463. [IgnoreDataMember]
  464. public virtual IEnumerable<PersonInfo> AllPeople
  465. {
  466. get { return People; }
  467. }
  468. [IgnoreDataMember]
  469. public virtual IEnumerable<string> AllStudios
  470. {
  471. get { return Studios; }
  472. }
  473. [IgnoreDataMember]
  474. public virtual IEnumerable<string> AllGenres
  475. {
  476. get { return Genres; }
  477. }
  478. /// <summary>
  479. /// Gets or sets the studios.
  480. /// </summary>
  481. /// <value>The studios.</value>
  482. public List<string> Studios { get; set; }
  483. /// <summary>
  484. /// Gets or sets the genres.
  485. /// </summary>
  486. /// <value>The genres.</value>
  487. public List<string> Genres { get; set; }
  488. /// <summary>
  489. /// Gets or sets the home page URL.
  490. /// </summary>
  491. /// <value>The home page URL.</value>
  492. public string HomePageUrl { get; set; }
  493. /// <summary>
  494. /// Gets or sets the community rating.
  495. /// </summary>
  496. /// <value>The community rating.</value>
  497. public float? CommunityRating { get; set; }
  498. /// <summary>
  499. /// Gets or sets the community rating vote count.
  500. /// </summary>
  501. /// <value>The community rating vote count.</value>
  502. public int? VoteCount { get; set; }
  503. /// <summary>
  504. /// Gets or sets the run time ticks.
  505. /// </summary>
  506. /// <value>The run time ticks.</value>
  507. public long? RunTimeTicks { get; set; }
  508. /// <summary>
  509. /// Gets or sets the original run time ticks.
  510. /// </summary>
  511. /// <value>The original run time ticks.</value>
  512. public long? OriginalRunTimeTicks { get; set; }
  513. /// <summary>
  514. /// Gets or sets the production year.
  515. /// </summary>
  516. /// <value>The production year.</value>
  517. public int? ProductionYear { get; set; }
  518. /// <summary>
  519. /// If the item is part of a series, this is it's number in the series.
  520. /// This could be episode number, album track number, etc.
  521. /// </summary>
  522. /// <value>The index number.</value>
  523. public int? IndexNumber { get; set; }
  524. /// <summary>
  525. /// For an episode this could be the season number, or for a song this could be the disc number.
  526. /// </summary>
  527. /// <value>The parent index number.</value>
  528. public int? ParentIndexNumber { get; set; }
  529. [IgnoreDataMember]
  530. public virtual string OfficialRatingForComparison
  531. {
  532. get { return OfficialRating; }
  533. }
  534. [IgnoreDataMember]
  535. public virtual string CustomRatingForComparison
  536. {
  537. get { return CustomRating; }
  538. }
  539. /// <summary>
  540. /// Loads local trailers from the file system
  541. /// </summary>
  542. /// <returns>List{Video}.</returns>
  543. private IEnumerable<Trailer> LoadLocalTrailers()
  544. {
  545. ItemResolveArgs resolveArgs;
  546. try
  547. {
  548. resolveArgs = ResolveArgs;
  549. if (!resolveArgs.IsDirectory)
  550. {
  551. return new List<Trailer>();
  552. }
  553. }
  554. catch (IOException ex)
  555. {
  556. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  557. return new List<Trailer>();
  558. }
  559. var files = new List<FileSystemInfo>();
  560. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  561. // Path doesn't exist. No biggie
  562. if (folder != null)
  563. {
  564. try
  565. {
  566. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  567. }
  568. catch (IOException ex)
  569. {
  570. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  571. }
  572. }
  573. // Support xbmc trailers (-trailer suffix on video file names)
  574. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  575. {
  576. try
  577. {
  578. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  579. {
  580. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  581. {
  582. return true;
  583. }
  584. }
  585. }
  586. catch (IOException ex)
  587. {
  588. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  589. }
  590. return false;
  591. }));
  592. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  593. {
  594. // Try to retrieve it from the db. If we don't find it, use the resolved version
  595. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  596. if (dbItem != null)
  597. {
  598. dbItem.ResetResolveArgs(video.ResolveArgs);
  599. video = dbItem;
  600. }
  601. return video;
  602. }).ToList();
  603. }
  604. /// <summary>
  605. /// Loads the theme songs.
  606. /// </summary>
  607. /// <returns>List{Audio.Audio}.</returns>
  608. private IEnumerable<Audio.Audio> LoadThemeSongs()
  609. {
  610. ItemResolveArgs resolveArgs;
  611. try
  612. {
  613. resolveArgs = ResolveArgs;
  614. if (!resolveArgs.IsDirectory)
  615. {
  616. return new List<Audio.Audio>();
  617. }
  618. }
  619. catch (IOException ex)
  620. {
  621. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  622. return new List<Audio.Audio>();
  623. }
  624. var files = new List<FileSystemInfo>();
  625. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  626. // Path doesn't exist. No biggie
  627. if (folder != null)
  628. {
  629. try
  630. {
  631. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  632. }
  633. catch (IOException ex)
  634. {
  635. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  636. }
  637. }
  638. // Support plex/xbmc convention
  639. files.AddRange(resolveArgs.FileSystemChildren
  640. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  641. );
  642. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  643. {
  644. // Try to retrieve it from the db. If we don't find it, use the resolved version
  645. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  646. if (dbItem != null)
  647. {
  648. dbItem.ResetResolveArgs(audio.ResolveArgs);
  649. audio = dbItem;
  650. }
  651. return audio;
  652. }).ToList();
  653. }
  654. /// <summary>
  655. /// Loads the video backdrops.
  656. /// </summary>
  657. /// <returns>List{Video}.</returns>
  658. private IEnumerable<Video> LoadThemeVideos()
  659. {
  660. ItemResolveArgs resolveArgs;
  661. try
  662. {
  663. resolveArgs = ResolveArgs;
  664. if (!resolveArgs.IsDirectory)
  665. {
  666. return new List<Video>();
  667. }
  668. }
  669. catch (IOException ex)
  670. {
  671. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  672. return new List<Video>();
  673. }
  674. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  675. // Path doesn't exist. No biggie
  676. if (folder == null)
  677. {
  678. return new List<Video>();
  679. }
  680. IEnumerable<FileSystemInfo> files;
  681. try
  682. {
  683. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  684. }
  685. catch (IOException ex)
  686. {
  687. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  688. return new List<Video>();
  689. }
  690. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  691. {
  692. // Try to retrieve it from the db. If we don't find it, use the resolved version
  693. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  694. if (dbItem != null)
  695. {
  696. dbItem.ResetResolveArgs(item.ResolveArgs);
  697. item = dbItem;
  698. }
  699. return item;
  700. }).ToList();
  701. }
  702. /// <summary>
  703. /// Overrides the base implementation to refresh metadata for local trailers
  704. /// </summary>
  705. /// <param name="cancellationToken">The cancellation token.</param>
  706. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  707. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  708. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  709. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  710. /// <returns>true if a provider reports we changed</returns>
  711. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  712. {
  713. if (resetResolveArgs || ResolveArgs == null)
  714. {
  715. // Reload this
  716. ResetResolveArgs();
  717. }
  718. // Refresh for the item
  719. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  720. cancellationToken.ThrowIfCancellationRequested();
  721. var themeSongsChanged = false;
  722. var themeVideosChanged = false;
  723. var localTrailersChanged = false;
  724. if (LocationType == LocationType.FileSystem && Parent != null)
  725. {
  726. var hasThemeMedia = this as IHasThemeMedia;
  727. if (hasThemeMedia != null)
  728. {
  729. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  730. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  731. }
  732. var hasTrailers = this as IHasTrailers;
  733. if (hasTrailers != null)
  734. {
  735. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  736. }
  737. }
  738. cancellationToken.ThrowIfCancellationRequested();
  739. // Get the result from the item task
  740. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  741. var changed = updateReason.HasValue;
  742. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  743. {
  744. cancellationToken.ThrowIfCancellationRequested();
  745. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  746. }
  747. return changed;
  748. }
  749. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  750. {
  751. var newItems = LoadLocalTrailers().ToList();
  752. var newItemIds = newItems.Select(i => i.Id).ToList();
  753. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  754. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  755. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  756. item.LocalTrailerIds = newItemIds;
  757. return itemsChanged || results.Contains(true);
  758. }
  759. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  760. {
  761. var newThemeVideos = LoadThemeVideos().ToList();
  762. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  763. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  764. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  765. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  766. item.ThemeVideoIds = newThemeVideoIds;
  767. return themeVideosChanged || results.Contains(true);
  768. }
  769. /// <summary>
  770. /// Refreshes the theme songs.
  771. /// </summary>
  772. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  773. {
  774. var newThemeSongs = LoadThemeSongs().ToList();
  775. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  776. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  777. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  778. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  779. item.ThemeSongIds = newThemeSongIds;
  780. return themeSongsChanged || results.Contains(true);
  781. }
  782. /// <summary>
  783. /// Gets or sets the provider ids.
  784. /// </summary>
  785. /// <value>The provider ids.</value>
  786. public Dictionary<string, string> ProviderIds { get; set; }
  787. /// <summary>
  788. /// Override this to false if class should be ignored for indexing purposes
  789. /// </summary>
  790. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  791. [IgnoreDataMember]
  792. public virtual bool IncludeInIndex
  793. {
  794. get { return true; }
  795. }
  796. /// <summary>
  797. /// Override this to true if class should be grouped under a container in indicies
  798. /// The container class should be defined via IndexContainer
  799. /// </summary>
  800. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  801. [IgnoreDataMember]
  802. public virtual bool GroupInIndex
  803. {
  804. get { return false; }
  805. }
  806. /// <summary>
  807. /// Override this to return the folder that should be used to construct a container
  808. /// for this item in an index. GroupInIndex should be true as well.
  809. /// </summary>
  810. /// <value>The index container.</value>
  811. [IgnoreDataMember]
  812. public virtual Folder IndexContainer
  813. {
  814. get { return null; }
  815. }
  816. /// <summary>
  817. /// Gets the user data key.
  818. /// </summary>
  819. /// <returns>System.String.</returns>
  820. public virtual string GetUserDataKey()
  821. {
  822. return Id.ToString();
  823. }
  824. /// <summary>
  825. /// Determines if a given user has access to this item
  826. /// </summary>
  827. /// <param name="user">The user.</param>
  828. /// <param name="localizationManager">The localization manager.</param>
  829. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  830. /// <exception cref="System.ArgumentNullException">user</exception>
  831. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  832. {
  833. if (user == null)
  834. {
  835. throw new ArgumentNullException("user");
  836. }
  837. var maxAllowedRating = user.Configuration.MaxParentalRating;
  838. if (maxAllowedRating == null)
  839. {
  840. return true;
  841. }
  842. var rating = CustomRatingForComparison;
  843. if (string.IsNullOrEmpty(rating))
  844. {
  845. rating = OfficialRatingForComparison;
  846. }
  847. if (string.IsNullOrEmpty(rating))
  848. {
  849. return !user.Configuration.BlockNotRated;
  850. }
  851. var value = localizationManager.GetRatingLevel(rating);
  852. // Could not determine the integer value
  853. if (!value.HasValue)
  854. {
  855. return true;
  856. }
  857. return value.Value <= maxAllowedRating.Value;
  858. }
  859. /// <summary>
  860. /// Determines if this folder should be visible to a given user.
  861. /// Default is just parental allowed. Can be overridden for more functionality.
  862. /// </summary>
  863. /// <param name="user">The user.</param>
  864. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  865. /// <exception cref="System.ArgumentNullException">user</exception>
  866. public virtual bool IsVisible(User user)
  867. {
  868. if (user == null)
  869. {
  870. throw new ArgumentNullException("user");
  871. }
  872. return IsParentalAllowed(user, LocalizationManager);
  873. }
  874. /// <summary>
  875. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  876. /// </summary>
  877. /// <param name="id">The id.</param>
  878. /// <returns>BaseItem.</returns>
  879. /// <exception cref="System.ArgumentException"></exception>
  880. protected BaseItem FindParentItem(Guid id)
  881. {
  882. if (id == Guid.Empty)
  883. {
  884. throw new ArgumentException();
  885. }
  886. var parent = Parent;
  887. while (parent != null && !parent.IsRoot)
  888. {
  889. if (parent.Id == id) return parent;
  890. parent = parent.Parent;
  891. }
  892. return null;
  893. }
  894. /// <summary>
  895. /// Gets a value indicating whether this instance is folder.
  896. /// </summary>
  897. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  898. [IgnoreDataMember]
  899. public virtual bool IsFolder
  900. {
  901. get
  902. {
  903. return false;
  904. }
  905. }
  906. /// <summary>
  907. /// Determine if we have changed vs the passed in copy
  908. /// </summary>
  909. /// <param name="copy">The copy.</param>
  910. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  911. /// <exception cref="System.ArgumentNullException"></exception>
  912. public virtual bool HasChanged(BaseItem copy)
  913. {
  914. if (copy == null)
  915. {
  916. throw new ArgumentNullException();
  917. }
  918. var changed = copy.DateModified != DateModified;
  919. if (changed)
  920. {
  921. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  922. }
  923. return changed;
  924. }
  925. public virtual string GetClientTypeName()
  926. {
  927. return GetType().Name;
  928. }
  929. /// <summary>
  930. /// Determines if the item is considered new based on user settings
  931. /// </summary>
  932. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  933. /// <exception cref="System.ArgumentNullException"></exception>
  934. public bool IsRecentlyAdded()
  935. {
  936. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  937. }
  938. /// <summary>
  939. /// Adds a person to the item
  940. /// </summary>
  941. /// <param name="person">The person.</param>
  942. /// <exception cref="System.ArgumentNullException"></exception>
  943. public void AddPerson(PersonInfo person)
  944. {
  945. if (person == null)
  946. {
  947. throw new ArgumentNullException("person");
  948. }
  949. if (string.IsNullOrWhiteSpace(person.Name))
  950. {
  951. throw new ArgumentNullException();
  952. }
  953. // Normalize
  954. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  955. {
  956. person.Type = PersonType.GuestStar;
  957. }
  958. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  959. {
  960. person.Type = PersonType.Director;
  961. }
  962. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  963. {
  964. person.Type = PersonType.Producer;
  965. }
  966. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  967. {
  968. person.Type = PersonType.Writer;
  969. }
  970. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  971. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  972. {
  973. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  974. if (existing != null)
  975. {
  976. existing.Type = PersonType.GuestStar;
  977. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  978. return;
  979. }
  980. }
  981. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  982. {
  983. // If the actor already exists without a role and we have one, fill it in
  984. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase)));
  985. if (existing == null)
  986. {
  987. // Wasn't there - add it
  988. People.Add(person);
  989. }
  990. else
  991. {
  992. // Was there, if no role and we have one - fill it in
  993. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  994. {
  995. existing.Role = person.Role;
  996. }
  997. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  998. }
  999. }
  1000. else
  1001. {
  1002. var existing = People.FirstOrDefault(p =>
  1003. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  1004. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  1005. // Check for dupes based on the combination of Name and Type
  1006. if (existing == null)
  1007. {
  1008. People.Add(person);
  1009. }
  1010. else
  1011. {
  1012. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1013. }
  1014. }
  1015. }
  1016. /// <summary>
  1017. /// Adds a studio to the item
  1018. /// </summary>
  1019. /// <param name="name">The name.</param>
  1020. /// <exception cref="System.ArgumentNullException"></exception>
  1021. public void AddStudio(string name)
  1022. {
  1023. if (string.IsNullOrWhiteSpace(name))
  1024. {
  1025. throw new ArgumentNullException("name");
  1026. }
  1027. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1028. {
  1029. Studios.Add(name);
  1030. }
  1031. }
  1032. /// <summary>
  1033. /// Adds a genre to the item
  1034. /// </summary>
  1035. /// <param name="name">The name.</param>
  1036. /// <exception cref="System.ArgumentNullException"></exception>
  1037. public void AddGenre(string name)
  1038. {
  1039. if (string.IsNullOrWhiteSpace(name))
  1040. {
  1041. throw new ArgumentNullException("name");
  1042. }
  1043. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1044. {
  1045. Genres.Add(name);
  1046. }
  1047. }
  1048. /// <summary>
  1049. /// Marks the played.
  1050. /// </summary>
  1051. /// <param name="user">The user.</param>
  1052. /// <param name="datePlayed">The date played.</param>
  1053. /// <param name="userManager">The user manager.</param>
  1054. /// <returns>Task.</returns>
  1055. /// <exception cref="System.ArgumentNullException"></exception>
  1056. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1057. {
  1058. if (user == null)
  1059. {
  1060. throw new ArgumentNullException();
  1061. }
  1062. var key = GetUserDataKey();
  1063. var data = userManager.GetUserData(user.Id, key);
  1064. if (datePlayed.HasValue)
  1065. {
  1066. // Incremenet
  1067. data.PlayCount++;
  1068. }
  1069. // Ensure it's at least one
  1070. data.PlayCount = Math.Max(data.PlayCount, 1);
  1071. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1072. data.Played = true;
  1073. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1074. }
  1075. /// <summary>
  1076. /// Marks the unplayed.
  1077. /// </summary>
  1078. /// <param name="user">The user.</param>
  1079. /// <param name="userManager">The user manager.</param>
  1080. /// <returns>Task.</returns>
  1081. /// <exception cref="System.ArgumentNullException"></exception>
  1082. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  1083. {
  1084. if (user == null)
  1085. {
  1086. throw new ArgumentNullException();
  1087. }
  1088. var key = GetUserDataKey();
  1089. var data = userManager.GetUserData(user.Id, key);
  1090. //I think it is okay to do this here.
  1091. // if this is only called when a user is manually forcing something to un-played
  1092. // then it probably is what we want to do...
  1093. data.PlayCount = 0;
  1094. data.PlaybackPositionTicks = 0;
  1095. data.LastPlayedDate = null;
  1096. data.Played = false;
  1097. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1098. }
  1099. /// <summary>
  1100. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1101. /// </summary>
  1102. /// <returns>Task.</returns>
  1103. public virtual Task ChangedExternally()
  1104. {
  1105. return RefreshMetadata(CancellationToken.None);
  1106. }
  1107. /// <summary>
  1108. /// Finds a parent of a given type
  1109. /// </summary>
  1110. /// <typeparam name="T"></typeparam>
  1111. /// <returns>``0.</returns>
  1112. public T FindParent<T>()
  1113. where T : Folder
  1114. {
  1115. var parent = Parent;
  1116. while (parent != null)
  1117. {
  1118. var result = parent as T;
  1119. if (result != null)
  1120. {
  1121. return result;
  1122. }
  1123. parent = parent.Parent;
  1124. }
  1125. return null;
  1126. }
  1127. /// <summary>
  1128. /// Gets an image
  1129. /// </summary>
  1130. /// <param name="type">The type.</param>
  1131. /// <returns>System.String.</returns>
  1132. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1133. public string GetImage(ImageType type)
  1134. {
  1135. if (type == ImageType.Backdrop)
  1136. {
  1137. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1138. }
  1139. if (type == ImageType.Screenshot)
  1140. {
  1141. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1142. }
  1143. string val;
  1144. Images.TryGetValue(type, out val);
  1145. return val;
  1146. }
  1147. /// <summary>
  1148. /// Gets an image
  1149. /// </summary>
  1150. /// <param name="type">The type.</param>
  1151. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1152. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1153. public bool HasImage(ImageType type)
  1154. {
  1155. if (type == ImageType.Backdrop)
  1156. {
  1157. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1158. }
  1159. if (type == ImageType.Screenshot)
  1160. {
  1161. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1162. }
  1163. return !string.IsNullOrEmpty(GetImage(type));
  1164. }
  1165. /// <summary>
  1166. /// Sets an image
  1167. /// </summary>
  1168. /// <param name="type">The type.</param>
  1169. /// <param name="path">The path.</param>
  1170. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1171. public void SetImage(ImageType type, string path)
  1172. {
  1173. if (type == ImageType.Backdrop)
  1174. {
  1175. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1176. }
  1177. if (type == ImageType.Screenshot)
  1178. {
  1179. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1180. }
  1181. var typeKey = type;
  1182. // If it's null remove the key from the dictionary
  1183. if (string.IsNullOrEmpty(path))
  1184. {
  1185. if (Images.ContainsKey(typeKey))
  1186. {
  1187. Images.Remove(typeKey);
  1188. }
  1189. }
  1190. else
  1191. {
  1192. Images[typeKey] = path;
  1193. }
  1194. }
  1195. /// <summary>
  1196. /// Deletes the image.
  1197. /// </summary>
  1198. /// <param name="type">The type.</param>
  1199. /// <param name="index">The index.</param>
  1200. /// <returns>Task.</returns>
  1201. public Task DeleteImage(ImageType type, int? index)
  1202. {
  1203. if (type == ImageType.Backdrop)
  1204. {
  1205. if (!index.HasValue)
  1206. {
  1207. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1208. }
  1209. var file = BackdropImagePaths[index.Value];
  1210. BackdropImagePaths.Remove(file);
  1211. RemoveImageSourceForPath(file);
  1212. // Delete the source file
  1213. DeleteImagePath(file);
  1214. }
  1215. else if (type == ImageType.Screenshot)
  1216. {
  1217. if (!index.HasValue)
  1218. {
  1219. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1220. }
  1221. var hasScreenshots = (IHasScreenshots)this;
  1222. var file = hasScreenshots.ScreenshotImagePaths[index.Value];
  1223. hasScreenshots.ScreenshotImagePaths.Remove(file);
  1224. // Delete the source file
  1225. DeleteImagePath(file);
  1226. }
  1227. else
  1228. {
  1229. // Delete the source file
  1230. DeleteImagePath(GetImage(type));
  1231. // Remove it from the item
  1232. SetImage(type, null);
  1233. }
  1234. // Refresh metadata
  1235. // Need to disable slow providers or the image might get re-downloaded
  1236. return RefreshMetadata(CancellationToken.None, forceSave: true, allowSlowProviders: false);
  1237. }
  1238. /// <summary>
  1239. /// Deletes the image path.
  1240. /// </summary>
  1241. /// <param name="path">The path.</param>
  1242. private void DeleteImagePath(string path)
  1243. {
  1244. var currentFile = new FileInfo(path);
  1245. // This will fail if the file is hidden
  1246. if (currentFile.Exists)
  1247. {
  1248. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1249. {
  1250. currentFile.Attributes &= ~FileAttributes.Hidden;
  1251. }
  1252. currentFile.Delete();
  1253. }
  1254. }
  1255. /// <summary>
  1256. /// Validates that images within the item are still on the file system
  1257. /// </summary>
  1258. public void ValidateImages()
  1259. {
  1260. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1261. var deletedKeys = Images
  1262. .Where(image => !File.Exists(image.Value))
  1263. .Select(i => i.Key)
  1264. .ToList();
  1265. // Now remove them from the dictionary
  1266. foreach (var key in deletedKeys)
  1267. {
  1268. Images.Remove(key);
  1269. }
  1270. }
  1271. /// <summary>
  1272. /// Validates that backdrops within the item are still on the file system
  1273. /// </summary>
  1274. public void ValidateBackdrops()
  1275. {
  1276. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1277. var deletedImages = BackdropImagePaths
  1278. .Where(path => !File.Exists(path))
  1279. .ToList();
  1280. // Now remove them from the dictionary
  1281. foreach (var path in deletedImages)
  1282. {
  1283. BackdropImagePaths.Remove(path);
  1284. RemoveImageSourceForPath(path);
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// Adds the image source.
  1289. /// </summary>
  1290. /// <param name="path">The path.</param>
  1291. /// <param name="url">The URL.</param>
  1292. public void AddImageSource(string path, string url)
  1293. {
  1294. RemoveImageSourceForPath(path);
  1295. var pathMd5 = path.ToLower().GetMD5();
  1296. ImageSources.Add(new ImageSourceInfo
  1297. {
  1298. ImagePathMD5 = pathMd5,
  1299. ImageUrlMD5 = url.ToLower().GetMD5()
  1300. });
  1301. }
  1302. /// <summary>
  1303. /// Gets the image source info.
  1304. /// </summary>
  1305. /// <param name="path">The path.</param>
  1306. /// <returns>ImageSourceInfo.</returns>
  1307. public ImageSourceInfo GetImageSourceInfo(string path)
  1308. {
  1309. if (ImageSources.Count == 0)
  1310. {
  1311. return null;
  1312. }
  1313. var pathMd5 = path.ToLower().GetMD5();
  1314. return ImageSources.FirstOrDefault(i => i.ImagePathMD5 == pathMd5);
  1315. }
  1316. /// <summary>
  1317. /// Removes the image source for path.
  1318. /// </summary>
  1319. /// <param name="path">The path.</param>
  1320. public void RemoveImageSourceForPath(string path)
  1321. {
  1322. if (ImageSources.Count == 0)
  1323. {
  1324. return;
  1325. }
  1326. var pathMd5 = path.ToLower().GetMD5();
  1327. // Remove existing
  1328. foreach (var entry in ImageSources
  1329. .Where(i => i.ImagePathMD5 == pathMd5)
  1330. .ToList())
  1331. {
  1332. ImageSources.Remove(entry);
  1333. }
  1334. }
  1335. /// <summary>
  1336. /// Determines whether [contains image with source URL] [the specified URL].
  1337. /// </summary>
  1338. /// <param name="url">The URL.</param>
  1339. /// <returns><c>true</c> if [contains image with source URL] [the specified URL]; otherwise, <c>false</c>.</returns>
  1340. public bool ContainsImageWithSourceUrl(string url)
  1341. {
  1342. if (ImageSources.Count == 0)
  1343. {
  1344. return false;
  1345. }
  1346. var md5 = url.ToLower().GetMD5();
  1347. return ImageSources.Any(i => i.ImageUrlMD5 == md5);
  1348. }
  1349. /// <summary>
  1350. /// Validates the screenshots.
  1351. /// </summary>
  1352. public void ValidateScreenshots()
  1353. {
  1354. var hasScreenshots = (IHasScreenshots)this;
  1355. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1356. var deletedImages = hasScreenshots.ScreenshotImagePaths
  1357. .Where(path => !File.Exists(path))
  1358. .ToList();
  1359. // Now remove them from the dictionary
  1360. foreach (var path in deletedImages)
  1361. {
  1362. hasScreenshots.ScreenshotImagePaths.Remove(path);
  1363. }
  1364. }
  1365. /// <summary>
  1366. /// Gets the image path.
  1367. /// </summary>
  1368. /// <param name="imageType">Type of the image.</param>
  1369. /// <param name="imageIndex">Index of the image.</param>
  1370. /// <returns>System.String.</returns>
  1371. /// <exception cref="System.InvalidOperationException">
  1372. /// </exception>
  1373. /// <exception cref="System.ArgumentNullException">item</exception>
  1374. public string GetImagePath(ImageType imageType, int imageIndex)
  1375. {
  1376. if (imageType == ImageType.Backdrop)
  1377. {
  1378. return BackdropImagePaths[imageIndex];
  1379. }
  1380. if (imageType == ImageType.Screenshot)
  1381. {
  1382. var hasScreenshots = (IHasScreenshots)this;
  1383. return hasScreenshots.ScreenshotImagePaths[imageIndex];
  1384. }
  1385. if (imageType == ImageType.Chapter)
  1386. {
  1387. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1388. }
  1389. return GetImage(imageType);
  1390. }
  1391. /// <summary>
  1392. /// Gets the image date modified.
  1393. /// </summary>
  1394. /// <param name="imagePath">The image path.</param>
  1395. /// <returns>DateTime.</returns>
  1396. /// <exception cref="System.ArgumentNullException">item</exception>
  1397. public DateTime GetImageDateModified(string imagePath)
  1398. {
  1399. if (string.IsNullOrEmpty(imagePath))
  1400. {
  1401. throw new ArgumentNullException("imagePath");
  1402. }
  1403. var locationType = LocationType;
  1404. if (locationType == LocationType.Remote ||
  1405. locationType == LocationType.Virtual)
  1406. {
  1407. return FileSystem.GetLastWriteTimeUtc(imagePath);
  1408. }
  1409. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1410. // If we didn't the metafile entry, check the Season
  1411. if (metaFileEntry == null)
  1412. {
  1413. if (Parent != null)
  1414. {
  1415. metaFileEntry = Parent.ResolveArgs.GetMetaFileByPath(imagePath);
  1416. }
  1417. }
  1418. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1419. return metaFileEntry == null ? FileSystem.GetLastWriteTimeUtc(imagePath) : FileSystem.GetLastWriteTimeUtc(metaFileEntry);
  1420. }
  1421. /// <summary>
  1422. /// Gets the file system path to delete when the item is to be deleted
  1423. /// </summary>
  1424. /// <returns></returns>
  1425. public virtual IEnumerable<string> GetDeletePaths()
  1426. {
  1427. return new[] { Path };
  1428. }
  1429. }
  1430. }