ChannelManager.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. using System.Net;
  2. using System.Text;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Channels;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Localization;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Controller.Resolvers;
  14. using MediaBrowser.Model.Channels;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.MediaInfo;
  19. using MediaBrowser.Model.Net;
  20. using MediaBrowser.Model.Querying;
  21. using MediaBrowser.Model.Serialization;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using MediaBrowser.Server.Implementations.Library;
  30. namespace MediaBrowser.Server.Implementations.Channels
  31. {
  32. public class ChannelManager : IChannelManager, IDisposable
  33. {
  34. private IChannel[] _channels;
  35. private IChannelFactory[] _factories;
  36. private readonly IUserManager _userManager;
  37. private readonly IUserDataManager _userDataManager;
  38. private readonly IDtoService _dtoService;
  39. private readonly ILibraryManager _libraryManager;
  40. private readonly ILogger _logger;
  41. private readonly IServerConfigurationManager _config;
  42. private readonly IFileSystem _fileSystem;
  43. private readonly IJsonSerializer _jsonSerializer;
  44. private readonly IHttpClient _httpClient;
  45. private readonly ILocalizationManager _localization;
  46. private readonly ConcurrentDictionary<Guid, bool> _refreshedItems = new ConcurrentDictionary<Guid, bool>();
  47. private readonly ConcurrentDictionary<string, int> _downloadCounts = new ConcurrentDictionary<string, int>();
  48. private Timer _refreshTimer;
  49. private Timer _clearDownloadCountsTimer;
  50. public ChannelManager(IUserManager userManager, IDtoService dtoService, ILibraryManager libraryManager, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IUserDataManager userDataManager, IJsonSerializer jsonSerializer, ILocalizationManager localization, IHttpClient httpClient)
  51. {
  52. _userManager = userManager;
  53. _dtoService = dtoService;
  54. _libraryManager = libraryManager;
  55. _logger = logger;
  56. _config = config;
  57. _fileSystem = fileSystem;
  58. _userDataManager = userDataManager;
  59. _jsonSerializer = jsonSerializer;
  60. _localization = localization;
  61. _httpClient = httpClient;
  62. _refreshTimer = new Timer(s => _refreshedItems.Clear(), null, TimeSpan.FromHours(3), TimeSpan.FromHours(3));
  63. _clearDownloadCountsTimer = new Timer(s => _downloadCounts.Clear(), null, TimeSpan.FromHours(24), TimeSpan.FromHours(24));
  64. }
  65. private TimeSpan CacheLength
  66. {
  67. get
  68. {
  69. return TimeSpan.FromHours(6);
  70. }
  71. }
  72. public void AddParts(IEnumerable<IChannel> channels, IEnumerable<IChannelFactory> factories)
  73. {
  74. _channels = channels.Where(i => !(i is IFactoryChannel)).ToArray();
  75. _factories = factories.ToArray();
  76. }
  77. public string ChannelDownloadPath
  78. {
  79. get
  80. {
  81. var options = _config.GetChannelsConfiguration();
  82. if (!string.IsNullOrWhiteSpace(options.DownloadPath))
  83. {
  84. return options.DownloadPath;
  85. }
  86. return Path.Combine(_config.ApplicationPaths.ProgramDataPath, "channels");
  87. }
  88. }
  89. private IEnumerable<IChannel> GetAllChannels()
  90. {
  91. return _factories
  92. .SelectMany(i =>
  93. {
  94. try
  95. {
  96. return i.GetChannels().ToList();
  97. }
  98. catch (Exception ex)
  99. {
  100. _logger.ErrorException("Error getting channel list", ex);
  101. return new List<IChannel>();
  102. }
  103. })
  104. .Concat(_channels)
  105. .OrderBy(i => i.Name);
  106. }
  107. public Task<QueryResult<Channel>> GetChannelsInternal(ChannelQuery query, CancellationToken cancellationToken)
  108. {
  109. var user = string.IsNullOrWhiteSpace(query.UserId)
  110. ? null
  111. : _userManager.GetUserById(query.UserId);
  112. var channels = GetAllChannels()
  113. .Select(GetChannelEntity)
  114. .OrderBy(i => i.SortName)
  115. .ToList();
  116. if (query.SupportsLatestItems.HasValue)
  117. {
  118. var val = query.SupportsLatestItems.Value;
  119. channels = channels.Where(i => (GetChannelProvider(i) is ISupportsLatestMedia) == val)
  120. .ToList();
  121. }
  122. if (query.IsFavorite.HasValue)
  123. {
  124. var val = query.IsFavorite.Value;
  125. channels = channels.Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val)
  126. .ToList();
  127. }
  128. if (user != null)
  129. {
  130. channels = channels.Where(i => GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N")) && i.IsVisible(user))
  131. .ToList();
  132. }
  133. var all = channels;
  134. var totalCount = all.Count;
  135. if (query.StartIndex.HasValue)
  136. {
  137. all = all.Skip(query.StartIndex.Value).ToList();
  138. }
  139. if (query.Limit.HasValue)
  140. {
  141. all = all.Take(query.Limit.Value).ToList();
  142. }
  143. var returnItems = all.ToArray();
  144. var result = new QueryResult<Channel>
  145. {
  146. Items = returnItems,
  147. TotalRecordCount = totalCount
  148. };
  149. return Task.FromResult(result);
  150. }
  151. public async Task<QueryResult<BaseItemDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken)
  152. {
  153. var user = string.IsNullOrWhiteSpace(query.UserId)
  154. ? null
  155. : _userManager.GetUserById(query.UserId);
  156. var internalResult = await GetChannelsInternal(query, cancellationToken).ConfigureAwait(false);
  157. // Get everything
  158. var fields = Enum.GetNames(typeof(ItemFields))
  159. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  160. .ToList();
  161. var returnItems = internalResult.Items.Select(i => _dtoService.GetBaseItemDto(i, fields, user))
  162. .ToArray();
  163. var result = new QueryResult<BaseItemDto>
  164. {
  165. Items = returnItems,
  166. TotalRecordCount = internalResult.TotalRecordCount
  167. };
  168. return result;
  169. }
  170. public async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  171. {
  172. var allChannelsList = GetAllChannels().ToList();
  173. var numComplete = 0;
  174. foreach (var channelInfo in allChannelsList)
  175. {
  176. cancellationToken.ThrowIfCancellationRequested();
  177. try
  178. {
  179. var item = await GetChannel(channelInfo, cancellationToken).ConfigureAwait(false);
  180. _libraryManager.RegisterItem(item);
  181. }
  182. catch (OperationCanceledException)
  183. {
  184. throw;
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Name);
  189. }
  190. numComplete++;
  191. double percent = numComplete;
  192. percent /= allChannelsList.Count;
  193. progress.Report(100 * percent);
  194. }
  195. progress.Report(100);
  196. }
  197. private Channel GetChannelEntity(IChannel channel)
  198. {
  199. var item = GetChannel(GetInternalChannelId(channel.Name).ToString("N"));
  200. if (item == null)
  201. {
  202. item = GetChannel(channel, CancellationToken.None).Result;
  203. _libraryManager.RegisterItem(item);
  204. }
  205. return item;
  206. }
  207. public async Task<IEnumerable<MediaSourceInfo>> GetChannelItemMediaSources(string id, bool includeDynamicSources, CancellationToken cancellationToken)
  208. {
  209. var item = (IChannelMediaItem)_libraryManager.GetItemById(id);
  210. var channel = GetChannel(item.ChannelId);
  211. var channelPlugin = GetChannelProvider(channel);
  212. var requiresCallback = channelPlugin as IRequiresMediaInfoCallback;
  213. IEnumerable<ChannelMediaInfo> results;
  214. if (requiresCallback != null && includeDynamicSources)
  215. {
  216. results = await GetChannelItemMediaSourcesInternal(requiresCallback, item.ExternalId, cancellationToken)
  217. .ConfigureAwait(false);
  218. }
  219. else
  220. {
  221. results = item.ChannelMediaSources;
  222. }
  223. var sources = SortMediaInfoResults(results).Select(i => GetMediaSource(item, i))
  224. .ToList();
  225. var cachedVersions = GetCachedChannelItemMediaSources(item);
  226. sources.InsertRange(0, cachedVersions);
  227. return sources.Where(IsValidMediaSource);
  228. }
  229. private readonly ConcurrentDictionary<string, Tuple<DateTime, List<ChannelMediaInfo>>> _channelItemMediaInfo =
  230. new ConcurrentDictionary<string, Tuple<DateTime, List<ChannelMediaInfo>>>();
  231. private async Task<IEnumerable<ChannelMediaInfo>> GetChannelItemMediaSourcesInternal(IRequiresMediaInfoCallback channel, string id, CancellationToken cancellationToken)
  232. {
  233. Tuple<DateTime, List<ChannelMediaInfo>> cachedInfo;
  234. if (_channelItemMediaInfo.TryGetValue(id, out cachedInfo))
  235. {
  236. if ((DateTime.UtcNow - cachedInfo.Item1).TotalMinutes < 5)
  237. {
  238. return cachedInfo.Item2;
  239. }
  240. }
  241. var mediaInfo = await channel.GetChannelItemMediaInfo(id, cancellationToken)
  242. .ConfigureAwait(false);
  243. var list = mediaInfo.ToList();
  244. var item2 = new Tuple<DateTime, List<ChannelMediaInfo>>(DateTime.UtcNow, list);
  245. _channelItemMediaInfo.AddOrUpdate(id, item2, (key, oldValue) => item2);
  246. return list;
  247. }
  248. public IEnumerable<MediaSourceInfo> GetCachedChannelItemMediaSources(string id)
  249. {
  250. var item = (IChannelMediaItem)_libraryManager.GetItemById(id);
  251. return GetCachedChannelItemMediaSources(item);
  252. }
  253. public IEnumerable<MediaSourceInfo> GetCachedChannelItemMediaSources(IChannelMediaItem item)
  254. {
  255. var filenamePrefix = item.Id.ToString("N");
  256. var parentPath = Path.Combine(ChannelDownloadPath, item.ChannelId);
  257. try
  258. {
  259. var files = new DirectoryInfo(parentPath).EnumerateFiles("*", SearchOption.TopDirectoryOnly);
  260. if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  261. {
  262. files = files.Where(i => _libraryManager.IsVideoFile(i.FullName));
  263. }
  264. else
  265. {
  266. files = files.Where(i => _libraryManager.IsAudioFile(i.FullName));
  267. }
  268. var file = files
  269. .FirstOrDefault(i => i.Name.StartsWith(filenamePrefix, StringComparison.OrdinalIgnoreCase));
  270. if (file != null)
  271. {
  272. var cachedItem = _libraryManager.ResolvePath(file);
  273. if (cachedItem != null)
  274. {
  275. var hasMediaSources = _libraryManager.GetItemById(cachedItem.Id) as IHasMediaSources;
  276. if (hasMediaSources != null)
  277. {
  278. var source = hasMediaSources.GetMediaSources(true).FirstOrDefault();
  279. if (source != null)
  280. {
  281. source.Type = MediaSourceType.Cache;
  282. return new[] { source };
  283. }
  284. }
  285. }
  286. }
  287. }
  288. catch (DirectoryNotFoundException)
  289. {
  290. }
  291. return new List<MediaSourceInfo>();
  292. }
  293. private MediaSourceInfo GetMediaSource(IChannelMediaItem item, ChannelMediaInfo info)
  294. {
  295. var source = info.ToMediaSource();
  296. source.RunTimeTicks = source.RunTimeTicks ?? item.RunTimeTicks;
  297. return source;
  298. }
  299. private IEnumerable<ChannelMediaInfo> SortMediaInfoResults(IEnumerable<ChannelMediaInfo> channelMediaSources)
  300. {
  301. var list = channelMediaSources.ToList();
  302. var options = _config.GetChannelsConfiguration();
  303. var width = options.PreferredStreamingWidth;
  304. if (width.HasValue)
  305. {
  306. var val = width.Value;
  307. var res = list
  308. .OrderBy(i => (i.Width.HasValue && i.Width.Value <= val ? 0 : 1))
  309. .ThenBy(i => Math.Abs((i.Width ?? 0) - val))
  310. .ThenByDescending(i => i.Width ?? 0)
  311. .ThenBy(list.IndexOf)
  312. .ToList();
  313. return res;
  314. }
  315. return list
  316. .OrderByDescending(i => i.Width ?? 0)
  317. .ThenBy(list.IndexOf);
  318. }
  319. private async Task<Channel> GetChannel(IChannel channelInfo, CancellationToken cancellationToken)
  320. {
  321. var path = Path.Combine(_config.ApplicationPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(channelInfo.Name));
  322. var fileInfo = new DirectoryInfo(path);
  323. var isNew = false;
  324. if (!fileInfo.Exists)
  325. {
  326. _logger.Debug("Creating directory {0}", path);
  327. Directory.CreateDirectory(path);
  328. fileInfo = new DirectoryInfo(path);
  329. if (!fileInfo.Exists)
  330. {
  331. throw new IOException("Path not created: " + path);
  332. }
  333. isNew = true;
  334. }
  335. var id = GetInternalChannelId(channelInfo.Name);
  336. var item = _libraryManager.GetItemById(id) as Channel;
  337. if (item == null)
  338. {
  339. item = new Channel
  340. {
  341. Name = channelInfo.Name,
  342. Id = id,
  343. DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
  344. DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
  345. Path = path
  346. };
  347. isNew = true;
  348. }
  349. item.OfficialRating = GetOfficialRating(channelInfo.ParentalRating);
  350. item.Overview = channelInfo.Description;
  351. item.HomePageUrl = channelInfo.HomePageUrl;
  352. item.OriginalChannelName = channelInfo.Name;
  353. if (string.IsNullOrEmpty(item.Name))
  354. {
  355. item.Name = channelInfo.Name;
  356. }
  357. await item.RefreshMetadata(new MetadataRefreshOptions
  358. {
  359. ForceSave = isNew
  360. }, cancellationToken);
  361. return item;
  362. }
  363. private string GetOfficialRating(ChannelParentalRating rating)
  364. {
  365. switch (rating)
  366. {
  367. case ChannelParentalRating.Adult:
  368. return "XXX";
  369. case ChannelParentalRating.UsR:
  370. return "R";
  371. case ChannelParentalRating.UsPG13:
  372. return "PG-13";
  373. case ChannelParentalRating.UsPG:
  374. return "PG";
  375. default:
  376. return null;
  377. }
  378. }
  379. public Channel GetChannel(string id)
  380. {
  381. return (Channel)_libraryManager.GetItemById(new Guid(id));
  382. }
  383. public IEnumerable<ChannelFeatures> GetAllChannelFeatures()
  384. {
  385. return GetAllChannels()
  386. .Select(GetChannelEntity)
  387. .OrderBy(i => i.SortName)
  388. .Select(i => GetChannelFeatures(i.Id.ToString("N")));
  389. }
  390. public ChannelFeatures GetChannelFeatures(string id)
  391. {
  392. var channel = GetChannel(id);
  393. var channelProvider = GetChannelProvider(channel);
  394. return GetChannelFeaturesDto(channel, channelProvider, channelProvider.GetChannelFeatures());
  395. }
  396. public ChannelFeatures GetChannelFeaturesDto(Channel channel,
  397. IChannel provider,
  398. InternalChannelFeatures features)
  399. {
  400. var isIndexable = provider is IIndexableChannel;
  401. var supportsLatest = provider is ISupportsLatestMedia;
  402. return new ChannelFeatures
  403. {
  404. CanFilter = !features.MaxPageSize.HasValue,
  405. CanSearch = provider is ISearchableChannel,
  406. ContentTypes = features.ContentTypes,
  407. DefaultSortFields = features.DefaultSortFields,
  408. MaxPageSize = features.MaxPageSize,
  409. MediaTypes = features.MediaTypes,
  410. SupportsSortOrderToggle = features.SupportsSortOrderToggle,
  411. SupportsLatestMedia = supportsLatest,
  412. Name = channel.Name,
  413. Id = channel.Id.ToString("N"),
  414. SupportsContentDownloading = isIndexable || supportsLatest,
  415. AutoRefreshLevels = features.AutoRefreshLevels
  416. };
  417. }
  418. private Guid GetInternalChannelId(string name)
  419. {
  420. if (string.IsNullOrWhiteSpace(name))
  421. {
  422. throw new ArgumentNullException("name");
  423. }
  424. return ("Channel " + name).GetMBId(typeof(Channel));
  425. }
  426. public async Task<QueryResult<BaseItemDto>> GetLatestChannelItems(AllChannelMediaQuery query, CancellationToken cancellationToken)
  427. {
  428. var user = string.IsNullOrWhiteSpace(query.UserId)
  429. ? null
  430. : _userManager.GetUserById(query.UserId);
  431. var limit = query.Limit;
  432. // See below about parental control
  433. if (user != null)
  434. {
  435. query.StartIndex = null;
  436. query.Limit = null;
  437. }
  438. var internalResult = await GetLatestChannelItemsInternal(query, cancellationToken).ConfigureAwait(false);
  439. // Get everything
  440. var fields = Enum.GetNames(typeof(ItemFields))
  441. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  442. .ToList();
  443. var items = internalResult.Items;
  444. var totalRecordCount = internalResult.TotalRecordCount;
  445. // Supporting parental control is a hack because it has to be done after querying the remote data source
  446. // This will get screwy if apps try to page, so limit to 10 results in an attempt to always keep them on the first page
  447. if (user != null)
  448. {
  449. items = items.Where(i => i.IsVisible(user))
  450. .Take(limit ?? 10)
  451. .ToArray();
  452. totalRecordCount = items.Length;
  453. }
  454. var returnItems = items.Select(i => _dtoService.GetBaseItemDto(i, fields, user))
  455. .ToArray();
  456. var result = new QueryResult<BaseItemDto>
  457. {
  458. Items = returnItems,
  459. TotalRecordCount = totalRecordCount
  460. };
  461. return result;
  462. }
  463. public async Task<QueryResult<BaseItem>> GetLatestChannelItemsInternal(AllChannelMediaQuery query, CancellationToken cancellationToken)
  464. {
  465. var user = string.IsNullOrWhiteSpace(query.UserId)
  466. ? null
  467. : _userManager.GetUserById(query.UserId);
  468. if (!string.IsNullOrWhiteSpace(query.UserId) && user == null)
  469. {
  470. throw new ArgumentException("User not found.");
  471. }
  472. var channels = GetAllChannels();
  473. if (query.ChannelIds.Length > 0)
  474. {
  475. // Avoid implicitly captured closure
  476. var ids = query.ChannelIds;
  477. channels = channels
  478. .Where(i => ids.Contains(GetInternalChannelId(i.Name).ToString("N")))
  479. .ToArray();
  480. }
  481. // Avoid implicitly captured closure
  482. var userId = query.UserId;
  483. var tasks = channels
  484. .Select(async i =>
  485. {
  486. var indexable = i as ISupportsLatestMedia;
  487. if (indexable != null)
  488. {
  489. try
  490. {
  491. var result = await GetLatestItems(indexable, i, userId, cancellationToken).ConfigureAwait(false);
  492. var resultItems = result.ToList();
  493. return new Tuple<IChannel, ChannelItemResult>(i, new ChannelItemResult
  494. {
  495. Items = resultItems,
  496. TotalRecordCount = resultItems.Count
  497. });
  498. }
  499. catch (Exception ex)
  500. {
  501. _logger.ErrorException("Error getting all media from {0}", ex, i.Name);
  502. }
  503. }
  504. return new Tuple<IChannel, ChannelItemResult>(i, new ChannelItemResult { });
  505. });
  506. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  507. var totalCount = results.Length;
  508. IEnumerable<Tuple<IChannel, ChannelItemInfo>> items = results
  509. .SelectMany(i => i.Item2.Items.Select(m => new Tuple<IChannel, ChannelItemInfo>(i.Item1, m)));
  510. if (query.ContentTypes.Length > 0)
  511. {
  512. // Avoid implicitly captured closure
  513. var contentTypes = query.ContentTypes;
  514. items = items.Where(i => contentTypes.Contains(i.Item2.ContentType));
  515. }
  516. if (query.ExtraTypes.Length > 0)
  517. {
  518. // Avoid implicitly captured closure
  519. var contentTypes = query.ExtraTypes;
  520. items = items.Where(i => contentTypes.Contains(i.Item2.ExtraType));
  521. }
  522. // Avoid implicitly captured closure
  523. var token = cancellationToken;
  524. var itemTasks = items.Select(i =>
  525. {
  526. var channelProvider = i.Item1;
  527. var internalChannelId = GetInternalChannelId(channelProvider.Name);
  528. return GetChannelItemEntity(i.Item2, channelProvider, internalChannelId, token);
  529. });
  530. var internalItems = await Task.WhenAll(itemTasks).ConfigureAwait(false);
  531. internalItems = ApplyFilters(internalItems, query.Filters, user).ToArray();
  532. await RefreshIfNeeded(internalItems, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  533. if (query.StartIndex.HasValue)
  534. {
  535. internalItems = internalItems.Skip(query.StartIndex.Value).ToArray();
  536. }
  537. if (query.Limit.HasValue)
  538. {
  539. internalItems = internalItems.Take(query.Limit.Value).ToArray();
  540. }
  541. var returnItemArray = internalItems.ToArray();
  542. return new QueryResult<BaseItem>
  543. {
  544. TotalRecordCount = totalCount,
  545. Items = returnItemArray
  546. };
  547. }
  548. private async Task<IEnumerable<ChannelItemInfo>> GetLatestItems(ISupportsLatestMedia indexable, IChannel channel, string userId, CancellationToken cancellationToken)
  549. {
  550. var cacheLength = CacheLength;
  551. var cachePath = GetChannelDataCachePath(channel, userId, "channelmanager-latest", null, false);
  552. try
  553. {
  554. if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
  555. {
  556. return _jsonSerializer.DeserializeFromFile<List<ChannelItemInfo>>(cachePath);
  557. }
  558. }
  559. catch (FileNotFoundException)
  560. {
  561. }
  562. catch (DirectoryNotFoundException)
  563. {
  564. }
  565. await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  566. try
  567. {
  568. try
  569. {
  570. if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
  571. {
  572. return _jsonSerializer.DeserializeFromFile<List<ChannelItemInfo>>(cachePath);
  573. }
  574. }
  575. catch (FileNotFoundException)
  576. {
  577. }
  578. catch (DirectoryNotFoundException)
  579. {
  580. }
  581. var result = await indexable.GetLatestMedia(new ChannelLatestMediaSearch
  582. {
  583. UserId = userId
  584. }, cancellationToken).ConfigureAwait(false);
  585. var resultItems = result.ToList();
  586. CacheResponse(resultItems, cachePath);
  587. return resultItems;
  588. }
  589. finally
  590. {
  591. _resourcePool.Release();
  592. }
  593. }
  594. public async Task<QueryResult<BaseItem>> GetAllMediaInternal(AllChannelMediaQuery query, CancellationToken cancellationToken)
  595. {
  596. var channels = GetAllChannels();
  597. if (query.ChannelIds.Length > 0)
  598. {
  599. // Avoid implicitly captured closure
  600. var ids = query.ChannelIds;
  601. channels = channels
  602. .Where(i => ids.Contains(GetInternalChannelId(i.Name).ToString("N")))
  603. .ToArray();
  604. }
  605. var tasks = channels
  606. .Select(async i =>
  607. {
  608. var indexable = i as IIndexableChannel;
  609. if (indexable != null)
  610. {
  611. try
  612. {
  613. var result = await GetAllItems(indexable, i, new InternalAllChannelMediaQuery
  614. {
  615. UserId = query.UserId,
  616. ContentTypes = query.ContentTypes,
  617. ExtraTypes = query.ExtraTypes,
  618. TrailerTypes = query.TrailerTypes
  619. }, cancellationToken).ConfigureAwait(false);
  620. return new Tuple<IChannel, ChannelItemResult>(i, result);
  621. }
  622. catch (Exception ex)
  623. {
  624. _logger.ErrorException("Error getting all media from {0}", ex, i.Name);
  625. }
  626. }
  627. return new Tuple<IChannel, ChannelItemResult>(i, new ChannelItemResult { });
  628. });
  629. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  630. var totalCount = results.Length;
  631. IEnumerable<Tuple<IChannel, ChannelItemInfo>> items = results
  632. .SelectMany(i => i.Item2.Items.Select(m => new Tuple<IChannel, ChannelItemInfo>(i.Item1, m)))
  633. .OrderBy(i => i.Item2.Name);
  634. if (query.StartIndex.HasValue)
  635. {
  636. items = items.Skip(query.StartIndex.Value);
  637. }
  638. if (query.Limit.HasValue)
  639. {
  640. items = items.Take(query.Limit.Value);
  641. }
  642. // Avoid implicitly captured closure
  643. var token = cancellationToken;
  644. var itemTasks = items.Select(i =>
  645. {
  646. var channelProvider = i.Item1;
  647. var internalChannelId = GetInternalChannelId(channelProvider.Name);
  648. return GetChannelItemEntity(i.Item2, channelProvider, internalChannelId, token);
  649. });
  650. var internalItems = await Task.WhenAll(itemTasks).ConfigureAwait(false);
  651. var returnItemArray = internalItems.ToArray();
  652. return new QueryResult<BaseItem>
  653. {
  654. TotalRecordCount = totalCount,
  655. Items = returnItemArray
  656. };
  657. }
  658. public async Task<QueryResult<BaseItemDto>> GetAllMedia(AllChannelMediaQuery query, CancellationToken cancellationToken)
  659. {
  660. var user = string.IsNullOrWhiteSpace(query.UserId)
  661. ? null
  662. : _userManager.GetUserById(query.UserId);
  663. var internalResult = await GetAllMediaInternal(query, cancellationToken).ConfigureAwait(false);
  664. await RefreshIfNeeded(internalResult.Items, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  665. // Get everything
  666. var fields = Enum.GetNames(typeof(ItemFields))
  667. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  668. .ToList();
  669. var returnItems = internalResult.Items.Select(i => _dtoService.GetBaseItemDto(i, fields, user))
  670. .ToArray();
  671. var result = new QueryResult<BaseItemDto>
  672. {
  673. Items = returnItems,
  674. TotalRecordCount = internalResult.TotalRecordCount
  675. };
  676. return result;
  677. }
  678. private async Task<ChannelItemResult> GetAllItems(IIndexableChannel indexable, IChannel channel, InternalAllChannelMediaQuery query, CancellationToken cancellationToken)
  679. {
  680. var cacheLength = CacheLength;
  681. var folderId = _jsonSerializer.SerializeToString(query).GetMD5().ToString("N");
  682. var cachePath = GetChannelDataCachePath(channel, query.UserId, folderId, null, false);
  683. try
  684. {
  685. if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
  686. {
  687. return _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
  688. }
  689. }
  690. catch (FileNotFoundException)
  691. {
  692. }
  693. catch (DirectoryNotFoundException)
  694. {
  695. }
  696. await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  697. try
  698. {
  699. try
  700. {
  701. if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
  702. {
  703. return _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
  704. }
  705. }
  706. catch (FileNotFoundException)
  707. {
  708. }
  709. catch (DirectoryNotFoundException)
  710. {
  711. }
  712. var result = await indexable.GetAllMedia(query, cancellationToken).ConfigureAwait(false);
  713. CacheResponse(result, cachePath);
  714. return result;
  715. }
  716. finally
  717. {
  718. _resourcePool.Release();
  719. }
  720. }
  721. public async Task<QueryResult<BaseItem>> GetChannelItemsInternal(ChannelItemQuery query, IProgress<double> progress, CancellationToken cancellationToken)
  722. {
  723. // Get the internal channel entity
  724. var channel = GetChannel(query.ChannelId);
  725. // Find the corresponding channel provider plugin
  726. var channelProvider = GetChannelProvider(channel);
  727. var channelInfo = channelProvider.GetChannelFeatures();
  728. int? providerStartIndex = null;
  729. int? providerLimit = null;
  730. if (channelInfo.MaxPageSize.HasValue)
  731. {
  732. providerStartIndex = query.StartIndex;
  733. if (query.Limit.HasValue && query.Limit.Value > channelInfo.MaxPageSize.Value)
  734. {
  735. throw new ArgumentException(string.Format("{0} channel only supports a maximum of {1} records at a time.", channel.Name, channelInfo.MaxPageSize.Value));
  736. }
  737. providerLimit = query.Limit;
  738. // This will cause some providers to fail
  739. if (providerLimit == 0)
  740. {
  741. providerLimit = 1;
  742. }
  743. }
  744. var user = string.IsNullOrWhiteSpace(query.UserId)
  745. ? null
  746. : _userManager.GetUserById(query.UserId);
  747. ChannelItemSortField? sortField = null;
  748. ChannelItemSortField parsedField;
  749. if (query.SortBy.Length == 1 &&
  750. Enum.TryParse(query.SortBy[0], true, out parsedField))
  751. {
  752. sortField = parsedField;
  753. }
  754. var sortDescending = query.SortOrder.HasValue && query.SortOrder.Value == SortOrder.Descending;
  755. var itemsResult = await GetChannelItems(channelProvider,
  756. user,
  757. query.FolderId,
  758. providerStartIndex,
  759. providerLimit,
  760. sortField,
  761. sortDescending,
  762. cancellationToken)
  763. .ConfigureAwait(false);
  764. var providerTotalRecordCount = providerLimit.HasValue ? itemsResult.TotalRecordCount : null;
  765. var tasks = itemsResult.Items.Select(i => GetChannelItemEntity(i, channelProvider, channel.Id, cancellationToken));
  766. var internalItems = await Task.WhenAll(tasks).ConfigureAwait(false);
  767. if (user != null)
  768. {
  769. internalItems = internalItems.Where(i => i.IsVisible(user)).ToArray();
  770. if (providerTotalRecordCount.HasValue)
  771. {
  772. providerTotalRecordCount = providerTotalRecordCount.Value;
  773. }
  774. }
  775. return await GetReturnItems(internalItems, providerTotalRecordCount, user, query, progress, cancellationToken).ConfigureAwait(false);
  776. }
  777. public async Task<QueryResult<BaseItemDto>> GetChannelItems(ChannelItemQuery query, CancellationToken cancellationToken)
  778. {
  779. var user = string.IsNullOrWhiteSpace(query.UserId)
  780. ? null
  781. : _userManager.GetUserById(query.UserId);
  782. var internalResult = await GetChannelItemsInternal(query, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  783. // Get everything
  784. var fields = Enum.GetNames(typeof(ItemFields))
  785. .Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
  786. .ToList();
  787. var returnItems = internalResult.Items.Select(i => _dtoService.GetBaseItemDto(i, fields, user))
  788. .ToArray();
  789. var result = new QueryResult<BaseItemDto>
  790. {
  791. Items = returnItems,
  792. TotalRecordCount = internalResult.TotalRecordCount
  793. };
  794. return result;
  795. }
  796. private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
  797. private async Task<ChannelItemResult> GetChannelItems(IChannel channel,
  798. User user,
  799. string folderId,
  800. int? startIndex,
  801. int? limit,
  802. ChannelItemSortField? sortField,
  803. bool sortDescending,
  804. CancellationToken cancellationToken)
  805. {
  806. var userId = user.Id.ToString("N");
  807. var cacheLength = CacheLength;
  808. var cachePath = GetChannelDataCachePath(channel, userId, folderId, sortField, sortDescending);
  809. try
  810. {
  811. if (!startIndex.HasValue && !limit.HasValue)
  812. {
  813. if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
  814. {
  815. return _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
  816. }
  817. }
  818. }
  819. catch (FileNotFoundException)
  820. {
  821. }
  822. catch (DirectoryNotFoundException)
  823. {
  824. }
  825. await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  826. try
  827. {
  828. try
  829. {
  830. if (!startIndex.HasValue && !limit.HasValue)
  831. {
  832. if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
  833. {
  834. return _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
  835. }
  836. }
  837. }
  838. catch (FileNotFoundException)
  839. {
  840. }
  841. catch (DirectoryNotFoundException)
  842. {
  843. }
  844. var query = new InternalChannelItemQuery
  845. {
  846. UserId = userId,
  847. StartIndex = startIndex,
  848. Limit = limit,
  849. SortBy = sortField,
  850. SortDescending = sortDescending
  851. };
  852. if (!string.IsNullOrWhiteSpace(folderId))
  853. {
  854. var categoryItem = (IChannelItem)_libraryManager.GetItemById(new Guid(folderId));
  855. query.FolderId = categoryItem.ExternalId;
  856. }
  857. var result = await channel.GetChannelItems(query, cancellationToken).ConfigureAwait(false);
  858. if (!startIndex.HasValue && !limit.HasValue)
  859. {
  860. CacheResponse(result, cachePath);
  861. }
  862. return result;
  863. }
  864. finally
  865. {
  866. _resourcePool.Release();
  867. }
  868. }
  869. private void CacheResponse(object result, string path)
  870. {
  871. try
  872. {
  873. Directory.CreateDirectory(Path.GetDirectoryName(path));
  874. _jsonSerializer.SerializeToFile(result, path);
  875. }
  876. catch (Exception ex)
  877. {
  878. _logger.ErrorException("Error writing to channel cache file: {0}", ex, path);
  879. }
  880. }
  881. private string GetChannelDataCachePath(IChannel channel,
  882. string userId,
  883. string folderId,
  884. ChannelItemSortField? sortField,
  885. bool sortDescending)
  886. {
  887. var channelId = GetInternalChannelId(channel.Name).ToString("N");
  888. var userCacheKey = string.Empty;
  889. var hasCacheKey = channel as IHasCacheKey;
  890. if (hasCacheKey != null)
  891. {
  892. userCacheKey = hasCacheKey.GetCacheKey(userId) ?? string.Empty;
  893. }
  894. var filename = string.IsNullOrWhiteSpace(folderId) ? "root" : folderId;
  895. filename += userCacheKey;
  896. var version = (channel.DataVersion ?? string.Empty).GetMD5().ToString("N");
  897. if (sortField.HasValue)
  898. {
  899. filename += "-sortField-" + sortField.Value;
  900. }
  901. if (sortDescending)
  902. {
  903. filename += "-sortDescending";
  904. }
  905. filename = filename.GetMD5().ToString("N");
  906. return Path.Combine(_config.ApplicationPaths.CachePath,
  907. "channels",
  908. channelId,
  909. version,
  910. filename + ".json");
  911. }
  912. private async Task<QueryResult<BaseItem>> GetReturnItems(IEnumerable<BaseItem> items,
  913. int? totalCountFromProvider,
  914. User user,
  915. ChannelItemQuery query,
  916. IProgress<double> progress,
  917. CancellationToken cancellationToken)
  918. {
  919. items = ApplyFilters(items, query.Filters, user);
  920. var sortBy = query.SortBy.Length == 0 ? new[] { ItemSortBy.SortName } : query.SortBy;
  921. items = _libraryManager.Sort(items, user, sortBy, query.SortOrder ?? SortOrder.Ascending);
  922. var all = items.ToList();
  923. var totalCount = totalCountFromProvider ?? all.Count;
  924. if (!totalCountFromProvider.HasValue)
  925. {
  926. if (query.StartIndex.HasValue)
  927. {
  928. all = all.Skip(query.StartIndex.Value).ToList();
  929. }
  930. if (query.Limit.HasValue)
  931. {
  932. all = all.Take(query.Limit.Value).ToList();
  933. }
  934. }
  935. var returnItemArray = all.ToArray();
  936. await RefreshIfNeeded(returnItemArray, progress, cancellationToken).ConfigureAwait(false);
  937. return new QueryResult<BaseItem>
  938. {
  939. Items = returnItemArray,
  940. TotalRecordCount = totalCount
  941. };
  942. }
  943. private string GetIdToHash(string externalId, string channelName)
  944. {
  945. // Increment this as needed to force new downloads
  946. // Incorporate Name because it's being used to convert channel entity to provider
  947. return externalId + (channelName ?? string.Empty) + "16";
  948. }
  949. private T GetItemById<T>(string idString, string channelName, string channnelDataVersion, out bool isNew)
  950. where T : BaseItem, IChannelItem, new()
  951. {
  952. var id = GetIdToHash(idString, channelName).GetMBId(typeof(T));
  953. T item = null;
  954. try
  955. {
  956. item = _libraryManager.GetItemById(id) as T;
  957. }
  958. catch (Exception ex)
  959. {
  960. _logger.ErrorException("Error retrieving channel item from database", ex);
  961. }
  962. if (item == null || !string.Equals(item.DataVersion, channnelDataVersion, StringComparison.Ordinal))
  963. {
  964. item = new T();
  965. isNew = true;
  966. }
  967. else
  968. {
  969. isNew = false;
  970. }
  971. item.DataVersion = channnelDataVersion;
  972. item.Id = id;
  973. return item;
  974. }
  975. private async Task<BaseItem> GetChannelItemEntity(ChannelItemInfo info, IChannel channelProvider, Guid internalChannelId, CancellationToken cancellationToken)
  976. {
  977. BaseItem item;
  978. bool isNew;
  979. if (info.Type == ChannelItemType.Folder)
  980. {
  981. item = GetItemById<ChannelFolderItem>(info.Id, channelProvider.Name, channelProvider.DataVersion, out isNew);
  982. }
  983. else if (info.MediaType == ChannelMediaType.Audio)
  984. {
  985. item = GetItemById<ChannelAudioItem>(info.Id, channelProvider.Name, channelProvider.DataVersion, out isNew);
  986. }
  987. else
  988. {
  989. item = GetItemById<ChannelVideoItem>(info.Id, channelProvider.Name, channelProvider.DataVersion, out isNew);
  990. }
  991. item.RunTimeTicks = info.RunTimeTicks;
  992. if (isNew)
  993. {
  994. item.Name = info.Name;
  995. item.Genres = info.Genres;
  996. item.Studios = info.Studios;
  997. item.CommunityRating = info.CommunityRating;
  998. item.Overview = info.Overview;
  999. item.IndexNumber = info.IndexNumber;
  1000. item.ParentIndexNumber = info.ParentIndexNumber;
  1001. item.People = info.People;
  1002. item.PremiereDate = info.PremiereDate;
  1003. item.ProductionYear = info.ProductionYear;
  1004. item.ProviderIds = info.ProviderIds;
  1005. item.OfficialRating = info.OfficialRating;
  1006. item.DateCreated = info.DateCreated.HasValue ?
  1007. info.DateCreated.Value :
  1008. DateTime.UtcNow;
  1009. }
  1010. var channelItem = (IChannelItem)item;
  1011. channelItem.OriginalImageUrl = info.ImageUrl;
  1012. channelItem.ExternalId = info.Id;
  1013. channelItem.ChannelId = internalChannelId.ToString("N");
  1014. channelItem.ChannelItemType = info.Type;
  1015. if (isNew)
  1016. {
  1017. channelItem.Tags = info.Tags;
  1018. }
  1019. var channelMediaItem = item as IChannelMediaItem;
  1020. if (channelMediaItem != null)
  1021. {
  1022. channelMediaItem.ContentType = info.ContentType;
  1023. channelMediaItem.ExtraType = info.ExtraType;
  1024. channelMediaItem.ChannelMediaSources = info.MediaSources;
  1025. var mediaSource = info.MediaSources.FirstOrDefault();
  1026. item.Path = mediaSource == null ? null : mediaSource.Path;
  1027. item.DisplayMediaType = channelMediaItem.ContentType.ToString();
  1028. }
  1029. if (isNew)
  1030. {
  1031. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  1032. _libraryManager.RegisterItem(item);
  1033. }
  1034. return item;
  1035. }
  1036. private async Task RefreshIfNeeded(BaseItem[] programs, IProgress<double> progress, CancellationToken cancellationToken)
  1037. {
  1038. var numComplete = 0;
  1039. var numItems = programs.Length;
  1040. foreach (var program in programs)
  1041. {
  1042. await RefreshIfNeeded(program, cancellationToken).ConfigureAwait(false);
  1043. numComplete++;
  1044. double percent = numComplete;
  1045. percent /= numItems;
  1046. progress.Report(percent * 100);
  1047. }
  1048. }
  1049. private async Task RefreshIfNeeded(BaseItem program, CancellationToken cancellationToken)
  1050. {
  1051. if (_refreshedItems.ContainsKey(program.Id))
  1052. {
  1053. return;
  1054. }
  1055. await program.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  1056. _refreshedItems.TryAdd(program.Id, true);
  1057. }
  1058. internal IChannel GetChannelProvider(Channel channel)
  1059. {
  1060. return GetAllChannels().First(i => string.Equals(i.Name, channel.OriginalChannelName, StringComparison.OrdinalIgnoreCase));
  1061. }
  1062. private IEnumerable<BaseItem> ApplyFilters(IEnumerable<BaseItem> items, IEnumerable<ItemFilter> filters, User user)
  1063. {
  1064. foreach (var filter in filters.OrderByDescending(f => (int)f))
  1065. {
  1066. items = ApplyFilter(items, filter, user);
  1067. }
  1068. return items;
  1069. }
  1070. private IEnumerable<BaseItem> ApplyFilter(IEnumerable<BaseItem> items, ItemFilter filter, User user)
  1071. {
  1072. // Avoid implicitly captured closure
  1073. var currentUser = user;
  1074. switch (filter)
  1075. {
  1076. case ItemFilter.IsFavoriteOrLikes:
  1077. return items.Where(item =>
  1078. {
  1079. var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1080. if (userdata == null)
  1081. {
  1082. return false;
  1083. }
  1084. var likes = userdata.Likes ?? false;
  1085. var favorite = userdata.IsFavorite;
  1086. return likes || favorite;
  1087. });
  1088. case ItemFilter.Likes:
  1089. return items.Where(item =>
  1090. {
  1091. var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1092. return userdata != null && userdata.Likes.HasValue && userdata.Likes.Value;
  1093. });
  1094. case ItemFilter.Dislikes:
  1095. return items.Where(item =>
  1096. {
  1097. var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1098. return userdata != null && userdata.Likes.HasValue && !userdata.Likes.Value;
  1099. });
  1100. case ItemFilter.IsFavorite:
  1101. return items.Where(item =>
  1102. {
  1103. var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1104. return userdata != null && userdata.IsFavorite;
  1105. });
  1106. case ItemFilter.IsResumable:
  1107. return items.Where(item =>
  1108. {
  1109. var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  1110. return userdata != null && userdata.PlaybackPositionTicks > 0;
  1111. });
  1112. case ItemFilter.IsPlayed:
  1113. return items.Where(item => item.IsPlayed(currentUser));
  1114. case ItemFilter.IsUnplayed:
  1115. return items.Where(item => item.IsUnplayed(currentUser));
  1116. case ItemFilter.IsFolder:
  1117. return items.Where(item => item.IsFolder);
  1118. case ItemFilter.IsNotFolder:
  1119. return items.Where(item => !item.IsFolder);
  1120. }
  1121. return items;
  1122. }
  1123. public async Task<BaseItemDto> GetChannelFolder(string userId, CancellationToken cancellationToken)
  1124. {
  1125. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  1126. // Get everything
  1127. var fields = Enum.GetNames(typeof(ItemFields)).Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true)).ToList();
  1128. var folder = await GetInternalChannelFolder(userId, cancellationToken).ConfigureAwait(false);
  1129. return _dtoService.GetBaseItemDto(folder, fields, user);
  1130. }
  1131. public async Task<Folder> GetInternalChannelFolder(string userId, CancellationToken cancellationToken)
  1132. {
  1133. var name = _localization.GetLocalizedString("ViewTypeChannels");
  1134. return await _libraryManager.GetNamedView(name, "channels", "zz_" + name, cancellationToken).ConfigureAwait(false);
  1135. }
  1136. public async Task DownloadChannelItem(IChannelMediaItem item, string destination,
  1137. IProgress<double> progress, CancellationToken cancellationToken)
  1138. {
  1139. var itemId = item.Id.ToString("N");
  1140. var sources = await GetChannelItemMediaSources(itemId, true, cancellationToken)
  1141. .ConfigureAwait(false);
  1142. var list = sources.Where(i => i.Protocol == MediaProtocol.Http).ToList();
  1143. foreach (var source in list)
  1144. {
  1145. try
  1146. {
  1147. await TryDownloadChannelItem(source, item, destination, progress, cancellationToken).ConfigureAwait(false);
  1148. return;
  1149. }
  1150. catch (HttpException ex)
  1151. {
  1152. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  1153. {
  1154. MarkBadMediaSource(source);
  1155. }
  1156. }
  1157. }
  1158. }
  1159. private async Task TryDownloadChannelItem(MediaSourceInfo source,
  1160. IChannelMediaItem item,
  1161. string destination,
  1162. IProgress<double> progress,
  1163. CancellationToken cancellationToken)
  1164. {
  1165. var options = new HttpRequestOptions
  1166. {
  1167. CancellationToken = cancellationToken,
  1168. Url = source.Path,
  1169. Progress = new Progress<double>()
  1170. };
  1171. var host = new Uri(source.Path).Host.ToLower();
  1172. var channel = GetChannel(item.ChannelId);
  1173. var channelProvider = GetChannelProvider(channel);
  1174. var limit = channelProvider.GetChannelFeatures().DailyDownloadLimit;
  1175. if (!ValidateDownloadLimit(host, limit))
  1176. {
  1177. _logger.Error(string.Format("Download limit has been reached for {0}", channel.Name));
  1178. throw new ChannelDownloadException(string.Format("Download limit has been reached for {0}", channel.Name));
  1179. }
  1180. foreach (var header in source.RequiredHttpHeaders)
  1181. {
  1182. options.RequestHeaders[header.Key] = header.Value;
  1183. }
  1184. Directory.CreateDirectory(Path.GetDirectoryName(destination));
  1185. // Determine output extension
  1186. var response = await _httpClient.GetTempFileResponse(options).ConfigureAwait(false);
  1187. if (response.ContentType.StartsWith("text/html"))
  1188. {
  1189. throw new HttpException("File not found")
  1190. {
  1191. StatusCode = HttpStatusCode.NotFound
  1192. };
  1193. }
  1194. IncrementDownloadCount(host, limit);
  1195. if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase) && response.ContentType.StartsWith("video/", StringComparison.OrdinalIgnoreCase))
  1196. {
  1197. var extension = response.ContentType.Split('/')
  1198. .Last()
  1199. .Replace("quicktime", "mov", StringComparison.OrdinalIgnoreCase);
  1200. destination += "." + extension;
  1201. }
  1202. else if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) && response.ContentType.StartsWith("audio/", StringComparison.OrdinalIgnoreCase))
  1203. {
  1204. var extension = response.ContentType.Replace("audio/mpeg", "audio/mp3", StringComparison.OrdinalIgnoreCase)
  1205. .Split('/')
  1206. .Last();
  1207. destination += "." + extension;
  1208. }
  1209. else
  1210. {
  1211. File.Delete(response.TempFilePath);
  1212. throw new ApplicationException("Unexpected response type encountered: " + response.ContentType);
  1213. }
  1214. File.Copy(response.TempFilePath, destination, true);
  1215. try
  1216. {
  1217. File.Delete(response.TempFilePath);
  1218. }
  1219. catch
  1220. {
  1221. }
  1222. }
  1223. private readonly ReaderWriterLockSlim _mediaSourceHistoryLock = new ReaderWriterLockSlim();
  1224. private bool IsValidMediaSource(MediaSourceInfo source)
  1225. {
  1226. if (source.Protocol == MediaProtocol.Http)
  1227. {
  1228. return !GetBadMediaSourceHistory().Contains(source.Path, StringComparer.OrdinalIgnoreCase);
  1229. }
  1230. return true;
  1231. }
  1232. private void MarkBadMediaSource(MediaSourceInfo source)
  1233. {
  1234. var list = GetBadMediaSourceHistory();
  1235. list.Add(source.Path);
  1236. var path = GetMediaSourceHistoryPath();
  1237. Directory.CreateDirectory(Path.GetDirectoryName(path));
  1238. if (_mediaSourceHistoryLock.TryEnterWriteLock(TimeSpan.FromSeconds(5)))
  1239. {
  1240. try
  1241. {
  1242. File.WriteAllLines(path, list.ToArray(), Encoding.UTF8);
  1243. }
  1244. catch (Exception ex)
  1245. {
  1246. _logger.ErrorException("Error saving file", ex);
  1247. }
  1248. finally
  1249. {
  1250. _mediaSourceHistoryLock.ExitWriteLock();
  1251. }
  1252. }
  1253. }
  1254. private ConcurrentBag<string> _badMediaSources = null;
  1255. private ConcurrentBag<string> GetBadMediaSourceHistory()
  1256. {
  1257. if (_badMediaSources == null)
  1258. {
  1259. var path = GetMediaSourceHistoryPath();
  1260. if (_mediaSourceHistoryLock.TryEnterReadLock(TimeSpan.FromSeconds(1)))
  1261. {
  1262. if (_badMediaSources == null)
  1263. {
  1264. try
  1265. {
  1266. _badMediaSources = new ConcurrentBag<string>(File.ReadAllLines(path, Encoding.UTF8));
  1267. }
  1268. catch (IOException)
  1269. {
  1270. _badMediaSources = new ConcurrentBag<string>();
  1271. }
  1272. catch (Exception ex)
  1273. {
  1274. _logger.ErrorException("Error reading file", ex);
  1275. _badMediaSources = new ConcurrentBag<string>();
  1276. }
  1277. finally
  1278. {
  1279. _mediaSourceHistoryLock.ExitReadLock();
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return _badMediaSources;
  1285. }
  1286. private string GetMediaSourceHistoryPath()
  1287. {
  1288. return Path.Combine(_config.ApplicationPaths.DataPath, "channels", "failures.txt");
  1289. }
  1290. private void IncrementDownloadCount(string key, int? limit)
  1291. {
  1292. if (!limit.HasValue)
  1293. {
  1294. return;
  1295. }
  1296. int current;
  1297. _downloadCounts.TryGetValue(key, out current);
  1298. current++;
  1299. _downloadCounts.AddOrUpdate(key, current, (k, v) => current);
  1300. }
  1301. private bool ValidateDownloadLimit(string key, int? limit)
  1302. {
  1303. if (!limit.HasValue)
  1304. {
  1305. return true;
  1306. }
  1307. int current;
  1308. _downloadCounts.TryGetValue(key, out current);
  1309. return current < limit.Value;
  1310. }
  1311. public void Dispose()
  1312. {
  1313. if (_clearDownloadCountsTimer != null)
  1314. {
  1315. _clearDownloadCountsTimer.Dispose();
  1316. _clearDownloadCountsTimer = null;
  1317. }
  1318. if (_refreshTimer != null)
  1319. {
  1320. _refreshTimer.Dispose();
  1321. _refreshTimer = null;
  1322. }
  1323. }
  1324. }
  1325. }