private void FireAnEventBasedOnUserNoticeType(IrcMessage message)
        {
            if (message.Tags.TryGetValue("msg-id", out string userNoticeType))
            {
                switch (userNoticeType)
                {
                case "sub":
                    var subscription = new TwitchSubscription(message);
                    OnUserSubscribed(subscription);
                    break;

                case "resub":
                    var resubscription = new TwitchSubscription(message);
                    OnUserResubscribed(resubscription);
                    break;

                case "subgift":
                    var subscriptionGift = new TwitchSubscriptionGift(message);
                    OnSubscriptionGifted(subscriptionGift);
                    break;

                case "raid":
                    var channelRaid = new TwitchChannelRaid(message);
                    OnChannelRaided(channelRaid);
                    break;

                case "ritual":
                    var channelRitual = new TwitchChannelRitual(message);
                    OnChannelRitualPerformed(channelRitual);
                    break;
                }
            }
        }
Example #2
0
        public static async Task UnsubscribeTwitchStreamWebhook(TwitchSubscription Subscription, ILogger Log)
        {
            Log.LogInformation("UnsubscribeTwitchStreamWebhook Begin");
            await SubscriptionActionTwitchStreamWebhook(Subscription, TwitchSubscriptionMode.Unsubscribe, Log);

            Log.LogInformation("UnsubscribeTwitchStreamWebhook End");
        }
    public void OnSubscribe(TwitchSubscription subscribe)
    {
        var player = gameManager.Players.GetPlayerByUserId(subscribe.UserId);

        if (player)
        {
            if (subscribe.ReceiverUserId == null)
            {
                player.IsSubscriber = true;
            }
            else
            {
                var receiver = gameManager.Players.GetPlayerByUserId(subscribe.ReceiverUserId);
                if (receiver)
                {
                    player.IsSubscriber = true;
                }
            }
            gameManager.Camera.ObservePlayer(player, MaxObserveTime);
        }

        var activePlayers = gameManager.Players.GetAllPlayers();

        foreach (var plr in activePlayers)
        {
            plr.Cheer();
        }

        AddSubscriber(subscribe);
    }
Example #4
0
        private static async Task SubscriptionActionTwitchStreamWebhook(TwitchSubscription Subscription, TwitchSubscriptionMode SubscriptionMode, ILogger Log)
        {
            Log.LogInformation("SubscriptionActionTwitchStreamWebhook Begin");
            Log.LogInformation($"TwitchName: {Subscription.TwitchName}");
            Log.LogInformation($"TwitterName: {Subscription.TwitterName}");
            Log.LogInformation($"DiscordName: {Subscription.DiscordName}");

            var userId = await GetTwitchStreamUserId(Subscription.TwitchName, Log);

            Log.LogInformation($"UserID: {userId}");

            var twitterPart = string.IsNullOrWhiteSpace(Subscription.TwitterName) ? Utility.NameNullString : Subscription.TwitterName;
            var discordPart = string.IsNullOrWhiteSpace(Subscription.DiscordName) ? Utility.NameNullString : Subscription.DiscordName;
            var callbackUri = $"{TwitchWebhookBaseUri}/{Subscription.TwitchName}/{twitterPart}/{discordPart}";

            Log.LogInformation($"CallbackUri: {callbackUri}");

            var hubTopic = $"{TwitchStreamsEndpointUri}?user_id={userId}";

            Log.LogInformation($"HubTopic: {hubTopic}");

            var hubSubscription = new TwitchHubSubscription()
            {
                HubMode         = SubscriptionMode.ToString().ToLower(),
                HubSecret       = HubSecret,
                HubTopic        = hubTopic,
                HubCallback     = callbackUri,
                HubLeaseSeconds = 864000
            };

            var requestBody = JsonConvert.SerializeObject(hubSubscription);

            var authToken = await GetOAuthResponse(Log);

            var message = new HttpRequestMessage()
            {
                Content    = new StringContent(requestBody, Encoding.UTF8, Utility.ApplicationJsonContentType),
                Method     = HttpMethod.Post,
                RequestUri = new Uri(TwitchWebhooksHubEndpointUri)
            };

            message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken.AccessToken);
            message.Headers.TryAddWithoutValidation(ClientIdHeaderName, clientId);

            var response = await client.SendAsync(message, HttpCompletionOption.ResponseContentRead);

            LogHttpResponse(response, "SubscriptionActionTwitchStreamWebhook", Log);

            var responseBody = await response.Content.ReadAsStringAsync();

            Log.LogInformation($"Response: {responseBody}");

            Log.LogInformation("SubscriptionActionTwitchStreamWebhook End");
        }
Example #5
0
    public void OnTwitchSubscribe(TwitchSubscription data)
    {
        Debug.Log("OnTwitchSubscribe");
        var activePlayers = playerManager.GetAllPlayers();

        foreach (var player in activePlayers)
        {
            player.SubscriberCheer(data);
        }

        subEventManager.AddSubscriber(data);
    }
    private void AddSubscriber(TwitchSubscription data, bool increaseMultiplier = true)
    {
        if (increaseMultiplier)
        {
            CurrentBoost.LastSubscriber = string.IsNullOrEmpty(data.UserName)
               ? CurrentBoost.LastSubscriber
               : data.UserName;

            CurrentBoost.BoostTime = CurrentBoost.BoostTime.Add(TimeSpan.FromMinutes(SubMultiplierAdd));
            if (CurrentBoost.BoostTime > MaxBoostTime)
            {
                CurrentBoost.BoostTime = MaxBoostTime;
            }
        }

        SaveState();
    }
Example #7
0
    private void AddSubscriber(TwitchSubscription data)
    {
        CurrentBoost.LastSubscriber = string.IsNullOrEmpty(data.UserName)
            ? CurrentBoost.LastSubscriber
            : data.UserName;

        CurrentBoost.Elapsed = 0f;
        CurrentBoost.Active  = true;

        if (data.Months >= 0)
        {
            CurrentBoost.Multiplier = Mathf.Min(
                CurrentBoost.Multiplier + (UnityEngine.Random.value <= 0.10 ? 10 : 1), MaxMultiplier);
        }

        SaveState();
    }
    public void OnSubscribe(TwitchSubscription subscribe)
    {
        var player = gameManager.Players.GetPlayerByUserId(subscribe.UserId);

        if (!player)
        {
            player = gameManager.Players.GetPlayerByName(subscribe.UserName);
        }
        if (player)
        {
            gameManager.RavenBot?.Send(player.Name, Localization.MSG_SUB_CREW,
                                       gameManager.RavenNest.TwitchDisplayName,
                                       TierExpMultis[gameManager.Permissions.SubscriberTier]);

            if (subscribe.ReceiverUserId == null)
            {
                player.IsSubscriber = true;
            }
            else
            {
                var receiver = gameManager.Players.GetPlayerByUserId(subscribe.ReceiverUserId);
                if (receiver)
                {
                    player.IsSubscriber = true;
                }
            }

            player.AddSubscribe(subscribe.ReceiverUserId != null);
            gameManager.Camera.ObservePlayer(player, MaxObserveTime);
        }

        var activePlayers = gameManager.Players.GetAllPlayers();

        foreach (var plr in activePlayers)
        {
            plr.Cheer();
        }

        if (!player)
        {
            gameManager.RavenNest.Stream.SendPlayerLoyaltyData(subscribe);
        }

        AddSubscriber(subscribe, CurrentBoost.Active);
    }
        public void SendPlayerLoyaltyData(TwitchSubscription d)
        {
            if (client.Desynchronized)
            {
                return;
            }
            var data = new UserLoyaltyUpdate
            {
                IsModerator    = d.IsModerator,
                IsSubscriber   = d.IsSubscriber,
                NewCheeredBits = 0,
                UserName       = d.UserName,
                NewGiftedSubs  = d.ReceiverUserId == null || d.ReceiverUserId == d.UserId ? 0 : 1,
                UserId         = d.UserId
            };

            connection.SendNoAwait("update_user_loyalty", data);
        }
Example #10
0
    public void AddSubscriber(TwitchSubscription data)
    {
        subscribers.Add(data);
        CurrentBoost.Elapsed = 0f;
        CurrentBoost.Active  = true;

        CurrentBoost.LastSubscriber = string.IsNullOrEmpty(data.UserName)
            ? CurrentBoost.LastSubscriber
            : data.UserName;

        if (data.Months >= 0)
        {
            var multiplierCount = 1;
            if (UnityEngine.Random.value <= 0.10)
            {
                multiplierCount = 10;
            }
            CurrentBoost.Multiplier = Mathf.Min(CurrentBoost.Multiplier + multiplierCount, MaxMultiplier);
        }
        SaveState();
    }
        public static async Task Run(
            [QueueTrigger("%TwitchChannelEventLookupQueue%", Connection = "TwitchStreamStorage")] TwitchSubscription Subscription,
            [Queue("%TwitchChannelEventProcessQueue%", Connection = "TwitchStreamStorage")] IAsyncCollector <TwitchChannelEventItem> EventProccessQueue,
            ILogger log)
        {
            log.LogInformation($"TwitchChannelEventLookup function processed: {Subscription.TwitchName}");

            var response = await TwitchClient.GetTwitchSubscriptionEvents(Subscription, log);

            foreach (var channelEvent in response.Events)
            {
                log.LogInformation($"TwitchChannelEventLookup Queing event {channelEvent.Id} for channel {Subscription.TwitchName}");
                await EventProccessQueue.AddAsync(new TwitchChannelEventItem()
                {
                    Event        = channelEvent,
                    Subscription = Subscription
                });
            }

            log.LogInformation("TwitchChannelEventLookup end");
        }
Example #12
0
        public static async Task Run(
            [QueueTrigger("%TwitchSubscribeQueue%", Connection = "TwitchStreamStorage")]
            TwitchSubscription Subscription,
            ILogger log)
        {
            log.LogInformation("TwitchSubscriptionAdd Begin");

            log.LogInformation($"TwitchSubscriptionAdd Process TwitchName {Subscription.TwitchName} TwitterName {Subscription.TwitterName}");

            log.LogInformation($"TwitchSubscriptionAdd Subscribing TwitchName {Subscription.TwitchName} TwitterName {Subscription.TwitterName}");
            try
            {
                await TwitchClient.SubscribeTwitchStreamWebhook(Subscription, log);

                log.LogInformation($"TwitchSubscriptionAdd Subscribed TwitchName {Subscription.TwitchName} TwitterName {Subscription.TwitterName}");
            } catch (System.Exception e)
            {
                log.LogError(e, "TwitchSubscriptionAdd exception subscribing");
            }

            log.LogInformation("TwitchSubscriptionAdd End");
        }
    private void AddSubscriber(TwitchSubscription data)
    {
        CurrentBoost.LastSubscriber = string.IsNullOrEmpty(data.UserName)
            ? CurrentBoost.LastSubscriber
            : data.UserName;

        if (gameManager.Permissions.ExpMultiplierLimit == 0)
        {
            return;
        }

        CurrentBoost.Elapsed = 0f;
        CurrentBoost.Active  = true;

        if (data.Months >= 0)
        {
            CurrentBoost.Multiplier = Mathf.Min(
                CurrentBoost.Multiplier + (UnityEngine.Random.value <= 0.10 ? 10 : 1),
                gameManager.Permissions.ExpMultiplierLimit);
        }

        SaveState();
    }
Example #14
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", "get", Route = "TwitchWebhookIngestion/{StreamName}/{TwitterName?}/{DiscordName?}")] HttpRequest Req,
            string StreamName,
            string TwitterName,
            string DiscordName,
            [Queue("%TwitchStreamActivity%")] ICollector <Stream> queue,
            ILogger Log)
        {
            Log.LogInformation($"TwitchWebhookIngestion function processed a request.");
            Log.LogInformation($"StreamName: {StreamName}");
            Log.LogInformation($"TwitterName: {TwitterName}");
            Log.LogInformation($"DiscordName: {DiscordName}");

            var subscription = new TwitchSubscription()
            {
                TwitchName  = StreamName,
                TwitterName = TwitterName != Utility.NameNullString ? TwitterName : string.Empty,
                DiscordName = DiscordName != Utility.NameNullString ? DiscordName : string.Empty
            };

            if (Req.Query.TryGetValue("hub.mode", out var hubMode))
            {
                Log.LogInformation($"Received hub.mode Query string: {Req.QueryString}");
                if (hubMode.ToString().ToLower() == "subscribe" || hubMode.ToString().ToLower() == "unsubscribe")
                {
                    Log.LogInformation($"Returning hub.challenge {Req.Query["hub.challenge"]}");
                    return(new OkObjectResult(Req.Query["hub.challenge"].ToString()));
                }
                else
                {
                    Log.LogError($"Failed subscription: {Req.QueryString}");
                    // Subscription hub expects 200 result when subscription fails
                    return(new OkResult());
                }
            }
            else
            {
                Log.LogInformation("No hub.mode supplied.");
            }

            Log.LogInformation("Processing body stream");
            Log.LogInformation($"CanSeek: {Req.Body.CanSeek}");

            var bodyString = await Req.ReadAsStringAsync();

            Log.LogInformation("Payload:");
            Log.LogInformation(bodyString);

            StreamData webhook;

            try
            {
                webhook = JsonConvert.DeserializeObject <StreamData>(bodyString);
            }
            catch (Exception e)
            {
                Log.LogError($"Invalid JSON. exception {e.Message}. {bodyString}");
                return(new BadRequestResult());
            }

            Log.LogInformation($"Request contains {webhook.Data.Count} objects.");

            if (!Req.Headers.TryGetValue(SignatureHeader, out var signature))
            {
                Log.LogError($"Missing {SignatureHeader} header");
                return(new BadRequestResult());
            }

            var fields = signature.ToString().Split("=");

            if (fields.Length != 2)
            {
                Log.LogError($"Malformed {SignatureHeader} header. Missing '='?");
                return(new BadRequestObjectResult(signature));
            }

            var header = fields[1];

            if (string.IsNullOrEmpty(header))
            {
                Log.LogError($"Malformed {SignatureHeader} header. Signature is null or empty");
                return(new BadRequestObjectResult(fields));
            }

            var expectedHash = Utility.FromHex(header);

            if (expectedHash == null)
            {
                Log.LogError($"Malformed {SignatureHeader} header. Invalid hex signature");
                return(new BadRequestObjectResult(SignatureHeader));
            }

            var actualHash = await Utility.ComputeRequestBodySha256HashAsync(Req, HashSecret);

            if (!Utility.SecretEqual(expectedHash, actualHash))
            {
                Log.LogError($"Signature mismatch. actaulHash {Convert.ToBase64String(actualHash)} did not match expectedHash {Convert.ToBase64String(expectedHash)}");
                return(new BadRequestObjectResult(signature));
            }

            foreach (var item in webhook.Data)
            {
                if (string.IsNullOrWhiteSpace(item.UserName))
                {
                    Log.LogInformation($"Setting missing Username to {StreamName}");
                    item.UserName = StreamName;
                }

                item.Subscription = subscription;

                Log.LogInformation($"Queing notification for stream {item.UserName} type {item.Type} started at {item.StartedAt}");
                queue.Add(item);
            }

            Log.LogInformation("Processing complete");
            return(new OkResult());
        }
Example #15
0
        public static async Task <TwitchChannelEventResponse> GetTwitchSubscriptionEvents(TwitchSubscription Subscription, ILogger Log)
        {
            Log.LogInformation("GetTwitchSubscriptionEvents Begin");
            Log.LogInformation($"GetTwitchSubscriptionEvents TwitchName: {Subscription.TwitchName}");
            Log.LogInformation($"GetTwitchSubscriptionEvents TwitterName: {Subscription.TwitterName}");
            Log.LogInformation($"GetTwitchSubscriptionEvents DiscordName: {Subscription.DiscordName}");

            var userId = await GetTwitchStreamUserId(Subscription.TwitchName, Log);

            Log.LogInformation($"GetTwitchSubscriptionEvents UserID: {userId}");

            var requestUri = string.Format(TwitchChannelEventUriTemplate, userId);

            Log.LogInformation($"GetTwitchSubscriptionEvents RequestUri: {requestUri}");

            var message = new HttpRequestMessage()
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri(requestUri)
            };

            message.Headers.TryAddWithoutValidation(ClientIdHeaderName, clientId);

            var httpResponse = await client.SendAsync(message, HttpCompletionOption.ResponseContentRead);

            LogHttpResponse(httpResponse, "GetTwitchSubscriptionEvents", Log);

            if (!httpResponse.IsSuccessStatusCode)
            {
                Log.LogInformation("GetTwitchSubscriptionEvents End");
                return(null);
            }
            else
            {
                var responseBody = await httpResponse.Content.ReadAsStringAsync();

                Log.LogInformation("GetTwitchSubscriptionEvents ResponseBody:");
                Log.LogInformation(responseBody);

                var response = JsonConvert.DeserializeObject <TwitchChannelEventResponse>(responseBody);

                Log.LogInformation("GetTwitchStreamUserId End");
                return(response);
            }
        }
Example #16
0
 public void SubscriberCheer(TwitchSubscription data)
 {
     this.playerAnimations.ForceCheer();
 }
Example #17
0
 protected virtual void OnUserResubscribed(TwitchSubscription resubscription)
 {
     UserResubscribed?.Invoke(this, new UserSubscribedEventArgs(resubscription));
 }
Example #18
0
 public UserSubscribedEventArgs(TwitchSubscription subscription)
 {
     Subscription = subscription;
 }
Example #19
0
 private async void OnUserSub(TwitchSubscription obj) => await SendAsync("twitch_sub", obj);