public async void OnStreamUpdate_Called_When_StreamAlreadyOnline()
            {
                var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o =>
                                                                             o.Streams == new[]
                {
                    Mock.Of <Stream>(u => u.UserId == "UserId")
                }
                                                                             );

                var mockHandler = TwitchLibMock.HttpCallHandler(("https://api.twitch.tv/helix/streams", usersFollowsResponseJson));

                _api = TwitchLibMock.TwitchApi(mockHandler);

                var eventExecuteCount = 0;

                _liveStreamMonitor = new LiveStreamMonitorService(_api);
                _liveStreamMonitor.SetChannelsById(Utils.CreateListWithStrings("UserId"));
                _liveStreamMonitor.OnStreamUpdate += (sender, e) => eventExecuteCount++;

                await _liveStreamMonitor.UpdateLiveStreamersAsync();

                await _liveStreamMonitor.UpdateLiveStreamersAsync();

                Assert.Equal(1, eventExecuteCount);
            }
        private async Task ConfigLiveMonitorAsync()
        {
            API = new TwitchAPI();

            API.Settings.ClientId    = _settings.ClientId;
            API.Settings.AccessToken = _settings.ChannelAuthToken;

            Monitor = new LiveStreamMonitorService(API, 30);
            //FollowerService = new FollowerService(API, 30, 10);

            List <string> channels = new List <string> {
                _settings.ChannelId
            };

            Monitor.SetChannelsById(channels);

            Monitor.OnStreamOnline  += Monitor_OnStreamOnline;
            Monitor.OnStreamOffline += Monitor_OnStreamOffline;
            Monitor.OnStreamUpdate  += Monitor_OnStreamUpdate;

            Monitor.OnServiceStarted += Monitor_OnServiceStarted;
            Monitor.OnChannelsSet    += Monitor_OnChannelsSet;


            //FollowerService.SetChannelsById(channels);
            //FollowerService.OnChannelsSet += Follower_OnChannelsSet;
            //FollowerService.OnNewFollowersDetected += Follower_OnNewFollow;
            //FollowerService.OnServiceStarted += Follower_OnServiceStarted;

            Monitor.Start(); //Keep at the end!
            //FollowerService.Start();

            await Task.Delay(-1);
        }
            public void Start_Throws_InvalidOperationException_When_ServiceAlreadyStarted()
            {
                _liveStreamMonitor = new LiveStreamMonitorService(_api);
                _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString());
                _liveStreamMonitor.Start();

                AssertException.Throws <InvalidOperationException>(AlreadyStartedExceptionMessage, () => _liveStreamMonitor.Start());
            }
            public void OnChannelsSet_Raised_When_ChannelsSet()
            {
                var eventRaised = false;

                _liveStreamMonitor = new LiveStreamMonitorService(_api);
                _liveStreamMonitor.OnChannelsSet += (sender, e) => eventRaised = true;
                _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString());

                Assert.True(eventRaised);
            }
        // -----
        // General Purpose Functions
        // -----

        public async Task UpdateChannelsToMonitor()
        {
            await GetStreamerIdDictAsync();

            try
            {
                _liveStreamMonitor.SetChannelsById(StreamIdList);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Stopping Live Stream Monitor: {e.Message}");
                if (_liveStreamMonitor.Enabled)
                {
                    _liveStreamMonitor.Stop();
                }
            }
            await GetProfImgUrlsAsync(StreamIdList);

            GetStreamerList();
        }
            public async void LiveStreams_Contains_UserId_When_ServiceUpdated()
            {
                var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o =>
                                                                             o.Streams == new[]
                {
                    Mock.Of <Stream>(u => u.UserId == "UserId")
                }
                                                                             );

                _api = TwitchLibMock.TwitchApi(
                    ("https://api.twitch.tv/helix/streams", usersFollowsResponseJson)
                    );

                _liveStreamMonitor = new LiveStreamMonitorService(_api);
                _liveStreamMonitor.SetChannelsById(Utils.CreateListWithStrings("UserId"));

                await _liveStreamMonitor.UpdateLiveStreamersAsync();

                Assert.True(_liveStreamMonitor.LiveStreams.ContainsKey("UserId"));
            }
Example #7
0
        public async static Task UpdateMonitorList()
        {
            twitchService = new TwitchService(_client);
            var records = await twitchService.GetTwitchMonitorList();

            Log.Information($"Twitch Records Retrieved: ${records}");
            List <string> userNameList = new List <string>();

            foreach (var record in records)
            {
                userNameList.Add(record.twitchId);
            }
            userIdList = userNameList;

            if (userIdList.Count >= 1)
            {
                try
                {
                    Monitor.SetChannelsById(userIdList);
                }
                catch (Exception e)
                {
                    Log.Error($"Twitch User Not Found: ${e.Message}");
                    Log.Error(userIdList.ToString());
                }
                if (!twitchMonitorStarted)
                {
                    Log.Information($"Starting Twitch Monitor for {userIdList.Count} users");
                    Monitor.Start();
                    Monitor.OnStreamOnline += twitchService.Monitor_OnStreamOnline;
                    twitchMonitorStarted    = true;
                }
            }
            else
            {
                if (twitchMonitorStarted)
                {
                    Monitor.Stop();
                }
            }
        }
Example #8
0
        private async Task ConfigLiveMonitorAsync()
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var guildService = scope.ServiceProvider.GetRequiredService <IGuildService>();

                _api = new TwitchAPI();

                _api.Settings.ClientId    = "d0qgyohqojd71mpvsz7p0ldre5lfic";
                _api.Settings.AccessToken = "ciif9s2t2hhrn8tcx92e9p6g8xxpbq";

                _monitor = new LiveStreamMonitorService(_api, 60);

                var guilds = await guildService.GetAllAsync();

                var items             = guilds.Select(g => g.TwitchPlugin.TwitchChannelSubscriptions).ToList();
                var channelsToMonitor = new List <string>();

                foreach (var subscription in items
                         .SelectMany(item => item
                                     .Where(subscription => !channelsToMonitor.Contains(subscription.StreamerId))))
                {
                    channelsToMonitor.Add(subscription.StreamerId);
                }

                _monitor.SetChannelsById(channelsToMonitor);

                _monitor.OnStreamOnline  += Monitor_OnStreamOnline;
                _monitor.OnStreamOffline += Monitor_OnStreamOffline;
                _monitor.OnStreamUpdate  += Monitor_OnStreamUpdate;

                _monitor.OnServiceStarted += Monitor_OnServiceStarted;
                _monitor.OnChannelsSet    += Monitor_OnChannelsSet;

                _monitor.Start();

                await Task.Delay(-1);
            }
        }
            public void OnServiceTick_Raised_When_ServiceTicked()
            {
                var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o =>
                                                                             o.Streams == new[]
                {
                    Mock.Of <Stream>()
                }
                                                                             );

                _api = TwitchLibMock.TwitchApi(
                    ("https://api.twitch.tv/helix/users/follows", usersFollowsResponseJson)
                    );

                var signalEvent = new ManualResetEvent(false);

                _liveStreamMonitor = new LiveStreamMonitorService(_api, checkIntervalInSeconds: 1);
                _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString());
                _liveStreamMonitor.OnServiceTick += (sender, e) => signalEvent.Set();
                _liveStreamMonitor.Start();

                Assert.True(signalEvent.WaitOne(1500));
            }
Example #10
0
        public async Task ConfigLiveMonitorAsync()
        {
            API = new TwitchAPI();
            API.Settings.ClientId    = "jxjz93r6z6x0n09a7khp6wq4dvle8k";
            API.Settings.Secret      = "mlabuaroc67pgokd5kc8hqulokkmsd";
            API.Settings.AccessToken = API.Helix.Extensions.GetAccessToken();

            Monitor = new LiveStreamMonitorService(API, 60);
            List <string> lst = new List <string> {
                "67794893"
            };

            //Monitor.SetChannelsById(lst);
            Monitor.SetChannelsById(lst);

            Monitor.OnStreamOnline   += Monitor_OnStreamOnline;
            Monitor.OnStreamOffline  += Monitor_OnStreamOffline;
            Monitor.OnStreamUpdate   += Monitor_OnStreamUpdate;
            Monitor.OnServiceStarted += Monitor_OnServiceStarted;
            Monitor.OnChannelsSet    += Monitor_OnChannelsSet;
            Monitor.Start(); //Keep at the end!
            await Task.Delay(-1);
        }
Example #11
0
        private async Task ConfigLiveMonitorAsync()
        {
            api = new TwitchAPI();

            api.Settings.ClientId    = Resources.client_id;
            api.Settings.AccessToken = Resources.bot_access_token;

            Monitor = new LiveStreamMonitorService(api, 60);

            List <string> lst = new List <string> {
                Resources.channel_name
            };

            Monitor.SetChannelsById(lst);

            Monitor.OnStreamOnline   += Monitor_OnStreamOnline;
            Monitor.OnStreamOffline  += Monitor_OnStreamOffline;
            Monitor.OnStreamUpdate   += Monitor_OnStreamUpdate;
            Monitor.OnServiceStarted += Monitor_OnServiceStarted;
            Monitor.OnChannelsSet    += Monitor_OnChannelsSet;

            followerService = new FollowerService(api);
            followerService.SetChannelsByName(channel);
            followerService.OnNewFollowersDetected += FollowerService_OnNewFollowersDetected;
            //followerService.OnServiceStopped += (o, e) => Console.WriteLine("Follower service started");
            //followerService.OnServiceStarted += (o, e) => Console.WriteLine($"Follower service started with interval: seconds.");
            followerService.OnServiceStopped += (o, e) => form.WriteChat("Follower service started", false);
            followerService.OnServiceStarted += (o, e) => form.WriteChat($"Follower service started with default interval", false);

            followerService.Start();


            Monitor.Start(); //Keep at the end!

            await Task.Delay(-1);
        }
        public async Task CreateStreamMonoAsync()
        {
            // Check to see if a _liveStreamService has already been created
            if (_liveStreamMonitor != null)
            {
                return; // If one has, don't make a new one. Causes bot to send tons of duplicate alerts.
            }
            StreamModels = new Dictionary <string, StreamModel>();
            await Task.Run(GetStreamerList);

            await GetStreamerIdDictAsync();

            await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: GUILD COUNT {_discord.Guilds.Count}");

            List <SocketTextChannel>  notifChannels = new List <SocketTextChannel>();
            IEnumerator <SocketGuild> eguilds       = _discord.Guilds.GetEnumerator();

            eguilds.MoveNext();
            while (eguilds.Current != null)
            {
                int currentPos = 0;

                await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Current Guild: {eguilds.Current.Name}");

                IEnumerator <SocketTextChannel> echannels = eguilds.Current.TextChannels.GetEnumerator();

                echannels.MoveNext();
                while (currentPos != eguilds.Current.TextChannels.Count - 1)
                {
                    currentPos++;
                    if (echannels.Current != null && echannels.Current.Name.Contains(NotifChannelName))
                    {
                        notifChannels.Add(echannels.Current);
                        break;
                    }
                    echannels.MoveNext();
                }
                echannels.Dispose();
                eguilds.MoveNext();
            }
            eguilds.Dispose();
            StreamNotifChannels = notifChannels;

            if (StreamNotifChannels.Any())
            {
                await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Successfully collected Stream Update Notification channels. Amount: {StreamNotifChannels.Count()}");
            }
            else
            {
                await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService ERROR]: No Stream Update Notification channels were found!");
            }

            try
            {
                StreamProfileImages = await GetProfImgUrlsAsync(StreamIdList);
            }
            catch (TwitchLib.Api.Core.Exceptions.InternalServerErrorException ex)
            {
                if (CreationAttempts == 1)
                {
                    await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Maximum number of creation attempts exceeded. Live Stream Monitor Service is no longer available.");

                    CreationAttempts = 0;
                    return;
                }

                await Console.Out.WriteLineAsync($"{ex.GetType().Name} - Attempt #{CreationAttempts}: Error collecting Profile Images. Attempting to verify the streamers before trying again.");

                VerifyAndGetStreamIdAsync().RunSynchronously();
                CreationAttempts++;
                await CreateStreamMonoAsync();
            }

            _liveStreamMonitor = new LiveStreamMonitorService(TwApi, UpdInt, 100);

            _liveStreamMonitor.OnServiceTick    += OnServiceTickEvent;
            _liveStreamMonitor.OnChannelsSet    += OnChannelsSetEvent;
            _liveStreamMonitor.OnServiceStarted += OnServiceStartedEvent;
            _liveStreamMonitor.OnServiceStopped += OnServiceStoppedEvent;
            _liveStreamMonitor.OnStreamOnline   += OnStreamOnlineEventAsync;
            _liveStreamMonitor.OnStreamOffline  += OnStreamOfflineEvent;

            try
            {
                _liveStreamMonitor.SetChannelsById(StreamIdList);

                _liveStreamMonitor.Start();
            }
            catch (ArgumentException e)
            {
                Console.WriteLine($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Stream list is empty. Start the service manually using \";lsm start\" once you have added at least one streamer.");
            }

            await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Was service enabled? - {_liveStreamMonitor.Enabled}");
        }
            public void SetChannelsById_Throws_ArgumentException_When_ChannelsArgumentEmpty()
            {
                _liveStreamMonitor = new LiveStreamMonitorService(_api);

                AssertException.Throws <ArgumentException>(ChannelListEmptyExceptionMessage, () => _liveStreamMonitor.SetChannelsById(new List <string>()));
            }
            public void SetChannelsById_Throws_ArgumentNullException_When_ChannelsArgumentNull()
            {
                _liveStreamMonitor = new LiveStreamMonitorService(_api);

                AssertException.Throws <ArgumentNullException>(() => _liveStreamMonitor.SetChannelsById(null));
            }