BaseItem.cs 52 KB

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