BaseItem.cs 45 KB

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