BaseItem.cs 52 KB

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