BaseItem.cs 52 KB

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