DefaultIntroProvider.cs 12 KB

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