Пример #1
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));
        }
Пример #2
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);
            }
        }
 /// <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
     }));
 }
Пример #4
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) }
                }));
            }
        }
Пример #5
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));
                }
            }
        }
Пример #6
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);
            }
        }
Пример #7
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;
            }
        }
Пример #8
0
 public void SetCommands(IEnumerable <CommandModelBase> commands)
 {
     try
     {
         this.Data = JSONSerializerHelper.SerializeToString(commands);
     }
     catch (Exception ex)
     {
         Logger.Log(ex);
     }
 }
Пример #9
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);
            }
        }
Пример #10
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); }
        }
        /// <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));
        }
Пример #12
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); }
        }
Пример #13
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);
            }
        }
Пример #14
0
        public async Task <VTubeStudioWebSocketResponsePacket> SendAndReceive(VTubeStudioWebSocketRequestPacket packet, int delaySeconds = 5)
        {
            Logger.Log(LogLevel.Debug, "VTube Studio Packet Sent - " + JSONSerializerHelper.SerializeToString(packet));

            this.responses.Remove(packet.requestID);

            await this.Send(JSONSerializerHelper.SerializeToString(packet));

            int cycles = delaySeconds * 10;

            for (int i = 0; i < cycles && !this.responses.ContainsKey(packet.requestID); i++)
            {
                await Task.Delay(100);
            }

            this.responses.TryGetValue(packet.requestID, out VTubeStudioWebSocketResponsePacket response);
            return(response);
        }
Пример #15
0
        private static async void Chat_OnPacketReceived(object sender, Base.Models.Clients.Chat.ChatRawPacketModel packet)
        {
            if (!packet.Command.Equals("PING") && !packet.Command.Equals(ChatMessagePacketModel.CommandID) && !packet.Command.Equals(ChatUserJoinPacketModel.CommandID) &&
                !packet.Command.Equals(ChatUserLeavePacketModel.CommandID))
            {
                System.Console.WriteLine("PACKET: " + packet.Command);

                await semaphore.WaitAndRelease(async() =>
                {
                    using (StreamWriter writer = new StreamWriter(File.Open("Packets.txt", FileMode.Append)))
                    {
                        await writer.WriteLineAsync(JSONSerializerHelper.SerializeToString(packet));
                        await writer.WriteLineAsync();
                        await writer.FlushAsync();
                    }
                });
            }
        }
Пример #16
0
        public async Task SaveDatabaseData()
        {
            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.GetAddedChangedValues();
            await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath,
                                                             "REPLACE INTO Users(ID, TwitchID, TwitchUsername, YouTubeID, YouTubeUsername, FacebookID, FacebookUsername, TrovoID, TrovoUsername, GlimeshID, GlimeshUsername, Data) " +
                                                             "VALUES($ID, $TwitchID, $TwitchUsername, $YouTubeID, $YouTubeUsername, $FacebookID, $FacebookUsername, $TrovoID, $TrovoUsername, $GlimeshID, $GlimeshUsername, $Data)",
                                                             changedUsers.Select(u => new Dictionary <string, object>()
            {
                { "$ID", u.ID.ToString() }, { "$TwitchID", u.TwitchID }, { "$TwitchUsername", u.TwitchUsername }, { "$YouTubeID", null }, { "$YouTubeUsername", null },
                { "$FacebookID", null }, { "$FacebookUsername", null }, { "$TrovoID", null }, { "$TrovoUsername", null }, { "$GlimeshID", null }, { "$GlimeshUsername", null },
                { "$Data", JSONSerializerHelper.SerializeToString(u) }
            }));

            List <Guid> removedCommands = new List <Guid>();
            await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "DELETE FROM Commands WHERE ID = $ID",
                                                             this.Commands.GetRemovedValues().Select(id => new Dictionary <string, object>()
            {
                { "$ID", id.ToString() }
            }));

            await ChannelSession.Services.Database.BulkWrite(this.DatabaseFilePath, "REPLACE INTO Commands(ID, TypeID, Data) VALUES($ID, $TypeID, $Data)",
                                                             this.Commands.GetAddedChangedValues().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, Quote, GameName, DateTime) VALUES($ID, $Quote, $GameName, $DateTime)",
                                                             this.Quotes.GetAddedChangedValues().Select(q => new Dictionary <string, object>()
            {
                { "$ID", q.ID.ToString() }, { "$Quote", q.Quote }, { "$GameName", q.GameName }, { "$DateTime", q.DateTime.ToString() }
            }));
        }
Пример #17
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        hosterUsername = message.Message.Substring(0, message.Message.IndexOf(' '));
                        UserViewModel user           = await ChannelSession.Services.User.GetUserFullSearch(StreamingPlatformTypeEnum.Twitch, userID : null, hosterUsername);

                        if (user != null)
                        {
                            await ChannelSession.Services.User.AddOrUpdateActiveUser(user);

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

                                GlobalEvents.HostOccurred(user);

                                await ChannelSession.Services.Events.PerformEvent(EventTypeEnum.TwitchChannelHosted, parameters);

                                await ChannelSession.Services.Alerts.AddAlert(new AlertChatMessageViewModel(StreamingPlatformTypeEnum.Twitch, user, string.Format("{0} hosted the channel", user.FullDisplayName), ChannelSession.Settings.AlertHostColor));
                            }
                        }
                    }
                }
                else
                {
                    UserViewModel user = await ChannelSession.Services.User.GetUserFullSearch(StreamingPlatformTypeEnum.Twitch, message.UserID, message.UserLogin);

                    this.OnMessageOccurred(this, new TwitchChatMessageViewModel(message, user));
                }
            }
        }
Пример #18
0
        public IEnumerable <T> GetChangedValues()
        {
            Dictionary <T, int> currentHashes = new Dictionary <T, int>();

            foreach (T value in this.ToList())
            {
                currentHashes[value] = JSONSerializerHelper.SerializeToString(value).GetHashCode();
            }

            List <T> results = new List <T>();

            lock (valuesUpdateLock)
            {
                foreach (var current in currentHashes)
                {
                    if (this.changedValues.ContainsKey(current.Key) && this.changedValues[current.Key] != current.Value)
                    {
                        results.Add(current.Key);
                    }
                    this.changedValues[current.Key] = current.Value;
                }
            }
            return(results);
        }
Пример #19
0
        private async Task <T> PostAsyncWithResult <T>(string endpoint, object data)
        {
            try
            {
                using (AdvancedHttpClient client = new AdvancedHttpClient(MixItUpAPIEndpoint))
                {
                    string content = JSONSerializerHelper.SerializeToString(data);
                    HttpResponseMessage response = await client.PostAsync(endpoint, new StringContent(content, Encoding.UTF8, "application/json"));

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string resultContent = await response.Content.ReadAsStringAsync();

                        return(JSONSerializerHelper.DeserializeFromString <T>(resultContent));
                    }
                    else
                    {
                        await this.ProcessResponseIfError(response);
                    }
                }
            }
            catch (Exception ex) { Logger.Log(ex); }
            return(default(T));
        }
Пример #20
0
        /// <summary>
        /// Sends a chat message to the specified channel from the extension.
        /// </summary>
        /// <param name="clientID">The client ID of the extension</param>
        /// <param name="clientSecret">The client secret of the extension</param>
        /// <param name="ownerID">The owner user ID of the extension</param>
        /// <param name="version">The version of the extension</param>
        /// <param name="channelID">The channel ID to broadcast to</param>
        /// <param name="message">The message to send</param>
        /// <returns>Whether the chat message send was successful. Throws a HttpRestRequestException in the event of failed request</returns>
        public static async Task <bool> SendChatMessage(string clientID, string clientSecret, string ownerID, string version, string channelID, string message)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateString(clientSecret, "clientSecret");
            Validator.ValidateString(ownerID, "ownerID");
            Validator.ValidateString(version, "version");
            Validator.ValidateString(channelID, "channelID");
            Validator.ValidateString(message, "message");

            using (AdvancedHttpClient client = TwitchExtensionService.GetHttpClient(clientID, clientSecret, ownerID, channelID))
            {
                HttpResponseMessage response = await client.PostAsync($"https://api.twitch.tv/extensions/{clientID}/{version}/channels/{channelID}/chat",
                                                                      AdvancedHttpClient.CreateContentFromString(JSONSerializerHelper.SerializeToString(new ExtensionChatMessageModel(message))));

                if (response.IsSuccessStatusCode)
                {
                    return(true);
                }
                else
                {
                    throw new HttpRestRequestException(response);
                }
            }
        }
Пример #21
0
        private void PubSub_OnMessageReceived(object sender, PubSubMessagePacketModel packet)
        {
            Logger.Log(LogLevel.Debug, string.Format("PUB SUB MESSAGE: {0} {1} ", packet.type, packet.message));

            Logger.Log(LogLevel.Debug, JSONSerializerHelper.SerializeToString(packet));
        }
Пример #22
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);
 }
Пример #23
0
 private void Client_OnPacketReceived(object sender, ChatRawPacketModel packet)
 {
     if (!TwitchChatService.ExcludedDiagnosticPacketLogging.Contains(packet.Command))
     {
         if (ChannelSession.AppSettings.DiagnosticLogging)
         {
             Logger.Log(LogLevel.Debug, string.Format("Twitch Client Packet Received: {0}", JSONSerializerHelper.SerializeToString(packet)));
         }
     }
 }
        public async Task BulkWrite(string databaseFilePath, string commandString, IEnumerable <Dictionary <string, object> > parameters)
        {
            await this.EstablishConnection(databaseFilePath, async (connection) =>
            {
                for (int i = 0; i < parameters.Count(); i += WindowsDatabaseService.MaxBulkInsertRows)
                {
                    var rowsToInsert = parameters.Skip(i).Take(WindowsDatabaseService.MaxBulkInsertRows);

                    using (SQLiteTransaction transaction = connection.BeginTransaction())
                    {
                        using (SQLiteCommand command = new SQLiteCommand(commandString, connection))
                        {
                            foreach (Dictionary <string, object> rowParameters in rowsToInsert)
                            {
                                try
                                {
                                    foreach (var kvp in rowParameters)
                                    {
                                        command.Parameters.Add(new SQLiteParameter(kvp.Key, value: kvp.Value));
                                    }

                                    Logger.Log(LogLevel.Debug, string.Format("SQLite Query: {0} - {1}", commandString, JSONSerializerHelper.SerializeToString(rowParameters)));

                                    await command.ExecuteNonQueryAsync();
                                    command.Parameters.Clear();
                                }
                                catch (Exception ex) { Logger.Log(ex); }
                            }
                        }
                        transaction.Commit();
                    }
                }
            });
        }
Пример #25
0
 /// <summary>
 /// Logs a YouTube service response
 /// </summary>
 /// <typeparam name="T">The type of the request</typeparam>
 /// <param name="request">The request to log</param>
 /// <param name="response">The response to log</param>
 protected void LogResponse <T>(YouTubePartnerBaseServiceRequest <T> request, IDirectResponseSchema response)
 {
     if (Logger.Level == LogLevel.Debug)
     {
         Logger.Log(LogLevel.Debug, "Rest API Request Complete: " + request.RestPath + " - " + JSONSerializerHelper.SerializeToString(response));
     }
 }
Пример #26
0
 /// <summary>
 /// Logs a YouTube service request.
 /// </summary>
 /// <typeparam name="T">The type of the request</typeparam>
 /// <param name="request">The request to log</param>
 protected void LogRequest <T>(YouTubePartnerBaseServiceRequest <T> request)
 {
     if (Logger.Level == LogLevel.Debug)
     {
         Logger.Log(LogLevel.Debug, "Rest API Request Sent: " + request.RestPath + " - " + JSONSerializerHelper.SerializeToString(request, propertiesToIgnore: requestPropertiesToIgnore));
     }
 }
Пример #27
0
 /// <summary>
 /// Sends the specified packet.
 /// </summary>
 /// <param name="packet">The packet to send</param>
 /// <returns>An awaitable Task</returns>
 protected async Task Send(ChatPacketModel packet)
 {
     await this.Send(JSONSerializerHelper.SerializeToString(packet));
 }
 private async Task Send(PubSubPacketModel packet)
 {
     await this.Send(JSONSerializerHelper.SerializeToString(packet));
 }
 /// <summary>
 /// Sends a ping packet.
 /// </summary>
 /// <returns>An awaitable Task</returns>
 public async Task Ping()
 {
     await this.Send(JSONSerializerHelper.SerializeToString(new { type = "PING" }));
 }
Пример #30
0
        /// <summary>
        /// Sends a broadcast to PubSub for the extension.
        /// </summary>
        /// <param name="clientID">The client ID of the extension</param>
        /// <param name="clientSecret">The client secret of the extension</param>
        /// <param name="ownerID">The owner user ID of the extension</param>
        /// <param name="channelID">The channel ID to broadcast to</param>
        /// <param name="data">The data to broadcast</param>
        /// <returns>Whether the broadcast was successful or not. Throws a HttpRestRequestException in the event of failed request</returns>
        public static async Task <bool> SendBroadcast(string clientID, string clientSecret, string ownerID, string channelID, object data)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateString(clientSecret, "clientSecret");
            Validator.ValidateString(ownerID, "ownerID");
            Validator.ValidateString(channelID, "channelID");
            Validator.ValidateVariable(data, "data");

            using (AdvancedHttpClient client = TwitchExtensionService.GetHttpClient(clientID, clientSecret, ownerID, channelID))
            {
                HttpResponseMessage response = await client.PostAsync("https://api.twitch.tv/extensions/message/" + channelID,
                                                                      AdvancedHttpClient.CreateContentFromString(JSONSerializerHelper.SerializeToString(new BroadcastBodyModel(data))));

                if (response.IsSuccessStatusCode)
                {
                    return(true);
                }
                else
                {
                    throw new HttpRestRequestException(response);
                }
            }
        }