BaseItem.cs 54 KB

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