BaseItem.cs 52 KB

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