Example #1
0
        public static async Task <decimal> RedeemAmazonAsync(this IWebView view, string claimcode, CancellationToken ct, int delayMS)
        {
            string amazonCashInUrl = "https://www.amazon.com/gc/redeem/";

            if (view.Source.ToString().ToLower().Contains(amazonCashInUrl) == false)
            {
                await view.WaitPageLoadComplete(() =>
                {
                    view.Source = amazonCashInUrl.ToUri();
                }, ct : ct);
            }
            else
            {
                await view.WaitPageLoadComplete(() =>
                {
                    view.Reload(false);
                }, ct : ct);
            }

            view.ExecuteJavascript(string.Format("document.querySelector('#gc-redemption-input').value='{0}'", claimcode));

            await view.WaitPageLoadComplete(() =>
            {
                view.ExecuteJavascript("document.querySelector(\"#gc-redemption-apply input\").click()");
            }, ct : ct);

            await Task.Delay(delayMS);

            return(await view.GetAmazonBalanceAsync());
        }
Example #2
0
        public static async Task <decimal> AuthenticateToAmazonAsync(this IWebView view, string username, string password, CancellationToken ct)
        {
            string amazonLoginUrl = @"https://www.amazon.com/gc/redeem/";

            if (view.Source == null)
            {
                await view.WaitPageLoadComplete(() =>
                {
                    view.Source = amazonLoginUrl.ToUri();
                }, ct : ct);
            }

            if (view.Source.ToString().ToLower() != amazonLoginUrl)
            {
                await view.WaitPageLoadComplete(() =>
                {
                    view.Source = amazonLoginUrl.ToUri();
                }, ct : ct);
            }
            else
            {
                view.Reload(true);
            }

            if (view.Source.ToString().ToLower().Contains("signin"))
            {
                view.ExecuteJavascript(string.Format("document.querySelector(\"#ap_email\").value=\"{0}\"", username));
                view.ExecuteJavascript(string.Format("document.querySelector(\"#ap_password\").value=\"{0}\"", password));

                await view.WaitPageLoadComplete(() =>
                {
                    view.ExecuteJavascript("document.querySelector(\"#signInSubmit\").click()");
                }, 10);

                while (true)
                {
                    await Task.Delay(250, ct);

                    ct.ThrowIfCancellationRequested();
                    if (view.Source.ToString().ToLower().Contains("/redeem/"))
                    {
                        break;
                    }
                }
            }

            return(await view.GetAmazonBalanceAsync());
        }
Example #3
0
        /// <summary>
        /// Must be called every time a new page is being loaded, at DOM ready time.
        /// </summary>
        public void InjectSelectionHandlers()
        {
            this.ClearSelection();

            view.ExecuteJavascript(
                "var webControlSelectionHandler = function(e){ " +
                "if ( window.getSelection().rangeCount > 0 ) { " +
                "var range = window.getSelection().getRangeAt(0);" +
                "var clonedSelection = range.cloneContents();" +
                "var div = document.createElement( 'div' );" +
                "div.appendChild( clonedSelection );" +
                String.Format("{0}.{1}", SELECTION_OBJECT, SELECTION_HTML_CALLBACK) + "( div.innerHTML ); }" +
                "else { " +
                String.Format("{0}.{1}", SELECTION_OBJECT, SELECTION_HTML_CALLBACK) + "( '' ); }" +
                String.Format("{0}.{1}", SELECTION_OBJECT, SELECTION_TEXT_CALLBACK) + "( window.getSelection().toString() ); };");

            view.ExecuteJavascript("document.addEventListener('select', webControlSelectionHandler, true);");
            view.ExecuteJavascript("document.addEventListener('selectstart', webControlSelectionHandler, true);");
        }
Example #4
0
 public void ExcecuteJavascript(string icode)
 {
     try
     {
         _CurrentWebControl.ExecuteJavascript(icode);
     }
     catch (Exception e)
     {
         LogBrowser(string.Format("Can not execute javascript: {0}, reason: {1}", icode, e));
     }
 }
        protected void OnSongLoaded()
        {
            loaded = true;
            if (!ShowChords)             // defaults to true
            {
                control.ExecuteJavascript("presentation.setShowChords(false)");
            }

            if (SongLoaded != null)
            {
                SongLoaded(this, EventArgs.Empty);
            }
        }
        public static void SaveAsync(string source, string localfile, string elementname, string width, string height, string dpi)
        {
            var path = Path.GetDirectoryName(localfile);
            //var source = ((Group.HtmlSource)s.Element).Source;
            string html = null;

            if (source.StartsWith("http://") || source.StartsWith("https://") || source.StartsWith("~"))
            {
                /*try {
                 *      var ctx = HttpContext.Current;
                 *      var app = ctx.Request.ApplicationPath;
                 *      var root = ctx.Request.Url.Authority + "/" + app;
                 *      var oldpath = ctx.Request.Url.AbsolutePath;
                 *      path = null;
                 *      if (source.StartsWith(root)) {
                 *              path = source.Substring(root.Length);
                 *      } else if (source.StartsWith("~")) {
                 *              path = source.Substring(1);
                 *      }
                 *      if (path != null) {
                 *              using (var w = new StringWriter()) {
                 *                      ctx.RewritePath(path);
                 *                      ctx.Server.Execute(path, w, false);
                 *                      ctx.RewritePath(oldpath);
                 *                      html = w.ToString();
                 *              }
                 *      }
                 * } catch {
                 * } finally {*/
                /*	if (html == null) {
                 *              var web = new WebClient();
                 *              web.Encoding = Encoding.UTF8;
                 *              html = web.DownloadString(source);
                 *      }
                 * //} */
            }
            var binpath = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            //AppDomain.CurrentDomain.AppendPrivatePath("Lazy\\Awesomium");
            if (!AssemblyResolverInitialized)
            {
                int resolving = 0;
                AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
                    try {
                        resolving++;
                        var apath = binpath;
                        var aname = new System.Reflection.AssemblyName(args.Name);
                        aname.CodeBase = Path.Combine(apath, args.Name + ".dll");
                        return(resolving > 1 ? null : System.Reflection.Assembly.Load(aname));
                    } catch {
                        return(null);
                    } finally {
                        resolving--;
                    }
                };
                AssemblyResolverInitialized = true;
            }

            if (Instances++ == 0)
            {
                WebCore.Initialize(new WebConfig()
                {
                    LogPath = path, LogLevel = LogLevel.Verbose
                });
            }

            if (Session == null)
            {
                Session = WebCore.CreateWebSession(new WebPreferences()
                {
                    AcceptLanguage             = Thread.CurrentThread.CurrentUICulture.Name.ToLower(),
                    DefaultEncoding            = "utf-8",
                    EnableGPUAcceleration      = false,
                    FileAccessFromFileURL      = true,
                    UniversalAccessFromFileURL = true,
                    WebAudio    = false,
                    WebGL       = true,
                    WebSecurity = false
                });
            }
            if (View == null)
            {
                View = WebCore.CreateWebView(1280, 1024, Session);
            }
            var config = new PrintConfig();

            //s.GetSize(s.Element);
            config.PageSize = new AweRect(0, 0, (int)(double.Parse(width) + 0.5), (int)(double.Parse(height) + 0.5));
            config.SplitPagesIntoMultipleFiles = false;
            var Dpi = 600.0;

            double.TryParse(dpi, out Dpi);
            config.Dpi = Dpi;
            IDisposable fileLock = null;

            SavedSignal.Reset();
            View.PrintComplete += (sender, args) => {
                File.Move(args.Files [0], localfile);
                Environment.Exit(0);
            };
            View.PrintFailed += (sender, args) => {
                Environment.Exit(1);
            };
            var    loaded   = false;
            Action onloaded = () => {
                lock (Lock) {
                    if (loaded)
                    {
                        return;
                    }
                    var part = !string.IsNullOrWhiteSpace(elementname);
                    if (part)
                    {
                        View.ExecuteJavascript(@"
						var obj = top.document.getElementById('"                         + elementname + @"');
						var selection = window.getSelection();
						var range = document.createRange();
						range.setStartBefore(obj);
						range.setEndAfter(obj) ;
						selection.addRange(range);
					"                    );
                        config.PrintSelectionOnly = true;
                    }
                    else
                    {
                        config.PrintSelectionOnly = false;
                    }
                    //FileLock = s.Compiler.FileLock(tempFile);
                    View.PrintToFile(path, config);
                    loaded = true;
                }
            };

            View.LoadingFrameComplete += (sender, args) => { if (args.IsMainFrame)
                                                             {
                                                                 onloaded();
                                                             }
            };
            View.LoadingFrameFailed += (sender, args) => { if (args.IsMainFrame)
                                                           {
                                                               onloaded();
                                                           }
            };

            View.Source = new Uri(source);
            while (View.IsLoading)
            {
                Thread.Sleep(100); WebCore.Update();
            }
            Thread.Sleep(300);
            WebCore.Update();
            onloaded();
            while (View.IsPrinting)
            {
                Thread.Sleep(100); WebCore.Update();
            }
        }
 public void ExecuteJavaScript(string code)
 {
     _IWebView.ExecuteJavascript(code);
 }
Example #8
0
        public static async Task <decimal> ValidateAmazonAsync(this IWebView view, string username, string password, string claimcode, CancellationToken ct, int delayMS)
        {
            Application.Current.MainWindow.Dispatcher.Invoke(() => { ((MainWindow)Application.Current.MainWindow).browserPlaceHolder.GetChildOfType <System.Windows.Controls.Canvas>().Background = System.Windows.Media.Brushes.Gray; });

            string amazonValidateInUrl = "https://www.amazon.com/gc/redeem/";

            if (view.Source.ToString().ToLower().Contains(amazonValidateInUrl) == false)
            {
                await view.WaitPageLoadComplete(() =>
                {
                    view.Source = amazonValidateInUrl.ToUri();
                },
                                                ct : ct);
            }

            await view.WaitPageLoadComplete(() =>
            {
                view.Reload(false);
            }, ct : ct);

            view.ExecuteJavascript(string.Format("document.querySelector('#gc-redemption-input').value='{0}'", claimcode));

            await Task.Delay(250);

            view.ExecuteJavascript("document.querySelector('#gc-redemption-check-value input').click()");

            await Task.Delay(delayMS);

            string  gcValue;
            bool    codeError    = false;
            bool    captchaError = false;
            decimal parsedValue  = -1;

            while (true)
            {
                gcValue      = HttpUtility.HtmlDecode(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-check-value-heading').innerHTML").ToString());
                codeError    = bool.Parse(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-error') ? (document.querySelector('#gc-redemption-error').innerHTML.toLowerCase().indexOf('claim code is invalid')>-1 ? true : false) : false").ToString());
                captchaError = bool.Parse(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-captcha') ? (document.querySelector('#gc-redemption-captcha').innerHTML.toLowerCase().indexOf('security verification')>-1 ? true : false) : false").ToString());

                if (codeError)
                {
                    break;
                }

                if (captchaError)
                {
                    captchaSolvedSignal = new SemaphoreSlim(0, 1);
                    //  Application.Current.MainWindow.Dispatcher.Invoke(() => { ((MainWindow)Application.Current.MainWindow).browserPlaceHolder.IsEnabled = true; });
                    // Application.Current.MainWindow.Dispatcher.Invoke(() => { MessageBox.Show("Captcha Detected. Enter Captcha and manually click 'check'."); });

                    while (true)
                    {
                        await Task.Delay(500);

                        gcValue   = HttpUtility.HtmlDecode(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-check-value-heading').innerHTML").ToString());
                        codeError = bool.Parse(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-error') ? (document.querySelector('#gc-redemption-error').innerHTML.toLowerCase().indexOf('claim code is invalid')>-1 ? true : false) : false").ToString());
                        if (codeError)
                        {
                            Application.Current.MainWindow.Dispatcher.Invoke(() => { ((MainWindow)Application.Current.MainWindow).CaptchaPanel.Visibility = Visibility.Hidden; });
                            return(parsedValue);
                        }

                        if (gcValue == null || gcValue == "undefined" || gcValue == "null" || gcValue == "")
                        {
                            await Task.Delay(500);

                            var captchaImageData = view.GetCaptchaData();
                            var captchaResult    = SolveCaptcha_Tesseract(captchaImageData.BitmapImageToBitmap());
                            if (captchaResult.Key < .6)
                            {
                                await Application.Current.MainWindow.Dispatcher.Invoke(async() =>
                                {
                                    ((MainWindow)Application.Current.MainWindow).CaptchaPanel.Visibility = Visibility.Visible;
                                    ((MainWindow)Application.Current.MainWindow).CaptchaImage.Source     = captchaImageData;

                                    await captchaSolvedSignal.WaitAsync();

                                    captchaResult = new KeyValuePair <float, string>(1, ((MainWindow)Application.Current.MainWindow).txtCaptchaResult.Text);

                                    ((MainWindow)Application.Current.MainWindow).txtCaptchaResult.Text = string.Empty;
                                });
                            }


                            view.ExecuteJavascript(string.Format("document.querySelector('input[name=\"captchaInput\"]').value='{0}'", captchaResult.Value));

                            await Task.Delay(250);

                            view.ExecuteJavascript("document.querySelector('#gc-redemption-check-value input').click()");
                        }


                        try
                        {
                            await Task.Delay(500);

                            string gcParsedClaimCode = HttpUtility.HtmlDecode(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-check-value-result-box span').innerHTML").ToString()).Split()[2].ToLower();
                            gcValue = HttpUtility.HtmlDecode(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-check-value-heading').innerHTML").ToString());

                            if (gcParsedClaimCode == claimcode.Replace("-", "").ToLower())
                            {
                                decimal.TryParse(gcValue.Split()[0].Replace("$", ""), out parsedValue);
                                Application.Current.MainWindow.Dispatcher.Invoke(() => { ((MainWindow)Application.Current.MainWindow).CaptchaPanel.Visibility = Visibility.Hidden; });
                                return(parsedValue);
                            }
                            else
                            {
                            }
                        }
                        catch (IndexOutOfRangeException ex)
                        {
                        }
                        //else
                        //{
                        //    //await Application.Current.MainWindow.Dispatcher.Invoke(async () =>
                        //    //{
                        //    //    ((MainWindow)Application.Current.MainWindow).CaptchaPanel.Visibility = Visibility.Visible;
                        //    //    ((MainWindow)Application.Current.MainWindow).CaptchaImage.Source = await view.GetCaptchaData();
                        //    //    await captchaSolvedSignal.WaitAsync();

                        //    //    await Task.Delay(250);
                        //    //    view.ExecuteJavascript(string.Format("document.querySelector('input[name=\"captchaInput\"]').value='{0}'", ((MainWindow)Application.Current.MainWindow).txtCaptchaResult.Text));

                        //    //    view.ExecuteJavascript("document.querySelector('#gc-redemption-check-value input').click()");
                        //    //});

                        //    //continue;
                        //}
                    }
                }

                if (gcValue == null || gcValue == "undefined" || gcValue == "null" || gcValue == "")
                {
                    //await view.WaitPageLoadComplete(() =>
                    //{
                    //    view.Reload(false);
                    //});
                    await Task.Delay(delayMS);

                    continue;
                }
                else
                {
                    gcValue = HttpUtility.HtmlDecode(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-check-value-heading').innerHTML").ToString());

                    string gcParsedClaimCode = HttpUtility.HtmlDecode(view.ExecuteJavascriptWithResult("document.querySelector('#gc-redemption-check-value-result-box span').innerHTML").ToString()).Split()[2].ToLower();

                    if (gcParsedClaimCode == claimcode.Replace("-", "").ToLower())
                    {
                        decimal.TryParse(gcValue.Split()[0].Replace("$", ""), out parsedValue);
                        return(parsedValue);
                    }
                    else
                    {
                        continue;
                    }
                }
            }


            return(parsedValue);
        }