DefaultIntroProvider.cs 13 KB

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