BaseItem.cs 59 KB

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