BaseItem.cs 57 KB

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