BaseItem.cs 60 KB

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