BaseItem.cs 44 KB

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