BaseItem.cs 51 KB

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