BaseItem.cs 59 KB

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