DefaultIntroProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 (trailerTypes.Count > 0 && IsSupporter)
  100. {
  101. var channelTrailers = await _channelManager.GetAllMediaInternal(new AllChannelMediaQuery
  102. {
  103. ContentTypes = new[] { ChannelMediaContentType.MovieExtra },
  104. ExtraTypes = new[] { ExtraType.Trailer },
  105. UserId = user.Id.ToString("N"),
  106. TrailerTypes = trailerTypes.ToArray()
  107. }, CancellationToken.None);
  108. candidates.AddRange(channelTrailers.Items.Select(i => new ItemWithTrailer
  109. {
  110. Item = i,
  111. Type = ItemWithTrailerType.ChannelTrailer,
  112. User = user,
  113. WatchingItem = item,
  114. Random = random
  115. }));
  116. candidates.AddRange(libaryItems.Where(i => i is Trailer).Select(i => new ItemWithTrailer
  117. {
  118. Item = i,
  119. Type = ItemWithTrailerType.LibraryTrailer,
  120. User = user,
  121. WatchingItem = item,
  122. Random = random
  123. }));
  124. }
  125. var customIntros = !string.IsNullOrWhiteSpace(config.CustomIntroPath) ?
  126. GetCustomIntros(item) :
  127. new List<IntroInfo>();
  128. var trailerLimit = 2;
  129. if (customIntros.Count > 0)
  130. {
  131. trailerLimit--;
  132. }
  133. // Avoid implicitly captured closure
  134. return candidates.Where(i =>
  135. {
  136. if (config.EnableIntrosParentalControl && !FilterByParentalRating(ratingLevel, i.Item))
  137. {
  138. return false;
  139. }
  140. if (!config.EnableIntrosForWatchedContent && i.IsPlayed)
  141. {
  142. return false;
  143. }
  144. return !IsDuplicate(item, i.Item);
  145. })
  146. .OrderByDescending(i => i.Score)
  147. .ThenBy(i => Guid.NewGuid())
  148. .ThenByDescending(i => (i.IsPlayed ? 0 : 1))
  149. .Select(i => i.IntroInfo)
  150. .Take(trailerLimit)
  151. .Concat(customIntros.Take(1));
  152. }
  153. private bool IsDuplicate(BaseItem playingContent, BaseItem test)
  154. {
  155. var id = playingContent.GetProviderId(MetadataProviders.Imdb);
  156. if (!string.IsNullOrWhiteSpace(id) && string.Equals(id, test.GetProviderId(MetadataProviders.Imdb), StringComparison.OrdinalIgnoreCase))
  157. {
  158. return true;
  159. }
  160. id = playingContent.GetProviderId(MetadataProviders.Tmdb);
  161. if (!string.IsNullOrWhiteSpace(id) && string.Equals(id, test.GetProviderId(MetadataProviders.Tmdb), StringComparison.OrdinalIgnoreCase))
  162. {
  163. return true;
  164. }
  165. return false;
  166. }
  167. private CinemaModeConfiguration GetOptions()
  168. {
  169. return _serverConfig.GetConfiguration<CinemaModeConfiguration>("cinemamode");
  170. }
  171. private List<IntroInfo> GetCustomIntros(BaseItem item)
  172. {
  173. try
  174. {
  175. return GetCustomIntroFiles()
  176. .OrderBy(i => Guid.NewGuid())
  177. .Select(i => new IntroInfo
  178. {
  179. Path = i
  180. }).ToList();
  181. }
  182. catch (IOException)
  183. {
  184. return new List<IntroInfo>();
  185. }
  186. }
  187. private IEnumerable<string> GetCustomIntroFiles(CinemaModeConfiguration options = null)
  188. {
  189. options = options ?? GetOptions();
  190. if (string.IsNullOrWhiteSpace(options.CustomIntroPath))
  191. {
  192. return new List<string>();
  193. }
  194. return Directory.EnumerateFiles(options.CustomIntroPath, "*", SearchOption.AllDirectories)
  195. .Where(EntityResolutionHelper.IsVideoFile);
  196. }
  197. private bool FilterByParentalRating(int? ratingLevel, BaseItem item)
  198. {
  199. // Only content rated same or lower
  200. if (ratingLevel.HasValue)
  201. {
  202. var level = string.IsNullOrWhiteSpace(item.OfficialRating)
  203. ? (int?)null
  204. : _localization.GetRatingLevel(item.OfficialRating);
  205. return level.HasValue && level.Value <= ratingLevel.Value;
  206. }
  207. return true;
  208. }
  209. internal static int GetSimiliarityScore(BaseItem item1, BaseItem item2, Random random)
  210. {
  211. var points = 0;
  212. if (!string.IsNullOrEmpty(item1.OfficialRating) && string.Equals(item1.OfficialRating, item2.OfficialRating, StringComparison.OrdinalIgnoreCase))
  213. {
  214. points += 10;
  215. }
  216. // Find common genres
  217. points += item1.Genres.Where(i => item2.Genres.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  218. // Find common tags
  219. points += GetTags(item1).Where(i => GetTags(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  220. // Find common keywords
  221. points += GetKeywords(item1).Where(i => GetKeywords(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  222. // Find common studios
  223. points += item1.Studios.Where(i => item2.Studios.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 5);
  224. var item2PeopleNames = item2.People.Select(i => i.Name)
  225. .Distinct(StringComparer.OrdinalIgnoreCase)
  226. .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  227. points += item1.People.Where(i => item2PeopleNames.ContainsKey(i.Name)).Sum(i =>
  228. {
  229. if (string.Equals(i.Type, PersonType.Director, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  230. {
  231. return 5;
  232. }
  233. if (string.Equals(i.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  234. {
  235. return 3;
  236. }
  237. if (string.Equals(i.Type, PersonType.Composer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Composer, StringComparison.OrdinalIgnoreCase))
  238. {
  239. return 3;
  240. }
  241. if (string.Equals(i.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  242. {
  243. return 3;
  244. }
  245. if (string.Equals(i.Type, PersonType.Writer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  246. {
  247. return 2;
  248. }
  249. return 1;
  250. });
  251. // Add some randomization so that you're not always seeing the same ones for a given movie
  252. points += random.Next(0, 50);
  253. return points;
  254. }
  255. private static IEnumerable<string> GetTags(BaseItem item)
  256. {
  257. var hasTags = item as IHasTags;
  258. if (hasTags != null)
  259. {
  260. return hasTags.Tags;
  261. }
  262. return new List<string>();
  263. }
  264. private static IEnumerable<string> GetKeywords(BaseItem item)
  265. {
  266. var hasTags = item as IHasKeywords;
  267. if (hasTags != null)
  268. {
  269. return hasTags.Keywords;
  270. }
  271. return new List<string>();
  272. }
  273. public IEnumerable<string> GetAllIntroFiles()
  274. {
  275. return GetCustomIntroFiles();
  276. }
  277. private bool IsSupporter
  278. {
  279. get { return _security.IsMBSupporter; }
  280. }
  281. public string Name
  282. {
  283. get { return "Default"; }
  284. }
  285. internal class ItemWithTrailer
  286. {
  287. internal BaseItem Item;
  288. internal ItemWithTrailerType Type;
  289. internal User User;
  290. internal BaseItem WatchingItem;
  291. internal Random Random;
  292. private bool? _isPlayed;
  293. public bool IsPlayed
  294. {
  295. get
  296. {
  297. if (!_isPlayed.HasValue)
  298. {
  299. _isPlayed = Item.IsPlayed(User);
  300. }
  301. return _isPlayed.Value;
  302. }
  303. }
  304. private int? _score;
  305. public int Score
  306. {
  307. get
  308. {
  309. if (!_score.HasValue)
  310. {
  311. _score = GetSimiliarityScore(WatchingItem, Item, Random);
  312. }
  313. return _score.Value;
  314. }
  315. }
  316. public IntroInfo IntroInfo
  317. {
  318. get
  319. {
  320. var id = Item.Id;
  321. if (Type == ItemWithTrailerType.ItemWithTrailer)
  322. {
  323. var hasTrailers = Item as IHasTrailers;
  324. if (hasTrailers != null)
  325. {
  326. id = hasTrailers.LocalTrailerIds.FirstOrDefault();
  327. }
  328. }
  329. return new IntroInfo
  330. {
  331. ItemId = id
  332. };
  333. }
  334. }
  335. }
  336. internal enum ItemWithTrailerType
  337. {
  338. LibraryTrailer,
  339. ChannelTrailer,
  340. ItemWithTrailer
  341. }
  342. }
  343. public class CinemaModeConfigurationFactory : IConfigurationFactory
  344. {
  345. public IEnumerable<ConfigurationStore> GetConfigurations()
  346. {
  347. return new[]
  348. {
  349. new ConfigurationStore
  350. {
  351. ConfigurationType = typeof(CinemaModeConfiguration),
  352. Key = "cinemamode"
  353. }
  354. };
  355. }
  356. }
  357. }