DefaultIntroProvider.cs 15 KB

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