BaseItem.cs 56 KB

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