DefaultIntroProvider.cs 15 KB

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