예제 #1
0
        /// <summary>
        /// Processes a received text packet.
        /// </summary>
        /// <param name="packet">The text packet received</param>
        /// <returns>An awaitable Task</returns>
        protected override Task ProcessReceivedPacket(string packet)
        {
            Logger.Log(LogLevel.Debug, "Trovo Chat Packet: " + packet);

            ChatPacketModel response = JSONSerializerHelper.DeserializeFromString <ChatPacketModel>(packet);

            if (response != null && !string.IsNullOrEmpty(response.type))
            {
                switch (response.type)
                {
                case "RESPONSE":
                    if (this.replyIDListeners.ContainsKey(response.nonce))
                    {
                        this.replyIDListeners[response.nonce] = response;
                    }
                    break;

                case "CHAT":
                    this.SendSpecificPacket(response, this.OnChatMessageReceived);
                    break;
                }
            }

            return(Task.FromResult(0));
        }
예제 #2
0
        /// <summary>
        /// Performs a GraphQL query with the specified query text and returns the specified type.
        /// </summary>
        /// <typeparam name="T">The type of the result</typeparam>
        /// <param name="query">The query to perform</param>
        /// <param name="key">The key to get for the data</param>
        /// <returns>The result data</returns>
        protected async Task <T> QueryAsync <T>(string query, string key)
        {
            try
            {
                GraphQLHttpClient client = await this.GetGraphQLClient();

                GraphQLResponse <JObject> response = await client.SendQueryAsync <JObject>(new GraphQLRequest(query));

                Logger.Log(LogLevel.Debug, JSONSerializerHelper.SerializeToString(response));

                if (response.Errors != null && response.Errors.Length > 0)
                {
                    foreach (GraphQLError error in response.Errors)
                    {
                        Logger.Log(LogLevel.Error, $"GraphQL Query Error: {query} - {error.Message}");
                    }
                }

                if (response.Data != null && response.Data.ContainsKey(key))
                {
                    return(response.Data[key].ToObject <T>());
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
            return(default(T));
        }
        /// <summary>
        /// Creates a new instance of the ClientPacketModelBase class.
        /// </summary>
        /// <param name="serializedChatPacketArray">The serialized packet array</param>
        protected ClientPacketModelBase(string serializedChatPacketArray)
            : this()
        {
            JArray array = JSONSerializerHelper.DeserializeFromString <JArray>(serializedChatPacketArray);

            if (array.Count > 0)
            {
                this.JoinRef = array[0]?.ToString();
            }
            if (array.Count > 1)
            {
                this.NormalRef = array[1]?.ToString();
            }
            if (array.Count > 2)
            {
                this.Topic = array[2]?.ToString();
            }
            if (array.Count > 3)
            {
                this.Event = array[3]?.ToString();
            }
            if (array.Count > 4 && array[4] != null)
            {
                this.Payload = (JObject)array[4];
            }
        }
예제 #4
0
        public async Task SendTrigger(string eventName, Dictionary <string, string> values)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    JObject jobj = new JObject();
                    foreach (var kvp in values)
                    {
                        jobj[kvp.Key] = kvp.Value;
                    }
                    HttpContent content = new StringContent(JSONSerializerHelper.SerializeToString(jobj), Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync(string.Format(WebHookURLFormat, eventName, this.token.accessToken), content);

                    if (!response.IsSuccessStatusCode)
                    {
                        Logger.Log(await response.Content.ReadAsStringAsync());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
예제 #5
0
        public async Task <UserDataModel> GetUserDataByPlatformUsername(StreamingPlatformTypeEnum platform, string platformUsername)
        {
            if (string.IsNullOrEmpty(platformUsername) || platform == StreamingPlatformTypeEnum.None || platform == StreamingPlatformTypeEnum.All)
            {
                return(null);
            }

            if (this.platformUsernameLookups[platform].TryGetValue(platformUsername, out Guid id) && this.UserData.TryGetValue(id, out UserDataModel userData))
            {
                return(userData);
            }

            string columnName = null;

            switch (platform)
            {
            case StreamingPlatformTypeEnum.Twitch: columnName = "TwitchUsername"; break;
            }

            userData = null;
            if (!string.IsNullOrEmpty(columnName))
            {
                await ChannelSession.Services.Database.Read(this.DatabaseFilePath, "SELECT * FROM Users WHERE " + columnName + " LIKE $PlatformUsername",
                                                            new Dictionary <string, object>() { { "$PlatformUsername", platformUsername } },
                                                            (Dictionary <string, object> data) =>
                {
                    userData = JSONSerializerHelper.DeserializeFromString <UserDataModel>(data["Data"].ToString());
                });
            }

            this.SetUserData(userData);
            return(userData);
        }
 /// <summary>
 /// Generates the serialized packet array for sending over the web socket connection.
 /// </summary>
 /// <returns>The serialized packet array</returns>
 public string ToSerializedPacketArray()
 {
     return(JSONSerializerHelper.SerializeToString(new JArray()
     {
         this.JoinRef, this.NormalRef, this.Topic, this.Event, this.Payload
     }));
 }
예제 #7
0
        private async Task <bool> ConnectSocket()
        {
            await this.socket.Connect("https://nodeapi.treatstream.com/", "token=" + this.socketToken);

            this.socket.Listen("connect", (data) =>
            {
                this.WebSocketConnected = true;
            });

            this.socket.Listen("realTimeTreat", (data) =>
            {
                if (data != null)
                {
                    TreatStreamEvent tsEvent = JSONSerializerHelper.DeserializeFromString <TreatStreamEvent>(data.ToString());
                    if (tsEvent != null)
                    {
                        this.DonationOccurred(tsEvent);
                        Task.Run(async() =>
                        {
                            await EventService.ProcessDonationEvent(EventTypeEnum.TreatStreamDonation, tsEvent.ToGenericDonation());
                        });
                    }
                }
            });

            this.socket.Listen("error", async(errorData) =>
            {
                if (errorData != null)
                {
                    Logger.Log(errorData.ToString());
                }

                this.WebSocketDisconnectedOccurred();
                await this.ConnectSocket();
            });

            this.socket.Listen("disconnect", async(errorData) =>
            {
                if (errorData != null)
                {
                    Logger.Log(errorData.ToString());
                }

                this.WebSocketDisconnectedOccurred();
                await this.ConnectSocket();
            });

            for (int i = 0; i < 10 && !this.WebSocketConnected; i++)
            {
                await Task.Delay(1000);
            }

            if (this.WebSocketConnected)
            {
                this.WebSocketConnectedOccurred();
                return(true);
            }
            return(false);
        }
예제 #8
0
 public T GetContent <T>()
 {
     if (!string.IsNullOrEmpty(this.content))
     {
         return(JSONSerializerHelper.DeserializeFromString <T>(this.content));
     }
     return(default(T));
 }
예제 #9
0
 public static async Task <T> DeserializeAbstractFromFile <T>(string filePath, bool ignoreErrors = false)
 {
     if (File.Exists(filePath))
     {
         return(JSONSerializerHelper.DeserializeAbstractFromString <T>(await FileSerializerHelper.fileService.ReadFile(filePath), ignoreErrors));
     }
     return(default(T));
 }
예제 #10
0
        public async Task SaveDatabaseData()
        {
            if (this.IsStreamer)
            {
                IEnumerable <Guid> removedUsers = this.UserData.GetRemovedValues();
                await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "DELETE FROM Users WHERE ID = @ID", removedUsers.Select(u => new Dictionary <string, object>()
                {
                    { "@ID", u.ToString() }
                }));

                IEnumerable <UserDataModel> changedUsers = this.UserData.GetChangedValues();
                await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "REPLACE INTO Users(ID, Data) VALUES(@ID, @Data)",
                                                                 changedUsers.Select(u => new Dictionary <string, object>()
                {
                    { "@ID", u.ID.ToString() }, { "@Data", JSONSerializerHelper.SerializeToString(u) }
                }));

                List <Guid> removedCommands = new List <Guid>();
                removedCommands.AddRange(this.ChatCommands.GetRemovedValues().Select(c => c.ID));
                removedCommands.AddRange(this.EventCommands.GetRemovedValues().Select(c => c.ID));
                removedCommands.AddRange(this.TimerCommands.GetRemovedValues().Select(c => c.ID));
                removedCommands.AddRange(this.ActionGroupCommands.GetRemovedValues().Select(c => c.ID));
                removedCommands.AddRange(this.GameCommands.GetRemovedValues().Select(c => c.ID));
                removedCommands.AddRange(this.TwitchChannelPointsCommands.GetRemovedValues().Select(c => c.ID));
                removedCommands.AddRange(this.CustomCommands.GetRemovedValues());
                await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "DELETE FROM Commands WHERE ID = @ID",
                                                                 removedCommands.Select(id => new Dictionary <string, object>()
                {
                    { "@ID", id.ToString() }
                }));

                List <CommandBase> addedChangedCommands = new List <CommandBase>();
                addedChangedCommands.AddRange(this.ChatCommands.GetAddedChangedValues());
                addedChangedCommands.AddRange(this.EventCommands.GetAddedChangedValues());
                addedChangedCommands.AddRange(this.TimerCommands.GetAddedChangedValues());
                addedChangedCommands.AddRange(this.ActionGroupCommands.GetAddedChangedValues());
                addedChangedCommands.AddRange(this.GameCommands.GetAddedChangedValues());
                addedChangedCommands.AddRange(this.TwitchChannelPointsCommands.GetAddedChangedValues());
                addedChangedCommands.AddRange(this.CustomCommands.GetAddedChangedValues());
                await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "REPLACE INTO Commands(ID, TypeID, Data) VALUES(@ID, @TypeID, @Data)",
                                                                 addedChangedCommands.Select(c => new Dictionary <string, object>()
                {
                    { "@ID", c.ID.ToString() }, { "@TypeID", (int)c.Type }, { "@Data", JSONSerializerHelper.SerializeToString(c) }
                }));

                await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "DELETE FROM Quotes WHERE ID = @ID",
                                                                 this.Quotes.GetRemovedValues().Select(q => new Dictionary <string, object>()
                {
                    { "@ID", q.ID.ToString() }
                }));

                await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "REPLACE INTO Quotes(ID, Data) VALUES(@ID, @Data)",
                                                                 this.Quotes.GetAddedChangedValues().Select(q => new Dictionary <string, object>()
                {
                    { "@ID", q.ID.ToString() }, { "@Data", JSONSerializerHelper.SerializeToString(q.Model) }
                }));
            }
        }
        /// <summary>
        /// Updates the channel with the information supplied. Only limited information can be updated
        /// via this API. See the ChannelUpdateableModel for the fields that are updateable.
        /// </summary>
        /// <param name="channel">The channel to update</param>
        /// <returns>The updated channel</returns>
        public async Task <ChannelModel> UpdateChannel(ChannelModel channel)
        {
            Validator.ValidateVariable(channel, "channel");

            // Need to strip out all of the non-updateable fields in order for the API to not return a 403 error
            ChannelUpdateableModel updateableChannel = JSONSerializerHelper.Clone <ChannelUpdateableModel>(channel);

            return(await this.PatchAsync <ChannelModel>("channels/" + channel.id, this.CreateContentFromObject(updateableChannel)));
        }
예제 #12
0
        private async void UserClient_OnMessageReceived(object sender, ChatMessagePacketModel message)
        {
            if (message != null && !string.IsNullOrEmpty(message.Message))
            {
                if (!string.IsNullOrEmpty(message.UserLogin) && message.UserLogin.Equals("jtv"))
                {
                    if (Regex.IsMatch(message.Message, TwitchChatService.HostChatMessageRegexPattern))
                    {
                        Logger.Log(LogLevel.Debug, JSONSerializerHelper.SerializeToString(message));

                        string        hoster = message.Message.Substring(0, message.Message.IndexOf(' '));
                        UserViewModel user   = ChannelSession.Services.User.GetUserByUsername(hoster, StreamingPlatformTypeEnum.Twitch);
                        if (user == null)
                        {
                            UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByLogin(hoster);

                            if (twitchUser != null)
                            {
                                user = await ChannelSession.Services.User.AddOrUpdateUser(twitchUser);
                            }
                        }

                        if (user != null)
                        {
                            EventTrigger trigger = new EventTrigger(EventTypeEnum.TwitchChannelHosted, user);
                            if (ChannelSession.Services.Events.CanPerformEvent(trigger))
                            {
                                foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values.ToList())
                                {
                                    currency.AddAmount(user.Data, currency.OnHostBonus);
                                }

                                GlobalEvents.HostOccurred(user);

                                await ChannelSession.Services.Events.PerformEvent(trigger);

                                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} hosted the channel", user.Username), ChannelSession.Settings.AlertHostColor));
                            }
                        }
                    }
                }
                else
                {
                    UserViewModel user = ChannelSession.Services.User.GetUserByTwitchID(message.UserID);
                    if (user == null)
                    {
                        UserModel twitchUser = await ChannelSession.TwitchUserConnection.GetNewAPIUserByLogin(message.UserLogin);

                        if (twitchUser != null)
                        {
                            user = await ChannelSession.Services.User.AddOrUpdateUser(twitchUser);
                        }
                    }
                    this.OnMessageOccurred(this, new TwitchChatMessageViewModel(message, user));
                }
            }
        }
예제 #13
0
        public static async Task SerializeToFile <T>(string filePath, T data)
        {
            string dataString = JSONSerializerHelper.SerializeToString(data);

            if (!string.IsNullOrEmpty(dataString))
            {
                await FileSerializerHelper.fileService.SaveFile(filePath, dataString);
            }
        }
예제 #14
0
        public override void DuplicateAction(ActionContainerControl actionContainer)
        {
            List <ActionBase> actions = new List <ActionBase>()
            {
                actionContainer.GetAction()
            };

            actions = JSONSerializerHelper.Clone <List <ActionBase> >(actions);
            this.AddActionControlContainer(new ActionContainerControl(this.window, this, actions.First()));
        }
예제 #15
0
        private async void UserClient_OnUserNoticeReceived(object sender, ChatUserNoticePacketModel userNotice)
        {
            try
            {
                if (RaidUserNoticeMessageTypeID.Equals(userNotice.MessageTypeID))
                {
                    UserViewModel user = ChannelSession.Services.User.GetUserByTwitchID(userNotice.UserID.ToString());
                    if (user == null)
                    {
                        user = new UserViewModel(userNotice);
                    }
                    user.SetTwitchChatDetails(userNotice);

                    EventTrigger trigger = new EventTrigger(EventTypeEnum.TwitchChannelRaided, user);
                    if (ChannelSession.Services.Events.CanPerformEvent(trigger))
                    {
                        ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestRaidUserData]        = user.ID;
                        ChannelSession.Settings.LatestSpecialIdentifiersData[SpecialIdentifierStringBuilder.LatestRaidViewerCountData] = userNotice.RaidViewerCount;

                        foreach (CurrencyModel currency in ChannelSession.Settings.Currency.Values.ToList())
                        {
                            currency.AddAmount(user.Data, currency.OnHostBonus);
                        }

                        GlobalEvents.RaidOccurred(user, userNotice.RaidViewerCount);

                        trigger.SpecialIdentifiers["hostviewercount"] = userNotice.RaidViewerCount.ToString();
                        trigger.SpecialIdentifiers["raidviewercount"] = userNotice.RaidViewerCount.ToString();
                        await ChannelSession.Services.Events.PerformEvent(trigger);

                        await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} raided with {1} viewers", user.Username, userNotice.RaidViewerCount), ChannelSession.Settings.AlertRaidColor));
                    }
                }
                else if (SubMysteryGiftUserNoticeMessageTypeID.Equals(userNotice.MessageTypeID) && userNotice.SubTotalGifted > 0)
                {
                    if (ChannelSession.Services.Events.TwitchEventService != null)
                    {
                        await ChannelSession.Services.Events.TwitchEventService.AddMassGiftedSub(new TwitchMassGiftedSubEventModel(userNotice));
                    }
                }
                else if (SubGiftPaidUpgradeUserNoticeMessageTypeID.Equals(userNotice.MessageTypeID))
                {
                    if (ChannelSession.Services.Events.TwitchEventService != null)
                    {
                        await ChannelSession.Services.Events.TwitchEventService.AddSub(new TwitchSubEventModel(userNotice));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ForceLog(LogLevel.Debug, JSONSerializerHelper.SerializeToString(userNotice));
                Logger.Log(ex);
                throw ex;
            }
        }
        /// <summary>
        /// Updates the specified MixPlay game version.
        /// </summary>
        /// <param name="version">The MixPlay game version to update</param>
        /// <returns>The updated MixPlay game version</returns>
        public async Task <MixPlayGameVersionModel> UpdateMixPlayGameVersion(MixPlayGameVersionModel version)
        {
            Validator.ValidateVariable(version, "version");

            // Need to strip out all of the non-updateable fields in order for the API to not return a 403 error
            MixPlayGameVersionUpdateableModel updateableVersion = JSONSerializerHelper.Clone <MixPlayGameVersionUpdateableModel>(version);

            updateableVersion.controls = version.controls;

            return(await this.PutAsync <MixPlayGameVersionModel>("interactive/versions/" + version.id, this.CreateContentFromObject(updateableVersion)));
        }
예제 #17
0
        private async Task <bool> ConnectSocket()
        {
            try
            {
                this.WebSocketConnected     = false;
                this.socket.OnConnected    -= Socket_OnConnected;
                this.socket.OnDisconnected -= Socket_OnDisconnected;
                await this.socket.Disconnect();

                this.socket.OnConnected += Socket_OnConnected;

                this.socket.Listen("authenticated", () =>
                {
                    this.WebSocketConnected = true;
                });

                this.socket.Listen($"channel:{this.channel.ID}:tip", async(data) =>
                {
                    try
                    {
                        if (data != null)
                        {
                            RainmakerDonation donation = JSONSerializerHelper.DeserializeFromString <RainmakerDonation>(data.ToString());
                            if (donation != null && !string.IsNullOrEmpty(donation.Name) && donation.Amount >= 0)
                            {
                                await EventService.ProcessDonationEvent(EventTypeEnum.RainmakerDonation, donation.ToGenericDonation());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(ex);
                    }
                });

                await this.socket.Connect("wss://rainmaker.gg");

                for (int i = 0; i < 10 && !this.WebSocketConnected; i++)
                {
                    await Task.Delay(1000);
                }

                if (this.WebSocketConnected)
                {
                    this.socket.OnDisconnected += Socket_OnDisconnected;
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }

            return(this.WebSocketConnected);
        }
예제 #18
0
 public void SetCommands(IEnumerable <CommandModelBase> commands)
 {
     try
     {
         this.Data = JSONSerializerHelper.SerializeToString(commands);
     }
     catch (Exception ex)
     {
         Logger.Log(ex);
     }
 }
예제 #19
0
        public async Task LoadAllUserData()
        {
            if (!this.fullUserDataLoadOccurred)
            {
                this.fullUserDataLoadOccurred = true;

                await ChannelSession.Services.Database.Read(this.DatabaseFilePath, "SELECT * FROM Users", (Action <Dictionary <string, object> >)((Dictionary <string, object> data) =>
                {
                    this.SetUserData((UserDataModel)JSONSerializerHelper.DeserializeFromString <UserDataModel>((string)data[(string)"Data"].ToString()));
                }));
            }
        }
예제 #20
0
        private MethodPacket BuildUpdateScenesPacket(IEnumerable <MixPlayConnectedSceneModel> scenes)
        {
            Validator.ValidateList(scenes, "scenes");
            MixPlayConnectedSceneCollectionModel collection = new MixPlayConnectedSceneCollectionModel();

            foreach (MixPlayConnectedSceneModel scene in scenes)
            {
                // Need to strip out all of the non-updateable fields in order for the API to not return a 403 error
                collection.scenes.Add(JSONSerializerHelper.Clone <MixPlayConnectedSceneModel>(scene));
            }
            return(new MethodParamsPacket("updateScenes", JObject.FromObject(collection)));
        }
예제 #21
0
        public async Task SendIssueReport(IssueReportModel report)
        {
            string content  = JSONSerializerHelper.SerializeToString(report);
            var    response = await this.PostAsync("issuereport", new StringContent(content, Encoding.UTF8, "application/json"));

            if (!response.IsSuccessStatusCode)
            {
                string resultContent = await response.Content.ReadAsStringAsync();

                Logger.Log(resultContent);
            }
        }
예제 #22
0
 public List <CommandModelBase> GetCommands()
 {
     try
     {
         return(JSONSerializerHelper.DeserializeFromString <List <CommandModelBase> >(this.Data));
     }
     catch (Exception ex)
     {
         Logger.Log(ex);
     }
     return(null);
 }
예제 #23
0
        protected override async Task ProcessReceivedPacket(string packetJSON)
        {
            try
            {
                DiscordWebSocketPacket packet = JSONSerializerHelper.DeserializeFromString <DiscordWebSocketPacket>(packetJSON);
                this.lastSequenceNumber = packet.Sequence;

                switch (packet.OPCodeType)
                {
                case DiscordWebSocketPacketTypeEnum.Other:
                    if (packet.IsReadyPacket)
                    {
                        this.BotUser   = new DiscordUser((JObject)packet.Data["user"]);
                        this.sessionID = packet.Data["session_id"].ToString();
                        this.IsReady   = true;
                    }
                    break;

                case DiscordWebSocketPacketTypeEnum.Heartbeat:
                    break;

                case DiscordWebSocketPacketTypeEnum.Hello:
                    this.heartbeatTime = (int)packet.Data["heartbeat_interval"];

                    JObject data = new JObject();
                    data["token"]           = this.botToken;
                    data["large_threshold"] = 100;

                    JObject propertiesObj = new JObject();
                    propertiesObj["$device"] = "Mix It Up";
                    data["properties"]       = propertiesObj;

                    DiscordWebSocketPacket identifyPacket = new DiscordWebSocketPacket()
                    {
                        OPCodeType = DiscordWebSocketPacketTypeEnum.Identify, Data = data
                    };
                    await this.Send(identifyPacket);

                    break;

                case DiscordWebSocketPacketTypeEnum.HeartbeatAck:
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
예제 #24
0
        /// <summary>
        /// Validates whether the specific JWT bearer token is valid and returns the payload of the token if successful.
        /// </summary>
        /// <param name="bearerToken">The authentication bearer token</param>
        /// <param name="clientSecret">The client secret of the extension</param>
        /// <param name="payload">The payload contained in the JWT bearer token</param>
        /// <returns>An error message indicating why the validation failed, null if successful</returns>
        public static string ValidateAuthenticationToken(string bearerToken, string clientSecret, out TwitchJWTTokenPayloadModel payload)
        {
            Validator.ValidateString(bearerToken, "bearerToken");
            Validator.ValidateString(clientSecret, "clientSecret");

            payload = null;
            if (!string.IsNullOrEmpty(bearerToken))
            {
                bearerToken = bearerToken.Replace("Bearer ", "");
            }

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            if (!tokenHandler.CanReadToken(bearerToken))
            {
                return("Invalid JWT token");
            }

            var validationParameters = new TokenValidationParameters
            {
                ValidateAudience         = false,
                ValidateIssuer           = false,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Convert.FromBase64String(clientSecret))
            };

            JwtSecurityToken token = null;

            try
            {
                tokenHandler.ValidateToken(bearerToken, validationParameters, out SecurityToken validatedToken);
                if (validatedToken != null)
                {
                    token = (JwtSecurityToken)validatedToken;
                }
            }
            catch (Exception ex)
            {
                return("Token validation failed - " + ex.ToString());
            }

            if (token != null && token.Payload != null)
            {
                payload = JSONSerializerHelper.DeserializeFromString <TwitchJWTTokenPayloadModel>(token.Payload.SerializeToJson());
                if (payload != null && !string.IsNullOrEmpty(payload.channel_id) && !string.IsNullOrEmpty(payload.opaque_user_id))
                {
                    return(null);
                }
            }
            return("Mising or invalid payload");
        }
예제 #25
0
        private async Task PutAsync(string endpoint, object data)
        {
            try
            {
                using (AdvancedHttpClient client = new AdvancedHttpClient(MixItUpAPIEndpoint))
                {
                    string content = JSONSerializerHelper.SerializeToString(data);
                    HttpResponseMessage response = await client.PutAsync(endpoint, new StringContent(content, Encoding.UTF8, "application/json"));

                    await this.ProcessResponseIfError(response);
                }
            }
            catch (Exception ex) { Logger.Log(ex); }
        }
예제 #26
0
 private Guid DuplicateCommand(Guid id)
 {
     if (id != Guid.Empty)
     {
         CustomCommandModel command = (CustomCommandModel)ChannelSession.Settings.GetCommand(id);
         if (command != null)
         {
             command    = JSONSerializerHelper.DeserializeFromString <CustomCommandModel>(JSONSerializerHelper.SerializeToString(command));
             command.ID = Guid.NewGuid();
             ChannelSession.Settings.SetCommand(command);
             return(command.ID);
         }
     }
     return(Guid.Empty);
 }
        /// <summary>
        /// Processes a JSON packet received from the server.
        /// </summary>
        /// <param name="packet">The packet JSON</param>
        /// <returns>An awaitable Task</returns>
        protected override Task ProcessReceivedPacket(string packet)
        {
            List <JToken> packetJTokens = new List <JToken>();

            JToken packetJToken = JToken.Parse(packet);

            if (packetJToken is JArray)
            {
                foreach (JToken t in (JArray)packetJToken)
                {
                    packetJTokens.Add(t);
                }
            }
            else
            {
                packetJTokens.Add(packetJToken);
            }

            foreach (JToken token in packetJTokens)
            {
                WebSocketPacket webSocketPacket = token.ToObject <WebSocketPacket>();
                string          data            = JSONSerializerHelper.SerializeToString(token);

                this.OnPacketReceivedOccurred?.Invoke(this, webSocketPacket);

                if (webSocketPacket.type.Equals("method"))
                {
                    MethodPacket methodPacket = JsonConvert.DeserializeObject <MethodPacket>(data);
                    this.SendSpecificPacket(methodPacket, this.OnMethodOccurred);
                }
                else if (webSocketPacket.type.Equals("reply"))
                {
                    ReplyPacket replyPacket = JsonConvert.DeserializeObject <ReplyPacket>(data);
                    if (this.replyIDListeners.ContainsKey(replyPacket.id))
                    {
                        this.replyIDListeners[replyPacket.id] = replyPacket;
                    }
                    this.SendSpecificPacket(replyPacket, this.OnReplyOccurred);
                }
                else if (webSocketPacket.type.Equals("event"))
                {
                    EventPacket eventPacket = JsonConvert.DeserializeObject <EventPacket>(data);
                    this.SendSpecificPacket(eventPacket, this.OnEventOccurred);
                }
            }

            return(Task.FromResult(0));
        }
예제 #28
0
        public async Task Send(WebSocketPacket packet)
        {
            try
            {
                foreach (WebSocketServerBase webSocketServer in this.webSocketServers)
                {
                    Logger.Log(LogLevel.Debug, "Sending Web Socket Packet - " + JSONSerializerHelper.SerializeToString(packet));

                    await webSocketServer.Send(packet);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
예제 #29
0
        private async Task PatchAsync(string endpoint, object data)
        {
            try
            {
                using (AdvancedHttpClient client = new AdvancedHttpClient(MixItUpAPIEndpoint))
                {
                    string             content = JSONSerializerHelper.SerializeToString(data);
                    HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("PATCH"), endpoint);
                    message.Content = new StringContent(content, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.SendAsync(message);

                    await this.ProcessResponseIfError(response);
                }
            }
            catch (Exception ex) { Logger.Log(ex); }
        }
예제 #30
0
        /// <summary>
        /// Processes the webhook request sent from Twitch.
        /// </summary>
        /// <typeparam name="T">The type of data contained in the webhook request</typeparam>
        /// <param name="request">The Http request made</param>
        /// <param name="secret">The optional secret used for request verification</param>
        /// <returns>The webhook result</returns>
        public static async Task <WebhookResultModel <T> > GetWebhookResult <T>(HttpRequest request, string secret = null)
        {
            string headerSignature = null;

            if (request.Headers.ContainsKey("X-Hub-Signature"))
            {
                headerSignature = request.Headers["X-Hub-Signature"];
                headerSignature = headerSignature.Split('=').LastOrDefault();
            }
            long headerContentLength = request.ContentLength.GetValueOrDefault();

            string body = string.Empty;
            long   bodyContentLength = 0;
            string bodySignature     = null;

            using (StreamReader reader = new StreamReader(request.Body))
            {
                body = await reader.ReadToEndAsync();
            }

            Dictionary <string, string> queryParameters = new Dictionary <string, string>();

            foreach (var kvp in request.Query)
            {
                queryParameters[kvp.Key] = kvp.Value;
            }

            WebhookDataWrapperModel <T> dataWrapper = null;

            if (!string.IsNullOrEmpty(body))
            {
                bodyContentLength = body.Length;
                if (!string.IsNullOrEmpty(secret))
                {
                    byte[] secretBytes = Encoding.UTF8.GetBytes(secret);
                    using (HMACSHA256 hmacSha256 = new HMACSHA256(secretBytes))
                    {
                        byte[] hashBytes = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(body));
                        bodySignature = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
                    }
                }
                dataWrapper = JSONSerializerHelper.DeserializeFromString <WebhookDataWrapperModel <T> >(body);
            }

            return(new WebhookResultModel <T>(headerSignature, headerContentLength, bodySignature, bodyContentLength, queryParameters, (dataWrapper != null) ? dataWrapper.data : new List <T>()));
        }