BaseItem.cs 60 KB

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