BaseItem.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  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. 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. public Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool resetResolveArgs = true)
  656. {
  657. return RefreshMetadata(new MetadataRefreshOptions { ResetResolveArgs = resetResolveArgs }, cancellationToken);
  658. }
  659. /// <summary>
  660. /// Overrides the base implementation to refresh metadata for local trailers
  661. /// </summary>
  662. /// <param name="options">The options.</param>
  663. /// <param name="cancellationToken">The cancellation token.</param>
  664. /// <returns>true if a provider reports we changed</returns>
  665. public async Task<bool> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  666. {
  667. if (options.ResetResolveArgs)
  668. {
  669. // Reload this
  670. ResetResolveArgs();
  671. }
  672. await ProviderManager.RefreshMetadata(this, options, cancellationToken).ConfigureAwait(false);
  673. return false;
  674. }
  675. [Obsolete]
  676. public virtual async Task<bool> RefreshMetadataDirect(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  677. {
  678. // Refresh for the item
  679. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh);
  680. cancellationToken.ThrowIfCancellationRequested();
  681. var themeSongsChanged = false;
  682. var themeVideosChanged = false;
  683. var localTrailersChanged = false;
  684. if (LocationType == LocationType.FileSystem && Parent != null)
  685. {
  686. var hasThemeMedia = this as IHasThemeMedia;
  687. if (hasThemeMedia != null)
  688. {
  689. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, cancellationToken, forceSave, forceRefresh).ConfigureAwait(false);
  690. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, cancellationToken, forceSave, forceRefresh).ConfigureAwait(false);
  691. }
  692. var hasTrailers = this as IHasTrailers;
  693. if (hasTrailers != null)
  694. {
  695. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, cancellationToken, forceSave, forceRefresh).ConfigureAwait(false);
  696. }
  697. }
  698. cancellationToken.ThrowIfCancellationRequested();
  699. // Get the result from the item task
  700. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  701. var changed = updateReason.HasValue;
  702. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  703. {
  704. cancellationToken.ThrowIfCancellationRequested();
  705. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  706. }
  707. return changed;
  708. }
  709. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  710. {
  711. var newItems = LoadLocalTrailers().ToList();
  712. var newItemIds = newItems.Select(i => i.Id).ToList();
  713. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  714. var tasks = newItems.Select(i => i.RefreshMetadata(new MetadataRefreshOptions
  715. {
  716. ForceSave = forceSave,
  717. ReplaceAllMetadata = forceRefresh,
  718. ResetResolveArgs = false
  719. }, cancellationToken));
  720. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  721. item.LocalTrailerIds = newItemIds;
  722. return itemsChanged || results.Contains(true);
  723. }
  724. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  725. {
  726. var newThemeVideos = LoadThemeVideos().ToList();
  727. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  728. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  729. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(new MetadataRefreshOptions
  730. {
  731. ForceSave = forceSave,
  732. ReplaceAllMetadata = forceRefresh,
  733. ResetResolveArgs = false
  734. }, cancellationToken));
  735. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  736. item.ThemeVideoIds = newThemeVideoIds;
  737. return themeVideosChanged || results.Contains(true);
  738. }
  739. /// <summary>
  740. /// Refreshes the theme songs.
  741. /// </summary>
  742. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false)
  743. {
  744. var newThemeSongs = LoadThemeSongs().ToList();
  745. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  746. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  747. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(new MetadataRefreshOptions
  748. {
  749. ForceSave = forceSave,
  750. ReplaceAllMetadata = forceRefresh,
  751. ResetResolveArgs = false
  752. }, cancellationToken));
  753. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  754. item.ThemeSongIds = newThemeSongIds;
  755. return themeSongsChanged || results.Contains(true);
  756. }
  757. /// <summary>
  758. /// Gets or sets the provider ids.
  759. /// </summary>
  760. /// <value>The provider ids.</value>
  761. public Dictionary<string, string> ProviderIds { get; set; }
  762. /// <summary>
  763. /// Override this to false if class should be ignored for indexing purposes
  764. /// </summary>
  765. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  766. [IgnoreDataMember]
  767. public virtual bool IncludeInIndex
  768. {
  769. get { return true; }
  770. }
  771. /// <summary>
  772. /// Override this to true if class should be grouped under a container in indicies
  773. /// The container class should be defined via IndexContainer
  774. /// </summary>
  775. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  776. [IgnoreDataMember]
  777. public virtual bool GroupInIndex
  778. {
  779. get { return false; }
  780. }
  781. /// <summary>
  782. /// Override this to return the folder that should be used to construct a container
  783. /// for this item in an index. GroupInIndex should be true as well.
  784. /// </summary>
  785. /// <value>The index container.</value>
  786. [IgnoreDataMember]
  787. public virtual Folder IndexContainer
  788. {
  789. get { return null; }
  790. }
  791. /// <summary>
  792. /// Gets the user data key.
  793. /// </summary>
  794. /// <returns>System.String.</returns>
  795. public virtual string GetUserDataKey()
  796. {
  797. return Id.ToString();
  798. }
  799. /// <summary>
  800. /// Gets the preferred metadata language.
  801. /// </summary>
  802. /// <returns>System.String.</returns>
  803. public string GetPreferredMetadataLanguage()
  804. {
  805. string lang = null;
  806. var hasLang = this as IHasPreferredMetadataLanguage;
  807. if (hasLang != null)
  808. {
  809. lang = hasLang.PreferredMetadataLanguage;
  810. }
  811. if (string.IsNullOrEmpty(lang))
  812. {
  813. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  814. .Select(i => i.PreferredMetadataLanguage)
  815. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  816. }
  817. if (string.IsNullOrEmpty(lang))
  818. {
  819. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  820. }
  821. return lang;
  822. }
  823. /// <summary>
  824. /// Gets the preferred metadata language.
  825. /// </summary>
  826. /// <returns>System.String.</returns>
  827. public string GetPreferredMetadataCountryCode()
  828. {
  829. string lang = null;
  830. var hasLang = this as IHasPreferredMetadataLanguage;
  831. if (hasLang != null)
  832. {
  833. lang = hasLang.PreferredMetadataCountryCode;
  834. }
  835. if (string.IsNullOrEmpty(lang))
  836. {
  837. lang = Parents.OfType<IHasPreferredMetadataLanguage>()
  838. .Select(i => i.PreferredMetadataCountryCode)
  839. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  840. }
  841. if (string.IsNullOrEmpty(lang))
  842. {
  843. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  844. }
  845. return lang;
  846. }
  847. public virtual bool IsSaveLocalMetadataEnabled()
  848. {
  849. return ConfigurationManager.Configuration.SaveLocalMeta;
  850. }
  851. /// <summary>
  852. /// Determines if a given user has access to this item
  853. /// </summary>
  854. /// <param name="user">The user.</param>
  855. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  856. /// <exception cref="System.ArgumentNullException">user</exception>
  857. public bool IsParentalAllowed(User user)
  858. {
  859. if (user == null)
  860. {
  861. throw new ArgumentNullException("user");
  862. }
  863. var maxAllowedRating = user.Configuration.MaxParentalRating;
  864. if (maxAllowedRating == null)
  865. {
  866. return true;
  867. }
  868. var rating = CustomRatingForComparison;
  869. if (string.IsNullOrEmpty(rating))
  870. {
  871. rating = OfficialRatingForComparison;
  872. }
  873. if (string.IsNullOrEmpty(rating))
  874. {
  875. return !GetBlockUnratedValue(user.Configuration);
  876. }
  877. var value = LocalizationManager.GetRatingLevel(rating);
  878. // Could not determine the integer value
  879. if (!value.HasValue)
  880. {
  881. return true;
  882. }
  883. return value.Value <= maxAllowedRating.Value;
  884. }
  885. /// <summary>
  886. /// Gets the block unrated value.
  887. /// </summary>
  888. /// <param name="config">The configuration.</param>
  889. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  890. protected virtual bool GetBlockUnratedValue(UserConfiguration config)
  891. {
  892. return config.BlockNotRated;
  893. }
  894. /// <summary>
  895. /// Determines if this folder should be visible to a given user.
  896. /// Default is just parental allowed. Can be overridden for more functionality.
  897. /// </summary>
  898. /// <param name="user">The user.</param>
  899. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  900. /// <exception cref="System.ArgumentNullException">user</exception>
  901. public virtual bool IsVisible(User user)
  902. {
  903. if (user == null)
  904. {
  905. throw new ArgumentNullException("user");
  906. }
  907. return IsParentalAllowed(user);
  908. }
  909. /// <summary>
  910. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  911. /// </summary>
  912. /// <param name="id">The id.</param>
  913. /// <returns>BaseItem.</returns>
  914. /// <exception cref="System.ArgumentException"></exception>
  915. protected BaseItem FindParentItem(Guid id)
  916. {
  917. if (id == Guid.Empty)
  918. {
  919. throw new ArgumentException();
  920. }
  921. var parent = Parent;
  922. while (parent != null && !parent.IsRoot)
  923. {
  924. if (parent.Id == id) return parent;
  925. parent = parent.Parent;
  926. }
  927. return null;
  928. }
  929. /// <summary>
  930. /// Gets a value indicating whether this instance is folder.
  931. /// </summary>
  932. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  933. [IgnoreDataMember]
  934. public virtual bool IsFolder
  935. {
  936. get
  937. {
  938. return false;
  939. }
  940. }
  941. /// <summary>
  942. /// Determine if we have changed vs the passed in copy
  943. /// </summary>
  944. /// <param name="copy">The copy.</param>
  945. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  946. /// <exception cref="System.ArgumentNullException"></exception>
  947. public virtual bool HasChanged(BaseItem copy)
  948. {
  949. if (copy == null)
  950. {
  951. throw new ArgumentNullException();
  952. }
  953. if (IsInMixedFolder != copy.IsInMixedFolder)
  954. {
  955. Logger.Debug(Name + " changed due to different value for IsInMixedFolder.");
  956. return true;
  957. }
  958. var changed = copy.DateModified != DateModified;
  959. if (changed)
  960. {
  961. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  962. }
  963. return changed;
  964. }
  965. public virtual string GetClientTypeName()
  966. {
  967. return GetType().Name;
  968. }
  969. /// <summary>
  970. /// Determines if the item is considered new based on user settings
  971. /// </summary>
  972. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  973. /// <exception cref="System.ArgumentNullException"></exception>
  974. public bool IsRecentlyAdded()
  975. {
  976. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  977. }
  978. /// <summary>
  979. /// Adds a person to the item
  980. /// </summary>
  981. /// <param name="person">The person.</param>
  982. /// <exception cref="System.ArgumentNullException"></exception>
  983. public void AddPerson(PersonInfo person)
  984. {
  985. if (person == null)
  986. {
  987. throw new ArgumentNullException("person");
  988. }
  989. if (string.IsNullOrWhiteSpace(person.Name))
  990. {
  991. throw new ArgumentNullException();
  992. }
  993. // Normalize
  994. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  995. {
  996. person.Type = PersonType.GuestStar;
  997. }
  998. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  999. {
  1000. person.Type = PersonType.Director;
  1001. }
  1002. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1003. {
  1004. person.Type = PersonType.Producer;
  1005. }
  1006. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1007. {
  1008. person.Type = PersonType.Writer;
  1009. }
  1010. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1011. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1012. {
  1013. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1014. if (existing != null)
  1015. {
  1016. existing.Type = PersonType.GuestStar;
  1017. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1018. return;
  1019. }
  1020. }
  1021. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1022. {
  1023. // If the actor already exists without a role and we have one, fill it in
  1024. 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)));
  1025. if (existing == null)
  1026. {
  1027. // Wasn't there - add it
  1028. People.Add(person);
  1029. }
  1030. else
  1031. {
  1032. // Was there, if no role and we have one - fill it in
  1033. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role))
  1034. {
  1035. existing.Role = person.Role;
  1036. }
  1037. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1038. }
  1039. }
  1040. else
  1041. {
  1042. var existing = People.FirstOrDefault(p =>
  1043. string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) &&
  1044. string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase));
  1045. // Check for dupes based on the combination of Name and Type
  1046. if (existing == null)
  1047. {
  1048. People.Add(person);
  1049. }
  1050. else
  1051. {
  1052. existing.SortOrder = person.SortOrder ?? existing.SortOrder;
  1053. }
  1054. }
  1055. }
  1056. /// <summary>
  1057. /// Adds a studio to the item
  1058. /// </summary>
  1059. /// <param name="name">The name.</param>
  1060. /// <exception cref="System.ArgumentNullException"></exception>
  1061. public void AddStudio(string name)
  1062. {
  1063. if (string.IsNullOrWhiteSpace(name))
  1064. {
  1065. throw new ArgumentNullException("name");
  1066. }
  1067. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1068. {
  1069. Studios.Add(name);
  1070. }
  1071. }
  1072. /// <summary>
  1073. /// Adds a genre to the item
  1074. /// </summary>
  1075. /// <param name="name">The name.</param>
  1076. /// <exception cref="System.ArgumentNullException"></exception>
  1077. public void AddGenre(string name)
  1078. {
  1079. if (string.IsNullOrWhiteSpace(name))
  1080. {
  1081. throw new ArgumentNullException("name");
  1082. }
  1083. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1084. {
  1085. Genres.Add(name);
  1086. }
  1087. }
  1088. /// <summary>
  1089. /// Marks the played.
  1090. /// </summary>
  1091. /// <param name="user">The user.</param>
  1092. /// <param name="datePlayed">The date played.</param>
  1093. /// <param name="userManager">The user manager.</param>
  1094. /// <returns>Task.</returns>
  1095. /// <exception cref="System.ArgumentNullException"></exception>
  1096. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1097. {
  1098. if (user == null)
  1099. {
  1100. throw new ArgumentNullException();
  1101. }
  1102. var key = GetUserDataKey();
  1103. var data = userManager.GetUserData(user.Id, key);
  1104. if (datePlayed.HasValue)
  1105. {
  1106. // Incremenet
  1107. data.PlayCount++;
  1108. }
  1109. // Ensure it's at least one
  1110. data.PlayCount = Math.Max(data.PlayCount, 1);
  1111. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1112. data.Played = true;
  1113. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1114. }
  1115. /// <summary>
  1116. /// Marks the unplayed.
  1117. /// </summary>
  1118. /// <param name="user">The user.</param>
  1119. /// <param name="userManager">The user manager.</param>
  1120. /// <returns>Task.</returns>
  1121. /// <exception cref="System.ArgumentNullException"></exception>
  1122. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  1123. {
  1124. if (user == null)
  1125. {
  1126. throw new ArgumentNullException();
  1127. }
  1128. var key = GetUserDataKey();
  1129. var data = userManager.GetUserData(user.Id, key);
  1130. //I think it is okay to do this here.
  1131. // if this is only called when a user is manually forcing something to un-played
  1132. // then it probably is what we want to do...
  1133. data.PlayCount = 0;
  1134. data.PlaybackPositionTicks = 0;
  1135. data.LastPlayedDate = null;
  1136. data.Played = false;
  1137. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1138. }
  1139. /// <summary>
  1140. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1141. /// </summary>
  1142. /// <returns>Task.</returns>
  1143. public virtual Task ChangedExternally()
  1144. {
  1145. return RefreshMetadata(CancellationToken.None);
  1146. }
  1147. /// <summary>
  1148. /// Finds a parent of a given type
  1149. /// </summary>
  1150. /// <typeparam name="T"></typeparam>
  1151. /// <returns>``0.</returns>
  1152. public T FindParent<T>()
  1153. where T : Folder
  1154. {
  1155. var parent = Parent;
  1156. while (parent != null)
  1157. {
  1158. var result = parent as T;
  1159. if (result != null)
  1160. {
  1161. return result;
  1162. }
  1163. parent = parent.Parent;
  1164. }
  1165. return null;
  1166. }
  1167. /// <summary>
  1168. /// Gets an image
  1169. /// </summary>
  1170. /// <param name="type">The type.</param>
  1171. /// <param name="imageIndex">Index of the image.</param>
  1172. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1173. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1174. public bool HasImage(ImageType type, int imageIndex)
  1175. {
  1176. if (type == ImageType.Backdrop)
  1177. {
  1178. return BackdropImagePaths.Count > imageIndex;
  1179. }
  1180. if (type == ImageType.Screenshot)
  1181. {
  1182. var hasScreenshots = this as IHasScreenshots;
  1183. return hasScreenshots != null && hasScreenshots.ScreenshotImagePaths.Count > imageIndex;
  1184. }
  1185. return !string.IsNullOrEmpty(this.GetImagePath(type));
  1186. }
  1187. public void SetImagePath(ImageType type, int index, string path)
  1188. {
  1189. if (type == ImageType.Backdrop)
  1190. {
  1191. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1192. }
  1193. if (type == ImageType.Screenshot)
  1194. {
  1195. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1196. }
  1197. var typeKey = type;
  1198. // If it's null remove the key from the dictionary
  1199. if (string.IsNullOrEmpty(path))
  1200. {
  1201. if (Images.ContainsKey(typeKey))
  1202. {
  1203. Images.Remove(typeKey);
  1204. }
  1205. }
  1206. else
  1207. {
  1208. Images[typeKey] = path;
  1209. }
  1210. }
  1211. /// <summary>
  1212. /// Deletes the image.
  1213. /// </summary>
  1214. /// <param name="type">The type.</param>
  1215. /// <param name="index">The index.</param>
  1216. /// <returns>Task.</returns>
  1217. public Task DeleteImage(ImageType type, int? index)
  1218. {
  1219. if (type == ImageType.Backdrop)
  1220. {
  1221. if (!index.HasValue)
  1222. {
  1223. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1224. }
  1225. var file = BackdropImagePaths[index.Value];
  1226. BackdropImagePaths.Remove(file);
  1227. RemoveImageSourceForPath(file);
  1228. // Delete the source file
  1229. DeleteImagePath(file);
  1230. }
  1231. else if (type == ImageType.Screenshot)
  1232. {
  1233. if (!index.HasValue)
  1234. {
  1235. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1236. }
  1237. var hasScreenshots = (IHasScreenshots)this;
  1238. var file = hasScreenshots.ScreenshotImagePaths[index.Value];
  1239. hasScreenshots.ScreenshotImagePaths.Remove(file);
  1240. // Delete the source file
  1241. DeleteImagePath(file);
  1242. }
  1243. else
  1244. {
  1245. // Delete the source file
  1246. DeleteImagePath(this.GetImagePath(type));
  1247. // Remove it from the item
  1248. this.SetImagePath(type, null);
  1249. }
  1250. // Refresh metadata
  1251. // Need to disable slow providers or the image might get re-downloaded
  1252. return RefreshMetadata(new MetadataRefreshOptions
  1253. {
  1254. ForceSave = true,
  1255. ImageRefreshMode = MetadataRefreshMode.None,
  1256. MetadataRefreshMode = MetadataRefreshMode.None
  1257. }, CancellationToken.None);
  1258. }
  1259. /// <summary>
  1260. /// Deletes the image path.
  1261. /// </summary>
  1262. /// <param name="path">The path.</param>
  1263. private void DeleteImagePath(string path)
  1264. {
  1265. var currentFile = new FileInfo(path);
  1266. // This will fail if the file is hidden
  1267. if (currentFile.Exists)
  1268. {
  1269. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1270. {
  1271. currentFile.Attributes &= ~FileAttributes.Hidden;
  1272. }
  1273. currentFile.Delete();
  1274. }
  1275. }
  1276. /// <summary>
  1277. /// Validates that images within the item are still on the file system
  1278. /// </summary>
  1279. public bool ValidateImages()
  1280. {
  1281. var changed = false;
  1282. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1283. var deletedKeys = Images
  1284. .Where(image => !File.Exists(image.Value))
  1285. .Select(i => i.Key)
  1286. .ToList();
  1287. // Now remove them from the dictionary
  1288. foreach (var key in deletedKeys)
  1289. {
  1290. Images.Remove(key);
  1291. changed = true;
  1292. }
  1293. if (ValidateBackdrops())
  1294. {
  1295. changed = true;
  1296. }
  1297. if (ValidateScreenshots())
  1298. {
  1299. changed = true;
  1300. }
  1301. return changed;
  1302. }
  1303. /// <summary>
  1304. /// Validates that backdrops within the item are still on the file system
  1305. /// </summary>
  1306. private bool ValidateBackdrops()
  1307. {
  1308. var changed = false;
  1309. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1310. var deletedImages = BackdropImagePaths
  1311. .Where(path => !File.Exists(path))
  1312. .ToList();
  1313. // Now remove them from the dictionary
  1314. foreach (var path in deletedImages)
  1315. {
  1316. BackdropImagePaths.Remove(path);
  1317. RemoveImageSourceForPath(path);
  1318. changed = true;
  1319. }
  1320. return changed;
  1321. }
  1322. /// <summary>
  1323. /// Adds the image source.
  1324. /// </summary>
  1325. /// <param name="path">The path.</param>
  1326. /// <param name="url">The URL.</param>
  1327. public void AddImageSource(string path, string url)
  1328. {
  1329. RemoveImageSourceForPath(path);
  1330. var pathMd5 = path.ToLower().GetMD5();
  1331. ImageSources.Add(new ImageSourceInfo
  1332. {
  1333. ImagePathMD5 = pathMd5,
  1334. ImageUrlMD5 = url.ToLower().GetMD5()
  1335. });
  1336. }
  1337. /// <summary>
  1338. /// Gets the image source info.
  1339. /// </summary>
  1340. /// <param name="path">The path.</param>
  1341. /// <returns>ImageSourceInfo.</returns>
  1342. public ImageSourceInfo GetImageSourceInfo(string path)
  1343. {
  1344. if (ImageSources.Count == 0)
  1345. {
  1346. return null;
  1347. }
  1348. var pathMd5 = path.ToLower().GetMD5();
  1349. return ImageSources.FirstOrDefault(i => i.ImagePathMD5 == pathMd5);
  1350. }
  1351. /// <summary>
  1352. /// Removes the image source for path.
  1353. /// </summary>
  1354. /// <param name="path">The path.</param>
  1355. public void RemoveImageSourceForPath(string path)
  1356. {
  1357. if (ImageSources.Count == 0)
  1358. {
  1359. return;
  1360. }
  1361. var pathMd5 = path.ToLower().GetMD5();
  1362. // Remove existing
  1363. foreach (var entry in ImageSources
  1364. .Where(i => i.ImagePathMD5 == pathMd5)
  1365. .ToList())
  1366. {
  1367. ImageSources.Remove(entry);
  1368. }
  1369. }
  1370. /// <summary>
  1371. /// Determines whether [contains image with source URL] [the specified URL].
  1372. /// </summary>
  1373. /// <param name="url">The URL.</param>
  1374. /// <returns><c>true</c> if [contains image with source URL] [the specified URL]; otherwise, <c>false</c>.</returns>
  1375. public bool ContainsImageWithSourceUrl(string url)
  1376. {
  1377. if (ImageSources.Count == 0)
  1378. {
  1379. return false;
  1380. }
  1381. var md5 = url.ToLower().GetMD5();
  1382. return ImageSources.Any(i => i.ImageUrlMD5 == md5);
  1383. }
  1384. /// <summary>
  1385. /// Validates the screenshots.
  1386. /// </summary>
  1387. private bool ValidateScreenshots()
  1388. {
  1389. var changed = false;
  1390. var hasScreenshots = this as IHasScreenshots;
  1391. if (hasScreenshots == null)
  1392. {
  1393. return changed;
  1394. }
  1395. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1396. var deletedImages = hasScreenshots.ScreenshotImagePaths
  1397. .Where(path => !File.Exists(path))
  1398. .ToList();
  1399. // Now remove them from the dictionary
  1400. foreach (var path in deletedImages)
  1401. {
  1402. hasScreenshots.ScreenshotImagePaths.Remove(path);
  1403. changed = true;
  1404. }
  1405. return changed;
  1406. }
  1407. /// <summary>
  1408. /// Gets the image path.
  1409. /// </summary>
  1410. /// <param name="imageType">Type of the image.</param>
  1411. /// <param name="imageIndex">Index of the image.</param>
  1412. /// <returns>System.String.</returns>
  1413. /// <exception cref="System.InvalidOperationException">
  1414. /// </exception>
  1415. /// <exception cref="System.ArgumentNullException">item</exception>
  1416. public string GetImagePath(ImageType imageType, int imageIndex)
  1417. {
  1418. if (imageType == ImageType.Backdrop)
  1419. {
  1420. return BackdropImagePaths.Count > imageIndex ? BackdropImagePaths[imageIndex] : null;
  1421. }
  1422. if (imageType == ImageType.Screenshot)
  1423. {
  1424. var hasScreenshots = (IHasScreenshots)this;
  1425. return hasScreenshots.ScreenshotImagePaths.Count > imageIndex ? hasScreenshots.ScreenshotImagePaths[imageIndex] : null;
  1426. }
  1427. if (imageType == ImageType.Chapter)
  1428. {
  1429. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1430. }
  1431. string val;
  1432. Images.TryGetValue(imageType, out val);
  1433. return val;
  1434. }
  1435. /// <summary>
  1436. /// Gets the image date modified.
  1437. /// </summary>
  1438. /// <param name="imagePath">The image path.</param>
  1439. /// <returns>DateTime.</returns>
  1440. /// <exception cref="System.ArgumentNullException">item</exception>
  1441. public DateTime GetImageDateModified(string imagePath)
  1442. {
  1443. if (string.IsNullOrEmpty(imagePath))
  1444. {
  1445. throw new ArgumentNullException("imagePath");
  1446. }
  1447. var locationType = LocationType;
  1448. if (locationType == LocationType.Remote ||
  1449. locationType == LocationType.Virtual)
  1450. {
  1451. return FileSystem.GetLastWriteTimeUtc(imagePath);
  1452. }
  1453. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1454. // If we didn't the metafile entry, check the Season
  1455. if (metaFileEntry == null)
  1456. {
  1457. if (Parent != null)
  1458. {
  1459. metaFileEntry = Parent.ResolveArgs.GetMetaFileByPath(imagePath);
  1460. }
  1461. }
  1462. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1463. return metaFileEntry == null ? FileSystem.GetLastWriteTimeUtc(imagePath) : FileSystem.GetLastWriteTimeUtc(metaFileEntry);
  1464. }
  1465. /// <summary>
  1466. /// Gets the file system path to delete when the item is to be deleted
  1467. /// </summary>
  1468. /// <returns></returns>
  1469. public virtual IEnumerable<string> GetDeletePaths()
  1470. {
  1471. return new[] { Path };
  1472. }
  1473. public Task SwapImages(ImageType type, int index1, int index2)
  1474. {
  1475. if (type != ImageType.Screenshot && type != ImageType.Backdrop)
  1476. {
  1477. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1478. }
  1479. var file1 = GetImagePath(type, index1);
  1480. var file2 = GetImagePath(type, index2);
  1481. FileSystem.SwapFiles(file1, file2);
  1482. // Directory watchers should repeat this, but do a quick refresh first
  1483. return RefreshMetadata(new MetadataRefreshOptions
  1484. {
  1485. ForceSave = true,
  1486. MetadataRefreshMode = MetadataRefreshMode.None
  1487. }, CancellationToken.None);
  1488. }
  1489. public virtual bool IsPlayed(User user)
  1490. {
  1491. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1492. return userdata != null && userdata.Played;
  1493. }
  1494. public virtual bool IsUnplayed(User user)
  1495. {
  1496. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1497. return userdata == null || !userdata.Played;
  1498. }
  1499. }
  1500. }