BaseItem.cs 52 KB

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