Example #1
0
        public ChannelReader <IEnumerable <RedditEntry> > Feed(string feedId)
        {
            var channel = Channel.CreateUnbounded <IEnumerable <RedditEntry> >();

            var connection = new HubConnectionState
            {
                ConnectionId  = Context.ConnectionId,
                FeedId        = feedId,
                StreamChannel = channel,
            };

            if (_feedService.TryGetFeed(feedId, out var feed))
            {
                var data = feed.GetData();
                if (data.Count() > 0)
                {
                    _ = connection.StreamChannel.Writer.WriteAsync(data);
                    connection.LastEntryName = feed.LastEntryName;
                }
            }
            else
            {
                _feedService.AddFeed(feedId, new RedditFeed
                {
                    Id = feedId
                });
            }

            _stateService.AddConnection(connection);

            return(channel.Reader);
        }
Example #2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            do
            {
                try
                {
                    foreach (var feed in _feedService.GetAll())
                    {
                        var subreddit = feed.Id;
                        var listing   = await _apiService.GetNew(subreddit : subreddit, limit : 10);

                        if (listing.Children.Count > 0)
                        {
                            _logger.LogInformation("Pushing new data from {0}: {1}",
                                                   subreddit, string.Join(", ", listing.Children.Select(d => d.Title)));
                            feed.AddRange(listing.Children);
                        }
                    }

                    var connections = _stateService.GetAll();
                    foreach (var c in connections)
                    {
                        if (_feedService.TryGetFeed(c.FeedId, out var existingFeed))
                        {
                            var data = existingFeed.GetData(c.LastEntryName);
                            if (data.Count() > 0)
                            {
                                _logger.LogInformation("Streaming new data: {0}",
                                                       string.Join(", ", data.Select(d => d.Title)));
                                _ = c.StreamChannel.Writer.WriteAsync(data, stoppingToken);
                                c.LastEntryName = existingFeed.LastEntryName;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Write(ex.Message);
                }

                await Task.Delay(1000, stoppingToken);
            }while (!stoppingToken.IsCancellationRequested);
        }