BaseItem.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  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. if (LocationType != LocationType.FileSystem)
  600. {
  601. return new List<Trailer>();
  602. }
  603. ItemResolveArgs resolveArgs;
  604. try
  605. {
  606. resolveArgs = ResolveArgs;
  607. }
  608. catch (IOException ex)
  609. {
  610. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  611. return new List<Trailer>();
  612. }
  613. if (!resolveArgs.IsDirectory)
  614. {
  615. return new List<Trailer>();
  616. }
  617. var files = new List<FileSystemInfo>();
  618. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  619. // Path doesn't exist. No biggie
  620. if (folder != null)
  621. {
  622. try
  623. {
  624. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  625. }
  626. catch (IOException ex)
  627. {
  628. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  629. }
  630. }
  631. // Support xbmc trailers (-trailer suffix on video file names)
  632. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  633. {
  634. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  635. {
  636. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  637. {
  638. return true;
  639. }
  640. }
  641. return false;
  642. }));
  643. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  644. {
  645. // Try to retrieve it from the db. If we don't find it, use the resolved version
  646. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  647. if (dbItem != null)
  648. {
  649. dbItem.ResolveArgs = video.ResolveArgs;
  650. video = dbItem;
  651. }
  652. return video;
  653. }).ToList();
  654. }
  655. /// <summary>
  656. /// Loads the theme songs.
  657. /// </summary>
  658. /// <returns>List{Audio.Audio}.</returns>
  659. private IEnumerable<Audio.Audio> LoadThemeSongs()
  660. {
  661. if (LocationType != LocationType.FileSystem)
  662. {
  663. return new List<Audio.Audio>();
  664. }
  665. ItemResolveArgs resolveArgs;
  666. try
  667. {
  668. resolveArgs = ResolveArgs;
  669. }
  670. catch (IOException ex)
  671. {
  672. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  673. return new List<Audio.Audio>();
  674. }
  675. if (!resolveArgs.IsDirectory)
  676. {
  677. return new List<Audio.Audio>();
  678. }
  679. var files = new List<FileSystemInfo>();
  680. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  681. // Path doesn't exist. No biggie
  682. if (folder != null)
  683. {
  684. try
  685. {
  686. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  687. }
  688. catch (IOException ex)
  689. {
  690. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  691. }
  692. }
  693. // Support plex/xbmc convention
  694. files.AddRange(resolveArgs.FileSystemChildren
  695. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.FullName), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.FullName))
  696. );
  697. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  698. {
  699. // Try to retrieve it from the db. If we don't find it, use the resolved version
  700. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  701. if (dbItem != null)
  702. {
  703. dbItem.ResolveArgs = audio.ResolveArgs;
  704. audio = dbItem;
  705. }
  706. return audio;
  707. }).ToList();
  708. }
  709. /// <summary>
  710. /// Loads the video backdrops.
  711. /// </summary>
  712. /// <returns>List{Video}.</returns>
  713. private IEnumerable<Video> LoadThemeVideos()
  714. {
  715. if (LocationType != LocationType.FileSystem)
  716. {
  717. return new List<Video>();
  718. }
  719. ItemResolveArgs resolveArgs;
  720. try
  721. {
  722. resolveArgs = ResolveArgs;
  723. }
  724. catch (IOException ex)
  725. {
  726. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  727. return new List<Video>();
  728. }
  729. if (!resolveArgs.IsDirectory)
  730. {
  731. return new List<Video>();
  732. }
  733. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  734. // Path doesn't exist. No biggie
  735. if (folder == null)
  736. {
  737. return new List<Video>();
  738. }
  739. IEnumerable<FileSystemInfo> files;
  740. try
  741. {
  742. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  743. }
  744. catch (IOException ex)
  745. {
  746. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  747. return new List<Video>();
  748. }
  749. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  750. {
  751. // Try to retrieve it from the db. If we don't find it, use the resolved version
  752. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  753. if (dbItem != null)
  754. {
  755. dbItem.ResolveArgs = item.ResolveArgs;
  756. item = dbItem;
  757. }
  758. return item;
  759. }).ToList();
  760. }
  761. /// <summary>
  762. /// Overrides the base implementation to refresh metadata for local trailers
  763. /// </summary>
  764. /// <param name="cancellationToken">The cancellation token.</param>
  765. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  766. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  767. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  768. /// <returns>true if a provider reports we changed</returns>
  769. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  770. {
  771. // Reload this
  772. ResolveArgs = null;
  773. // Refresh for the item
  774. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  775. cancellationToken.ThrowIfCancellationRequested();
  776. var themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  777. var themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  778. var localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  779. cancellationToken.ThrowIfCancellationRequested();
  780. cancellationToken.ThrowIfCancellationRequested();
  781. // Get the result from the item task
  782. var changed = await itemRefreshTask.ConfigureAwait(false);
  783. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  784. {
  785. cancellationToken.ThrowIfCancellationRequested();
  786. await LibraryManager.UpdateItem(this, cancellationToken).ConfigureAwait(false);
  787. }
  788. return changed;
  789. }
  790. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  791. {
  792. var newItems = LoadLocalTrailers().ToList();
  793. var newItemIds = newItems.Select(i => i.Id).ToList();
  794. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  795. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  796. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  797. LocalTrailerIds = newItemIds;
  798. return itemsChanged || results.Contains(true);
  799. }
  800. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  801. {
  802. var newThemeVideos = LoadThemeVideos().ToList();
  803. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  804. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  805. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  806. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  807. ThemeVideoIds = newThemeVideoIds;
  808. return themeVideosChanged || results.Contains(true);
  809. }
  810. /// <summary>
  811. /// Refreshes the theme songs.
  812. /// </summary>
  813. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  814. {
  815. var newThemeSongs = LoadThemeSongs().ToList();
  816. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  817. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  818. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  819. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  820. ThemeSongIds = newThemeSongIds;
  821. return themeSongsChanged || results.Contains(true);
  822. }
  823. /// <summary>
  824. /// Gets or sets the trailer URL.
  825. /// </summary>
  826. /// <value>The trailer URL.</value>
  827. public List<string> TrailerUrls { get; set; }
  828. /// <summary>
  829. /// Gets or sets the provider ids.
  830. /// </summary>
  831. /// <value>The provider ids.</value>
  832. public Dictionary<string, string> ProviderIds { get; set; }
  833. /// <summary>
  834. /// Override this to false if class should be ignored for indexing purposes
  835. /// </summary>
  836. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  837. [IgnoreDataMember]
  838. public virtual bool IncludeInIndex
  839. {
  840. get { return true; }
  841. }
  842. /// <summary>
  843. /// Override this to true if class should be grouped under a container in indicies
  844. /// The container class should be defined via IndexContainer
  845. /// </summary>
  846. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  847. [IgnoreDataMember]
  848. public virtual bool GroupInIndex
  849. {
  850. get { return false; }
  851. }
  852. /// <summary>
  853. /// Override this to return the folder that should be used to construct a container
  854. /// for this item in an index. GroupInIndex should be true as well.
  855. /// </summary>
  856. /// <value>The index container.</value>
  857. [IgnoreDataMember]
  858. public virtual Folder IndexContainer
  859. {
  860. get { return null; }
  861. }
  862. /// <summary>
  863. /// Gets the user data key.
  864. /// </summary>
  865. /// <returns>System.String.</returns>
  866. public virtual string GetUserDataKey()
  867. {
  868. return Id.ToString();
  869. }
  870. /// <summary>
  871. /// Determines if a given user has access to this item
  872. /// </summary>
  873. /// <param name="user">The user.</param>
  874. /// <param name="localizationManager">The localization manager.</param>
  875. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  876. /// <exception cref="System.ArgumentNullException">user</exception>
  877. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  878. {
  879. if (user == null)
  880. {
  881. throw new ArgumentNullException("user");
  882. }
  883. if (user.Configuration.MaxParentalRating == null)
  884. {
  885. return true;
  886. }
  887. var rating = CustomRating ?? OfficialRating;
  888. if (string.IsNullOrEmpty(rating))
  889. {
  890. return !user.Configuration.BlockNotRated;
  891. }
  892. var value = localizationManager.GetRatingLevel(rating);
  893. // Could not determine the integer value
  894. if (!value.HasValue)
  895. {
  896. return true;
  897. }
  898. return value.Value <= user.Configuration.MaxParentalRating.Value;
  899. }
  900. /// <summary>
  901. /// Determines if this folder should be visible to a given user.
  902. /// Default is just parental allowed. Can be overridden for more functionality.
  903. /// </summary>
  904. /// <param name="user">The user.</param>
  905. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  906. /// <exception cref="System.ArgumentNullException">user</exception>
  907. public virtual bool IsVisible(User user)
  908. {
  909. if (user == null)
  910. {
  911. throw new ArgumentNullException("user");
  912. }
  913. return IsParentalAllowed(user, LocalizationManager);
  914. }
  915. /// <summary>
  916. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  917. /// </summary>
  918. /// <param name="id">The id.</param>
  919. /// <returns>BaseItem.</returns>
  920. /// <exception cref="System.ArgumentException"></exception>
  921. protected BaseItem FindParentItem(Guid id)
  922. {
  923. if (id == Guid.Empty)
  924. {
  925. throw new ArgumentException();
  926. }
  927. var parent = Parent;
  928. while (parent != null && !parent.IsRoot)
  929. {
  930. if (parent.Id == id) return parent;
  931. parent = parent.Parent;
  932. }
  933. //not found - load from repo
  934. return LibraryManager.RetrieveItem(id);
  935. }
  936. /// <summary>
  937. /// Gets a value indicating whether this instance is folder.
  938. /// </summary>
  939. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  940. [IgnoreDataMember]
  941. public virtual bool IsFolder
  942. {
  943. get
  944. {
  945. return false;
  946. }
  947. }
  948. /// <summary>
  949. /// Determine if we have changed vs the passed in copy
  950. /// </summary>
  951. /// <param name="copy">The copy.</param>
  952. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  953. /// <exception cref="System.ArgumentNullException"></exception>
  954. public virtual bool HasChanged(BaseItem copy)
  955. {
  956. if (copy == null)
  957. {
  958. throw new ArgumentNullException();
  959. }
  960. var changed = copy.DateModified != DateModified;
  961. if (changed)
  962. {
  963. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  964. }
  965. return changed;
  966. }
  967. /// <summary>
  968. /// Determines if the item is considered new based on user settings
  969. /// </summary>
  970. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  971. /// <exception cref="System.ArgumentNullException"></exception>
  972. public bool IsRecentlyAdded()
  973. {
  974. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  975. }
  976. /// <summary>
  977. /// Adds a person to the item
  978. /// </summary>
  979. /// <param name="person">The person.</param>
  980. /// <exception cref="System.ArgumentNullException"></exception>
  981. public void AddPerson(PersonInfo person)
  982. {
  983. if (person == null)
  984. {
  985. throw new ArgumentNullException("person");
  986. }
  987. if (string.IsNullOrWhiteSpace(person.Name))
  988. {
  989. throw new ArgumentNullException();
  990. }
  991. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  992. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  993. {
  994. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  995. if (existing != null)
  996. {
  997. existing.Type = PersonType.GuestStar;
  998. return;
  999. }
  1000. }
  1001. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1002. {
  1003. // If the actor already exists without a role and we have one, fill it in
  1004. 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)));
  1005. if (existing == null)
  1006. {
  1007. // Wasn't there - add it
  1008. People.Add(person);
  1009. }
  1010. else
  1011. {
  1012. // Was there, if no role and we have one - fill it in
  1013. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  1014. }
  1015. }
  1016. else
  1017. {
  1018. // Check for dupes based on the combination of Name and Type
  1019. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  1020. {
  1021. People.Add(person);
  1022. }
  1023. }
  1024. }
  1025. /// <summary>
  1026. /// Adds a studio to the item
  1027. /// </summary>
  1028. /// <param name="name">The name.</param>
  1029. /// <exception cref="System.ArgumentNullException"></exception>
  1030. public void AddStudio(string name)
  1031. {
  1032. if (string.IsNullOrWhiteSpace(name))
  1033. {
  1034. throw new ArgumentNullException("name");
  1035. }
  1036. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1037. {
  1038. Studios.Add(name);
  1039. }
  1040. }
  1041. /// <summary>
  1042. /// Adds a tagline to the item
  1043. /// </summary>
  1044. /// <param name="name">The name.</param>
  1045. /// <exception cref="System.ArgumentNullException"></exception>
  1046. public void AddTagline(string name)
  1047. {
  1048. if (string.IsNullOrWhiteSpace(name))
  1049. {
  1050. throw new ArgumentNullException("name");
  1051. }
  1052. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  1053. {
  1054. Taglines.Add(name);
  1055. }
  1056. }
  1057. /// <summary>
  1058. /// Adds a TrailerUrl to the item
  1059. /// </summary>
  1060. /// <param name="url">The URL.</param>
  1061. /// <exception cref="System.ArgumentNullException"></exception>
  1062. public void AddTrailerUrl(string url)
  1063. {
  1064. if (string.IsNullOrWhiteSpace(url))
  1065. {
  1066. throw new ArgumentNullException("url");
  1067. }
  1068. if (TrailerUrls == null)
  1069. {
  1070. TrailerUrls = new List<string>();
  1071. }
  1072. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  1073. {
  1074. TrailerUrls.Add(url);
  1075. }
  1076. }
  1077. /// <summary>
  1078. /// Adds a genre to the item
  1079. /// </summary>
  1080. /// <param name="name">The name.</param>
  1081. /// <exception cref="System.ArgumentNullException"></exception>
  1082. public void AddGenre(string name)
  1083. {
  1084. if (string.IsNullOrWhiteSpace(name))
  1085. {
  1086. throw new ArgumentNullException("name");
  1087. }
  1088. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1089. {
  1090. Genres.Add(name);
  1091. }
  1092. }
  1093. /// <summary>
  1094. /// Adds the production location.
  1095. /// </summary>
  1096. /// <param name="location">The location.</param>
  1097. /// <exception cref="System.ArgumentNullException">location</exception>
  1098. public void AddProductionLocation(string location)
  1099. {
  1100. if (string.IsNullOrWhiteSpace(location))
  1101. {
  1102. throw new ArgumentNullException("location");
  1103. }
  1104. if (ProductionLocations == null)
  1105. {
  1106. ProductionLocations = new List<string>();
  1107. }
  1108. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1109. {
  1110. ProductionLocations.Add(location);
  1111. }
  1112. }
  1113. /// <summary>
  1114. /// Marks the item as either played or unplayed
  1115. /// </summary>
  1116. /// <param name="user">The user.</param>
  1117. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1118. /// <param name="userManager">The user manager.</param>
  1119. /// <returns>Task.</returns>
  1120. /// <exception cref="System.ArgumentNullException"></exception>
  1121. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1122. {
  1123. if (user == null)
  1124. {
  1125. throw new ArgumentNullException();
  1126. }
  1127. var key = GetUserDataKey();
  1128. var data = await userManager.GetUserData(user.Id, key).ConfigureAwait(false);
  1129. if (wasPlayed)
  1130. {
  1131. data.PlayCount = Math.Max(data.PlayCount, 1);
  1132. if (!data.LastPlayedDate.HasValue)
  1133. {
  1134. data.LastPlayedDate = DateTime.UtcNow;
  1135. }
  1136. }
  1137. else
  1138. {
  1139. //I think it is okay to do this here.
  1140. // if this is only called when a user is manually forcing something to un-played
  1141. // then it probably is what we want to do...
  1142. data.PlayCount = 0;
  1143. data.PlaybackPositionTicks = 0;
  1144. data.LastPlayedDate = null;
  1145. }
  1146. data.Played = wasPlayed;
  1147. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1148. }
  1149. /// <summary>
  1150. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1151. /// </summary>
  1152. /// <returns>Task.</returns>
  1153. public virtual Task ChangedExternally()
  1154. {
  1155. return RefreshMetadata(CancellationToken.None);
  1156. }
  1157. /// <summary>
  1158. /// Finds a parent of a given type
  1159. /// </summary>
  1160. /// <typeparam name="T"></typeparam>
  1161. /// <returns>``0.</returns>
  1162. public T FindParent<T>()
  1163. where T : Folder
  1164. {
  1165. var parent = Parent;
  1166. while (parent != null)
  1167. {
  1168. var result = parent as T;
  1169. if (result != null)
  1170. {
  1171. return result;
  1172. }
  1173. parent = parent.Parent;
  1174. }
  1175. return null;
  1176. }
  1177. /// <summary>
  1178. /// Gets an image
  1179. /// </summary>
  1180. /// <param name="type">The type.</param>
  1181. /// <returns>System.String.</returns>
  1182. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1183. public string GetImage(ImageType type)
  1184. {
  1185. if (type == ImageType.Backdrop)
  1186. {
  1187. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1188. }
  1189. if (type == ImageType.Screenshot)
  1190. {
  1191. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1192. }
  1193. string val;
  1194. Images.TryGetValue(type, out val);
  1195. return val;
  1196. }
  1197. /// <summary>
  1198. /// Gets an image
  1199. /// </summary>
  1200. /// <param name="type">The type.</param>
  1201. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1202. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1203. public bool HasImage(ImageType type)
  1204. {
  1205. if (type == ImageType.Backdrop)
  1206. {
  1207. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1208. }
  1209. if (type == ImageType.Screenshot)
  1210. {
  1211. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1212. }
  1213. return !string.IsNullOrEmpty(GetImage(type));
  1214. }
  1215. /// <summary>
  1216. /// Sets an image
  1217. /// </summary>
  1218. /// <param name="type">The type.</param>
  1219. /// <param name="path">The path.</param>
  1220. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1221. public void SetImage(ImageType type, string path)
  1222. {
  1223. if (type == ImageType.Backdrop)
  1224. {
  1225. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1226. }
  1227. if (type == ImageType.Screenshot)
  1228. {
  1229. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1230. }
  1231. var typeKey = type;
  1232. // If it's null remove the key from the dictionary
  1233. if (string.IsNullOrEmpty(path))
  1234. {
  1235. if (Images.ContainsKey(typeKey))
  1236. {
  1237. Images.Remove(typeKey);
  1238. }
  1239. }
  1240. else
  1241. {
  1242. Images[typeKey] = path;
  1243. }
  1244. }
  1245. /// <summary>
  1246. /// Deletes the image.
  1247. /// </summary>
  1248. /// <param name="type">The type.</param>
  1249. /// <param name="index">The index.</param>
  1250. /// <returns>Task.</returns>
  1251. public Task DeleteImage(ImageType type, int? index)
  1252. {
  1253. if (type == ImageType.Backdrop)
  1254. {
  1255. if (!index.HasValue)
  1256. {
  1257. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1258. }
  1259. var file = BackdropImagePaths[index.Value];
  1260. BackdropImagePaths.Remove(file);
  1261. // Delete the source file
  1262. File.Delete(file);
  1263. }
  1264. else if (type == ImageType.Screenshot)
  1265. {
  1266. if (!index.HasValue)
  1267. {
  1268. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1269. }
  1270. var file = ScreenshotImagePaths[index.Value];
  1271. ScreenshotImagePaths.Remove(file);
  1272. // Delete the source file
  1273. File.Delete(file);
  1274. }
  1275. else
  1276. {
  1277. // Delete the source file
  1278. File.Delete(GetImage(type));
  1279. // Remove it from the item
  1280. SetImage(type, null);
  1281. }
  1282. // Refresh metadata
  1283. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1284. }
  1285. }
  1286. }