BaseItem.cs 52 KB

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