BaseItem.cs 53 KB

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