BaseItem.cs 57 KB

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