BaseItem.cs 44 KB

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