public Wikipedia(string url) { var bc = new BrowserClient(); var html = bc.DownloadString(url); var doc = new HtmlDocument(); doc.LoadHtml(html); try { var image = "http:" + doc.DocumentNode.SelectNodes("//table").First( o => o.Attributes["class"] != null && o.Attributes["class"].Value.Contains("infobox")) .SelectNodes(".//a[@class='image']/img") .OrderByDescending(o => int.Parse(o.Attributes["width"].Value)) .First().Attributes["src"].Value; ImageView.Create(image, url); } catch { } _description = ""; foreach (var text in doc.DocumentNode.SelectNodes("//p").Select(o => o.InnerText.RemoveBrackets())) { foreach(var sentence in text.RegexSplit(@"\.\n|\. ").Where(o => !string.IsNullOrWhiteSpace(o)).Select(o => o.Trim())) { var _sentence = sentence.RegexRemove("\\(.+?\\)"); _description += _sentence + (_sentence.EndsWith(".") ? "" : ".") + Environment.NewLine; if (_description.Length > 300) goto BreakLoops; } } BreakLoops: _description = _description.HtmlDecode().Trim(); }
public void InitMultiplayer(BrowserClient browserClient) { this.browserClient = browserClient; client = browserClient; AddEvents(); CreateVoiceChat(); }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty;; string clientSecret = string.Empty; BrowserClient client = null; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { //Remove the comments from the below line context.SetError, and invalidate context //if you want to force sending clientId/secrects once obtain access tokens. context.Validated(); //context.SetError("invalid_clientId", "ClientId should be sent."); //return Task.FromResult<object>(null); } using (AuthRepository _repo = new AuthRepository()) { client = _repo.FindClient(context.ClientId); } //if (client == null) //{ // context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId)); // return Task.FromResult<object>(null); //} //if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential) //{ // if (string.IsNullOrWhiteSpace(clientSecret)) // { // context.SetError("invalid_clientId", "Client secret should be sent."); // return Task.FromResult<object>(null); // } // else // { // if (client.Secret != Helper.GetHash(clientSecret)) // { // context.SetError("invalid_clientId", "Client secret is invalid."); // return Task.FromResult<object>(null); // } // } //} if (!client.Active) { context.SetError("invalid_clientId", "Client is inactive."); return(Task.FromResult <object>(null)); } context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin); context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString()); context.Validated(); return(Task.FromResult <object>(null)); }
public AccountAvatarsPO ReadAvatar() { var now = DateTime.Now; var avatar = Avatar ?? new AccountAvatarsPO { CreateTime = now, Valid = true }; try { var url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token={0}"; var r = new BrowserClient(); var response = r.SendHttpRequest(string.Format(url, avatar.Token), true, "GET", "", null, null, null, "UTF-8", "application/json", "application/json"); //r.SendHttpRequestGet(string.Format(url,avatar.Token),"", "application/json", null); Logger.Info(response); var user = response.JsonToObjContract <GoogleUser>(); if (user != null) { avatar.ChannelIdentity = user.Id; avatar.ChannelId = Channel.Id; avatar.DisplayName = user.Name; avatar.Code = user.Id; } } catch (Exception ex) { Logger.Error(ex); } return(avatar); }
public async Task IssueSessionCookieAsync(params Claim[] claims) { _userToSignIn = new ClaimsPrincipal(new ClaimsIdentity(claims, "test", "name", "role")); var response = await BrowserClient.GetAsync(Url("__signin")); response.StatusCode.Should().Be(204); }
internal async Task Connect(ConnectionInfo connectionInfo, Session session, ILogger logger) { var address = connectionInfo.Network == "unix" ? $"unix://{connectionInfo.Address}" : connectionInfo.Address; var channel = new Channel(address, ChannelCredentials.Insecure); await channel.ConnectAsync(); var interceptedChannel = channel.Intercept(new ExceptionLoggingInterceptor(logger)); Console.Error.WriteLine("[DEBUG] GRPC Channel Connected"); Whisper = new WhisperClient(interceptedChannel, session, logger); Clipboard = new ClipboardClient(interceptedChannel, session, logger); Filesystem = new FilesystemClient(interceptedChannel, session, logger); Cursor = new CursorClient(interceptedChannel, session, logger); Keyboard = new KeyboardClient(interceptedChannel, session, logger); Network = new NetworkClient(interceptedChannel, session, logger); Process = new ProcessClient(interceptedChannel, session, logger); Browser = new BrowserClient(interceptedChannel, session, logger); Hover = new HoverClient(interceptedChannel, session, logger); Window = new WindowClient(interceptedChannel, session, logger); Storage = new StorageClient(interceptedChannel, session, logger); UI = new UIClient(interceptedChannel, session, logger); }
private string ReadFromProxy(ApiTerminal.Clients.Request.WoowRequest request) { var r = new BrowserClient(); var resp = r.SendHttpRequest(Config.ProxyApiUri, false, "POST", request.ObjToJson(), null, null, null, "UTF-8", "application/json", "application/json"); return(resp.Content); }
public Wikipedia(string url) { var bc = new BrowserClient(); var html = bc.DownloadString(url); var doc = new HtmlDocument(); doc.LoadHtml(html); try { var image = "http:" + doc.DocumentNode .SelectNodes("//table").First(o => o.Attributes["class"] != null && o.Attributes["class"].Value.Contains("infobox")) .SelectNodes(".//a[@class='image']/img") .OrderByDescending(o => int.Parse(o.Attributes["width"].Value)) .First().Attributes["src"].Value; ImageView.Create(image, url); }catch { } var count = 0; _description = ""; foreach (var text in doc.DocumentNode.SelectNodes("//p").Select(o => o.InnerText.RemoveBrackets())) { foreach (var sentence in text.RegexSplit(@"\.\n|\. ").Where(o => !string.IsNullOrWhiteSpace(o)).Select(o => o.Trim())) { _description += sentence + (sentence.EndsWith(".") ? "" : ".") + Environment.NewLine; if (_description.Length > 300) goto BreakLoops; } } BreakLoops: _description = _description.HtmlDecode().Trim(); }
public void Initialize(string basePath = null, bool enableLogging = false) { var builder = new WebHostBuilder(); builder.ConfigureServices(ConfigureServices); builder.Configure(app => { if (basePath != null) { app.Map(basePath, map => { ConfigureApp(map); }); } else { ConfigureApp(app); } }); if (enableLogging) { builder.ConfigureLogging((ctx, b) => b.AddConsole()); } Server = new TestServer(builder); Handler = Server.CreateHandler(); BrowserClient = new BrowserClient(new BrowserHandler(Handler)); BackChannelClient = new HttpClient(Handler); }
/// <summary> /// Creates a ChromiumWebBrowser object with the given initial URL. /// If createImmediately is true, then the underlying CfxBrowser is /// created immediately with the default CfxRequestContext. /// </summary> public ChromiumBrowser(string initialUrl, bool createImmediately) { if (BrowserProcess.initialized) { SetStyle(ControlStyles.ContainerControl | ControlStyles.ResizeRedraw | ControlStyles.FixedWidth | ControlStyles.FixedHeight | ControlStyles.StandardClick | ControlStyles.StandardDoubleClick | ControlStyles.UserMouse | ControlStyles.SupportsTransparentBackColor | ControlStyles.EnableNotifyMessage | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UseTextForAccessibility | ControlStyles.Opaque , false); SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.CacheText | ControlStyles.DoubleBuffer | ControlStyles.Selectable , true); UpdateStyles(); if (initialUrl == null) { this.initialUrl = "about:blank"; } else { this.initialUrl = initialUrl; } client = new BrowserClient(this); globalObject = new JSObject(); globalObject.SetBrowser("window", this); if (createImmediately) { CreateBrowser(); } } else { BackColor = System.Drawing.Color.White; Width = 200; Height = 160; var label = new Label(); label.AutoSize = true; label.Text = "ChromiumWebBrowser"; label.Parent = this; } }
public async Task LogoutAsync() { var old = BrowserClient.AllowAutoRedirect; BrowserClient.AllowAutoRedirect = false; await BrowserClient.GetAsync(LogoutPage); BrowserClient.AllowAutoRedirect = old; }
/* helpers */ public async Task LoginAsync(ClaimsPrincipal subject) { var old = BrowserClient.AllowAutoRedirect; BrowserClient.AllowAutoRedirect = false; Subject = subject; await BrowserClient.GetAsync(LoginPage); BrowserClient.AllowAutoRedirect = old; }
public override void OnPageHandlerExecuting(PageHandlerExecutingContext context) { context.HttpContext.Items.TryGetValue("ServiceUser", out var serviceUser); context.HttpContext.Items.TryGetValue("Lang", out var userLang); ServiceUser = serviceUser as ServiceUser; BrowserClient = new BrowserClient { Language = userLang as string, }; base.OnPageHandlerExecuting(context); }
public TorrentLeechEntry(HtmlNode node, BrowserClient client) { _client = client; var titleNode = node.SelectSingleNode(".//span[@class='title']/a"); Title = titleNode.InnerText; Id = int.Parse(titleNode.Attributes["href"].Value.RegexMatch(@"\d+").Value); Friendly = Title.TorrentName(); var size = node.SelectSingleNode(".//td[5]").InnerText; double number = double.Parse(size.RegexMatch(@"\d+").Value); if (size.Contains("GB")) number *= 1024; Size = number; Torrent = "http://www.torrentleech.org/rss/download/{0}/ed2597d8977cde9da218/{1}".Template(Id,Title.RegexReplace(@"\s", ".")); }
public static TwitterSearch FromUsers(string since = "0", params string[] users) { var url = "http://search.twitter.com/search.json?include_entities=true&q="; foreach (var twitter in users) { url += "from%3a{0}+OR+".Template(twitter); } url = url.Remove(url.Length - 4, 4); url += "&since_id=" + since; var json = new BrowserClient().DownloadString(url); return(FromJson(json)); }
public TorrentLeechEntry(HtmlNode node, BrowserClient client) { _client = client; var titleNode = node.SelectSingleNode(".//span[@class='title']/a"); Title = titleNode.InnerText; Id = int.Parse(titleNode.Attributes["href"].Value.RegexMatch(@"\d+").Value); Friendly = Title.TorrentName(); var size = node.SelectSingleNode(".//td[5]").InnerText; double number = double.Parse(size.RegexMatch(@"\d+").Value); if (size.Contains("GB")) { number *= 1024; } Size = number; Torrent = "http://www.torrentleech.org/rss/download/{0}/ed2597d8977cde9da218/{1}".Template(Id, Title.RegexReplace(@"\s", ".")); }
private void InitClient() { var player = new Player(Properties.Settings.Default.UserName) { IPAddress = NetUtils.GetAddress() }; browserClient = new BrowserClient(player); browserClient.SetBrowserTcp(player.IPAddress, NetSettings.PORT_FOR_CLIENTS); AddEvents(); browserClient.RequestDataAboutHosts(); timer = new Timer(); timer.Interval = 10000; timer.Enabled = true; timer.Tick += btnRefresh_Click; timer.Start(); }
/// <summary> /// 刷新令牌 /// </summary> /// <param name="refreshToken"></param> /// <returns></returns> public AccountAvatarsPO RefreshToken(string refreshToken) { var now = DateTime.Now; var avatar = Avatar ?? new AccountAvatarsPO { CreateTime = now, Valid = true }; var url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; Logger.Info(Channel.SerializeXml()); var data = string.Format( "grant_type=refresh_token&refresh_token={0}&redirect_uri={1}&client_id={2}&client_secret={3}&scope={4}", refreshToken, HttpUtility.UrlEncode(Channel.CodeCallback), Channel.AppId, Channel.AppSecret, Channel.Parameters); Logger.Info("data=" + data); try { var r = new BrowserClient(); var response = r.SendHttpRequest(url, true, "POST", data, null, null, null, "utf-8", "application/json", "application/x-www-form-urlencoded"); Logger.Info(response); var token = response.JsonToObjContract <Response.MsonlineToken>(); if (token != null) { avatar.ChannelId = Channel.Id; avatar.Token = token.AccessToken; avatar.RefreshToken = token.RefreshToken; avatar.TokenGenerated = now; avatar.TokenExpires = now.AddSeconds(token.ExpiresIn); avatar.UpdateTime = now; } } catch (Exception ex) { Logger.Error(ex); } return(avatar); }
public string ReadApi(string url) { try { var kv = new Dictionary <string, string> { { "Authorization", $"Bearer {Avatar.Token}" } }; var r = new BrowserClient(); var response = r.SendHttpRequest(url, true, "GET", "", kv, null, null, "utf-8", "application/json", "application/x-www-form-urlencoded"); Logger.Info(response); return(response.Content); } catch (Exception ex) { Logger.Error(ex); } return(""); }
/// <summary> /// Initializes the web host provider. /// </summary> public void Initialize(string webRoot) { // start the server instance _server = new TestServer(webRoot, this); _server.Start(); // create client collection _clients = new Dictionary <string, TestClient>(); _connectEvent = new ManualResetEvent(false); // tests always occur on index.htm for now var url = _server.RootUrl + "index.htm"; // start each client process _processes = BrowserClient.GetAvailableClients() .Select(c => CreateProcess(c, url)) .Where(p => p != null).ToArray(); // wait for them all to connect WaitForClients(_processes.Length); }
public AccountAvatarsPO RefreshToken(string refreshToken) { var now = DateTime.Now; var avatar = Avatar ?? new AccountAvatarsPO { CreateTime = now, Valid = true }; var url = "https://www.googleapis.com/oauth2/v4/token"; var data = string.Format( "grant_type=refresh_token&refresh_token={0}&redirect_uri={1}&client_id={2}&client_secret={3}", refreshToken, System.Web.HttpContext.Current.Server.UrlEncode(Channel.CodeCallback), Channel.AppId, Channel.AppSecret); try { var r = new BrowserClient(); var response = r.SendHttpRequest(url, true, "POST", data, null, null, null, "UTF-8", "application/json", "application/x-www-form-urlencoded"); Logger.Info(response); var token = response.JsonToObjContract <Response.MsonlineToken>(); if (token != null) { avatar.ChannelId = Channel.Id; avatar.Token = token.AccessToken; avatar.RefreshToken = token.RefreshToken; avatar.TokenGenerated = now; avatar.TokenExpires = now.AddSeconds(token.ExpiresIn); avatar.UpdateTime = now; avatar.CreateTime = now; } } catch (Exception ex) { Logger.Error(ex); } return(avatar); }
private Process CreateProcess(BrowserClient client, string url) { try { var info = new ProcessStartInfo(client.ExePath, client.Arguments + " " + url); info.UseShellExecute = false; var proc = Process.Start(info); var handle = WaitForWindow(proc); if (handle != IntPtr.Zero) { ShowWindowAsync(handle, 11); } return(proc); } catch { return(null); } }
public async Task <AuthorizeResponse> RequestAuthorizationEndpointAsync( string clientId, string responseType, string scope = null, string redirectUri = null, string state = null, string nonce = null, string loginHint = null, string acrValues = null, string responseMode = null, string codeChallenge = null, string codeChallengeMethod = null, object extra = null) { var old = BrowserClient.AllowAutoRedirect; BrowserClient.AllowAutoRedirect = false; var url = CreateAuthorizeUrl(clientId, responseType, scope, redirectUri, state, nonce, loginHint, acrValues, responseMode, codeChallenge, codeChallengeMethod, extra); var result = await BrowserClient.GetAsync(url); result.StatusCode.Should().Be(HttpStatusCode.Found); BrowserClient.AllowAutoRedirect = old; var redirect = result.Headers.Location.ToString(); if (redirect.StartsWith(IdentityServerPipeline.ErrorPage)) { // request error page in pipeline so we can get error info await BrowserClient.GetAsync(redirect); // no redirect to client return(null); } return(new AuthorizeResponse(redirect)); }
private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { try { Stats.Text = "Downloading Data..."; Uri URL = new Uri(this.toolStripTextBox1.Text); BrowserClient Manager = new BrowserClient(); Manager.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(Manager_DownloadStringCompleted); Manager.DownloadStringAsync(URL); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } }
public void RemoveLoginCookie() { BrowserClient.RemoveCookie(BaseUrl, IdentityServerConstants.DefaultCookieAuthenticationScheme); }
private void MyCtor(Control parent) { _mono = Type.GetType("Mono.Runtime") != null; this.Parent = parent; //SetStyle( // ControlStyles.ResizeRedraw // | ControlStyles.FixedWidth // | ControlStyles.FixedHeight // | ControlStyles.StandardClick // | ControlStyles.StandardDoubleClick // | ControlStyles.UserMouse // | ControlStyles.SupportsTransparentBackColor // | ControlStyles.DoubleBuffer // | ControlStyles.OptimizedDoubleBuffer // | ControlStyles.Opaque // , false); SetStyle(ControlStyles.AllPaintingInWmPaint, true); Console.WriteLine("can enable ime:" + this.CanEnableIme); this.ImeMode = ImeMode.On; client = new BrowserClient(this); //client.GetLifeSpanHandler += (sender, e) => e.SetReturnValue(lifeSpanHandler); //client.GetRenderHandler += (sender, e) => e.SetReturnValue(renderHandler); //client.GetLoadHandler += (sender, e) => e.SetReturnValue(loadHandler); //client.GetKeyboardHandler += (sender, e) => e.SetReturnValue(keyboardHandler); //lifeSpanHandler = new CfxLifeSpanHandler(); //lifeSpanHandler.OnAfterCreated += lifeSpanHandler_OnAfterCreated; renderHandler = client.RenderHandler;// new CfxRenderHandler(); renderHandler.GetRootScreenRect += renderHandler_GetRootScreenRect; renderHandler.GetScreenInfo += renderHandler_GetScreenInfo; renderHandler.GetScreenPoint += renderHandler_GetScreenPoint; renderHandler.GetViewRect += renderHandler_GetViewRect; renderHandler.OnCursorChange += renderHandler_OnCursorChange; renderHandler.OnPaint += renderHandler_OnPaint; //renderHandler.OnPopupShow += renderHandler_OnPopupShow; //renderHandler.OnPopupSize += renderHandler_OnPopupSize; //renderHandler.OnScrollOffsetChanged += renderHandler_OnScrollOffsetChanged; //renderHandler.StartDragging += renderHandler_StartDragging; //renderHandler.UpdateDragCursor += renderHandler_UpdateDragCursor; loadHandler = client.LoadHandler;// new CfxLoadHandler(); loadHandler.OnLoadError += loadHandler_OnLoadError; keyboardHandler = new CfxKeyboardHandler(); keyboardHandler.OnPreKeyEvent += KeyboardHandler_OnPreKeyEvent; lifeSpanHandler = client.lifeSpanHandler; lifeSpanHandler.OnAfterCreated += lifeSpanHandler_OnAfterCreated; var settings = new CfxBrowserSettings(); var windowInfo = new CfxWindowInfo(); if (CfxRuntime.PlatformOS == CfxPlatformOS.Windows) { windowInfo.SetAsWindowless(this.Parent.Handle); } else { windowInfo.SetAsWindowless(this.Parent.Handle); } //windowInfo.SetAsWindowless(this.Parent.Handle); // Create handle now for InvokeRequired to work properly // CreateHandle(); if (string.IsNullOrEmpty(initialUrl)) { initialUrl = "about:version"; } GlobalObject = new JSObject(); GlobalObject.SetBrowser("window", this); // CreateHandle(); // CfxBrowserHost.CreateBrowser(windowInfo, client, "about:blank", settings, null); //Browser = CfxBrowserHost.CreateBrowserSync(windowInfo, client, initialUrl, settings, null); //if (!CfxBrowserHost.CreateBrowser(windowInfo, client, initialUrl, settings, null)) // throw new ChromiumWebBrowserException("Failed to create browser instance."); CfxBrowserHost.CreateBrowser(windowInfo, client, initialUrl, settings, null); }
public void RemoveSessionCookie() { BrowserClient.RemoveCookie(BaseUrl, IdentityServerConstants.DefaultCheckSessionCookieName); }
public Cookie GetSessionCookie() { return(BrowserClient.GetCookie(BaseUrl, IdentityServerConstants.DefaultCheckSessionCookieName)); }
public Task <string> Get() => BrowserClient.GetTextAsync("http://localhost/PupppeterSharpAspNetFrameworkSample/api/foo");
public async Task RevokeSessionCookieAsync() { var response = await BrowserClient.GetAsync(Url("__signout")); response.StatusCode.Should().Be(204); }
public TorrentLeech() { _browserClient = new BrowserClient("torrentleech.org"); }