BaseItem.cs 53 KB

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