BaseItem.cs 58 KB

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