BaseItem.cs 60 KB

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