DefaultIntroProvider.cs 18 KB

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