示例#1
0
        internal static void OpenUrl(string url)
        {
            // https://stackoverflow.com/questions/4580263/how-to-open-in-default-browser-in-c-sharp

            try {
                if (url != null)
                {
                    Process.Start(url);
                }
                else
                {
                    Console.WriteLine();
                    CliOutput.WriteError("URL is null!");
                }
            }
            catch {
                // hack because of this: https://github.com/dotnet/corefx/issues/10361
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    url = url.Replace("&", "^&");
                    Process.Start(new ProcessStartInfo("cmd", $"/c start {url}")
                    {
                        CreateNoWindow = true
                    });
                }
                else
                {
                    throw;
                }
            }
        }
示例#2
0
        public static BasicAccount CreateAccount(bool auto)
        {
            RapidWebDriver rwd;


            try {
                CliOutput.WriteInfo("Please wait...");
                rwd = RapidWebDriver.CreateQuick(true);
            }
            catch (Exception exception) {
                CliOutput.WriteError("Exception: {0}", exception.Message);
                //throw;
                CliOutput.WriteError("Error creating webdriver");

                return(BasicAccount.Null);
            }

            string uname, pwd, email;

            if (auto)
            {
                uname = Strings.CreateRandom(10);
                pwd   = Strings.CreateRandom(10);
                email = WebAgent.EMail.GetEmail();
            }
            else
            {
                Console.Write("Username: "******"Password: "******"Email: ");
                email = Console.ReadLine();
            }

            Console.WriteLine("\nUsername: {0}\nPassword: {1}\nEmail: {2}\n", uname, pwd, email);


            try {
                CliOutput.WriteInfo("Registering account...");
                var acc = CreateAccountInternal(rwd, uname, email, pwd);


                CliOutput.WriteInfo("Cleaning up...");
                rwd.Dispose();

                return(acc);
            }
            catch (Exception exception) {
                CliOutput.WriteError("Exception: {0}", exception.Message);
                //throw;
                CliOutput.WriteError("Error creating account");

                return(BasicAccount.Null);
            }
        }
示例#3
0
        private static bool StartSearches(string imgUrl, SearchEngines engines, SearchResults res)
        {
            ISearchEngine[] available = GetAvailableEngines()
                                        .Where(e => engines.HasFlag(e.Engine))
                                        .ToArray();

            int i = 0;

            res.Results    = new SearchResult[available.Length + 1];
            res.Results[i] = new SearchResult(imgUrl, "(Original image)");

            i++;

            foreach (var idx in available)
            {
                string wait = String.Format("{0}: ...", idx.Engine);

                CliOutput.WithColor(ConsoleColor.Blue, () =>
                {
                    //
                    Console.Write(wait);
                });


                // Run search
                var result = idx.GetResult(imgUrl);

                if (result != null)
                {
                    string url = result.Url;


                    if (url != null)
                    {
                        CliOutput.OnCurrentLine(ConsoleColor.Green, "{0}: Done\n", result.Name);

                        if (RuntimeInfo.Config.PriorityEngines.HasFlag(idx.Engine))
                        {
                            WebAgent.OpenUrl(result.Url);
                        }
                    }
                    else
                    {
                        CliOutput.OnCurrentLine(ConsoleColor.Yellow, "{0}: Done (url is null!)\n", result.Name);
                    }

                    res.Results[i] = result;
                }

                // todo

                i++;
            }


            return(true);
        }
示例#4
0
        private static void RunCommands(object obj)
        {
            // todo: copied code

            switch (obj)
            {
            case ContextMenuCommand c1:
            {
                var c = (IIntegrated)c1;
                RunIntegrated(c, ContextMenuCommand.Add, ContextMenuCommand.Remove);

                break;
            }

            case PathCommand c1:
            {
                var c = (IIntegrated)c1;
                RunIntegrated(c, PathCommand.Add, PathCommand.Remove);

                break;
            }

            case CreateSauceNaoCommand c:
            {
                var acc = SauceNao.CreateAccount(c.Auto);

                CliOutput.WriteInfo("Account information:");

                var accStr = acc.ToString();
                var output = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
                             + "\\saucenao_account.txt";

                File.WriteAllText(output, accStr);

                Console.WriteLine(accStr);

                CliOutput.WriteInfo("Adding key to cfg file");
                RuntimeInfo.Config.SauceNaoAuth = acc.ApiKey;
                RuntimeInfo.Config.WriteToFile();
                break;
            }

            case ResetCommand c:
            {
                ResetCommand.RunReset(c.All);
                break;
            }

            case InfoCommand c:
            {
                InfoCommand.Show();
                break;
            }
            }
        }
示例#5
0
        private static BasicAccount CreateAccountInternal(RapidWebDriver rwd,
                                                          string username = null,
                                                          string email    = null,
                                                          string password = null)
        {
            var cd = rwd.Value;

            cd.Url = BASE_URL + "user.php";

            var usernameEle = cd.FindElement(ByUsername);

            usernameEle.SendKeys(username);


            var emailEle = cd.FindElement(ByEmail);

            emailEle.SendKeys(email);


            var pwdEle = cd.FindElement(ByPassword);

            pwdEle.SendKeys(password);


            var pwd2Ele = cd.FindElement(ByPasswordConfirmation);

            pwd2Ele.SendKeys(password);

            var regEle = cd.FindElement(ByRegister);

            regEle.Click();

            var body     = cd.FindElement(ByBody);
            var response = body.Text;

            Thread.Sleep(TimeSpan.FromSeconds(5));

            if (cd.Url != ACC_OV_URL || !response.Contains("welcome"))
            {
                CliOutput.WriteError("Error registering: {0} (body: {1})", cd.Url, response);
                return(BasicAccount.Null);
            }

            CliOutput.WriteSuccess("Success!");

            // https://saucenao.com/user.php?page=search-api

            cd.Url = ACC_API_URL;

            var apiEle  = cd.FindElement(ByApiKey);
            var apiText = apiEle.Text.Split(' ')[2];

            return(new BasicAccount(username, password, email, apiText));
        }
示例#6
0
        public static void RunContextMenuIntegration(string option)
        {
            switch (option)
            {
            case OPT_ADD:
                string fullPath = RuntimeInfo.ExeLocation;

                if (!RuntimeInfo.IsExeInAppFolder)
                {
                    bool v = CliOutput.ReadConfirm("Could not find exe in system path. Add now?");

                    if (v)
                    {
                        RuntimeInfo.Setup();
                        return;
                    }
                }

                // Add command
                string[] commandCode =
                {
                    "@echo off",
                    String.Format("reg.exe add {0} /ve /d \"{1} \"\"%%1\"\"\" /f >nul",
                                  RuntimeInfo.REG_SHELL_CMD, fullPath)
                };

                Cli.CreateRunBatchFile("add_to_menu.bat", commandCode);


                // Add icon
                string[] iconCode =
                {
                    "@echo off",
                    String.Format("reg.exe add {0} /v Icon /d \"{1}\" /f >nul",RuntimeInfo.REG_SHELL, fullPath)
                };

                Cli.CreateRunBatchFile("add_icon_to_menu.bat", iconCode);
                break;

            case OPT_REM:
                // reg delete HKEY_CLASSES_ROOT\*\shell\SmartImage

                // const string DEL = @"reg delete HKEY_CLASSES_ROOT\*\shell\SmartImage";

                string[] code =
                {
                    "@echo off",
                    String.Format(@"reg.exe delete {0} /f >nul", RuntimeInfo.REG_SHELL)
                };

                Cli.CreateRunBatchFile("rem_from_menu.bat", code);
                break;
            }
        }
示例#7
0
        public static bool RunSearch(string img, ref SearchResult[] res)
        {
            /*
             * Run
             */

            string auth     = SearchConfig.Config.ImgurAuth;
            bool   useImgur = !String.IsNullOrWhiteSpace(auth);

            var engines  = SearchConfig.Config.Engines;
            var priority = SearchConfig.Config.PriorityEngines;

            if (engines == SearchEngines.None)
            {
                //todo
                //CliOutput.WriteError("Please configure search engine preferences!");
                engines = SearchEngines.All;
            }


            // Exit
            if (!IsFileValid(img))
            {
                SearchConfig.Cleanup();

                return(false);
            }

            // Display config
            CliOutput.WriteInfo(SearchConfig.Config);

            string imgUrl = Upload(img, useImgur);

            CliOutput.WriteInfo("Temporary image url: {0}", imgUrl);

            Console.WriteLine();

            //Console.ReadLine();

            //
            // Search
            //


            // Where the actual searching occurs

            var t = StartSearches(imgUrl, engines, ref res);


            return(true);
        }
示例#8
0
 private static void RunIntegrated(IIntegrated c, Action add, Action remove)
 {
     if (c.Add)
     {
         add();
     }
     else if (c.Remove)
     {
         remove();
     }
     else
     {
         CliOutput.WriteError("Option unknown: {0}", c.Option);
     }
 }
示例#9
0
        public static void ShowInfo()
        {
            Console.Clear();


            // Config

            CliOutput.WriteInfo("Search engines: {0}", SearchConfig.Config.Engines);
            CliOutput.WriteInfo("Priority engines: {0}", SearchConfig.Config.PriorityEngines);

            string sn     = SearchConfig.Config.SauceNaoAuth;
            bool   snNull = String.IsNullOrWhiteSpace(sn);

            CliOutput.WriteInfo("SauceNao authentication: {0} ({1})",
                                snNull ? CliOutput.MUL_SIGN.ToString() : sn, snNull ? "Basic" : "Advanced");

            string imgur     = SearchConfig.Config.ImgurAuth;
            bool   imgurNull = String.IsNullOrWhiteSpace(imgur);

            CliOutput.WriteInfo("Imgur authentication: {0}",
                                imgurNull ? CliOutput.MUL_SIGN.ToString() : imgur);

            CliOutput.WriteInfo("Image upload service: {0}",
                                imgurNull ? "ImgOps" : "Imgur");

            CliOutput.WriteInfo("Application folder: {0}", RuntimeInfo.AppFolder);
            CliOutput.WriteInfo("Executable location: {0}", RuntimeInfo.ExeLocation);
            CliOutput.WriteInfo("Config location: {0}", RuntimeInfo.ConfigLocation);
            CliOutput.WriteInfo("Context menu integrated: {0}", RuntimeInfo.IsContextMenuAdded);
            CliOutput.WriteInfo("In path: {0}\n", RuntimeInfo.IsAppFolderInPath);


            // Version

            var versionsInfo = VersionsInfo.Create();

            CliOutput.WriteInfo("Current version: {0}", versionsInfo.Current);
            CliOutput.WriteInfo("Latest version: {0}", versionsInfo.Latest.Version);
            CliOutput.WriteInfo("{0}", versionsInfo.Status);

            Console.WriteLine();

            // Author

            CliOutput.WriteInfo("Readme: {0}", RuntimeInfo.Readme);
            CliOutput.WriteInfo("Author: {0}", RuntimeInfo.Author);
        }
示例#10
0
        private static bool IsFileValid(string img)
        {
            if (!File.Exists(img))
            {
                CliOutput.WriteError("File does not exist: {0}", img);
                return(false);
            }

            bool extOkay = ImageExtensions.Any(img.EndsWith);

            if (!extOkay)
            {
                return(CliOutput.ReadConfirm("File extension is not recognized as a common image format. Continue?"));
            }


            return(true);
        }
示例#11
0
        private static string Upload(string img, bool useImgur)
        {
            string imgUrl;

            if (useImgur)
            {
                CliOutput.WriteInfo("Using Imgur for image upload");
                var imgur = new Imgur();
                imgUrl = imgur.Upload(img);
            }
            else
            {
                CliOutput.WriteInfo("Using ImgOps for image upload (2 hour cache)");
                var imgOps = new ImgOps();
                imgUrl = imgOps.UploadTempImage(img, out _);
            }


            return(imgUrl);
        }
示例#12
0
            public static void RunReset(bool all = false)
            {
                RuntimeInfo.Config.Reset();

                // Computer\HKEY_CLASSES_ROOT\*\shell\SmartImage

                ContextMenuCommand.Remove();

                // will be added automatically if run again
                //Path.Remove();

                if (all)
                {
                    RuntimeInfo.Config.Reset();
                    RuntimeInfo.Config.WriteToFile();

                    CliOutput.WriteSuccess("Reset cfg");
                    return;
                }
            }
示例#13
0
            public static void Add()
            {
                string fullPath = RuntimeInfo.ExeLocation;

                if (!RuntimeInfo.IsExeInAppFolder)
                {
                    bool v = CliOutput.ReadConfirm("Could not find exe in system path. Add now?");

                    if (v)
                    {
                        PathCommand.Add();
                        return;
                    }

                    if (fullPath == null)
                    {
                        throw new ApplicationException();
                    }
                }


                // Add command
                string[] commandCode =
                {
                    "@echo off",
                    String.Format("reg.exe add {0} /ve /d \"{1} \"\"%%1\"\"\" /f >nul",RuntimeInfo.REG_SHELL_CMD,
                                  fullPath)
                };

                Cli.CreateRunBatchFile("add_to_menu.bat", commandCode);


                // Add icon
                string[] iconCode =
                {
                    "@echo off",
                    String.Format("reg.exe add {0} /v Icon /d \"{1}\" /f >nul",RuntimeInfo.REG_SHELL,  fullPath),
                };

                Cli.CreateRunBatchFile("add_icon_to_menu.bat", iconCode);
            }
示例#14
0
        public static void RunReset(string option)
        {
            bool all = option == OPT_ALL;

            SearchConfig.Config.Reset();

            // Computer\HKEY_CLASSES_ROOT\*\shell\SmartImage

            RunContextMenuIntegration(OPT_REM);

            // will be added automatically if run again
            //Path.Remove();

            if (all)
            {
                SearchConfig.Config.Reset();
                SearchConfig.Config.WriteToFile();

                CliOutput.WriteSuccess("Reset cfg");
            }
        }
示例#15
0
        //  ____                       _   ___
        // / ___| _ __ ___   __ _ _ __| |_|_ _|_ __ ___   __ _  __ _  ___
        // \___ \| '_ ` _ \ / _` | '__| __|| || '_ ` _ \ / _` |/ _` |/ _ \
        //  ___) | | | | | | (_| | |  | |_ | || | | | | | (_| | (_| |  __/
        // |____/|_| |_| |_|\__,_|_|   \__|___|_| |_| |_|\__,_|\__, |\___|
        //                                                     |___/

        // todo: further improve UI

        // todo: remove SmartImage nuget package stuff

        // todo: fix access modifiers


        /**
         * Entry point
         */
        private static void Main(string[] args)
        {
            Console.Title = RuntimeInfo.NAME;
            Console.SetWindowSize(120, 35);
            Console.Clear();

            RuntimeInfo.Setup();
            SearchConfig.ReadSearchConfigArguments(args);

            if (SearchConfig.Config.NoArguments)
            {
                Commands.RunCommandMenu();
                Console.Clear();
            }

            var img = SearchConfig.Config.Image;

            bool run = !String.IsNullOrWhiteSpace(img);

            if (!run)
            {
                return;
            }

            var results = new SearchResult[(int)SearchEngines.All];
            var ok      = Search.RunSearch(img, ref results);

            if (!ok)
            {
                CliOutput.WriteError("Search failed");
                return;
            }

            Commands.HandleConsoleOptions(results);

            // Exit
            SearchConfig.Cleanup();
        }
示例#16
0
        private SauceNaoResult[] GetApiResults(string url)
        {
            if (m_apiKey == null)
            {
                // todo
                return(Array.Empty <SauceNaoResult>());
            }

            var req = new RestRequest();

            req.AddQueryParameter("db", "999");
            req.AddQueryParameter("output_type", "2");
            req.AddQueryParameter("numres", "16");
            req.AddQueryParameter("api_key", m_apiKey);
            req.AddQueryParameter("url", url);


            var res = m_client.Execute(req);

            WebAgent.AssertResponse(res);


            //Console.WriteLine("{0} {1} {2}", res.IsSuccessful, res.ResponseStatus, res.StatusCode);
            //Console.WriteLine(res.Content);


            string c = res.Content;


            if (String.IsNullOrWhiteSpace(c))
            {
                CliOutput.WriteError("No SN results!");
            }

            return(ReadResults(c));
        }
示例#17
0
        /**
         * Entry point
         */
        private static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                return;
            }

            RuntimeInfo.Setup();

            CliParse.ReadArguments(args);

            var img = RuntimeInfo.Config.Image;

            bool run = img != null;

            if (run)
            {
                var sr      = new SearchResults();
                var ok      = Search.RunSearch(img, ref sr);
                var results = sr.Results;

                // Console.WriteLine("Elapsed: {0:F} sec", result.Duration.TotalSeconds);

                ConsoleKeyInfo cki;

                do
                {
                    Console.Clear();

                    for (int i = 0; i < sr.Results.Length; i++)
                    {
                        var r = sr.Results[i];

                        var tag = (i + 1).ToString();
                        if (r != null)
                        {
                            string str = r.Format(tag);

                            Console.Write(str);
                        }
                        else
                        {
                            Console.WriteLine("{0} - ...", tag);
                        }
                    }

                    Console.WriteLine();

                    // Exit
                    if (RuntimeInfo.Config.AutoExit)
                    {
                        SearchConfig.Cleanup();
                        return;
                    }

                    CliOutput.WriteSuccess("Enter the result number to open or escape to quit.");


                    while (!Console.KeyAvailable)
                    {
                        // Block until input is entered.
                    }


                    // Key was read

                    cki = Console.ReadKey(true);
                    char keyChar = cki.KeyChar;

                    if (Char.IsNumber(keyChar))
                    {
                        int idx = (int)Char.GetNumericValue(cki.KeyChar) - 1;

                        if (idx < results.Length && idx >= 0)
                        {
                            var res = results[idx];
                            WebAgent.OpenUrl(res.Url);
                        }
                    }
                } while (cki.Key != ConsoleKey.Escape);

                // Exit
                SearchConfig.Cleanup();
            }
            else
            {
                //CliOutput.WriteInfo("Exited");
            }
        }
示例#18
0
 internal void WriteToFile()
 {
     CliOutput.WriteInfo("Updating config");
     ExplorerSystem.WriteMap(ToMap(), RuntimeInfo.ConfigLocation);
     CliOutput.WriteInfo("Wrote to {0}", RuntimeInfo.ConfigLocation);
 }
示例#19
0
 // ##########################################################################################
 /// <summary> Funkcja aktualizująca podgląd wiadomości w interfejsie aplikacji. </summary>
 /// <param name="message"> Wiadomość która ma zostać wyświetlona. </param>
 private void UpdateUI(string message, MessageModifier modifier)
 {
     CliOutput.Invoke(new InvokeInterface(() => { FuncShowMessage(message, modifier); }));
 }
示例#20
0
 // ------------------------------------------------------------------------------------------
 /// <summary> Funkcja uruchamiająca wybrane funkcje dla interfejsu użytkownika. </summary>
 /// <param name="function"> Wywoływana funkcja interfejsu użytkownika. </param>
 private void InvokeUI(InvokeCommand function)
 {
     CliOutput.Invoke(new InvokeInterface(() => {
         function(null, null);
     }));
 }
示例#21
0
            internal static void Show()
            {
                Console.Clear();

                CliOutput.WriteInfo("Search engines: {0}", RuntimeInfo.Config.Engines);
                CliOutput.WriteInfo("Priority engines: {0}", RuntimeInfo.Config.PriorityEngines);

                var sn     = RuntimeInfo.Config.SauceNaoAuth;
                var snNull = String.IsNullOrWhiteSpace(sn);

                CliOutput.WriteInfo("SauceNao authentication: {0} ({1})", snNull ? CliOutput.MUL_SIGN.ToString() : sn,
                                    snNull ? "Basic" : "Advanced");

                var  imgur     = RuntimeInfo.Config.ImgurAuth;
                bool imgurNull = String.IsNullOrWhiteSpace(imgur);

                CliOutput.WriteInfo("Imgur authentication: {0}", imgurNull ? CliOutput.MUL_SIGN.ToString() : imgur);

                CliOutput.WriteInfo("Image upload service: {0}", imgurNull ? "ImgOps" : "Imgur");

                CliOutput.WriteInfo("Application folder: {0}", RuntimeInfo.AppFolder);
                CliOutput.WriteInfo("Executable location: {0}", RuntimeInfo.ExeLocation);
                CliOutput.WriteInfo("Config location: {0}", RuntimeInfo.ConfigLocation);
                CliOutput.WriteInfo("Context menu integrated: {0}", RuntimeInfo.IsContextMenuAdded);
                CliOutput.WriteInfo("In path: {0}\n", RuntimeInfo.IsAppFolderInPath);
                CliOutput.WriteInfo(".NET bundle extract folder: {0}", RuntimeInfo.BundleExtractFolder);


                //

                // CliOutput.WriteInfo("Supported search engines: {0}\n", SearchEngines.All);

                //

                var asm            = typeof(RuntimeInfo).Assembly.GetName();
                var currentVersion = asm.Version;

                CliOutput.WriteInfo("Current version: {0}", currentVersion);

                var release = ReleaseInfo.LatestRelease();

                CliOutput.WriteInfo("Latest version: {0} (tag {1}) ({2})", release.Version, release.TagName,
                                    release.PublishedAt);

                int vcmp = currentVersion.CompareTo(release.Version);

                if (vcmp < 0)
                {
                    CliOutput.WriteInfo("Update available");
                }
                else if (vcmp == 0)
                {
                    CliOutput.WriteInfo("Up to date");
                }
                else
                {
                    CliOutput.WriteInfo("(preview)");
                }

                CliOutput.WriteInfo("Readme: {0}", RuntimeInfo.Readme);
                CliOutput.WriteInfo("Author: {0}", RuntimeInfo.Author);
            }
示例#22
0
        private static bool StartSearches(string imgUrl, SearchEngines engines, ref SearchResult[] res)
        {
            // todo: improve
            // todo: use tasks

            var availableEngines = GetAvailableEngines()
                                   .Where(e => engines.HasFlag(e.Engine))
                                   .ToArray();

            int i = 0;

            res    = new SearchResult[availableEngines.Length + 1];
            res[i] = new SearchResult(imgUrl, "(Original image)");

            i++;


            foreach (var currentEngine in availableEngines)
            {
                string wait = String.Format("{0}: ...", currentEngine.Engine);

                CliOutput.WithColor(ConsoleColor.Blue, () =>
                {
                    //
                    Console.Write(wait);
                });

                var sw = Stopwatch.StartNew();

                // Run search
                var result = currentEngine.GetResult(imgUrl);

                sw.Stop();

                if (result != null)
                {
                    string url = result.Url;

                    var    sb = new StringBuilder();
                    double t  = sw.Elapsed.TotalSeconds;
                    double t2 = Math.Round(t, 3);
                    sb.AppendFormat("{0}: Done ({1:F3} sec)\n", result.Name, t2);


                    //todo

                    bool ok = url != null;

                    string sz = sb.ToString();


                    if (ok)
                    {
                        CliOutput.OnCurrentLine(ConsoleColor.Green, sz);

                        if (SearchConfig.Config.PriorityEngines.HasFlag(currentEngine.Engine))
                        {
                            WebAgent.OpenUrl(result.Url);
                        }
                    }
                    else
                    {
                        CliOutput.OnCurrentLine(ConsoleColor.Yellow, sz);
                    }

                    res[i] = result;
                }

                // todo

                i++;
            }


            return(true);
        }