BaseItem.cs 53 KB

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