DefaultIntroProvider.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. using MoreLinq;
  21. namespace MediaBrowser.Server.Implementations.Intros
  22. {
  23. public class DefaultIntroProvider : IIntroProvider
  24. {
  25. private readonly ISecurityManager _security;
  26. private readonly IChannelManager _channelManager;
  27. private readonly ILocalizationManager _localization;
  28. private readonly IConfigurationManager _serverConfig;
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly IMediaSourceManager _mediaSourceManager;
  32. public DefaultIntroProvider(ISecurityManager security, IChannelManager channelManager, ILocalizationManager localization, IConfigurationManager serverConfig, ILibraryManager libraryManager, IFileSystem fileSystem, IMediaSourceManager mediaSourceManager)
  33. {
  34. _security = security;
  35. _channelManager = channelManager;
  36. _localization = localization;
  37. _serverConfig = serverConfig;
  38. _libraryManager = libraryManager;
  39. _fileSystem = fileSystem;
  40. _mediaSourceManager = mediaSourceManager;
  41. }
  42. public async Task<IEnumerable<IntroInfo>> GetIntros(BaseItem item, User user)
  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 inputItems = _libraryManager.GetItems(new InternalItemsQuery(user)
  76. {
  77. IncludeItemTypes = new[] { typeof(Movie).Name }
  78. }, new string[] { });
  79. var itemsWithTrailers = inputItems
  80. .Where(i =>
  81. {
  82. var hasTrailers = i as IHasTrailers;
  83. if (hasTrailers != null && hasTrailers.LocalTrailerIds.Count > 0)
  84. {
  85. if (i is Movie)
  86. {
  87. return !IsDuplicate(item, i);
  88. }
  89. }
  90. return false;
  91. });
  92. candidates.AddRange(itemsWithTrailers.Select(i => new ItemWithTrailer
  93. {
  94. Item = i,
  95. Type = ItemWithTrailerType.ItemWithTrailer,
  96. User = user,
  97. WatchingItem = item,
  98. WatchingItemPeople = itemPeople,
  99. AllPeople = allPeople,
  100. Random = random,
  101. LibraryManager = _libraryManager
  102. }));
  103. }
  104. var trailerTypes = new List<TrailerType>();
  105. if (config.EnableIntrosFromUpcomingTrailers)
  106. {
  107. trailerTypes.Add(TrailerType.ComingSoonToTheaters);
  108. }
  109. if (config.EnableIntrosFromUpcomingDvdMovies)
  110. {
  111. trailerTypes.Add(TrailerType.ComingSoonToDvd);
  112. }
  113. if (config.EnableIntrosFromUpcomingStreamingMovies)
  114. {
  115. trailerTypes.Add(TrailerType.ComingSoonToStreaming);
  116. }
  117. if (config.EnableIntrosFromSimilarMovies)
  118. {
  119. trailerTypes.Add(TrailerType.Archive);
  120. }
  121. if (trailerTypes.Count > 0 && IsSupporter)
  122. {
  123. var channelTrailers = await _channelManager.GetAllMediaInternal(new AllChannelMediaQuery
  124. {
  125. ContentTypes = new[] { ChannelMediaContentType.MovieExtra },
  126. ExtraTypes = new[] { ExtraType.Trailer },
  127. UserId = user.Id.ToString("N"),
  128. TrailerTypes = trailerTypes.ToArray()
  129. }, CancellationToken.None);
  130. candidates.AddRange(channelTrailers.Items.Select(i => new ItemWithTrailer
  131. {
  132. Item = i,
  133. Type = ItemWithTrailerType.ChannelTrailer,
  134. User = user,
  135. WatchingItem = item,
  136. WatchingItemPeople = itemPeople,
  137. AllPeople = allPeople,
  138. Random = random,
  139. LibraryManager = _libraryManager
  140. }));
  141. }
  142. return GetResult(item, candidates, config, ratingLevel);
  143. }
  144. private IEnumerable<IntroInfo> GetResult(BaseItem item, IEnumerable<ItemWithTrailer> candidates, CinemaModeConfiguration config, int? ratingLevel)
  145. {
  146. var customIntros = !string.IsNullOrWhiteSpace(config.CustomIntroPath) ?
  147. GetCustomIntros(config) :
  148. new List<IntroInfo>();
  149. var mediaInfoIntros = !string.IsNullOrWhiteSpace(config.MediaInfoIntroPath) ?
  150. GetMediaInfoIntros(config, item) :
  151. new List<IntroInfo>();
  152. var trailerLimit = config.TrailerLimit;
  153. // Avoid implicitly captured closure
  154. return candidates.Where(i =>
  155. {
  156. if (config.EnableIntrosParentalControl && !FilterByParentalRating(ratingLevel, i.Item))
  157. {
  158. return false;
  159. }
  160. if (!config.EnableIntrosForWatchedContent && i.IsPlayed)
  161. {
  162. return false;
  163. }
  164. return !IsDuplicate(item, i.Item);
  165. })
  166. .OrderByDescending(i => i.Score)
  167. .ThenBy(i => Guid.NewGuid())
  168. .ThenByDescending(i => (i.IsPlayed ? 0 : 1))
  169. .Select(i => i.IntroInfo)
  170. .Take(trailerLimit)
  171. .Concat(customIntros.Take(1))
  172. .Concat(mediaInfoIntros);
  173. }
  174. private bool IsDuplicate(BaseItem playingContent, BaseItem test)
  175. {
  176. var id = playingContent.GetProviderId(MetadataProviders.Imdb);
  177. if (!string.IsNullOrWhiteSpace(id) && string.Equals(id, test.GetProviderId(MetadataProviders.Imdb), StringComparison.OrdinalIgnoreCase))
  178. {
  179. return true;
  180. }
  181. id = playingContent.GetProviderId(MetadataProviders.Tmdb);
  182. if (!string.IsNullOrWhiteSpace(id) && string.Equals(id, test.GetProviderId(MetadataProviders.Tmdb), StringComparison.OrdinalIgnoreCase))
  183. {
  184. return true;
  185. }
  186. return false;
  187. }
  188. private CinemaModeConfiguration GetOptions()
  189. {
  190. return _serverConfig.GetConfiguration<CinemaModeConfiguration>("cinemamode");
  191. }
  192. private List<IntroInfo> GetCustomIntros(CinemaModeConfiguration options)
  193. {
  194. try
  195. {
  196. return GetCustomIntroFiles(options, true, false)
  197. .OrderBy(i => Guid.NewGuid())
  198. .Select(i => new IntroInfo
  199. {
  200. Path = i
  201. }).ToList();
  202. }
  203. catch (IOException)
  204. {
  205. return new List<IntroInfo>();
  206. }
  207. }
  208. private IEnumerable<IntroInfo> GetMediaInfoIntros(CinemaModeConfiguration options, BaseItem item)
  209. {
  210. try
  211. {
  212. var hasMediaSources = item as IHasMediaSources;
  213. if (hasMediaSources == null)
  214. {
  215. return new List<IntroInfo>();
  216. }
  217. var mediaSource = _mediaSourceManager.GetStaticMediaSources(hasMediaSources, false)
  218. .FirstOrDefault();
  219. if (mediaSource == null)
  220. {
  221. return new List<IntroInfo>();
  222. }
  223. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  224. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  225. var allIntros = GetCustomIntroFiles(options, false, true)
  226. .OrderBy(i => Guid.NewGuid())
  227. .Select(i => new IntroInfo
  228. {
  229. Path = i
  230. }).ToList();
  231. var returnResult = new List<IntroInfo>();
  232. if (videoStream != null)
  233. {
  234. returnResult.AddRange(GetMediaInfoIntrosByVideoStream(allIntros, videoStream).Take(1));
  235. }
  236. if (audioStream != null)
  237. {
  238. returnResult.AddRange(GetMediaInfoIntrosByAudioStream(allIntros, audioStream).Take(1));
  239. }
  240. returnResult.AddRange(GetMediaInfoIntrosByTags(allIntros, item.Tags).Take(1));
  241. return returnResult.DistinctBy(i => i.Path, StringComparer.OrdinalIgnoreCase);
  242. }
  243. catch (IOException)
  244. {
  245. return new List<IntroInfo>();
  246. }
  247. }
  248. private IEnumerable<IntroInfo> GetMediaInfoIntrosByVideoStream(List<IntroInfo> allIntros, MediaStream stream)
  249. {
  250. var codec = stream.Codec;
  251. if (string.IsNullOrWhiteSpace(codec))
  252. {
  253. return new List<IntroInfo>();
  254. }
  255. return allIntros
  256. .Where(i => IsMatch(i.Path, codec));
  257. }
  258. private IEnumerable<IntroInfo> GetMediaInfoIntrosByAudioStream(List<IntroInfo> allIntros, MediaStream stream)
  259. {
  260. var codec = stream.Codec;
  261. if (string.IsNullOrWhiteSpace(codec))
  262. {
  263. return new List<IntroInfo>();
  264. }
  265. return allIntros
  266. .Where(i => IsAudioMatch(i.Path, stream));
  267. }
  268. private IEnumerable<IntroInfo> GetMediaInfoIntrosByTags(List<IntroInfo> allIntros, List<string> tags)
  269. {
  270. return allIntros
  271. .Where(i => tags.Any(t => IsMatch(i.Path, t)));
  272. }
  273. private bool IsMatch(string file, string attribute)
  274. {
  275. var filename = Path.GetFileNameWithoutExtension(file) ?? string.Empty;
  276. filename = Normalize(filename);
  277. if (string.IsNullOrWhiteSpace(filename))
  278. {
  279. return false;
  280. }
  281. attribute = Normalize(attribute);
  282. if (string.IsNullOrWhiteSpace(attribute))
  283. {
  284. return false;
  285. }
  286. return string.Equals(filename, attribute, StringComparison.OrdinalIgnoreCase);
  287. }
  288. private string Normalize(string value)
  289. {
  290. return value;
  291. }
  292. private bool IsAudioMatch(string path, MediaStream stream)
  293. {
  294. if (!string.IsNullOrWhiteSpace(stream.Codec))
  295. {
  296. if (IsMatch(path, stream.Codec))
  297. {
  298. return true;
  299. }
  300. }
  301. if (!string.IsNullOrWhiteSpace(stream.Profile))
  302. {
  303. if (IsMatch(path, stream.Profile))
  304. {
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. private IEnumerable<string> GetCustomIntroFiles(CinemaModeConfiguration options, bool enableCustomIntros, bool enableMediaInfoIntros)
  311. {
  312. var list = new List<string>();
  313. if (enableCustomIntros && !string.IsNullOrWhiteSpace(options.CustomIntroPath))
  314. {
  315. list.AddRange(_fileSystem.GetFilePaths(options.CustomIntroPath, true)
  316. .Where(_libraryManager.IsVideoFile));
  317. }
  318. if (enableMediaInfoIntros && !string.IsNullOrWhiteSpace(options.MediaInfoIntroPath))
  319. {
  320. list.AddRange(_fileSystem.GetFilePaths(options.MediaInfoIntroPath, true)
  321. .Where(_libraryManager.IsVideoFile));
  322. }
  323. return list.Distinct(StringComparer.OrdinalIgnoreCase);
  324. }
  325. private bool FilterByParentalRating(int? ratingLevel, BaseItem item)
  326. {
  327. // Only content rated same or lower
  328. if (ratingLevel.HasValue)
  329. {
  330. var level = string.IsNullOrWhiteSpace(item.OfficialRating)
  331. ? (int?)null
  332. : _localization.GetRatingLevel(item.OfficialRating);
  333. return level.HasValue && level.Value <= ratingLevel.Value;
  334. }
  335. return true;
  336. }
  337. internal static int GetSimiliarityScore(BaseItem item1, List<PersonInfo> item1People, List<PersonInfo> allPeople, BaseItem item2, Random random, ILibraryManager libraryManager)
  338. {
  339. var points = 0;
  340. if (!string.IsNullOrEmpty(item1.OfficialRating) && string.Equals(item1.OfficialRating, item2.OfficialRating, StringComparison.OrdinalIgnoreCase))
  341. {
  342. points += 10;
  343. }
  344. // Find common genres
  345. points += item1.Genres.Where(i => item2.Genres.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  346. // Find common tags
  347. points += GetTags(item1).Where(i => GetTags(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  348. // Find common keywords
  349. points += GetKeywords(item1).Where(i => GetKeywords(item2).Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 10);
  350. // Find common studios
  351. points += item1.Studios.Where(i => item2.Studios.Contains(i, StringComparer.OrdinalIgnoreCase)).Sum(i => 5);
  352. var item2PeopleNames = allPeople.Where(i => i.ItemId == item2.Id)
  353. .Select(i => i.Name)
  354. .Where(i => !string.IsNullOrWhiteSpace(i))
  355. .DistinctNames()
  356. .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  357. points += item1People.Where(i => item2PeopleNames.ContainsKey(i.Name)).Sum(i =>
  358. {
  359. if (string.Equals(i.Type, PersonType.Director, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  360. {
  361. return 5;
  362. }
  363. if (string.Equals(i.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  364. {
  365. return 3;
  366. }
  367. if (string.Equals(i.Type, PersonType.Composer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Composer, StringComparison.OrdinalIgnoreCase))
  368. {
  369. return 3;
  370. }
  371. if (string.Equals(i.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  372. {
  373. return 3;
  374. }
  375. if (string.Equals(i.Type, PersonType.Writer, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  376. {
  377. return 2;
  378. }
  379. return 1;
  380. });
  381. // Add some randomization so that you're not always seeing the same ones for a given movie
  382. points += random.Next(0, 50);
  383. return points;
  384. }
  385. private static IEnumerable<string> GetTags(BaseItem item)
  386. {
  387. var hasTags = item as IHasTags;
  388. if (hasTags != null)
  389. {
  390. return hasTags.Tags;
  391. }
  392. return new List<string>();
  393. }
  394. private static IEnumerable<string> GetKeywords(BaseItem item)
  395. {
  396. var hasTags = item as IHasKeywords;
  397. if (hasTags != null)
  398. {
  399. return hasTags.Keywords;
  400. }
  401. return new List<string>();
  402. }
  403. public IEnumerable<string> GetAllIntroFiles()
  404. {
  405. return GetCustomIntroFiles(GetOptions(), true, true);
  406. }
  407. private bool IsSupporter
  408. {
  409. get { return _security.IsMBSupporter; }
  410. }
  411. public string Name
  412. {
  413. get { return "Default"; }
  414. }
  415. internal class ItemWithTrailer
  416. {
  417. internal BaseItem Item;
  418. internal ItemWithTrailerType Type;
  419. internal User User;
  420. internal BaseItem WatchingItem;
  421. internal List<PersonInfo> WatchingItemPeople;
  422. internal List<PersonInfo> AllPeople;
  423. internal Random Random;
  424. internal ILibraryManager LibraryManager;
  425. private bool? _isPlayed;
  426. public bool IsPlayed
  427. {
  428. get
  429. {
  430. if (!_isPlayed.HasValue)
  431. {
  432. _isPlayed = Item.IsPlayed(User);
  433. }
  434. return _isPlayed.Value;
  435. }
  436. }
  437. private int? _score;
  438. public int Score
  439. {
  440. get
  441. {
  442. if (!_score.HasValue)
  443. {
  444. _score = GetSimiliarityScore(WatchingItem, WatchingItemPeople, AllPeople, Item, Random, LibraryManager);
  445. }
  446. return _score.Value;
  447. }
  448. }
  449. public IntroInfo IntroInfo
  450. {
  451. get
  452. {
  453. var id = Item.Id;
  454. if (Type == ItemWithTrailerType.ItemWithTrailer)
  455. {
  456. var hasTrailers = Item as IHasTrailers;
  457. if (hasTrailers != null)
  458. {
  459. id = hasTrailers.LocalTrailerIds.FirstOrDefault();
  460. }
  461. }
  462. return new IntroInfo
  463. {
  464. ItemId = id
  465. };
  466. }
  467. }
  468. }
  469. internal enum ItemWithTrailerType
  470. {
  471. LibraryTrailer,
  472. ChannelTrailer,
  473. ItemWithTrailer
  474. }
  475. }
  476. public class CinemaModeConfigurationFactory : IConfigurationFactory
  477. {
  478. public IEnumerable<ConfigurationStore> GetConfigurations()
  479. {
  480. return new[]
  481. {
  482. new ConfigurationStore
  483. {
  484. ConfigurationType = typeof(CinemaModeConfiguration),
  485. Key = "cinemamode"
  486. }
  487. };
  488. }
  489. }
  490. }