BaseItem.cs 60 KB

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