BaseItem.cs 56 KB

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