BaseItem.cs 44 KB

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