DefaultIntroProvider.cs 14 KB

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