BaseItem.cs 52 KB

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