BaseItem.cs 51 KB

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