BaseItem.cs 60 KB

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