DefaultIntroProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Security;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Controller.Entities.TV;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Localization;
  9. using MediaBrowser.Model.Channels;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Entities;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Intros
  19. {
  20. public class DefaultIntroProvider : IIntroProvider
  21. {
  22. private readonly ISecurityManager _security;
  23. private readonly IChannelManager _channelManager;
  24. private readonly ILocalizationManager _localization;
  25. private readonly IConfigurationManager _serverConfig;
  26. private readonly ILibraryManager _libraryManager;
  27. public DefaultIntroProvider(ISecurityManager security, IChannelManager channelManager, ILocalizationManager localization, IConfigurationManager serverConfig, ILibraryManager libraryManager)
  28. {
  29. _security = security;
  30. _channelManager = channelManager;
  31. _localization = localization;
  32. _serverConfig = serverConfig;
  33. _libraryManager = libraryManager;
  34. }
  35. public async Task<IEnumerable<IntroInfo>> GetIntros(BaseItem item, User user)
  36. {
  37. if (!user.Configuration.EnableCinemaMode)
  38. {
  39. return new List<IntroInfo>();
  40. }
  41. var config = GetOptions();
  42. if (item is Movie)
  43. {
  44. if (!config.EnableIntrosForMovies)
  45. {
  46. return new List<IntroInfo>();
  47. }
  48. }
  49. else if (item is Episode)
  50. {
  51. if (!config.EnableIntrosForEpisodes)
  52. {
  53. return new List<IntroInfo>();
  54. }
  55. }
  56. else
  57. {
  58. return new List<IntroInfo>();
  59. }
  60. var ratingLevel = string.IsNullOrWhiteSpace(item.OfficialRating)
  61. ? null
  62. : _localization.GetRatingLevel(item.OfficialRating);
  63. var random = new Random(Environment.TickCount + Guid.NewGuid().GetHashCode());
  64. var candidates = new List<ItemWithTrailer>();
  65. var itemPeople = _libraryManager.GetPeople(item);
  66. var allPeople = _libraryManager.GetPeople(new InternalPeopleQuery
  67. {
  68. AppearsInItemId = item.Id
  69. });
  70. if (config.EnableIntrosFromMoviesInLibrary)
  71. {
  72. var itemsWithTrailers = user.RootFolder
  73. .GetRecursiveChildren(user, i =>
  74. {
  75. var hasTrailers = i as IHasTrailers;
  76. if (hasTrailers != null && hasTrailers.LocalTrailerIds.Count > 0)
  77. {
  78. if (i is Movie)
  79. {
  80. return !IsDuplicate(item, i);
  81. }
  82. }
  83. return false;
  84. });
  85. candidates.AddRange(itemsWithTrailers.Select(i => new ItemWithTrailer
  86. {
  87. Item = i,
  88. Type = ItemWithTrailerType.ItemWithTrailer,
  89. User = user,
  90. WatchingItem = item,
  91. WatchingItemPeople = itemPeople,
  92. AllPeople = allPeople,
  93. Random = random,
  94. LibraryManager = _libraryManager
  95. }));
  96. }
  97. var trailerTypes = new List<TrailerType>();
  98. if (config.EnableIntrosFromUpcomingTrailers)
  99. {
  100. trailerTypes.Add(TrailerType.ComingSoonToTheaters);
  101. }
  102. if (config.EnableIntrosFromUpcomingDvdMovies)
  103. {
  104. trailerTypes.Add(TrailerType.ComingSoonToDvd);
  105. }
  106. if (config.EnableIntrosFromUpcomingStreamingMovies)
  107. {
  108. trailerTypes.Add(TrailerType.ComingSoonToStreaming);
  109. }
  110. if (config.EnableIntrosFromSimilarMovies)
  111. {
  112. trailerTypes.Add(TrailerType.Archive);
  113. }
  114. if (trailerTypes.Count > 0 && IsSupporter)
  115. {
  116. var channelTrailers = await _channelManager.GetAllMediaInternal(new AllChannelMediaQuery
  117. {
  118. ContentTypes = new[] { ChannelMediaContentType.MovieExtra },
  119. ExtraTypes = new[] { ExtraType.Trailer },
  120. UserId = user.Id.ToString("N"),
  121. TrailerTypes = trailerTypes.ToArray()
  122. }, CancellationToken.None);
  123. candidates.AddRange(channelTrailers.Items.Select(i => new ItemWithTrailer
  124. {
  125. Item = i,
  126. Type = ItemWithTrailerType.ChannelTrailer,
  127. User = user,
  128. WatchingItem = item,
  129. WatchingItemPeople = itemPeople,
  130. AllPeople = allPeople,
  131. Random = random,
  132. LibraryManager = _libraryManager
  133. }));
  134. }
  135. return GetResult(item, candidates, config, ratingLevel);
  136. }
  137. private IEnumerable<IntroInfo> GetResult(BaseItem item, IEnumerable<ItemWithTrailer> candidates, CinemaModeConfiguration config, int? ratingLevel)
  138. {
  139. var customIntros = !string.IsNullOrWhiteSpace(config.CustomIntroPath) ?
  140. GetCustomIntros(item) :
  141. new List<IntroInfo>();
  142. var trailerLimit = config.TrailerLimit;
  143. // Avoid implicitly captured closure
  144. return candidates.Where(i =>
  145. {
  146. if (config.EnableIntrosParentalControl && !FilterByParentalRating(ratingLevel, i.Item))
  147. {
  148. return false;
  149. }
  150. if (!config.EnableIntrosForWatchedContent && i.IsPlayed)
  151. {
  152. return false;
  153. }
  154. return !IsDuplicate(item, i.Item);
  155. })
  156. .OrderByDescending(i => i.Score)
  157. .ThenBy(i => Guid.NewGuid())
  158. .ThenByDescending(i => (i.IsPlayed ? 0 : 1))
  159. .Select(i => i.IntroInfo)
  160. .Take(trailerLimit)
  161. .Concat(customIntros.Take(1));
  162. }
  163. private bool IsDuplicate(BaseItem playingContent, BaseItem test)
  164. {
  165. var id = playingContent.GetProviderId(MetadataProviders.Imdb);
  166. if (!string.IsNullOrWhiteSpace(id) && string.Equals(id, test.GetProviderId(MetadataProviders.Imdb), StringComparison.OrdinalIgnoreCase))
  167. {
  168. return true;
  169. }
  170. id = playingContent.GetProviderId(MetadataProviders.Tmdb);
  171. if (!string.IsNullOrWhiteSpace(id) && string.Equals(id, test.GetProviderId(MetadataProviders.Tmdb), StringComparison.OrdinalIgnoreCase))
  172. {
  173. return true;
  174. }
  175. return false;
  176. }
  177. private CinemaModeConfiguration GetOptions()
  178. {
  179. return _serverConfig.GetConfiguration<CinemaModeConfiguration>("cinemamode");
  180. }
  181. private List<IntroInfo> GetCustomIntros(BaseItem item)
  182. {
  183. try
  184. {
  185. return GetCustomIntroFiles()
  186. .OrderBy(i => Guid.NewGuid())
  187. .Select(i => new IntroInfo
  188. {
  189. Path = i
  190. }).ToList();
  191. }
  192. catch (IOException)
  193. {
  194. return new List<IntroInfo>();
  195. }
  196. }
  197. private IEnumerable<string> GetCustomIntroFiles(CinemaModeConfiguration options = null)
  198. {
  199. options = options ?? GetOptions();
  200. if (string.IsNullOrWhiteSpace(options.CustomIntroPath))
  201. {
  202. return new List<string>();
  203. }
  204. return Directory.EnumerateFiles(options.CustomIntroPath, "*", SearchOption.AllDirectories)
  205. .Where(_libraryManager.IsVideoFile);
  206. }
  207. private bool FilterByParentalRating(int? ratingLevel, BaseItem item)
  208. {
  209. // Only content rated same or lower
  210. if (ratingLevel.HasValue)
  211. {
  212. var level = string.IsNullOrWhiteSpace(item.OfficialRating)
  213. ? (int?)null
  214. : _localization.GetRatingLevel(item.OfficialRating);
  215. return level.HasValue && level.Value <= ratingLevel.Value;
  216. }
  217. return true;
  218. }
  219. internal static int GetSimiliarityScore(BaseItem item1, List<PersonInfo> item1People, List<PersonInfo> allPeople, BaseItem item2, Random random, ILibraryManager libraryManager)
  220. {
  221. var points = 0;
  222. if (!string.IsNullOrEmpty(item1.OfficialRating) && string.Equals(item1.OfficialRating, item2.OfficialRating, StringComparison.OrdinalIgnoreCase))
  223. {
  224. points += 10;
  225. }
  226. // Find common genres
  227. points += item1.Genres.Where(i => item2.Genres.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  228. // Find common tags
  229. points += GetTags(item1).Where(i => GetTags(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  230. // Find common keywords
  231. points += GetKeywords(item1).Where(i => GetKeywords(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  232. // Find common studios
  233. points += item1.Studios.Where(i => item2.Studios.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 5);
  234. var item2PeopleNames = allPeople.Where(i => i.ItemId == item2.Id)
  235. .Select(i => i.Name)
  236. .Where(i => !string.IsNullOrWhiteSpace(i))
  237. .DistinctNames()
  238. .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  239. points += item1People.Where(i => item2PeopleNames.ContainsKey(i.Name)).Sum(i =>
  240. {
  241. if (string.Equals(i.Type, PersonType.Director, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  242. {
  243. return 5;
  244. }
  245. if (string.Equals(i.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  246. {
  247. return 3;
  248. }
  249. if (string.Equals(i.Type, PersonType.Composer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Composer, StringComparison.OrdinalIgnoreCase))
  250. {
  251. return 3;
  252. }
  253. if (string.Equals(i.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  254. {
  255. return 3;
  256. }
  257. if (string.Equals(i.Type, PersonType.Writer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  258. {
  259. return 2;
  260. }
  261. return 1;
  262. });
  263. // Add some randomization so that you're not always seeing the same ones for a given movie
  264. points += random.Next(0, 50);
  265. return points;
  266. }
  267. private static IEnumerable<string> GetTags(BaseItem item)
  268. {
  269. var hasTags = item as IHasTags;
  270. if (hasTags != null)
  271. {
  272. return hasTags.Tags;
  273. }
  274. return new List<string>();
  275. }
  276. private static IEnumerable<string> GetKeywords(BaseItem item)
  277. {
  278. var hasTags = item as IHasKeywords;
  279. if (hasTags != null)
  280. {
  281. return hasTags.Keywords;
  282. }
  283. return new List<string>();
  284. }
  285. public IEnumerable<string> GetAllIntroFiles()
  286. {
  287. return GetCustomIntroFiles();
  288. }
  289. private bool IsSupporter
  290. {
  291. get { return _security.IsMBSupporter; }
  292. }
  293. public string Name
  294. {
  295. get { return "Default"; }
  296. }
  297. internal class ItemWithTrailer
  298. {
  299. internal BaseItem Item;
  300. internal ItemWithTrailerType Type;
  301. internal User User;
  302. internal BaseItem WatchingItem;
  303. internal List<PersonInfo> WatchingItemPeople;
  304. internal List<PersonInfo> AllPeople;
  305. internal Random Random;
  306. internal ILibraryManager LibraryManager;
  307. private bool? _isPlayed;
  308. public bool IsPlayed
  309. {
  310. get
  311. {
  312. if (!_isPlayed.HasValue)
  313. {
  314. _isPlayed = Item.IsPlayed(User);
  315. }
  316. return _isPlayed.Value;
  317. }
  318. }
  319. private int? _score;
  320. public int Score
  321. {
  322. get
  323. {
  324. if (!_score.HasValue)
  325. {
  326. _score = GetSimiliarityScore(WatchingItem, WatchingItemPeople, AllPeople, Item, Random, LibraryManager);
  327. }
  328. return _score.Value;
  329. }
  330. }
  331. public IntroInfo IntroInfo
  332. {
  333. get
  334. {
  335. var id = Item.Id;
  336. if (Type == ItemWithTrailerType.ItemWithTrailer)
  337. {
  338. var hasTrailers = Item as IHasTrailers;
  339. if (hasTrailers != null)
  340. {
  341. id = hasTrailers.LocalTrailerIds.FirstOrDefault();
  342. }
  343. }
  344. return new IntroInfo
  345. {
  346. ItemId = id
  347. };
  348. }
  349. }
  350. }
  351. internal enum ItemWithTrailerType
  352. {
  353. LibraryTrailer,
  354. ChannelTrailer,
  355. ItemWithTrailer
  356. }
  357. }
  358. public class CinemaModeConfigurationFactory : IConfigurationFactory
  359. {
  360. public IEnumerable<ConfigurationStore> GetConfigurations()
  361. {
  362. return new[]
  363. {
  364. new ConfigurationStore
  365. {
  366. ConfigurationType = typeof(CinemaModeConfiguration),
  367. Key = "cinemamode"
  368. }
  369. };
  370. }
  371. }
  372. }