BaseItem.cs 52 KB

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