BaseItem.cs 57 KB

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