BaseItem.cs 58 KB

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