DefaultIntroProvider.cs 14 KB

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