BaseItem.cs 52 KB

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