DefaultIntroProvider.cs 15 KB

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