BaseItem.cs 53 KB

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