BaseItem.cs 53 KB

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