BaseItem.cs 56 KB

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