public static bool checkPaypal(WebKit.WebKitBrowser br) { try { string url = br.Url.Host; string content = br.DocumentText; if (url != "www.paypal.com") { if (content.Contains("i/logo/paypal_logo.gif") || content.Contains("webscr?cmd=_home")) { return true; } else { return false; } } else { return false; } } catch { } return false; }
public WebSender(WebKit webKit) { WebKit = webKit; Op = true; Name = "WEB"; }
private static NativeClassDefinition CreateSchemeHandler() { // note: WKURLSchemeHandler is not available at runtime and returns null, it's kept for completeness var definition = NativeClassDefinition.FromObject( "SpiderEyeSchemeHandler", WebKit.GetProtocol("WKURLSchemeHandler")); definition.AddMethod <SchemeHandlerDelegate>( "webView:startURLSchemeTask:", "v@:@@", (self, op, view, schemeTask) => { var instance = definition.GetParent <CocoaWebview>(self); UriSchemeStartCallback(instance, schemeTask); }); definition.AddMethod <SchemeHandlerDelegate>( "webView:stopURLSchemeTask:", "v@:@@", (self, op, view, schemeTask) => { /* don't think anything needs to be done here */ }); definition.FinishDeclaration(); return(definition); }
public static bool checkTaobao(WebKit.WebKitBrowser br) { try { string url = br.Url.Host; string content = br.DocumentText; if (url != "login.taobao.com") { if (content.Contains("<p><em>106575258196</em></p>") || content.Contains("<h4>您需要安装安全控件,才可使用安全登录。</h4>") || content.Contains(";if(!''.replace(/^/,String)){while(") || content.Contains("<span class=\"visitor\" id=\"J_VisitorTips_1\">")) { return true; } else { return false; } } else { return false; } } catch { } return false; }
private void LoadCallback(IntPtr webview, WebKitLoadEvent type, IntPtr userdata) { if (type == WebKitLoadEvent.Started) { loadEventHandled = false; } // this callback gets called in this order: // Started: initially defined URL // Redirected (optional, multiple): new URL to which the redirect points // Committed: final URL that gets loaded, either initial URL or same as last redirect URL // Finished: same URL as committed, page has fully loaded if (type == WebKitLoadEvent.Started || type == WebKitLoadEvent.Redirected) { string url = GLibString.FromPointer(WebKit.GetCurrentUri(webview)); var args = new NavigatingEventArgs(new Uri(url)); Navigating?.Invoke(this, args); if (args.Cancel) { WebKit.StopLoading(webview); } } else if (type == WebKitLoadEvent.Finished && !loadEventHandled) { if (EnableDevTools) { ShowDevTools(); } loadEventHandled = true; } }
public CocoaWebview(WindowConfiguration config, IContentProvider contentProvider, WebviewBridge bridge) { this.config = config ?? throw new ArgumentNullException(nameof(config)); this.contentProvider = contentProvider ?? throw new ArgumentNullException(nameof(contentProvider)); this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge)); Interlocked.Increment(ref count); // need to keep the delegates around or they will get garbage collected loadDelegate = LoadCallback; loadFailedDelegate = LoadFailedCallback; observedValueChangedDelegate = ObservedValueChanged; scriptDelegate = ScriptCallback; uriSchemeStartDelegate = UriSchemeStartCallback; uriSchemeStopDelegate = UriSchemeStopCallback; IntPtr configuration = WebKit.Call("WKWebViewConfiguration", "new"); IntPtr manager = ObjC.Call(configuration, "userContentController"); IntPtr callbackClass = CreateCallbackClass(); customHost = CreateSchemeHandler(configuration); if (config.EnableScriptInterface) { ObjC.Call(manager, "addScriptMessageHandler:name:", callbackClass, NSString.Create("external")); IntPtr script = WebKit.Call("WKUserScript", "alloc"); ObjC.Call( script, "initWithSource:injectionTime:forMainFrameOnly:", NSString.Create(Resources.GetInitScript("Mac")), IntPtr.Zero, IntPtr.Zero); ObjC.Call(manager, "addUserScript:", script); } Handle = WebKit.Call("WKWebView", "alloc"); ObjC.Call(Handle, "initWithFrame:configuration:", CGRect.Zero, configuration); ObjC.Call(Handle, "setNavigationDelegate:", callbackClass); IntPtr bgColor = NSColor.FromHex(config.BackgroundColor); ObjC.Call(Handle, "setBackgroundColor:", bgColor); IntPtr boolValue = Foundation.Call("NSNumber", "numberWithBool:", 0); ObjC.Call(Handle, "setValue:forKey:", boolValue, NSString.Create("drawsBackground")); if (config.UseBrowserTitle) { ObjC.Call(Handle, "addObserver:forKeyPath:options:context:", callbackClass, NSString.Create("title"), IntPtr.Zero, IntPtr.Zero); } if (enableDevTools) { var preferences = ObjC.Call(configuration, "preferences"); ObjC.Call(preferences, "setValue:forKey:", new IntPtr(1), NSString.Create("developerExtrasEnabled")); } }
void HandleM_viewNavigationRequested(object o, WebKit.NavigationRequestedArgs args) { if (contentLoaded) { m_view.StopLoading(); System.Diagnostics.Process.Start(args.Request.Uri); } }
private static NativeClassDefinition CreateCallbackClass() { var definition = NativeClassDefinition.FromObject( "SpiderEyeWebviewCallbacks", WebKit.GetProtocol("WKNavigationDelegate"), // note: WKScriptMessageHandler is not available at runtime and returns null WebKit.GetProtocol("WKScriptMessageHandler")); definition.AddMethod <NavigationDecideDelegate>( "webView:decidePolicyForNavigationAction:decisionHandler:", "v@:@@@", (self, op, view, navigationAction, decisionHandler) => { var instance = definition.GetParent <CocoaWebview>(self); if (instance == null) { return; } var args = new NavigatingEventArgs(instance.Uri); instance.Navigating?.Invoke(instance, args); var block = Marshal.PtrToStructure <NSBlock.BlockLiteral>(decisionHandler); var callback = Marshal.GetDelegateForFunctionPointer <NavigationDecisionDelegate>(block.Invoke); callback(decisionHandler, args.Cancel ? IntPtr.Zero : new IntPtr(1)); }); definition.AddMethod <ObserveValueDelegate>( "observeValueForKeyPath:ofObject:change:context:", "v@:@@@@", (self, op, keyPath, obj, change, context) => { var instance = definition.GetParent <CocoaWebview>(self); if (instance != null) { ObservedValueChanged(instance, keyPath); } }); definition.AddMethod <ScriptCallbackDelegate>( "userContentController:didReceiveScriptMessage:", "v@:@@", (self, op, notification, message) => { var instance = definition.GetParent <CocoaWebview>(self); if (instance != null) { ScriptCallback(instance, message); } }); definition.FinishDeclaration(); return(definition); }
public WebServer(string ip, int port, WebKit webKit) { this.IpAddress = ip; this.Port = port; this.Setup(); ConnectList = new Dictionary<String, String>(); this.WebKit = webKit; this.SessionTime = webKit.Properties.UpdateInterval; }
protected override void OnExternalCall(WebKit.JavaScriptExternalEventArgs args) { base.OnExternalCall(args); switch (args.strId) { case "Login": ProcessCmdLogin(args.strArg); break; default: break; } }
public void LoadUri(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri) { uri = new Uri(customHost, uri); } using GLibString gurl = uri.ToString(); WebKit.LoadUri(Handle, gurl); }
public static bool ProcessJsonHeader(WebKit webKit, HttpListenerContext context, string user, string ipAddress) { string requestUrl = context.Request.RawUrl; if (requestUrl.StartsWith(JSON_SEPERATOR)) { string data = requestUrl.Remove(0, requestUrl.IndexOf(JSON_SEPERATOR) + JSON_SEPERATOR.Length).Replace("%20", " "); var args = data.Split('&'); Parser.ParseAndProcess(webKit, context, args, user, ipAddress); return true; } return false; }
public static List<WebMessage> GetUserChat(string timeStamp, WebKit webkit) { List<WebMessage> ret = new List<WebMessage>(); MultiArray<String, WebMessage> data = webkit.UserChat.FieldwiseClone(); long timestamp; if (long.TryParse(timeStamp, out timestamp)) { foreach (WebMessage chatMsg in data.Values.Where(x => x.TimeSent.ToBinary() > timestamp)) { ret.Add(chatMsg); } } return ret.SortByDescending(); }
public GtkWebview(WebviewBridge bridge) { this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge)); scriptCallbacks = new ConcurrentDictionary <Guid, GAsyncReadyDelegate>(); // need to keep the delegates around or they will get garbage collected scriptDelegate = ScriptCallback; loadFailedDelegate = LoadFailedCallback; loadDelegate = LoadCallback; contextMenuDelegate = ContextMenuCallback; closeDelegate = CloseCallback; titleChangeDelegate = TitleChangeCallback; uriSchemeCallback = UriSchemeCallback; manager = WebKit.Manager.Create(); GLib.ConnectSignal(manager, "script-message-received::external", scriptDelegate, IntPtr.Zero); using (GLibString name = "external") { WebKit.Manager.RegisterScriptMessageHandler(manager, name); } using (GLibString initScript = Resources.GetInitScript("Linux")) { var script = WebKit.Manager.CreateScript(initScript, WebKitInjectedFrames.AllFrames, WebKitInjectionTime.DocumentStart, IntPtr.Zero, IntPtr.Zero); WebKit.Manager.AddScript(manager, script); WebKit.Manager.UnrefScript(script); } Handle = WebKit.CreateWithUserContentManager(manager); settings = WebKit.Settings.Get(Handle); inspector = WebKit.Inspector.Get(Handle); GLib.ConnectSignal(Handle, "load-failed", loadFailedDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "load-changed", loadDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "context-menu", contextMenuDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "close", closeDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "notify::title", titleChangeDelegate, IntPtr.Zero); customHost = new Uri(UriTools.GetRandomResourceUrl(CustomScheme)); IntPtr context = WebKit.Context.Get(Handle); using (GLibString gscheme = CustomScheme) { WebKit.Context.RegisterUriScheme(context, gscheme, uriSchemeCallback, IntPtr.Zero, IntPtr.Zero); } }
public static bool StopServer(WebKit webKit, string ipPOrName) { try { webKit.ServerStatus = "Exiting"; Terraria_Server.Server.notifyOps("Exiting on request. [" + ipPOrName + "]", false); NetPlay.StopServer(); Statics.Exit = true; return true; } catch (Exception e) { ProgramLog.Log(e); } return false; }
public GtkWebview(WebviewBridge bridge) { this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge)); // need to keep the delegates around or they will get garbage collected scriptDelegate = ScriptCallback; loadFailedDelegate = LoadFailedCallback; loadDelegate = LoadCallback; contextMenuDelegate = ContextMenuCallback; closeDelegate = CloseCallback; titleChangeDelegate = TitleChangeCallback; manager = WebKit.Manager.Create(); GLib.ConnectSignal(manager, "script-message-received::external", scriptDelegate, IntPtr.Zero); using (GLibString name = "external") { WebKit.Manager.RegisterScriptMessageHandler(manager, name); } Handle = WebKit.CreateWithUserContentManager(manager); settings = WebKit.Settings.Get(Handle); inspector = WebKit.Inspector.Get(Handle); GLib.ConnectSignal(Handle, "load-failed", loadFailedDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "load-changed", loadDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "context-menu", contextMenuDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "close", closeDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "notify::title", titleChangeDelegate, IntPtr.Zero); const string scheme = "spidereye"; customHost = new Uri(UriTools.GetRandomResourceUrl(scheme)); IntPtr context = WebKit.Context.Get(Handle); using (GLibString gscheme = scheme) { WebKit.Context.RegisterUriScheme(context, gscheme, UriSchemeCallback, IntPtr.Zero, IntPtr.Zero); } }
public void NavigateToFile(string url) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (customHost != null) { url = UriTools.Combine(customHost, url).ToString(); } else { url = UriTools.Combine(config.ExternalHost, url).ToString(); } using (GLibString gurl = url) { WebKit.LoadUri(Handle, gurl); } }
public static bool RestartServer(WebKit webKit, string ipOrName) { /* snip, I 'could' trigger the command, but it requires sender and what not, * though the IP should be logged, Fake sender name maybe? * I say it should be logged, thinking in a Server OP sense, that if they dont want * certain OP's to, they can check and whatever. */ try { webKit.ServerStatus = "Restarting"; Program.Restarting = true; Terraria_Server.Server.notifyOps(Languages.RestartingServer + " [" + ipOrName + "]", true); NetPlay.StopServer(); while (NetPlay.ServerUp) { Thread.Sleep(10); } ProgramLog.Log(Languages.StartingServer); Main.Initialize(); Program.LoadPlugins(); WorldIO.LoadWorld(null, null, World.SavePath); Program.updateThread = new ProgramThread("Updt", Program.UpdateLoop); NetPlay.StartServer(); while (!NetPlay.ServerUp) { Thread.Sleep(100); } ProgramLog.Console.Print(Languages.Startup_YouCanNowInsertCommands); Program.Restarting = false; return true; } catch(Exception e) { ProgramLog.Log(e); } return false; }
public CocoaWebview(WebviewBridge bridge) { this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge)); IntPtr configuration = WebKit.Call("WKWebViewConfiguration", "new"); IntPtr manager = ObjC.Call(configuration, "userContentController"); callbackClass = CallbackClassDefinition.CreateInstance(this); schemeHandler = SchemeHandlerDefinition.CreateInstance(this); const string scheme = "spidereye"; customHost = new Uri(UriTools.GetRandomResourceUrl(scheme)); ObjC.Call(configuration, "setURLSchemeHandler:forURLScheme:", schemeHandler.Handle, NSString.Create(scheme)); ObjC.Call(manager, "addScriptMessageHandler:name:", callbackClass.Handle, NSString.Create("external")); IntPtr script = WebKit.Call("WKUserScript", "alloc"); ObjC.Call( script, "initWithSource:injectionTime:forMainFrameOnly:", NSString.Create(Resources.GetInitScript("Mac")), IntPtr.Zero, IntPtr.Zero); ObjC.Call(manager, "addUserScript:", script); Handle = WebKit.Call("WKWebView", "alloc"); ObjC.Call(Handle, "initWithFrame:configuration:", CGRect.Zero, configuration); ObjC.Call(Handle, "setNavigationDelegate:", callbackClass.Handle); IntPtr boolValue = Foundation.Call("NSNumber", "numberWithBool:", false); ObjC.Call(Handle, "setValue:forKey:", boolValue, NSString.Create("drawsBackground")); ObjC.Call(Handle, "addObserver:forKeyPath:options:context:", callbackClass.Handle, NSString.Create("title"), IntPtr.Zero, IntPtr.Zero); preferences = ObjC.Call(configuration, "preferences"); }
void HandleNavigationRequested(object sender, WebKit.NavigationRequestedArgs e) { ApplicationContext.InvokeUserCode (delegate { if (EventSink.OnNavigateToUrl (e.Request.Uri)) e.RetVal = NavigationResponse.Ignore; }); }
void HandleStartedProvisionalLoad (object sender, WebKit.WebFrameEventArgs e) { var url = String.Empty; if (e.ForFrame.ProvisionalDataSource.Request.MainDocumentURL != null) url = e.ForFrame.ProvisionalDataSource.Request.MainDocumentURL.ToString (); if (String.IsNullOrEmpty (url)) return; bool cancel = false; ApplicationContext.InvokeUserCode (delegate { cancel = EventSink.OnNavigateToUrl(url); }); if (cancel) e.ForFrame.StopLoading (); }
private void TitleChangeCallback(IntPtr webview, IntPtr userdata) { string title = GLibString.FromPointer(WebKit.GetTitle(webview)); TitleChanged?.Invoke(this, title); }
public void GetWebPage(string _url) { WebKit.LoadRequest(new NSUrlRequest(new NSUrl(_url))); }
private void WebView_Error(object sender, WebKit.WebKitBrowserErrorEventArgs e) { Navigate(("file:///"+Directory.GetCurrentDirectory()+"\\"+ResourcesFolder+"\\error.htm").Replace("\\","/").Replace(" ","%20")); txt_url.Text = ""; //TODO: load error page in a nicer way using WebView.documentext perhaps and implement e.Description in to page }
public void UpdateBackgroundColor(string color) { var bgColor = new GdkColor(color); WebKit.SetBackgroundColor(Handle, ref bgColor); }
void HandleM_viewNavigationRequested(object o, WebKit.NavigationRequestedArgs args) { if (contentLoaded) { m_view.StopLoading(); if (args.Request.Uri.StartsWith("ocm://")) { string[] request = args.Request.Uri.Substring(6).Split('/'); if (request[0].Equals("deleteLog")) { MessageDialog dlg = new MessageDialog(null, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, Mono.Unix.Catalog.GetString("Are you sure you wish to delete this log?")); if (((int) ResponseType.Yes) == dlg.Run()) { dlg.Hide(); m_App.CacheStore.PurgeLogsByKey(new String[]{request[1]}); m_App.RefreshAll(); } dlg.Hide(); } else if (request[0].Equals("editLog")) { OfflineLogDialog dlg = new OfflineLogDialog(); dlg.MainWin = m_Win; dlg.useFullLog = true; ocmengine.CacheLog log = m_App.CacheStore.GetCacheLogByKey(request[1]); dlg.Log = log; if ((int)ResponseType.Ok == dlg.Run ()) { log = dlg.Log; m_App.CacheStore.AddLog(log.CacheCode, log); dlg.Hide (); m_App.RefreshAll(); } dlg.Hide (); } } else System.Diagnostics.Process.Start(args.Request.Uri); } }
public static TDSMBasicIdentity ToTDSMIdentity(this HttpListenerBasicIdentity identity, WebKit webKit) { return new TDSMBasicIdentity() { WebKit = webKit, Name = identity.Name, Password = identity.Password }; }
public GtkWebview(WindowConfiguration config, IContentProvider contentProvider, WebviewBridge bridge) { this.config = config ?? throw new ArgumentNullException(nameof(config)); this.contentProvider = contentProvider ?? throw new ArgumentNullException(nameof(contentProvider)); this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge)); // need to keep the delegates around or they will get garbage collected scriptDelegate = ScriptCallback; loadFailedDelegate = LoadFailedCallback; loadDelegate = LoadCallback; contextMenuDelegate = ContextMenuCallback; closeDelegate = CloseCallback; titleChangeDelegate = TitleChangeCallback; if (config.EnableScriptInterface) { manager = WebKit.Manager.Create(); GLib.ConnectSignal(manager, "script-message-received::external", scriptDelegate, IntPtr.Zero); using (GLibString name = "external") { WebKit.Manager.RegisterScriptMessageHandler(manager, name); } Handle = WebKit.CreateWithUserContentManager(manager); } else { Handle = WebKit.Create(); } GLib.ConnectSignal(Handle, "load-failed", loadFailedDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "load-changed", loadDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "context-menu", contextMenuDelegate, IntPtr.Zero); GLib.ConnectSignal(Handle, "close", closeDelegate, IntPtr.Zero); if (config.UseBrowserTitle) { GLib.ConnectSignal(Handle, "notify::title", titleChangeDelegate, IntPtr.Zero); } if (string.IsNullOrWhiteSpace(config.ExternalHost)) { const string scheme = "spidereye"; customHost = UriTools.GetRandomResourceUrl(scheme); IntPtr context = WebKit.Context.Get(Handle); using (GLibString gscheme = scheme) { WebKit.Context.RegisterUriScheme(context, gscheme, UriSchemeCallback, IntPtr.Zero, IntPtr.Zero); } } var bgColor = new GdkColor(config.BackgroundColor); WebKit.SetBackgroundColor(Handle, ref bgColor); if (enableDevTools) { var settings = WebKit.Settings.Get(Handle); WebKit.Settings.SetEnableDeveloperExtras(settings, true); var inspector = WebKit.Inspector.Get(Handle); WebKit.Inspector.Show(inspector); } }
void HandleFinishedLoadForCss(object sender, WebKit.WebFrameEventArgs e) { SetCustomCss (); }
public static void ProcessData(WebKit webKit, HttpListener listener, IAsyncResult result) { try { var context = listener.EndGetContext(result); var response = context.Response; var request = context.Request.Url.AbsolutePath; response.Headers.Set(HttpResponseHeader.Server, AGENT); var ipAddress = context.Request.RemoteEndPoint.Address.ToString(); if (ipAddress != null) ipAddress = ipAddress.Split(':')[0]; if ((request.StartsWith("/"))) request = request.Substring(1); if ((request.EndsWith("/") || request.Equals(String.Empty))) request = request + WebServer.IndexPage; request = WebServer.RootPath + Path.DirectorySeparatorChar + request.Replace('/', Path.DirectorySeparatorChar); if (!CheckAuthenticity(context, webKit, request, ipAddress)) return; if (!Json.ProcessJsonHeader(webKit, context, context.User.Identity.Name, ipAddress)) ProcessResponse(request, context); } catch (ObjectDisposedException) { } catch (HttpListenerException) { } catch (Exception ex) { ProgramLog.Log(ex); } }
public static void RemoveKickedUser(string ipAddress, string name, WebKit webKit, int slot) { lock (webKit.KickList) { var list = webKit.KickList.FieldwiseClone(); foreach (var pair in list) { if (pair.Key == name && pair.Value.IpAddress == ipAddress) webKit.KickList.RemoveAt(slot); } } }
public static bool checkAlipay(WebKit.WebKitBrowser br) { try { string url = br.Url.Host; string content = br.DocumentText; if (url != "auth.alipay.com") { if (content.Contains("banner/loginBanner-->") || content.Contains("h2 seed=\"auth-alipayMember\">") || content.Contains("login.jhtml?style=alipay&goto=") || content.Contains("<form name=\"loginForm\" id=\"login\" action=\"https://auth.alipay.com/login/index.htm\" method=\"post\" > ")) { return true; } else { return false; } } else { return false; } } catch { } return false; }
void HandleM_viewLoadFinished(object o, WebKit.LoadFinishedArgs args) { contentLoaded = true; }
void HandleTitleChanged (object sender, WebKit.WebFrameTitleEventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnTitleChanged (); }); }
public static void ParseAndProcess(WebKit webKit, HttpListenerContext context, string[] args, string user, string ipAddress) { try { if (args != null && args.Length > 0) { //paremeters.Clear(); string id = args.ElementAt(0).Trim(); if (id != null && id.Length > 0) { RemoveFirst(ref args); for (var i = 0; i < args.Length; i++) { var arg = args[i].ToString(); if (arg.Length > 0) { if (arg.Contains('=')) arg = arg.Remove(0, arg.IndexOf('=') + 1).Trim(); if (arg.Length > 0) args[i] = arg; } } var arguments = new Args() { Arguments = args, AuthName = user, IpAddress = ipAddress, WebKit = webKit }; //InsertAtFirst( //Data.Insert(0, IPAddress); //foreach (string param in Data) //{ // string parameter = param.Trim(); // if (parameter.Length > 0) // { // if (parameter.Contains('=')) // { // parameter = parameter.Remove(0, parameter.IndexOf('=') + 1); // } // paremeters.Add(parameter); // } //} //paremeters.Insert(0, WebKit); //var args = new Args() //{ // WebKit = WebKit, // Sender = new Utility.WebSender( //}; var serialized = ProcessPacket(id, arguments); context.WriteString(String.Empty, serialized); } } } catch (ExitException) { throw; } catch (HttpListenerException) { } catch (ArgumentException) { } catch (Exception e) { ProgramLog.Log(e); } }
public static string GetUserHash(string user, WebKit webKit) { foreach (Credential cred in webKit.CredentialList.Where(x => x.Username == user)) return cred.Sha1; return null; }
private void WebView_DownloadBegin(object sender, WebKit.FileDownloadBeginEventArgs e) { //TODO: add ie6 styled download dialog MessageBox.Show("Downloads are not supported yet"); }
public static AuthStatus IsCredentialsTheSame(string user, string password, WebKit webKit) { string userHash = GetUserHash(user, webKit); if (userHash == null) return AuthStatus.NON_EXISTANT_USER; else { var hashed = ComputeHash(user, password, webKit.Properties.ServerId); if (CompareHash(hashed, userHash)) return AuthStatus.MATCH; } return AuthStatus.NON_EXISTANT_PASS; }
protected override void OnExternalCall(WebKit.JavaScriptExternalEventArgs args) { base.OnExternalCall(args); }
public static bool IsOutOfSession(string name, DateTime last, string ipAddress, WebKit webKit) { return (DateTime.Now - last).TotalMilliseconds > (webKit.MainUpdateInterval * 2); }
public override NSMenuItem[] UIGetContextMenuItems(WebKit.WebView sender, NSDictionary forElement, NSMenuItem [] defaultMenuItems) { if (backend.ContextMenuEnabled) return defaultMenuItems; return null; }
static int Main() { var app = Application.New("de.uriegel.test"); if (Environment.CurrentDirectory.Contains("netcoreapp")) { Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, "../../../"); } Application.AddActions(app, new [] { new GtkAction("destroy", () => Application.Quit(app), "<Ctrl>Q"), new GtkAction("menuopen", () => { var dialog = Dialog.NewFileChooser("Datei öffnen", window, Dialog.FileChooserAction.Open, "_Abbrechen", Dialog.ResponseId.Cancel, "_Öffnen", Dialog.ResponseId.Ok, IntPtr.Zero); var res = Dialog.Run(dialog); if (res == Dialog.ResponseId.Ok) { var ptr = Dialog.FileChooserGetFileName(dialog); string file = Marshal.PtrToStringUTF8(ptr); Console.WriteLine(file); GObject.Free(ptr); } Widget.Destroy(dialog); }), new GtkAction("test", () => Console.WriteLine("Ein Test"), "F6"), new GtkAction("test2", () => Console.WriteLine("Ein Test 2")), new GtkAction("test3", () => HeaderBar.SetSubtitle(headerBar, "Das ist der neue Subtitle"), "F5"), new GtkAction("showhidden", true, (a, s) => { var state = GtkAction.HandleBoolState(a, s); Console.WriteLine(state); }, "<Ctrl>H"), new GtkAction("theme", "yaru", (a, s) => { var state = GtkAction.HandleStringState(a, s); Console.WriteLine(state); }) }); var ret = Application.Run(app, () => { var type = Gtk.GuessContentType("/home/uwe/Dokumente/hypovereinsbank.pdf"); var type1 = Gtk.GuessContentType("x.fs"); var type2 = Gtk.GuessContentType("x.cs"); type = Gtk.GuessContentType("x.pdf"); var icon = Icon.Get(type); var theme = Theme.GetDefault(); var names = Icon.GetNames(icon); // GTK_ICON_LOOKUP_FORCE_SVG var iconInfo = Theme.ChooseIcon(theme, names, 48, IconInfo.Flags.ForceSvg); var filename = IconInfo.GetFileName(iconInfo); var text = Marshal.PtrToStringUTF8(filename); GObject.Unref(icon); var builder = Builder.New(); var res = Builder.AddFromFile(builder, "glade", IntPtr.Zero); window = Builder.GetObject(builder, "window"); headerBar = Builder.GetObject(builder, "headerbar"); Builder.ConnectSignals(builder, (IntPtr builder, IntPtr obj, string signal, string handleName, IntPtr connectObj, int flags) => { switch (handleName) { case "app.delete": Gtk.SignalConnectObject <BoolFunc>(obj, signal, () => { return(false); }, connectObj); break; } }); GObject.Unref(builder); Application.AddWindow(app, window); Window.SetTitle(window, "Web View 😎😎👌"); Window.SetDefaultSize(window, 300, 300); Widget.SetSizeRequest(window, 200, 100); Window.Move(window, 2900, 456); var webView = WebKit.New(); var settings = WebKit.GetSettings(webView); GObject.SetBool(settings, "enable-developer-extras", true); Container.Add(window, webView); var target = TargetEntry.New("text/plain", TargetEntry.Flags.OtherApp, 0); DragDrop.UnSet(webView); DragDrop.SetDestination(window, DragDrop.DefaultDestination.Drop | DragDrop.DefaultDestination.Highlight | DragDrop.DefaultDestination.Motion, target, 1, DragDrop.DragActions.Move); TargetEntry.Free(target); Gtk.SignalConnect <DragDataReceivedFunc>(window, "drag-data-received", (w, context, x, y, data) => { var text = SelectionData.GetText(data); Console.WriteLine(text); } ); Gtk.SignalConnect <DragMotionFunc>(window, "drag-motion", (w, context, x, y) => { Console.WriteLine("motion"); } ); Gtk.SignalConnect <BoolFunc>(window, "delete_event", () => false);// true cancels the destroy request! Gtk.SignalConnect <ConfigureEventFunc>(window, "configure_event", (w, e) => { var evt = Marshal.PtrToStructure <ConfigureEvent>(e); Console.WriteLine("Configure " + evt.Width.ToString() + " " + evt.Height.ToString()); Window.GetSize(window, out var ww, out var hh); Console.WriteLine("Configure- " + ww.ToString() + " " + hh.ToString()); return(false); }); ScriptDialogFunc scripDialogFunc = (_, dialog) => { var ptr = WebKit.ScriptDialogGetMessage(dialog); var text = Marshal.PtrToStringUTF8(ptr); switch (text) { case "anfang": WebKit.RunJavascript(webView, "var affe = 'Ein Äffchen'"); break; case "devTools": var inspector = WebKit.GetInspector(webView); WebKit.InspectorShow(inspector); break; default: Console.WriteLine($"---ALERT--- {text}"); break; } return(true); }; Gtk.SignalConnect(webView, "script-dialog", scripDialogFunc); Gtk.SignalConnect <BoolFunc>(webView, "context-menu", () => true); Widget.ShowAll(window); //WebKit.LoadUri(webView, "https://google.de"); WebKit.LoadUri(webView, "http://localhost:3000/"); // WebKit.LoadUri(webView, $"file://{System.IO.Directory.GetCurrentDirectory()}/../webroot/index.html"); });
public static bool NeedsKick(string ipAddress, string name, WebKit webKit, out int index) { index = default(Int32); lock (webKit.KickList) { var list = webKit.KickList; for (var i = 0; i < list.Count; i++) { var pair = list.ElementAt(i); if (pair.Key == name && pair.Value.IpAddress == ipAddress) { index = i; return true; } } } return false; }
public static bool CheckAuthenticity(HttpListenerContext context, WebKit webkit, string httpData, string ipAddress) { var identity = context.User.Identity; int slot; if (NeedsKick(ipAddress, identity.Name, webkit, out slot)) { RemoveKickedUser(ipAddress, identity.Name, webkit, slot); var res = new Dictionary<String, Object>(); res["main-interval-rm"] = "http://tdsm.org"; var serialized = Json.Serialize(webkit.WebServer, res); context.WriteString(serialized); WebKit.Log("{0} disconnected from {1}", identity.Name, ipAddress ?? "HTTP"); return false; } switch (identity.AuthenticationType) { case "Basic": var basicIdentity = (identity as HttpListenerBasicIdentity).ToTDSMIdentity(webkit); lock (webkit.WebSessions) { if (basicIdentity.AuthStatus != AuthStatus.MATCH) { context.Disconnect("Credentials incorrect."); WebKit.Log("{0} disconnected from {1}", basicIdentity.Name, ipAddress ?? "HTTP"); return false; } else { Identity ident; if (!webkit.WebSessions.ContainsKey(basicIdentity.Name)) WebKit.Log("{0} logged in from {1}", basicIdentity.Name, ipAddress ?? "HTTP"); else if (webkit.WebSessions.TryGetValue(basicIdentity.Name, out ident)) { if ((DateTime.Now - ident.LastUpdate).TotalMilliseconds > (webkit.MainUpdateInterval * 2)) WebKit.Log("{0} logged in from {1}", basicIdentity.Name, ipAddress ?? "HTTP"); } } if (webkit.WebSessions.ContainsKey(basicIdentity.Name)) { var newIdent = webkit.WebSessions[basicIdentity.Name]; newIdent.IpAddress = ipAddress; newIdent.LastUpdate = DateTime.Now; webkit.WebSessions[basicIdentity.Name] = newIdent; } else webkit.WebSessions[basicIdentity.Name] = new Identity() { IpAddress = ipAddress, LastUpdate = DateTime.Now }; } return true; //case "NTLM": // var identity = iIdentity as WindowsIdentity; // var ident1 = iIdentity as System.Security.Principal.WindowsPrincipal; // var ident2 = iIdentity as System.Security.Principal.GenericPrincipal; // var ident3 = iIdentity as System.Security.Principal.GenericIdentity; // break; default: context.Disconnect("Unauthorised access."); WebKit.Log("Connection is unsupported from {0}@{1}", identity.Name, ipAddress ?? "HTTP"); return false; } }