BaseItem.cs 47 KB

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