BaseItem.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities.TV;
  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. private 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. ResetResolveArgs(CreateResolveArgs(pathInfo));
  315. }
  316. public void ResetResolveArgs()
  317. {
  318. ResolveArgs = null;
  319. }
  320. public void ResetResolveArgs(ItemResolveArgs args)
  321. {
  322. ResolveArgs = args;
  323. }
  324. /// <summary>
  325. /// Creates ResolveArgs on demand
  326. /// </summary>
  327. /// <param name="pathInfo">The path info.</param>
  328. /// <returns>ItemResolveArgs.</returns>
  329. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  330. protected internal virtual ItemResolveArgs CreateResolveArgs(FileSystemInfo pathInfo = null)
  331. {
  332. var path = Path;
  333. if (LocationType == LocationType.Remote || LocationType == LocationType.Virtual)
  334. {
  335. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager);
  336. }
  337. var isDirectory = false;
  338. if (UseParentPathToCreateResolveArgs)
  339. {
  340. path = System.IO.Path.GetDirectoryName(path);
  341. isDirectory = true;
  342. }
  343. pathInfo = pathInfo ?? (isDirectory ? new DirectoryInfo(path) : FileSystem.GetFileSystemInfo(path));
  344. if (pathInfo == null || !pathInfo.Exists)
  345. {
  346. throw new IOException("Unable to retrieve file system info for " + path);
  347. }
  348. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager)
  349. {
  350. FileInfo = pathInfo,
  351. Path = path,
  352. Parent = Parent
  353. };
  354. // Gather child folder and files
  355. if (args.IsDirectory)
  356. {
  357. var isPhysicalRoot = args.IsPhysicalRoot;
  358. // When resolving the root, we need it's grandchildren (children of user views)
  359. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  360. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  361. // Need to remove subpaths that may have been resolved from shortcuts
  362. // Example: if \\server\movies exists, then strip out \\server\movies\action
  363. if (isPhysicalRoot)
  364. {
  365. var paths = args.FileSystemDictionary.Keys.ToList();
  366. foreach (var subPath in paths
  367. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  368. {
  369. Logger.Info("Ignoring duplicate path: {0}", subPath);
  370. args.FileSystemDictionary.Remove(subPath);
  371. }
  372. }
  373. }
  374. //update our dates
  375. EntityResolutionHelper.EnsureDates(this, args, false);
  376. IsOffline = false;
  377. return args;
  378. }
  379. /// <summary>
  380. /// 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
  381. /// original ones.
  382. /// </summary>
  383. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  384. [IgnoreDataMember]
  385. protected virtual bool UseParentPathToCreateResolveArgs
  386. {
  387. get
  388. {
  389. return false;
  390. }
  391. }
  392. /// <summary>
  393. /// Gets or sets the name of the forced sort.
  394. /// </summary>
  395. /// <value>The name of the forced sort.</value>
  396. public string ForcedSortName { get; set; }
  397. private string _sortName;
  398. /// <summary>
  399. /// Gets or sets the name of the sort.
  400. /// </summary>
  401. /// <value>The name of the sort.</value>
  402. [IgnoreDataMember]
  403. public string SortName
  404. {
  405. get
  406. {
  407. if (!string.IsNullOrEmpty(ForcedSortName))
  408. {
  409. return ForcedSortName;
  410. }
  411. return _sortName ?? (_sortName = CreateSortName());
  412. }
  413. }
  414. /// <summary>
  415. /// Creates the name of the sort.
  416. /// </summary>
  417. /// <returns>System.String.</returns>
  418. protected virtual string CreateSortName()
  419. {
  420. if (Name == null) return null; //some items may not have name filled in properly
  421. var sortable = Name.Trim().ToLower();
  422. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  423. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  424. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  425. {
  426. var searchLower = search.ToLower();
  427. // Remove from beginning if a space follows
  428. if (sortable.StartsWith(searchLower + " "))
  429. {
  430. sortable = sortable.Remove(0, searchLower.Length + 1);
  431. }
  432. // Remove from middle if surrounded by spaces
  433. sortable = sortable.Replace(" " + searchLower + " ", " ");
  434. // Remove from end if followed by a space
  435. if (sortable.EndsWith(" " + searchLower))
  436. {
  437. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  438. }
  439. }
  440. return sortable;
  441. }
  442. /// <summary>
  443. /// Gets or sets the parent.
  444. /// </summary>
  445. /// <value>The parent.</value>
  446. [IgnoreDataMember]
  447. public Folder Parent { get; set; }
  448. /// <summary>
  449. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  450. /// </summary>
  451. /// <value>The premiere date.</value>
  452. public DateTime? PremiereDate { get; set; }
  453. /// <summary>
  454. /// Gets or sets the end date.
  455. /// </summary>
  456. /// <value>The end date.</value>
  457. public DateTime? EndDate { get; set; }
  458. /// <summary>
  459. /// Gets or sets the display type of the media.
  460. /// </summary>
  461. /// <value>The display type of the media.</value>
  462. public string DisplayMediaType { get; set; }
  463. /// <summary>
  464. /// Gets or sets the backdrop image paths.
  465. /// </summary>
  466. /// <value>The backdrop image paths.</value>
  467. public List<string> BackdropImagePaths { get; set; }
  468. /// <summary>
  469. /// Gets or sets the screenshot image paths.
  470. /// </summary>
  471. /// <value>The screenshot image paths.</value>
  472. public List<string> ScreenshotImagePaths { get; set; }
  473. /// <summary>
  474. /// Gets or sets the official rating.
  475. /// </summary>
  476. /// <value>The official rating.</value>
  477. public string OfficialRating { get; set; }
  478. /// <summary>
  479. /// Gets or sets the official rating description.
  480. /// </summary>
  481. /// <value>The official rating description.</value>
  482. public string OfficialRatingDescription { get; set; }
  483. /// <summary>
  484. /// Gets or sets the custom rating.
  485. /// </summary>
  486. /// <value>The custom rating.</value>
  487. public string CustomRating { get; set; }
  488. /// <summary>
  489. /// Gets or sets the language.
  490. /// </summary>
  491. /// <value>The language.</value>
  492. public string Language { get; set; }
  493. /// <summary>
  494. /// Gets or sets the overview.
  495. /// </summary>
  496. /// <value>The overview.</value>
  497. public string Overview { get; set; }
  498. /// <summary>
  499. /// Gets or sets the people.
  500. /// </summary>
  501. /// <value>The people.</value>
  502. public List<PersonInfo> People { get; set; }
  503. /// <summary>
  504. /// Gets or sets the tags.
  505. /// </summary>
  506. /// <value>The tags.</value>
  507. public List<string> Tags { get; set; }
  508. /// <summary>
  509. /// Override this if you need to combine/collapse person information
  510. /// </summary>
  511. /// <value>All people.</value>
  512. [IgnoreDataMember]
  513. public virtual IEnumerable<PersonInfo> AllPeople
  514. {
  515. get { return People; }
  516. }
  517. [IgnoreDataMember]
  518. public virtual IEnumerable<string> AllStudios
  519. {
  520. get { return Studios; }
  521. }
  522. [IgnoreDataMember]
  523. public virtual IEnumerable<string> AllGenres
  524. {
  525. get { return Genres; }
  526. }
  527. /// <summary>
  528. /// Gets or sets the studios.
  529. /// </summary>
  530. /// <value>The studios.</value>
  531. public List<string> Studios { get; set; }
  532. /// <summary>
  533. /// Gets or sets the genres.
  534. /// </summary>
  535. /// <value>The genres.</value>
  536. public List<string> Genres { get; set; }
  537. /// <summary>
  538. /// Gets or sets the home page URL.
  539. /// </summary>
  540. /// <value>The home page URL.</value>
  541. public string HomePageUrl { get; set; }
  542. /// <summary>
  543. /// Gets or sets the production locations.
  544. /// </summary>
  545. /// <value>The production locations.</value>
  546. public List<string> ProductionLocations { get; set; }
  547. /// <summary>
  548. /// Gets or sets the community rating.
  549. /// </summary>
  550. /// <value>The community rating.</value>
  551. public float? CommunityRating { get; set; }
  552. /// <summary>
  553. /// Gets or sets the community rating vote count.
  554. /// </summary>
  555. /// <value>The community rating vote count.</value>
  556. public int? VoteCount { get; set; }
  557. /// <summary>
  558. /// Gets or sets the run time ticks.
  559. /// </summary>
  560. /// <value>The run time ticks.</value>
  561. public long? RunTimeTicks { get; set; }
  562. /// <summary>
  563. /// Gets or sets the original run time ticks.
  564. /// </summary>
  565. /// <value>The original run time ticks.</value>
  566. public long? OriginalRunTimeTicks { get; set; }
  567. /// <summary>
  568. /// Gets or sets the aspect ratio.
  569. /// </summary>
  570. /// <value>The aspect ratio.</value>
  571. public string AspectRatio { get; set; }
  572. /// <summary>
  573. /// Gets or sets the production year.
  574. /// </summary>
  575. /// <value>The production year.</value>
  576. public int? ProductionYear { get; set; }
  577. /// <summary>
  578. /// If the item is part of a series, this is it's number in the series.
  579. /// This could be episode number, album track number, etc.
  580. /// </summary>
  581. /// <value>The index number.</value>
  582. public int? IndexNumber { get; set; }
  583. /// <summary>
  584. /// For an episode this could be the season number, or for a song this could be the disc number.
  585. /// </summary>
  586. /// <value>The parent index number.</value>
  587. public int? ParentIndexNumber { get; set; }
  588. public List<Guid> ThemeSongIds { get; set; }
  589. public List<Guid> ThemeVideoIds { get; set; }
  590. public List<Guid> LocalTrailerIds { get; set; }
  591. [IgnoreDataMember]
  592. public virtual string OfficialRatingForComparison
  593. {
  594. get { return OfficialRating; }
  595. }
  596. [IgnoreDataMember]
  597. public virtual string CustomRatingForComparison
  598. {
  599. get { return CustomRating; }
  600. }
  601. /// <summary>
  602. /// Loads local trailers from the file system
  603. /// </summary>
  604. /// <returns>List{Video}.</returns>
  605. private IEnumerable<Trailer> LoadLocalTrailers()
  606. {
  607. ItemResolveArgs resolveArgs;
  608. try
  609. {
  610. resolveArgs = ResolveArgs;
  611. if (!resolveArgs.IsDirectory)
  612. {
  613. return new List<Trailer>();
  614. }
  615. }
  616. catch (IOException ex)
  617. {
  618. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  619. return new List<Trailer>();
  620. }
  621. var files = new List<FileSystemInfo>();
  622. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  623. // Path doesn't exist. No biggie
  624. if (folder != null)
  625. {
  626. try
  627. {
  628. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  629. }
  630. catch (IOException ex)
  631. {
  632. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  633. }
  634. }
  635. // Support xbmc trailers (-trailer suffix on video file names)
  636. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  637. {
  638. try
  639. {
  640. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  641. {
  642. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  643. {
  644. return true;
  645. }
  646. }
  647. }
  648. catch (IOException ex)
  649. {
  650. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  651. }
  652. return false;
  653. }));
  654. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  655. {
  656. // Try to retrieve it from the db. If we don't find it, use the resolved version
  657. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  658. if (dbItem != null)
  659. {
  660. dbItem.ResolveArgs = video.ResolveArgs;
  661. video = dbItem;
  662. }
  663. return video;
  664. }).ToList();
  665. }
  666. /// <summary>
  667. /// Loads the theme songs.
  668. /// </summary>
  669. /// <returns>List{Audio.Audio}.</returns>
  670. private IEnumerable<Audio.Audio> LoadThemeSongs()
  671. {
  672. ItemResolveArgs resolveArgs;
  673. try
  674. {
  675. resolveArgs = ResolveArgs;
  676. if (!resolveArgs.IsDirectory)
  677. {
  678. return new List<Audio.Audio>();
  679. }
  680. }
  681. catch (IOException ex)
  682. {
  683. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  684. return new List<Audio.Audio>();
  685. }
  686. var files = new List<FileSystemInfo>();
  687. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  688. // Path doesn't exist. No biggie
  689. if (folder != null)
  690. {
  691. try
  692. {
  693. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  694. }
  695. catch (IOException ex)
  696. {
  697. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  698. }
  699. }
  700. // Support plex/xbmc convention
  701. files.AddRange(resolveArgs.FileSystemChildren
  702. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  703. );
  704. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  705. {
  706. // Try to retrieve it from the db. If we don't find it, use the resolved version
  707. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  708. if (dbItem != null)
  709. {
  710. dbItem.ResolveArgs = audio.ResolveArgs;
  711. audio = dbItem;
  712. }
  713. return audio;
  714. }).ToList();
  715. }
  716. /// <summary>
  717. /// Loads the video backdrops.
  718. /// </summary>
  719. /// <returns>List{Video}.</returns>
  720. private IEnumerable<Video> LoadThemeVideos()
  721. {
  722. ItemResolveArgs resolveArgs;
  723. try
  724. {
  725. resolveArgs = ResolveArgs;
  726. if (!resolveArgs.IsDirectory)
  727. {
  728. return new List<Video>();
  729. }
  730. }
  731. catch (IOException ex)
  732. {
  733. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  734. return new List<Video>();
  735. }
  736. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  737. // Path doesn't exist. No biggie
  738. if (folder == null)
  739. {
  740. return new List<Video>();
  741. }
  742. IEnumerable<FileSystemInfo> files;
  743. try
  744. {
  745. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  746. }
  747. catch (IOException ex)
  748. {
  749. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  750. return new List<Video>();
  751. }
  752. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  753. {
  754. // Try to retrieve it from the db. If we don't find it, use the resolved version
  755. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  756. if (dbItem != null)
  757. {
  758. dbItem.ResolveArgs = item.ResolveArgs;
  759. item = dbItem;
  760. }
  761. return item;
  762. }).ToList();
  763. }
  764. /// <summary>
  765. /// Overrides the base implementation to refresh metadata for local trailers
  766. /// </summary>
  767. /// <param name="cancellationToken">The cancellation token.</param>
  768. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  769. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  770. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  771. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  772. /// <returns>true if a provider reports we changed</returns>
  773. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  774. {
  775. if (resetResolveArgs || ResolveArgs == null)
  776. {
  777. // Reload this
  778. ResetResolveArgs();
  779. }
  780. // Refresh for the item
  781. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  782. cancellationToken.ThrowIfCancellationRequested();
  783. var themeSongsChanged = false;
  784. var themeVideosChanged = false;
  785. var localTrailersChanged = false;
  786. if (LocationType == LocationType.FileSystem && Parent != null)
  787. {
  788. themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  789. themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  790. localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  791. }
  792. cancellationToken.ThrowIfCancellationRequested();
  793. // Get the result from the item task
  794. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  795. var changed = updateReason.HasValue;
  796. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  797. {
  798. cancellationToken.ThrowIfCancellationRequested();
  799. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  800. }
  801. return changed;
  802. }
  803. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  804. {
  805. var newItems = LoadLocalTrailers().ToList();
  806. var newItemIds = newItems.Select(i => i.Id).ToList();
  807. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  808. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  809. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  810. LocalTrailerIds = newItemIds;
  811. return itemsChanged || results.Contains(true);
  812. }
  813. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  814. {
  815. var newThemeVideos = LoadThemeVideos().ToList();
  816. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  817. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  818. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  819. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  820. ThemeVideoIds = newThemeVideoIds;
  821. return themeVideosChanged || results.Contains(true);
  822. }
  823. /// <summary>
  824. /// Refreshes the theme songs.
  825. /// </summary>
  826. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  827. {
  828. var newThemeSongs = LoadThemeSongs().ToList();
  829. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  830. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  831. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  832. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  833. ThemeSongIds = newThemeSongIds;
  834. return themeSongsChanged || results.Contains(true);
  835. }
  836. /// <summary>
  837. /// Gets or sets the provider ids.
  838. /// </summary>
  839. /// <value>The provider ids.</value>
  840. public Dictionary<string, string> ProviderIds { get; set; }
  841. /// <summary>
  842. /// Override this to false if class should be ignored for indexing purposes
  843. /// </summary>
  844. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  845. [IgnoreDataMember]
  846. public virtual bool IncludeInIndex
  847. {
  848. get { return true; }
  849. }
  850. /// <summary>
  851. /// Override this to true if class should be grouped under a container in indicies
  852. /// The container class should be defined via IndexContainer
  853. /// </summary>
  854. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  855. [IgnoreDataMember]
  856. public virtual bool GroupInIndex
  857. {
  858. get { return false; }
  859. }
  860. /// <summary>
  861. /// Override this to return the folder that should be used to construct a container
  862. /// for this item in an index. GroupInIndex should be true as well.
  863. /// </summary>
  864. /// <value>The index container.</value>
  865. [IgnoreDataMember]
  866. public virtual Folder IndexContainer
  867. {
  868. get { return null; }
  869. }
  870. /// <summary>
  871. /// Gets the user data key.
  872. /// </summary>
  873. /// <returns>System.String.</returns>
  874. public virtual string GetUserDataKey()
  875. {
  876. return Id.ToString();
  877. }
  878. /// <summary>
  879. /// Determines if a given user has access to this item
  880. /// </summary>
  881. /// <param name="user">The user.</param>
  882. /// <param name="localizationManager">The localization manager.</param>
  883. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  884. /// <exception cref="System.ArgumentNullException">user</exception>
  885. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  886. {
  887. if (user == null)
  888. {
  889. throw new ArgumentNullException("user");
  890. }
  891. var maxAllowedRating = user.Configuration.MaxParentalRating;
  892. if (maxAllowedRating == null)
  893. {
  894. return true;
  895. }
  896. var rating = CustomRatingForComparison;
  897. if (string.IsNullOrEmpty(rating))
  898. {
  899. rating = OfficialRatingForComparison;
  900. }
  901. if (string.IsNullOrEmpty(rating))
  902. {
  903. return !user.Configuration.BlockNotRated;
  904. }
  905. var value = localizationManager.GetRatingLevel(rating);
  906. // Could not determine the integer value
  907. if (!value.HasValue)
  908. {
  909. return true;
  910. }
  911. return value.Value <= maxAllowedRating.Value;
  912. }
  913. /// <summary>
  914. /// Determines if this folder should be visible to a given user.
  915. /// Default is just parental allowed. Can be overridden for more functionality.
  916. /// </summary>
  917. /// <param name="user">The user.</param>
  918. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  919. /// <exception cref="System.ArgumentNullException">user</exception>
  920. public virtual bool IsVisible(User user)
  921. {
  922. if (user == null)
  923. {
  924. throw new ArgumentNullException("user");
  925. }
  926. return IsParentalAllowed(user, LocalizationManager);
  927. }
  928. /// <summary>
  929. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  930. /// </summary>
  931. /// <param name="id">The id.</param>
  932. /// <returns>BaseItem.</returns>
  933. /// <exception cref="System.ArgumentException"></exception>
  934. protected BaseItem FindParentItem(Guid id)
  935. {
  936. if (id == Guid.Empty)
  937. {
  938. throw new ArgumentException();
  939. }
  940. var parent = Parent;
  941. while (parent != null && !parent.IsRoot)
  942. {
  943. if (parent.Id == id) return parent;
  944. parent = parent.Parent;
  945. }
  946. return null;
  947. }
  948. /// <summary>
  949. /// Gets a value indicating whether this instance is folder.
  950. /// </summary>
  951. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  952. [IgnoreDataMember]
  953. public virtual bool IsFolder
  954. {
  955. get
  956. {
  957. return false;
  958. }
  959. }
  960. /// <summary>
  961. /// Determine if we have changed vs the passed in copy
  962. /// </summary>
  963. /// <param name="copy">The copy.</param>
  964. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  965. /// <exception cref="System.ArgumentNullException"></exception>
  966. public virtual bool HasChanged(BaseItem copy)
  967. {
  968. if (copy == null)
  969. {
  970. throw new ArgumentNullException();
  971. }
  972. var changed = copy.DateModified != DateModified;
  973. if (changed)
  974. {
  975. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  976. }
  977. return changed;
  978. }
  979. /// <summary>
  980. /// Determines if the item is considered new based on user settings
  981. /// </summary>
  982. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  983. /// <exception cref="System.ArgumentNullException"></exception>
  984. public bool IsRecentlyAdded()
  985. {
  986. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  987. }
  988. /// <summary>
  989. /// Adds a person to the item
  990. /// </summary>
  991. /// <param name="person">The person.</param>
  992. /// <exception cref="System.ArgumentNullException"></exception>
  993. public void AddPerson(PersonInfo person)
  994. {
  995. if (person == null)
  996. {
  997. throw new ArgumentNullException("person");
  998. }
  999. if (string.IsNullOrWhiteSpace(person.Name))
  1000. {
  1001. throw new ArgumentNullException();
  1002. }
  1003. // Normalize
  1004. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1005. {
  1006. person.Type = PersonType.GuestStar;
  1007. }
  1008. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  1009. {
  1010. person.Type = PersonType.Director;
  1011. }
  1012. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. person.Type = PersonType.Producer;
  1015. }
  1016. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1017. {
  1018. person.Type = PersonType.Writer;
  1019. }
  1020. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1021. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1022. {
  1023. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1024. if (existing != null)
  1025. {
  1026. existing.Type = PersonType.GuestStar;
  1027. return;
  1028. }
  1029. }
  1030. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1031. {
  1032. // If the actor already exists without a role and we have one, fill it in
  1033. 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)));
  1034. if (existing == null)
  1035. {
  1036. // Wasn't there - add it
  1037. People.Add(person);
  1038. }
  1039. else
  1040. {
  1041. // Was there, if no role and we have one - fill it in
  1042. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  1043. }
  1044. }
  1045. else
  1046. {
  1047. // Check for dupes based on the combination of Name and Type
  1048. if (!People.Any(p => string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase)))
  1049. {
  1050. People.Add(person);
  1051. }
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// Adds the tagline.
  1056. /// </summary>
  1057. /// <param name="item">The item.</param>
  1058. /// <param name="tagline">The tagline.</param>
  1059. /// <exception cref="System.ArgumentNullException">tagline</exception>
  1060. public void AddTagline(string tagline)
  1061. {
  1062. if (string.IsNullOrWhiteSpace(tagline))
  1063. {
  1064. throw new ArgumentNullException("tagline");
  1065. }
  1066. if (!Taglines.Contains(tagline, StringComparer.OrdinalIgnoreCase))
  1067. {
  1068. Taglines.Add(tagline);
  1069. }
  1070. }
  1071. /// <summary>
  1072. /// Adds a studio to the item
  1073. /// </summary>
  1074. /// <param name="name">The name.</param>
  1075. /// <exception cref="System.ArgumentNullException"></exception>
  1076. public void AddStudio(string name)
  1077. {
  1078. if (string.IsNullOrWhiteSpace(name))
  1079. {
  1080. throw new ArgumentNullException("name");
  1081. }
  1082. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1083. {
  1084. Studios.Add(name);
  1085. }
  1086. }
  1087. public void AddTag(string name)
  1088. {
  1089. if (string.IsNullOrWhiteSpace(name))
  1090. {
  1091. throw new ArgumentNullException("name");
  1092. }
  1093. if (!Tags.Contains(name, StringComparer.OrdinalIgnoreCase))
  1094. {
  1095. Tags.Add(name);
  1096. }
  1097. }
  1098. /// <summary>
  1099. /// Adds a genre to the item
  1100. /// </summary>
  1101. /// <param name="name">The name.</param>
  1102. /// <exception cref="System.ArgumentNullException"></exception>
  1103. public void AddGenre(string name)
  1104. {
  1105. if (string.IsNullOrWhiteSpace(name))
  1106. {
  1107. throw new ArgumentNullException("name");
  1108. }
  1109. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1110. {
  1111. Genres.Add(name);
  1112. }
  1113. }
  1114. /// <summary>
  1115. /// Adds the production location.
  1116. /// </summary>
  1117. /// <param name="location">The location.</param>
  1118. /// <exception cref="System.ArgumentNullException">location</exception>
  1119. public void AddProductionLocation(string location)
  1120. {
  1121. if (string.IsNullOrWhiteSpace(location))
  1122. {
  1123. throw new ArgumentNullException("location");
  1124. }
  1125. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1126. {
  1127. ProductionLocations.Add(location);
  1128. }
  1129. }
  1130. /// <summary>
  1131. /// Marks the played.
  1132. /// </summary>
  1133. /// <param name="user">The user.</param>
  1134. /// <param name="datePlayed">The date played.</param>
  1135. /// <param name="userManager">The user manager.</param>
  1136. /// <returns>Task.</returns>
  1137. /// <exception cref="System.ArgumentNullException"></exception>
  1138. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataRepository userManager)
  1139. {
  1140. if (user == null)
  1141. {
  1142. throw new ArgumentNullException();
  1143. }
  1144. var key = GetUserDataKey();
  1145. var data = userManager.GetUserData(user.Id, key);
  1146. data.PlayCount = Math.Max(data.PlayCount, 1);
  1147. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1148. data.Played = true;
  1149. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1150. }
  1151. /// <summary>
  1152. /// Marks the unplayed.
  1153. /// </summary>
  1154. /// <param name="user">The user.</param>
  1155. /// <param name="userManager">The user manager.</param>
  1156. /// <returns>Task.</returns>
  1157. /// <exception cref="System.ArgumentNullException"></exception>
  1158. public virtual async Task MarkUnplayed(User user, IUserDataRepository userManager)
  1159. {
  1160. if (user == null)
  1161. {
  1162. throw new ArgumentNullException();
  1163. }
  1164. var key = GetUserDataKey();
  1165. var data = userManager.GetUserData(user.Id, key);
  1166. //I think it is okay to do this here.
  1167. // if this is only called when a user is manually forcing something to un-played
  1168. // then it probably is what we want to do...
  1169. data.PlayCount = 0;
  1170. data.PlaybackPositionTicks = 0;
  1171. data.LastPlayedDate = null;
  1172. data.Played = false;
  1173. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1174. }
  1175. /// <summary>
  1176. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1177. /// </summary>
  1178. /// <returns>Task.</returns>
  1179. public virtual Task ChangedExternally()
  1180. {
  1181. return RefreshMetadata(CancellationToken.None);
  1182. }
  1183. /// <summary>
  1184. /// Finds a parent of a given type
  1185. /// </summary>
  1186. /// <typeparam name="T"></typeparam>
  1187. /// <returns>``0.</returns>
  1188. public T FindParent<T>()
  1189. where T : Folder
  1190. {
  1191. var parent = Parent;
  1192. while (parent != null)
  1193. {
  1194. var result = parent as T;
  1195. if (result != null)
  1196. {
  1197. return result;
  1198. }
  1199. parent = parent.Parent;
  1200. }
  1201. return null;
  1202. }
  1203. /// <summary>
  1204. /// Gets an image
  1205. /// </summary>
  1206. /// <param name="type">The type.</param>
  1207. /// <returns>System.String.</returns>
  1208. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1209. public string GetImage(ImageType type)
  1210. {
  1211. if (type == ImageType.Backdrop)
  1212. {
  1213. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1214. }
  1215. if (type == ImageType.Screenshot)
  1216. {
  1217. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1218. }
  1219. string val;
  1220. Images.TryGetValue(type, out val);
  1221. return val;
  1222. }
  1223. /// <summary>
  1224. /// Gets an image
  1225. /// </summary>
  1226. /// <param name="type">The type.</param>
  1227. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1228. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1229. public bool HasImage(ImageType type)
  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. return !string.IsNullOrEmpty(GetImage(type));
  1240. }
  1241. /// <summary>
  1242. /// Sets an image
  1243. /// </summary>
  1244. /// <param name="type">The type.</param>
  1245. /// <param name="path">The path.</param>
  1246. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1247. public void SetImage(ImageType type, string path)
  1248. {
  1249. if (type == ImageType.Backdrop)
  1250. {
  1251. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1252. }
  1253. if (type == ImageType.Screenshot)
  1254. {
  1255. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1256. }
  1257. var typeKey = type;
  1258. // If it's null remove the key from the dictionary
  1259. if (string.IsNullOrEmpty(path))
  1260. {
  1261. if (Images.ContainsKey(typeKey))
  1262. {
  1263. Images.Remove(typeKey);
  1264. }
  1265. }
  1266. else
  1267. {
  1268. Images[typeKey] = path;
  1269. }
  1270. }
  1271. /// <summary>
  1272. /// Deletes the image.
  1273. /// </summary>
  1274. /// <param name="type">The type.</param>
  1275. /// <param name="index">The index.</param>
  1276. /// <returns>Task.</returns>
  1277. public Task DeleteImage(ImageType type, int? index)
  1278. {
  1279. if (type == ImageType.Backdrop)
  1280. {
  1281. if (!index.HasValue)
  1282. {
  1283. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1284. }
  1285. var file = BackdropImagePaths[index.Value];
  1286. BackdropImagePaths.Remove(file);
  1287. // Delete the source file
  1288. File.Delete(file);
  1289. }
  1290. else if (type == ImageType.Screenshot)
  1291. {
  1292. if (!index.HasValue)
  1293. {
  1294. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1295. }
  1296. var file = ScreenshotImagePaths[index.Value];
  1297. ScreenshotImagePaths.Remove(file);
  1298. // Delete the source file
  1299. File.Delete(file);
  1300. }
  1301. else
  1302. {
  1303. // Delete the source file
  1304. File.Delete(GetImage(type));
  1305. // Remove it from the item
  1306. SetImage(type, null);
  1307. }
  1308. // Refresh metadata
  1309. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1310. }
  1311. /// <summary>
  1312. /// Validates that images within the item are still on the file system
  1313. /// </summary>
  1314. public void ValidateImages()
  1315. {
  1316. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1317. var deletedKeys = Images
  1318. .Where(image => !File.Exists(image.Value))
  1319. .Select(i => i.Key)
  1320. .ToList();
  1321. // Now remove them from the dictionary
  1322. foreach (var key in deletedKeys)
  1323. {
  1324. Images.Remove(key);
  1325. }
  1326. }
  1327. /// <summary>
  1328. /// Validates that backdrops within the item are still on the file system
  1329. /// </summary>
  1330. public void ValidateBackdrops()
  1331. {
  1332. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1333. var deletedImages = BackdropImagePaths
  1334. .Where(path => !File.Exists(path))
  1335. .ToList();
  1336. // Now remove them from the dictionary
  1337. foreach (var path in deletedImages)
  1338. {
  1339. BackdropImagePaths.Remove(path);
  1340. }
  1341. }
  1342. /// <summary>
  1343. /// Validates the screenshots.
  1344. /// </summary>
  1345. public void ValidateScreenshots()
  1346. {
  1347. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1348. var deletedImages = ScreenshotImagePaths
  1349. .Where(path => !File.Exists(path))
  1350. .ToList();
  1351. // Now remove them from the dictionary
  1352. foreach (var path in deletedImages)
  1353. {
  1354. ScreenshotImagePaths.Remove(path);
  1355. }
  1356. }
  1357. /// <summary>
  1358. /// Gets the image path.
  1359. /// </summary>
  1360. /// <param name="imageType">Type of the image.</param>
  1361. /// <param name="imageIndex">Index of the image.</param>
  1362. /// <returns>System.String.</returns>
  1363. /// <exception cref="System.InvalidOperationException">
  1364. /// </exception>
  1365. /// <exception cref="System.ArgumentNullException">item</exception>
  1366. public string GetImagePath(ImageType imageType, int imageIndex)
  1367. {
  1368. if (imageType == ImageType.Backdrop)
  1369. {
  1370. return BackdropImagePaths[imageIndex];
  1371. }
  1372. if (imageType == ImageType.Screenshot)
  1373. {
  1374. return ScreenshotImagePaths[imageIndex];
  1375. }
  1376. if (imageType == ImageType.Chapter)
  1377. {
  1378. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1379. }
  1380. return GetImage(imageType);
  1381. }
  1382. /// <summary>
  1383. /// Gets the image date modified.
  1384. /// </summary>
  1385. /// <param name="imagePath">The image path.</param>
  1386. /// <returns>DateTime.</returns>
  1387. /// <exception cref="System.ArgumentNullException">item</exception>
  1388. public DateTime GetImageDateModified(string imagePath)
  1389. {
  1390. if (string.IsNullOrEmpty(imagePath))
  1391. {
  1392. throw new ArgumentNullException("imagePath");
  1393. }
  1394. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1395. // If we didn't the metafile entry, check the Season
  1396. if (metaFileEntry == null)
  1397. {
  1398. var episode = this as Episode;
  1399. if (episode != null && episode.Season != null)
  1400. {
  1401. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  1402. }
  1403. }
  1404. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1405. return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.LastWriteTimeUtc;
  1406. }
  1407. }
  1408. }