예제 #1
0
        public void TestRestartAfterAbort([Values(true, false)] bool async)
        {
            var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get")
            {
                Method = HttpMethod.Get,
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

            Task.Run(() => request.PerformAsync());

            Assert.DoesNotThrow(request.Abort);

            if (async)
            {
                Assert.ThrowsAsync <OperationCanceledException>(() => request.PerformAsync());
            }
            else
            {
                Assert.Throws <TaskCanceledException>(request.Perform);
            }

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            var responseObject = request.ResponseObject;

            Assert.IsTrue(responseObject == null);
            Assert.IsFalse(hasThrown);
        }
예제 #2
0
        public void TestRestartAfterAbortViaCancellationToken()
        {
            var cancellationSource = new CancellationTokenSource();
            var request            = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get")
            {
                Method = HttpMethod.Get,
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

            cancellationSource.Cancel();
            request.PerformAsync(cancellationSource.Token).WaitSafely();

            Assert.ThrowsAsync <OperationCanceledException>(() => request.PerformAsync(cancellationSource.Token));

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            var responseObject = request.ResponseObject;

            Assert.IsTrue(responseObject == null);
            Assert.IsFalse(hasThrown);
        }
예제 #3
0
        private static void testValidGetInternal(bool async, JsonWebRequest <HttpBinGetResponse> request, string expectedUserAgent)
        {
            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

            if (async)
            {
                Assert.DoesNotThrowAsync(() => request.PerformAsync());
            }
            else
            {
                Assert.DoesNotThrow(request.Perform);
            }

            Assert.IsTrue(request.Completed);
            Assert.IsFalse(request.Aborted);

            var responseObject = request.ResponseObject;

            Assert.IsTrue(responseObject != null);
            Assert.IsTrue(responseObject.Headers.UserAgent == expectedUserAgent);

            // disabled due to hosted version returning incorrect response (https://github.com/postmanlabs/httpbin/issues/545)
            // Assert.AreEqual(url, responseObject.Url);

            Assert.IsFalse(hasThrown);
        }
예제 #4
0
        public void TestPostWithJsonRequest([Values(true, false)] bool async)
        {
            var request = new JsonWebRequest <HttpBinPostResponse>($"{default_protocol}://{host}/post")
            {
                Method = HttpMethod.Post,
                AllowInsecureRequests = true,
            };

            var testObject = new TestObject();

            request.AddRaw(JsonConvert.SerializeObject(testObject));

            if (async)
            {
                Assert.DoesNotThrowAsync(() => request.PerformAsync());
            }
            else
            {
                Assert.DoesNotThrow(request.Perform);
            }

            var responseObject = request.ResponseObject;

            Assert.IsTrue(request.Completed);
            Assert.IsFalse(request.Aborted);

            Assert.IsTrue(responseObject.Headers.ContentLength > 0);
            Assert.IsTrue(responseObject.Json != null);
            Assert.AreEqual(testObject.TestString, responseObject.Json.TestString);

            Assert.IsTrue(responseObject.Headers.ContentType == null);
        }
예제 #5
0
        public void TestAbortRequest()
        {
            var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get")
            {
                Method = HttpMethod.Get,
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

#pragma warning disable 4014
            request.PerformAsync();
#pragma warning restore 4014

            Assert.DoesNotThrow(request.Abort);

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            Assert.IsTrue(request.ResponseObject == null);

            Assert.IsFalse(hasThrown);
        }
예제 #6
0
        public void TestJsonWebRequestThrowsCorrectlyOnMultipleErrors([Values(true, false)] bool async)
        {
            var request = new JsonWebRequest <Drawable>("badrequest://www.google.com")
            {
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

            if (async)
            {
                Assert.ThrowsAsync <NotSupportedException>(() => request.PerformAsync());
            }
            else
            {
                Assert.Throws <NotSupportedException>(request.Perform);
            }

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            Assert.IsNull(request.GetResponseString());
            Assert.IsNull(request.ResponseObject);

            Assert.IsTrue(hasThrown);
        }
예제 #7
0
        public void TestAbortReceive([Values(true, false)] bool async)
        {
            var request = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get")
            {
                Method = HttpMethod.Get,
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed  += exception => hasThrown = exception != null;
            request.Started += () => request.Abort();

            if (async)
            {
                Assert.DoesNotThrowAsync(() => request.PerformAsync());
            }
            else
            {
                Assert.DoesNotThrow(request.Perform);
            }

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            Assert.IsTrue(request.ResponseObject == null);

            Assert.IsFalse(hasThrown);
        }
예제 #8
0
        private async void checkForUpdateAsync()
        {
            try
            {
                var releases = new JsonWebRequest <GitHubRelease>("https://api.github.com/repos/ppy/osu/releases/latest");

                await releases.PerformAsync();

                var latest = releases.ResponseObject;

                if (latest.TagName != version)
                {
                    notificationOverlay.Post(new SimpleNotification
                    {
                        Text = $"A newer release of osu! has been found ({version} → {latest.TagName}).\n\n"
                               + "Click here to download the new version, which can be installed over the top of your existing installation",
                        Icon      = FontAwesome.Solid.Upload,
                        Activated = () =>
                        {
                            host.OpenUrlExternally(getBestUrl(latest));
                            return(true);
                        }
                    });
                }
            }
            catch
            {
                // we shouldn't crash on a web failure. or any failure for the matter.
            }
        }
예제 #9
0
        public void TestRestartAfterAbort(bool async)
        {
            var request = new JsonWebRequest <HttpBinGetResponse>("https://httpbin.org/get")
            {
                Method = HttpMethod.GET
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

#pragma warning disable 4014
            request.PerformAsync();
#pragma warning restore 4014

            Assert.DoesNotThrow(request.Abort);

            if (async)
            {
                Assert.ThrowsAsync <InvalidOperationException>(request.PerformAsync);
            }
            else
            {
                Assert.Throws <InvalidOperationException>(request.Perform);
            }

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            var responseObject = request.ResponseObject;

            Assert.IsTrue(responseObject == null);
            Assert.IsFalse(hasThrown);
        }
예제 #10
0
        private async void Load()
        {
            var jwr = new JsonWebRequest <GitHubRelease>("https://api.github.com/repos/osuAkatsuki/Qsor/releases/latest");

            await jwr.PerformAsync();

            _updateManager = new UpdateManager($"https://github.com/osuAkatsuki/Qsor/releases/download/{jwr.ResponseObject.TagName}/");
        }
예제 #11
0
        private async Task <dynamic> getJsonFromApi(string request)
        {
            using (var req = new JsonWebRequest <dynamic>($"{base_url}/api/{request}"))
            {
                await req.PerformAsync();

                return(req.ResponseObject);
            }
        }
예제 #12
0
        public static async Task <bool> VerifyAccessToken(string accessToken)
        {
            var secret = Environment.GetEnvironmentVariable("HCAPTCHA_SECRET");

            if (string.IsNullOrEmpty(secret)) // Ignore if invalid or not
            {
                return(true);
            }

            var webRequest = new JsonWebRequest <HCaptchaResponse>("https://hcaptcha.com/siteverify")
            {
                Method = HttpMethod.Post
            };

            webRequest.AddParameter("response", accessToken);
            webRequest.AddParameter("secret", secret);

            await webRequest.PerformAsync();

            return(webRequest.ResponseObject.Success);
        }
        public void TestCancelReceive()
        {
            var cancellationSource = new CancellationTokenSource();
            var request            = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get")
            {
                Method = HttpMethod.Get,
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed  += exception => hasThrown = exception != null;
            request.Started += () => cancellationSource.Cancel();

            Assert.DoesNotThrowAsync(() => request.PerformAsync(cancellationSource.Token));

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            Assert.IsTrue(request.ResponseObject == null);
            Assert.IsFalse(hasThrown);
        }
예제 #14
0
        public void TestPostWithJsonResponse([Values(true, false)] bool async)
        {
            var request = new JsonWebRequest <HttpBinPostResponse>($"{default_protocol}://{host}/post")
            {
                Method = HttpMethod.Post,
                AllowInsecureRequests = true,
            };

            request.AddParameter("testkey1", "testval1");
            request.AddParameter("testkey2", "testval2");

            if (async)
            {
                Assert.DoesNotThrowAsync(() => request.PerformAsync());
            }
            else
            {
                Assert.DoesNotThrow(request.Perform);
            }

            var responseObject = request.ResponseObject;

            Assert.IsTrue(request.Completed);
            Assert.IsFalse(request.Aborted);

            Assert.IsTrue(responseObject.Form != null);
            Assert.IsTrue(responseObject.Form.Count == 2);

            Assert.IsTrue(responseObject.Headers.ContentLength > 0);

            Assert.IsTrue(responseObject.Form.ContainsKey("testkey1"));
            Assert.IsTrue(responseObject.Form["testkey1"] == "testval1");

            Assert.IsTrue(responseObject.Form.ContainsKey("testkey2"));
            Assert.IsTrue(responseObject.Form["testkey2"] == "testval2");

            Assert.IsTrue(responseObject.Headers.ContentType.StartsWith("multipart/form-data; boundary=", StringComparison.Ordinal));
        }
        public async Task TestCancelRequest()
        {
            var cancellationSource = new CancellationTokenSource();
            var request            = new JsonWebRequest <HttpBinGetResponse>($"{default_protocol}://{host}/get")
            {
                Method = HttpMethod.Get,
                AllowInsecureRequests = true,
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

            cancellationSource.Cancel();
            await request.PerformAsync(cancellationSource.Token).ConfigureAwait(false);

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            Assert.IsTrue(request.ResponseObject == null);

            Assert.IsFalse(hasThrown);
        }
예제 #16
0
        public void TestAbortRequest()
        {
            var request = new JsonWebRequest <HttpBinGetResponse>("https://httpbin.org/get")
            {
                Method = HttpMethod.GET
            };

            bool hasThrown = false;

            request.Failed += exception => hasThrown = exception != null;

#pragma warning disable 4014
            request.PerformAsync();
#pragma warning restore 4014

            Assert.DoesNotThrow(request.Abort);

            Assert.IsTrue(request.Completed);
            Assert.IsTrue(request.Aborted);

            Assert.IsTrue(request.ResponseObject == null);

            Assert.IsFalse(hasThrown);
        }
예제 #17
0
        static void Main(string[] args)
        {
            //RC-Channel-ID 30773965
            //ChatRoom 1a1bd140-55b3-4a63-815c-077b094ffba1


            try
            {
                ///Load bot configuration
                Config         = new BotConfiguration(Storage = new WindowsStorage("FoxBot"));
                Channel        = Config.GetBindable <string>(BotSetting.Channel);
                ChatBotChannel = Config.GetBindable <string>(BotSetting.BotChatRoom);

                ///Set log folder
                Logger.Storage = Storage.GetStorageForDirectory("logs");

                ///Create if not exist
                Directory.CreateDirectory("./Modues");

                ///Create client instance
                client = new IrcClient()
                {
                    //Username = Nick,
                    //AuthToken = ServerPass,
                };

                ///Initialize command service
                commands = new CommandService(new CommandServiceConfig()
                {
                    CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync,
                });

                ///Create form instance
                Form = new DialogWindow();

                ///------------------------------=================


                bool interrupt = false;
                ///Modules update thread. Please, use async func for long timed work in case not blocking other modules
                Thread updateThread = new Thread(() =>
                {
                    while (!interrupt)
                    {
                        ///update
                        if (DateTimeOffset.Now > GetUserListTimout)
                        {
                            var req = new JsonWebRequest <ChatData>($"https://tmi.twitch.tv/group/user/{Channel.Value.Replace("#", "")}/chatters");

                            req.Finished += () =>
                            {
                                DialogWindow.UpdateChattersList(req.ResponseObject);

                                if (BotEntry.ChannelsChatters.ContainsKey(BotEntry.Channel))
                                {
                                    BotEntry.ChannelsChatters[BotEntry.Channel] = req.ResponseObject.chatters;
                                }
                                else
                                {
                                    BotEntry.ChannelsChatters.Add(BotEntry.Channel, req.ResponseObject.chatters);
                                }
                            };

                            ///In case not block current thread
                            req.PerformAsync();

                            GetUserListTimout = GetUserListTimout.AddMinutes(5);
                        }

                        OnTickActions?.Invoke();

                        Thread.Sleep(50);
                    }
                });



                ///Load dust data
                using (var file = new StreamReader(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite)))
                {
                    if (!file.EndOfStream)
                    {
                        BotEntry.RedstoneDust = JsonConvert.DeserializeObject <SortedDictionary <string, RedstoneData> >(file.ReadToEnd());
                    }
                    if (BotEntry.RedstoneDust == null)
                    {
                        BotEntry.RedstoneDust = new SortedDictionary <string, RedstoneData> {
                        }
                    }
                    ;
                }



                ///Start update thread
                updateThread.Start();

                ///Load some configs in form
                Form.Load(Storage);

                services = new ServiceCollection()
                           .AddSingleton(client)
                           .AddSingleton(commands)
                           .AddSingleton(Form)
                           .BuildServiceProvider();

                client.ChannelMessage += HandleMessage;
                client.OnConnect      += Client_OnConnect;

                commands.AddModulesAsync(Assembly.GetEntryAssembly(), services);


                ///Try load all module in /Modules folder
                var dll = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\Modues", "*.dll", SearchOption.TopDirectoryOnly);
                foreach (var it in dll)
                {
                    try
                    {
                        Logger.Log($"Loading {it} module...");
                        commands.AddModulesAsync(Assembly.LoadFile(it), services);
                    }
                    catch
                    {
                        continue;
                    }
                }

                ///Load items metadata
                foreach (var data in RedstoneDust)
                {
                    data.Value.ReadJsonData();
                }

                PostInit?.Invoke();


                ///Run form
                Application.Run(Form);

                ///Save any config changes inside form
                Logger.Log($"Unloading form data...");
                Form.Unload(Storage);

                ///Interrupt a thread
                interrupt = true;
                Thread.Sleep(1000);

                ///Unload all data and exit
                Logger.Log($"====================UNLOADING SERVICES=====================");
                OnExiting?.Invoke();
                client.Disconnect();
                ///Commands.CommandsService.Unload(Storage);
                Logger.Log($"=================UNLOADING SERVICES ENDED==================");

                ///Prepare item metadata to unloading
                foreach (var data in RedstoneDust)
                {
                    data.Value.PrepareJsonData();
                }

                ///Unload dust data
                using (var file = new StreamWriter(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate)))
                {
                    file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented));
                }

                Thread.Sleep(1000);
            }
            catch (Exception e)
            {
                Logger.GetLogger(LoggingTarget.Stacktrace).Add($"FATAL ERROR: {e.Message}. SEE STACKTRACE FOR DETAIL");
                Logger.GetLogger(LoggingTarget.Stacktrace).Add(e.StackTrace);
                Thread.Sleep(50);

                foreach (var data in RedstoneDust)
                {
                    data.Value.PrepareJsonData();
                }

                using (var file = new StreamWriter(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate)))
                {
                    file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented));
                }
            }
        }
예제 #18
0
        public DialogWindow()
        {
            InitializeComponent();

            messageTextBox.PreviewKeyDown += MessageTextBox_PreviewKeyDown;
            chatListBox.DoubleClick       += ChatListBox_DoubleClick;


            singleton = this;

            channelTextBox.Text = BotEntry.Channel;

            UsernameTextBox.Text = BotEntry.Config.Get <string>(Config.BotSetting.Username);
            Token = OAuthToken.Parse(BotEntry.Config.Get <string>(Config.BotSetting.SuperSecretSettings));
            OATokenTextBox.Text         = Token.AccessToken ?? string.Empty;
            botChannelTextBox.Text      = BotEntry.ChatBotChannel.Value;
            BotEntry.NonCommandMessage += (IRCClient.ChannelMessageEventArgs msg) =>
            {
                Actions.Add(() =>
                {
                    foreach (string s in CommandsListBox.Items)
                    {
                        var arr = s.Split('⇒');
                        if (arr[0][0] != '!')
                        {
                            if (msg.Message.ToLower().Contains('!' + arr[0].ToLower()))
                            {
                                string output = arr[1].Replace("{username}", msg.Badge.DisplayName);
                                output        = output.Replace("{channel}", msg.Channel);
                                output        = output.Replace("{message}", msg.Message);
                                BotEntry.client.SendMessage(msg.Channel, output);
                                Logger.Log($"[GENERIC] [{arr[0]}] command executed for |{msg.Badge.DisplayName}|");
                            }
                        }
                        else
                        if (msg.Message.ToLower().Contains(arr[0].ToLower()))
                        {
                            string output = arr[1].Replace("{username}", msg.Badge.DisplayName);
                            output        = output.Replace("{channel}", msg.Channel);
                            output        = output.Replace("{message}", msg.Message);
                            BotEntry.client.SendMessage(msg.Channel, output);
                            Logger.Log($"[GENERIC] [{arr[0]}] command executed for |{msg.Badge.DisplayName}|");
                        }
                    }
                });
            };

            BotEntry.client.RoomStateChanged += (s, b) =>
            {
                Actions.Add(() =>
                {
                    if (BotEntry.client.CurrentChannelBadge != null && b == BotEntry.client.CurrentChannelBadge)
                    {
                        var areq = new JsonWebRequest <RoomModels>($"https://api.twitch.tv/kraken/chat/{BotEntry.client.CurrentChannelBadge.ChannelID}/rooms")
                        {
                            Method = HttpMethod.GET
                        };
                        areq.AddHeader("Accept", "application/vnd.twitchtv.v5+json");
                        areq.AddHeader("Client-ID", "i5ezz567chrsv4rzal4l9q7kuuq9qv");
                        areq.AddHeader("Authorization", "OAuth 5egkvsbduc7frz4lbhyw4u239bv7sr");

                        areq.Finished += () =>
                        {
                            //var str = areq.ResponseString;

                            Actions.Add(() =>
                            {
                                chatRoomsListBox.Items.Clear();
                                foreach (var it in areq.ResponseObject.Rooms)
                                {
                                    chatRoomsListBox.Items.Add(it);
                                }
                            });
                        };
                        areq.Failed += (e) =>
                        {
                            ExceptionExtensions.Rethrow(e);
                        };

                        areq.PerformAsync();
                    }
                });
            };

            BotEntry.client.OnConnect += (s, e) =>
            {
                Actions.Add(() =>
                {
                    connectionStateLabel.Text = $"Connected";
                    connectButton.Text        = $"Disconnect";
                    connectButton.Enabled     = true;
                    this.Text = "Twitch bot API. State: [Connected]";
                });
            };

            BotEntry.client.ConnectionClosed += (s, e) =>
            {
                Actions.Add(() =>
                {
                    connectButton.Enabled     = true;
                    connectButton.Text        = $"Connect";
                    connectionStateLabel.Text = "Disconnected";
                    this.Text = "Twitch bot API. State: Disconnected";
                });
            };

            if (BotEntry.client.Connected)
            {
                connectionStateLabel.Text = $"Connected";
                connectButton.Text        = $"Disconnect";
                connectButton.Enabled     = true;
                this.Text = "Twitch bot API. State: [Connected]";
            }
        }
예제 #19
0
        private void OnTick()
        {
            if (DateTimeOffset.Now > DustRecalculateTime)
            {
                var req = new WebRequest($"https://beta.decapi.me/twitch/uptime/{BotEntry.Channel.Value.Substring(1, BotEntry.Channel.Value.Length - 1)}");
                req.Finished += () =>
                {
                    var vars = req.ResponseString.Split(' ');
                    if (vars.Length >= 3 && vars[2] == "offline")
                    {
                        return;
                    }

                    var lreq = new JsonWebRequest <ChatData>($"https://tmi.twitch.tv/group/user/{BotEntry.Channel.Value.Replace("#", "")}/chatters");

                    lreq.Finished += () =>
                    {
                        foreach (var it in lreq.ResponseObject.chatters.viewers)
                        {
                            if (BotEntry.RedstoneDust.ContainsKey(it))
                            {
                                if (BotEntry.RedstoneDust[it].HasBoost)
                                {
                                    BotEntry.RedstoneDust[it].Dust += 1 * SubMultiply;
                                }
                                else
                                {
                                    BotEntry.RedstoneDust[it].Dust += 1;
                                }
                            }
                            else
                            {
                                BotEntry.RedstoneDust.Add(it, new RedstoneData
                                {
                                    Dust     = 1,
                                    HasBoost = false,
                                });
                            }
                            if (BotEntry.RedstoneDust[it].Chatter)
                            {
                                BotEntry.RedstoneDust[it].Dust   += 1;
                                BotEntry.RedstoneDust[it].Chatter = false;
                            }

                            BotEntry.RedstoneDust[it].PrepareJsonData();
                        }



                        using (var file = new StreamWriter(Storage.GetStream($"{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate)))
                        {
                            file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented));
                        }
                    };

                    lreq.Failed += (e) =>
                    {
                        var ex = e;
                    };

                    lreq.PerformAsync();
                };

                req.PerformAsync();



                DustRecalculateTime = DateTimeOffset.Now.AddSeconds(Colldown);
            }
        }