BaseItem.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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 (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 sort.
  331. /// </summary>
  332. /// <value>The name of the sort.</value>
  333. public string SortName { get; set; }
  334. /// <summary>
  335. /// Gets or sets the parent.
  336. /// </summary>
  337. /// <value>The parent.</value>
  338. [IgnoreDataMember]
  339. public Folder Parent { get; set; }
  340. /// <summary>
  341. /// Gets the collection folder parent.
  342. /// </summary>
  343. /// <value>The collection folder parent.</value>
  344. [IgnoreDataMember]
  345. public Folder CollectionFolder
  346. {
  347. get
  348. {
  349. if (this is AggregateFolder)
  350. {
  351. return null;
  352. }
  353. if (IsFolder)
  354. {
  355. var iCollectionFolder = this as ICollectionFolder;
  356. if (iCollectionFolder != null)
  357. {
  358. return (Folder)this;
  359. }
  360. }
  361. var parent = Parent;
  362. while (parent != null)
  363. {
  364. var iCollectionFolder = parent as ICollectionFolder;
  365. if (iCollectionFolder != null)
  366. {
  367. return parent;
  368. }
  369. parent = parent.Parent;
  370. }
  371. return null;
  372. }
  373. }
  374. /// <summary>
  375. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  376. /// </summary>
  377. /// <value>The premiere date.</value>
  378. public DateTime? PremiereDate { get; set; }
  379. /// <summary>
  380. /// Gets or sets the display type of the media.
  381. /// </summary>
  382. /// <value>The display type of the media.</value>
  383. public virtual string DisplayMediaType { get; set; }
  384. /// <summary>
  385. /// Gets or sets the backdrop image paths.
  386. /// </summary>
  387. /// <value>The backdrop image paths.</value>
  388. public List<string> BackdropImagePaths { get; set; }
  389. /// <summary>
  390. /// Gets or sets the screenshot image paths.
  391. /// </summary>
  392. /// <value>The screenshot image paths.</value>
  393. public List<string> ScreenshotImagePaths { get; set; }
  394. /// <summary>
  395. /// Gets or sets the official rating.
  396. /// </summary>
  397. /// <value>The official rating.</value>
  398. public string OfficialRating { get; set; }
  399. /// <summary>
  400. /// Gets or sets the custom rating.
  401. /// </summary>
  402. /// <value>The custom rating.</value>
  403. public string CustomRating { get; set; }
  404. /// <summary>
  405. /// Gets or sets the language.
  406. /// </summary>
  407. /// <value>The language.</value>
  408. public string Language { get; set; }
  409. /// <summary>
  410. /// Gets or sets the overview.
  411. /// </summary>
  412. /// <value>The overview.</value>
  413. public string Overview { get; set; }
  414. /// <summary>
  415. /// Gets or sets the taglines.
  416. /// </summary>
  417. /// <value>The taglines.</value>
  418. public List<string> Taglines { get; set; }
  419. /// <summary>
  420. /// Gets or sets the people.
  421. /// </summary>
  422. /// <value>The people.</value>
  423. public List<PersonInfo> People { get; set; }
  424. /// <summary>
  425. /// Override this if you need to combine/collapse person information
  426. /// </summary>
  427. /// <value>All people.</value>
  428. [IgnoreDataMember]
  429. public virtual IEnumerable<PersonInfo> AllPeople
  430. {
  431. get { return People; }
  432. }
  433. /// <summary>
  434. /// Gets or sets the studios.
  435. /// </summary>
  436. /// <value>The studios.</value>
  437. public virtual List<string> Studios { get; set; }
  438. /// <summary>
  439. /// Gets or sets the genres.
  440. /// </summary>
  441. /// <value>The genres.</value>
  442. public virtual List<string> Genres { get; set; }
  443. /// <summary>
  444. /// Gets or sets the community rating.
  445. /// </summary>
  446. /// <value>The community rating.</value>
  447. public float? CommunityRating { get; set; }
  448. /// <summary>
  449. /// Gets or sets the run time ticks.
  450. /// </summary>
  451. /// <value>The run time ticks.</value>
  452. public long? RunTimeTicks { get; set; }
  453. /// <summary>
  454. /// Gets or sets the aspect ratio.
  455. /// </summary>
  456. /// <value>The aspect ratio.</value>
  457. public string AspectRatio { get; set; }
  458. /// <summary>
  459. /// Gets or sets the production year.
  460. /// </summary>
  461. /// <value>The production year.</value>
  462. public virtual int? ProductionYear { get; set; }
  463. /// <summary>
  464. /// If the item is part of a series, this is it's number in the series.
  465. /// This could be episode number, album track number, etc.
  466. /// </summary>
  467. /// <value>The index number.</value>
  468. public int? IndexNumber { get; set; }
  469. /// <summary>
  470. /// For an episode this could be the season number, or for a song this could be the disc number.
  471. /// </summary>
  472. /// <value>The parent index number.</value>
  473. public int? ParentIndexNumber { get; set; }
  474. /// <summary>
  475. /// The _local trailers
  476. /// </summary>
  477. private List<Video> _localTrailers;
  478. /// <summary>
  479. /// The _local trailers initialized
  480. /// </summary>
  481. private bool _localTrailersInitialized;
  482. /// <summary>
  483. /// The _local trailers sync lock
  484. /// </summary>
  485. private object _localTrailersSyncLock = new object();
  486. /// <summary>
  487. /// Gets the local trailers.
  488. /// </summary>
  489. /// <value>The local trailers.</value>
  490. [IgnoreDataMember]
  491. public List<Video> LocalTrailers
  492. {
  493. get
  494. {
  495. LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers);
  496. return _localTrailers;
  497. }
  498. private set
  499. {
  500. _localTrailers = value;
  501. if (value == null)
  502. {
  503. _localTrailersInitialized = false;
  504. }
  505. }
  506. }
  507. /// <summary>
  508. /// Loads local trailers from the file system
  509. /// </summary>
  510. /// <returns>List{Video}.</returns>
  511. private List<Video> LoadLocalTrailers()
  512. {
  513. ItemResolveArgs resolveArgs;
  514. try
  515. {
  516. resolveArgs = ResolveArgs;
  517. }
  518. catch (IOException ex)
  519. {
  520. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  521. return new List<Video> { };
  522. }
  523. if (!resolveArgs.IsDirectory)
  524. {
  525. return new List<Video> { };
  526. }
  527. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  528. // Path doesn't exist. No biggie
  529. if (folder == null)
  530. {
  531. return new List<Video> { };
  532. }
  533. IEnumerable<WIN32_FIND_DATA> files;
  534. try
  535. {
  536. files = FileSystem.GetFiles(folder.Value.Path);
  537. }
  538. catch (IOException ex)
  539. {
  540. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  541. return new List<Video> { };
  542. }
  543. return LibraryManager.ResolvePaths<Video>(files, null).Select(video =>
  544. {
  545. // Try to retrieve it from the db. If we don't find it, use the resolved version
  546. var dbItem = Kernel.Instance.ItemRepository.RetrieveItem(video.Id) as Video;
  547. if (dbItem != null)
  548. {
  549. dbItem.ResolveArgs = video.ResolveArgs;
  550. video = dbItem;
  551. }
  552. return video;
  553. }).ToList();
  554. }
  555. /// <summary>
  556. /// Overrides the base implementation to refresh metadata for local trailers
  557. /// </summary>
  558. /// <param name="cancellationToken">The cancellation token.</param>
  559. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  560. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  561. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  562. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  563. /// <returns>true if a provider reports we changed</returns>
  564. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  565. {
  566. if (resetResolveArgs)
  567. {
  568. ResolveArgs = null;
  569. }
  570. // Lazy load these again
  571. LocalTrailers = null;
  572. // Refresh for the item
  573. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  574. cancellationToken.ThrowIfCancellationRequested();
  575. // Refresh metadata for local trailers
  576. var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders));
  577. cancellationToken.ThrowIfCancellationRequested();
  578. // Await the trailer tasks
  579. await Task.WhenAll(trailerTasks).ConfigureAwait(false);
  580. cancellationToken.ThrowIfCancellationRequested();
  581. // Get the result from the item task
  582. var changed = await itemRefreshTask.ConfigureAwait(false);
  583. if (changed || forceSave)
  584. {
  585. cancellationToken.ThrowIfCancellationRequested();
  586. await Kernel.Instance.ItemRepository.SaveItem(this, cancellationToken).ConfigureAwait(false);
  587. }
  588. return changed;
  589. }
  590. /// <summary>
  591. /// Clear out all metadata properties. Extend for sub-classes.
  592. /// </summary>
  593. public virtual void ClearMetaValues()
  594. {
  595. Images = null;
  596. SortName = null;
  597. PremiereDate = null;
  598. BackdropImagePaths = null;
  599. OfficialRating = null;
  600. CustomRating = null;
  601. Overview = null;
  602. Taglines = null;
  603. Language = null;
  604. Studios = null;
  605. Genres = null;
  606. CommunityRating = null;
  607. RunTimeTicks = null;
  608. AspectRatio = null;
  609. ProductionYear = null;
  610. ProviderIds = null;
  611. DisplayMediaType = GetType().Name;
  612. ResolveArgs = null;
  613. }
  614. /// <summary>
  615. /// Gets or sets the trailer URL.
  616. /// </summary>
  617. /// <value>The trailer URL.</value>
  618. public List<string> TrailerUrls { get; set; }
  619. /// <summary>
  620. /// Gets or sets the provider ids.
  621. /// </summary>
  622. /// <value>The provider ids.</value>
  623. public Dictionary<string, string> ProviderIds { get; set; }
  624. /// <summary>
  625. /// Override this to false if class should be ignored for indexing purposes
  626. /// </summary>
  627. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  628. [IgnoreDataMember]
  629. public virtual bool IncludeInIndex
  630. {
  631. get { return true; }
  632. }
  633. /// <summary>
  634. /// Override this to true if class should be grouped under a container in indicies
  635. /// The container class should be defined via IndexContainer
  636. /// </summary>
  637. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  638. [IgnoreDataMember]
  639. public virtual bool GroupInIndex
  640. {
  641. get { return false; }
  642. }
  643. /// <summary>
  644. /// Override this to return the folder that should be used to construct a container
  645. /// for this item in an index. GroupInIndex should be true as well.
  646. /// </summary>
  647. /// <value>The index container.</value>
  648. [IgnoreDataMember]
  649. public virtual Folder IndexContainer
  650. {
  651. get { return null; }
  652. }
  653. /// <summary>
  654. /// The _user data
  655. /// </summary>
  656. private IEnumerable<UserItemData> _userData;
  657. /// <summary>
  658. /// The _user data initialized
  659. /// </summary>
  660. private bool _userDataInitialized;
  661. /// <summary>
  662. /// The _user data sync lock
  663. /// </summary>
  664. private object _userDataSyncLock = new object();
  665. /// <summary>
  666. /// Gets the user data.
  667. /// </summary>
  668. /// <value>The user data.</value>
  669. [IgnoreDataMember]
  670. public IEnumerable<UserItemData> UserData
  671. {
  672. get
  673. {
  674. // Call ToList to exhaust the stream because we'll be iterating over this multiple times
  675. LazyInitializer.EnsureInitialized(ref _userData, ref _userDataInitialized, ref _userDataSyncLock, () => Kernel.Instance.UserDataRepository.RetrieveUserData(this).ToList());
  676. return _userData;
  677. }
  678. private set
  679. {
  680. _userData = value;
  681. if (value == null)
  682. {
  683. _userDataInitialized = false;
  684. }
  685. }
  686. }
  687. /// <summary>
  688. /// Gets the user data.
  689. /// </summary>
  690. /// <param name="user">The user.</param>
  691. /// <param name="createIfNull">if set to <c>true</c> [create if null].</param>
  692. /// <returns>UserItemData.</returns>
  693. /// <exception cref="System.ArgumentNullException"></exception>
  694. public UserItemData GetUserData(User user, bool createIfNull)
  695. {
  696. if (user == null)
  697. {
  698. throw new ArgumentNullException();
  699. }
  700. if (UserData == null)
  701. {
  702. if (!createIfNull)
  703. {
  704. return null;
  705. }
  706. AddOrUpdateUserData(user, new UserItemData { UserId = user.Id });
  707. }
  708. var data = UserData.FirstOrDefault(u => u.UserId == user.Id);
  709. if (data == null && createIfNull)
  710. {
  711. data = new UserItemData { UserId = user.Id };
  712. AddOrUpdateUserData(user, data);
  713. }
  714. return data;
  715. }
  716. /// <summary>
  717. /// Adds the or update user data.
  718. /// </summary>
  719. /// <param name="user">The user.</param>
  720. /// <param name="data">The data.</param>
  721. /// <exception cref="System.ArgumentNullException"></exception>
  722. public void AddOrUpdateUserData(User user, UserItemData data)
  723. {
  724. if (user == null)
  725. {
  726. throw new ArgumentNullException();
  727. }
  728. if (data == null)
  729. {
  730. throw new ArgumentNullException();
  731. }
  732. data.UserId = user.Id;
  733. if (UserData == null)
  734. {
  735. UserData = new[] { data };
  736. }
  737. else
  738. {
  739. var list = UserData.Where(u => u.UserId != user.Id).ToList();
  740. list.Add(data);
  741. UserData = list;
  742. }
  743. }
  744. /// <summary>
  745. /// The _user data id
  746. /// </summary>
  747. protected Guid _userDataId; //cache this so it doesn't have to be re-constructed on every reference
  748. /// <summary>
  749. /// Return the id that should be used to key user data for this item.
  750. /// Default is just this Id but subclasses can use provider Ids for transportability.
  751. /// </summary>
  752. /// <value>The user data id.</value>
  753. [IgnoreDataMember]
  754. public virtual Guid UserDataId
  755. {
  756. get
  757. {
  758. return _userDataId == Guid.Empty ? (_userDataId = Id) : _userDataId;
  759. }
  760. }
  761. /// <summary>
  762. /// Determines if a given user has access to this item
  763. /// </summary>
  764. /// <param name="user">The user.</param>
  765. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  766. /// <exception cref="System.ArgumentNullException"></exception>
  767. public bool IsParentalAllowed(User user)
  768. {
  769. if (user == null)
  770. {
  771. throw new ArgumentNullException();
  772. }
  773. return user.Configuration.MaxParentalRating == null || Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating;
  774. }
  775. /// <summary>
  776. /// Determines if this folder should be visible to a given user.
  777. /// Default is just parental allowed. Can be overridden for more functionality.
  778. /// </summary>
  779. /// <param name="user">The user.</param>
  780. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  781. /// <exception cref="System.ArgumentNullException">user</exception>
  782. public virtual bool IsVisible(User user)
  783. {
  784. if (user == null)
  785. {
  786. throw new ArgumentNullException("user");
  787. }
  788. return IsParentalAllowed(user);
  789. }
  790. /// <summary>
  791. /// Finds an item by ID, recursively
  792. /// </summary>
  793. /// <param name="id">The id.</param>
  794. /// <param name="user">The user.</param>
  795. /// <returns>BaseItem.</returns>
  796. /// <exception cref="System.ArgumentNullException">id</exception>
  797. public virtual BaseItem FindItemById(Guid id, User user)
  798. {
  799. if (id == Guid.Empty)
  800. {
  801. throw new ArgumentNullException("id");
  802. }
  803. if (Id == id)
  804. {
  805. return this;
  806. }
  807. if (LocalTrailers != null)
  808. {
  809. return LocalTrailers.FirstOrDefault(i => i.Id == id);
  810. }
  811. return null;
  812. }
  813. /// <summary>
  814. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  815. /// </summary>
  816. /// <param name="id">The id.</param>
  817. /// <returns>BaseItem.</returns>
  818. /// <exception cref="System.ArgumentException"></exception>
  819. protected BaseItem FindParentItem(Guid id)
  820. {
  821. if (id == Guid.Empty)
  822. {
  823. throw new ArgumentException();
  824. }
  825. var parent = Parent;
  826. while (parent != null && !parent.IsRoot)
  827. {
  828. if (parent.Id == id) return parent;
  829. parent = parent.Parent;
  830. }
  831. //not found - load from repo
  832. return Kernel.Instance.ItemRepository.RetrieveItem(id);
  833. }
  834. /// <summary>
  835. /// Gets a value indicating whether this instance is folder.
  836. /// </summary>
  837. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  838. [IgnoreDataMember]
  839. public virtual bool IsFolder
  840. {
  841. get
  842. {
  843. return false;
  844. }
  845. }
  846. /// <summary>
  847. /// Determine if we have changed vs the passed in copy
  848. /// </summary>
  849. /// <param name="copy">The copy.</param>
  850. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  851. /// <exception cref="System.ArgumentNullException"></exception>
  852. public virtual bool HasChanged(BaseItem copy)
  853. {
  854. if (copy == null)
  855. {
  856. throw new ArgumentNullException();
  857. }
  858. var changed = copy.DateModified != DateModified;
  859. if (changed)
  860. {
  861. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  862. }
  863. return changed;
  864. }
  865. /// <summary>
  866. /// Determines if the item is considered new based on user settings
  867. /// </summary>
  868. /// <param name="user">The user.</param>
  869. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  870. /// <exception cref="System.ArgumentNullException"></exception>
  871. public bool IsRecentlyAdded(User user)
  872. {
  873. if (user == null)
  874. {
  875. throw new ArgumentNullException();
  876. }
  877. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  878. }
  879. /// <summary>
  880. /// Determines if the item is considered recently played on user settings
  881. /// </summary>
  882. /// <param name="user">The user.</param>
  883. /// <returns><c>true</c> if [is recently played] [the specified user]; otherwise, <c>false</c>.</returns>
  884. /// <exception cref="System.ArgumentNullException"></exception>
  885. public bool IsRecentlyPlayed(User user)
  886. {
  887. if (user == null)
  888. {
  889. throw new ArgumentNullException();
  890. }
  891. var data = GetUserData(user, false);
  892. if (data == null || data.LastPlayedDate == null || data.PlayCount == 0)
  893. {
  894. return false;
  895. }
  896. return (DateTime.UtcNow - data.LastPlayedDate.Value).TotalDays < ConfigurationManager.Configuration.RecentlyPlayedDays;
  897. }
  898. /// <summary>
  899. /// Adds people to the item
  900. /// </summary>
  901. /// <param name="people">The people.</param>
  902. /// <exception cref="System.ArgumentNullException"></exception>
  903. public void AddPeople(IEnumerable<PersonInfo> people)
  904. {
  905. if (people == null)
  906. {
  907. throw new ArgumentNullException();
  908. }
  909. foreach (var person in people)
  910. {
  911. AddPerson(person);
  912. }
  913. }
  914. /// <summary>
  915. /// Adds a person to the item
  916. /// </summary>
  917. /// <param name="person">The person.</param>
  918. /// <exception cref="System.ArgumentNullException"></exception>
  919. public void AddPerson(PersonInfo person)
  920. {
  921. if (person == null)
  922. {
  923. throw new ArgumentNullException();
  924. }
  925. if (string.IsNullOrWhiteSpace(person.Name))
  926. {
  927. throw new ArgumentNullException();
  928. }
  929. if (People == null)
  930. {
  931. People = new List<PersonInfo>();
  932. }
  933. // Check for dupes based on the combination of Name and Type
  934. if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase)))
  935. {
  936. People.Add(person);
  937. }
  938. }
  939. /// <summary>
  940. /// Adds studios to the item
  941. /// </summary>
  942. /// <param name="studios">The studios.</param>
  943. /// <exception cref="System.ArgumentNullException"></exception>
  944. public void AddStudios(IEnumerable<string> studios)
  945. {
  946. if (studios == null)
  947. {
  948. throw new ArgumentNullException();
  949. }
  950. foreach (var name in studios)
  951. {
  952. AddStudio(name);
  953. }
  954. }
  955. /// <summary>
  956. /// Adds a studio to the item
  957. /// </summary>
  958. /// <param name="name">The name.</param>
  959. /// <exception cref="System.ArgumentNullException"></exception>
  960. public void AddStudio(string name)
  961. {
  962. if (string.IsNullOrWhiteSpace(name))
  963. {
  964. throw new ArgumentNullException();
  965. }
  966. if (Studios == null)
  967. {
  968. Studios = new List<string>();
  969. }
  970. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  971. {
  972. Studios.Add(name);
  973. }
  974. }
  975. /// <summary>
  976. /// Adds a tagline to the item
  977. /// </summary>
  978. /// <param name="name">The name.</param>
  979. /// <exception cref="System.ArgumentNullException"></exception>
  980. public void AddTagline(string name)
  981. {
  982. if (string.IsNullOrWhiteSpace(name))
  983. {
  984. throw new ArgumentNullException();
  985. }
  986. if (Taglines == null)
  987. {
  988. Taglines = new List<string>();
  989. }
  990. if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase))
  991. {
  992. Taglines.Add(name);
  993. }
  994. }
  995. /// <summary>
  996. /// Adds a TrailerUrl to the item
  997. /// </summary>
  998. /// <param name="url">The URL.</param>
  999. /// <exception cref="System.ArgumentNullException"></exception>
  1000. public void AddTrailerUrl(string url)
  1001. {
  1002. if (string.IsNullOrWhiteSpace(url))
  1003. {
  1004. throw new ArgumentNullException();
  1005. }
  1006. if (TrailerUrls == null)
  1007. {
  1008. TrailerUrls = new List<string>();
  1009. }
  1010. if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase))
  1011. {
  1012. TrailerUrls.Add(url);
  1013. }
  1014. }
  1015. /// <summary>
  1016. /// Adds a genre to the item
  1017. /// </summary>
  1018. /// <param name="name">The name.</param>
  1019. /// <exception cref="System.ArgumentNullException"></exception>
  1020. public void AddGenre(string name)
  1021. {
  1022. if (string.IsNullOrWhiteSpace(name))
  1023. {
  1024. throw new ArgumentNullException();
  1025. }
  1026. if (Genres == null)
  1027. {
  1028. Genres = new List<string>();
  1029. }
  1030. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1031. {
  1032. Genres.Add(name);
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// Adds genres to the item
  1037. /// </summary>
  1038. /// <param name="genres">The genres.</param>
  1039. /// <exception cref="System.ArgumentNullException"></exception>
  1040. public void AddGenres(IEnumerable<string> genres)
  1041. {
  1042. if (genres == null)
  1043. {
  1044. throw new ArgumentNullException();
  1045. }
  1046. foreach (var name in genres)
  1047. {
  1048. AddGenre(name);
  1049. }
  1050. }
  1051. /// <summary>
  1052. /// Marks the item as either played or unplayed
  1053. /// </summary>
  1054. /// <param name="user">The user.</param>
  1055. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1056. /// <returns>Task.</returns>
  1057. /// <exception cref="System.ArgumentNullException"></exception>
  1058. public virtual Task SetPlayedStatus(User user, bool wasPlayed, IUserManager userManager)
  1059. {
  1060. if (user == null)
  1061. {
  1062. throw new ArgumentNullException();
  1063. }
  1064. var data = GetUserData(user, true);
  1065. if (wasPlayed)
  1066. {
  1067. data.PlayCount = Math.Max(data.PlayCount, 1);
  1068. if (!data.LastPlayedDate.HasValue)
  1069. {
  1070. data.LastPlayedDate = DateTime.UtcNow;
  1071. }
  1072. }
  1073. else
  1074. {
  1075. //I think it is okay to do this here.
  1076. // if this is only called when a user is manually forcing something to un-played
  1077. // then it probably is what we want to do...
  1078. data.PlayCount = 0;
  1079. data.PlaybackPositionTicks = 0;
  1080. data.LastPlayedDate = null;
  1081. }
  1082. data.Played = wasPlayed;
  1083. return userManager.SaveUserDataForItem(user, this, data);
  1084. }
  1085. /// <summary>
  1086. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1087. /// </summary>
  1088. /// <returns>Task.</returns>
  1089. public virtual Task ChangedExternally()
  1090. {
  1091. return RefreshMetadata(CancellationToken.None);
  1092. }
  1093. /// <summary>
  1094. /// Finds a parent of a given type
  1095. /// </summary>
  1096. /// <typeparam name="T"></typeparam>
  1097. /// <returns>``0.</returns>
  1098. public T FindParent<T>()
  1099. where T : Folder
  1100. {
  1101. var parent = Parent;
  1102. while (parent != null)
  1103. {
  1104. var result = parent as T;
  1105. if (result != null)
  1106. {
  1107. return result;
  1108. }
  1109. parent = parent.Parent;
  1110. }
  1111. return null;
  1112. }
  1113. /// <summary>
  1114. /// Gets an image
  1115. /// </summary>
  1116. /// <param name="type">The type.</param>
  1117. /// <returns>System.String.</returns>
  1118. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1119. public string GetImage(ImageType type)
  1120. {
  1121. if (type == ImageType.Backdrop)
  1122. {
  1123. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1124. }
  1125. if (type == ImageType.Screenshot)
  1126. {
  1127. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1128. }
  1129. if (Images == null)
  1130. {
  1131. return null;
  1132. }
  1133. string val;
  1134. Images.TryGetValue(type.ToString(), out val);
  1135. return val;
  1136. }
  1137. /// <summary>
  1138. /// Gets an image
  1139. /// </summary>
  1140. /// <param name="type">The type.</param>
  1141. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1142. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1143. public bool HasImage(ImageType type)
  1144. {
  1145. if (type == ImageType.Backdrop)
  1146. {
  1147. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1148. }
  1149. if (type == ImageType.Screenshot)
  1150. {
  1151. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1152. }
  1153. return !string.IsNullOrEmpty(GetImage(type));
  1154. }
  1155. /// <summary>
  1156. /// Sets an image
  1157. /// </summary>
  1158. /// <param name="type">The type.</param>
  1159. /// <param name="path">The path.</param>
  1160. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1161. public void SetImage(ImageType type, string path)
  1162. {
  1163. if (type == ImageType.Backdrop)
  1164. {
  1165. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1166. }
  1167. if (type == ImageType.Screenshot)
  1168. {
  1169. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1170. }
  1171. var typeKey = type.ToString();
  1172. // If it's null remove the key from the dictionary
  1173. if (string.IsNullOrEmpty(path))
  1174. {
  1175. if (Images != null)
  1176. {
  1177. if (Images.ContainsKey(typeKey))
  1178. {
  1179. Images.Remove(typeKey);
  1180. }
  1181. }
  1182. }
  1183. else
  1184. {
  1185. // Ensure it exists
  1186. if (Images == null)
  1187. {
  1188. Images = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  1189. }
  1190. Images[typeKey] = path;
  1191. }
  1192. }
  1193. /// <summary>
  1194. /// Deletes the image.
  1195. /// </summary>
  1196. /// <param name="type">The type.</param>
  1197. /// <returns>Task.</returns>
  1198. public async Task DeleteImage(ImageType type)
  1199. {
  1200. if (!HasImage(type))
  1201. {
  1202. return;
  1203. }
  1204. // Delete the source file
  1205. File.Delete(GetImage(type));
  1206. // Remove it from the item
  1207. SetImage(type, null);
  1208. // Refresh metadata
  1209. await RefreshMetadata(CancellationToken.None).ConfigureAwait(false);
  1210. }
  1211. }
  1212. }