BaseItem.cs 52 KB

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