Exemplo n.º 1
0
        private MyWebClient GetWebClient(IProxySettings settings)
        {
            var mywc = new MyWebClient();

            mywc = WebHelper.ConfigureWebClientProxy(mywc, settings);
            return(mywc);
        }
Exemplo n.º 2
0
        public SynoReportViaSSH(DSMHost host, IProxySettings proxy = null)
        {
            RmExecutionMode = ConsoleCommandMode.InteractiveSudo;

            _host = host;

            int i = 0;

            AuthenticationMethod[] methods = new AuthenticationMethod[host.AuthenticationSection.Count];
            foreach (var m in host.AuthenticationMethods)
            {
                methods[i++] = m.getAuthenticationMethod();
            }

            if (proxy != null)
            {
                ProxyTypes proxypath;
                if (!Enum.TryParse(proxy.ProxyType, true, out proxypath))
                {
                    proxypath = ProxyTypes.None;
                }
                _ci = new ConnectionInfo(host.Host, host.Port, host.UserName, proxypath, proxy.Host, proxy.Port, proxy.UserName, proxy.Password, methods);
            }
            else
            {
                _ci = new ConnectionInfo(host.Host, host.Port, host.UserName, methods);
            }
        }
        public void SetProxySettings(IProxySettings contractObject)
        {
            lock (Anchor)
            {
                bool changed = false;

                if (null == contractObject)
                {
                    if (null != _authenticationSettings.ProxySettings)
                    {
                        _authenticationSettings.ProxySettings = null;
                        changed = true;
                    }
                }
                else
                {
                    var proxySettings = ProxySettings.Create(contractObject);

                    if (!proxySettings.Equals(_authenticationSettings.ProxySettings))
                    {
                        _authenticationSettings.ProxySettings = (ProxySettings)proxySettings.Clone();
                        changed = true;
                    }
                }

                if (changed)
                {
                    Save();
                    _webProxy = null;
                }
            }
        }
Exemplo n.º 4
0
        static async Task <Version> GetNewestVersion(IProxySettings settings, IGeneralSettings generalSettings, IProgress <double> progress = null)
        {
            progress?.Report(0);
            Newtonsoft.Json.Linq.JToken jsonData;
            try
            {
                if (generalSettings.AllowPrerelases)
                {
                    jsonData = await GetLatestPreRelease(settings);
                }
                else
                {
                    jsonData = await GetLatestStableRelease(settings);
                }
            }
            catch (HttpRequestException)
            {
                return(new Version(0, 0, 0, 0));
            }
            progress?.Report(0.5);
            var tag = ((string)jsonData["tag_name"]).TrimStart('v', 'V');

            InstallerUrlCache = GetInstallerUrl(jsonData);
            progress?.Report(0.9);
            var gitHubVersion = new Version(tag);

            NewestVersion = gitHubVersion;
            return(gitHubVersion);
        }
Exemplo n.º 5
0
        private async Task LoadProxiesAsync()
        {
            using (AsyncLock.Lock(_proxies))
            {
                _proxies.Clear();

                var(proxies, index) = await GetDbProxies();

                if (proxies != null && proxies.Length != 0 && index >= 0 && index < proxies.Length)
                {
                    _currentIndex = index;
                    _proxies.AddRange(proxies);
                }
                else
                {
                    _settings = _settingsProvider.GetSettings().Proxy;

                    (proxies, index) = await GetProxies(_settings);

                    if (proxies != null)
                    {
                        _proxies.AddRange(proxies);
                        _currentIndex = index;
                        await SetDbProxies(_currentIndex, _proxies.ToArray());
                    }
                }
            }
        }
Exemplo n.º 6
0
        internal static WebClient GetWebClient(IProxySettings settings)
        {
            var wc = new WebClient();

            wc = ConfigureWebClientProxy(wc, settings);
            return(wc);
        }
Exemplo n.º 7
0
        private async Task LoadData(IProxySettings settings, string version)
        {
            await Task.Delay(500);

            var httpClient = WebHelper.GetHttpClient(settings);

            httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("LogUploader");
            string res;

            try
            {
                res = await httpClient.GetStringAsync(BASE_ADDRESS + version);
            }
            catch (System.Net.Http.HttpRequestException e)
            {
                Logger.Error("Download of patchnotes failed");
                Logger.LogException(e);
                Logger.LogException(e.InnerException);
                DialogResult = DialogResult.Abort;
                Close();
                return;
            }

            var data       = Newtonsoft.Json.Linq.JObject.Parse(res);
            var patchnotes = (string)data["body"];
            var htmlNotes  = CommonMark.CommonMarkConverter.Convert(patchnotes);
            var html       = HTML_PART_A + htmlNotes + HTML_PART_B;

            webBrowser1.DocumentText = html;
            DialogResult             = DialogResult.OK;
        }
Exemplo n.º 8
0
        public static async Task <bool> UpdateAvailable(IProxySettings settings, IGeneralSettings generalSettings, IProgress <double> progress = null)
        {
            var GitTask       = GetNewestVersion(settings, generalSettings);
            var LocalVersion  = GetLocalVersion();
            var NewestVersion = await GitTask;

            return(NewestVersion > LocalVersion);
        }
Exemplo n.º 9
0
 public WebApiClient(
     IProxySettings proxySettings,
     IWgApiConfiguration wgApiConfiguration,
     ILogger <WebApiClient> logger)
 {
     _proxySettings      = proxySettings;
     _wgApiConfiguration = wgApiConfiguration;
     _log = logger;
 }
Exemplo n.º 10
0
        internal async static Task <Newtonsoft.Json.Linq.JToken> GetLatestPreRelease(IProxySettings settings)
        {
            string answer;

            using (var client = GetHttpClient(settings))
            {
                answer = await client.GetStringAsync(GitHubApiLinkPreRelease);
            }

            return(Newtonsoft.Json.Linq.JObject.Parse("{data:" + answer + "}")["data"][0]);
        }
Exemplo n.º 11
0
        internal static IWebProxy GetProxy(IProxySettings settings)
        {
            var Proxy = new WebProxy(settings.ProxyAddress, settings.ProxyPort);

            if (!string.IsNullOrEmpty(settings.ProxyUsername))
            {
                Proxy.Credentials           = new NetworkCredential(settings.ProxyUsername, settings.ProxyPassword);
                Proxy.UseDefaultCredentials = false;
            }
            Proxy.BypassProxyOnLocal = true;
            return(Proxy);
        }
Exemplo n.º 12
0
        private static HttpClient GetHttpClient(IProxySettings settings)
        {
            var client = WebHelper.GetHttpClient(settings);

            if (!client.DefaultRequestHeaders.UserAgent.TryParseAdd(USER_AGENT))
            {
                Logger.Warn($"[Updater] Was not able to add useraget \"{USER_AGENT}\" to the headers, forcing it");
                client.DefaultRequestHeaders.Add("User-Agent", USER_AGENT);
            }
            client.Timeout = Timeout.InfiniteTimeSpan;
            return(client);
        }
Exemplo n.º 13
0
        public WhatsNewUI(IProxySettings settings, string version)
        {
            DialogResult  = DialogResult.None;
            this.settings = settings;
            this.version  = version;

            InitializeComponent();
            ApplyLanguage(Language.Data);
            var html = HTML_LOAD_A + Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + HTML_LOAD_B;

            webBrowser1.DocumentText = html;
        }
Exemplo n.º 14
0
 internal static T ConfigureWebClientProxy <T>(T wc, IProxySettings settings) where T : WebClient
 {
     if (settings.UseProxy)
     {
         wc.Proxy = GetProxy(settings);
         wc.UseDefaultCredentials = false;
     }
     else
     {
         wc.Proxy = null;
     }
     return(wc);
 }
Exemplo n.º 15
0
        private static void SetProxyOfClientHandler(IProxySettings settings, HttpClientHandler httpClientHandler)
        {
            var proxy = new WebProxy
            {
                Address               = new Uri($"http://{settings.ProxyAddress}:{settings.ProxyPort}"),
                BypassProxyOnLocal    = false,
                UseDefaultCredentials = false,

                Credentials = new NetworkCredential(settings.ProxyUsername, settings.ProxyPassword)
            };

            httpClientHandler.Proxy = proxy;
        }
        private static WebProxy ObtainWebProxy(IProxySettings proxySettings)
        {
            var proxy = new WebProxy(proxySettings.Host, proxySettings.Port);

            var credential = proxySettings.Credential;

            if (null != credential)
            {
                proxy.Credentials = new NetworkCredential(credential.Username, credential.Password);
            }

            return(proxy);
        }
Exemplo n.º 17
0
        public static async Task Update(IProxySettings settings, IGeneralSettings generalSettings, IProgress <ProgressMessage> progress = null, CancellationToken ct = default)
        {
            Logger.Message("Start update");
            string installer = await DownloadInstaller(settings, generalSettings, new Progress <double>(p => progress?.Report(new ProgressMessage(p * 0.98, "Downloading Installer"))), ct);

            if (ct.IsCancellationRequested)
            {
                return;
            }
            progress?.Report(new ProgressMessage(0.99, "Starting Installer"));
            Logger.Message("Starting Installer");
            Process.Start(installer);
            Program.Exit(ExitCode.UPDATING);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Downloads the newest installer for github
        /// </summary>
        /// <param name="settings">the proxy settings</param>
        /// <param name="progress">the progress reporting</param>
        /// <returns></returns>
        private static async Task <string> DownloadInstaller(IProxySettings settings, IGeneralSettings generalSettings, IProgress <double> progress = null, CancellationToken cancellationToken = default)
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Temp\\LogUploaderInstaller.exe";

            progress?.Report(0.0);
            using (var client = GetHttpClient(settings))
            {
                string installerUrl;
                double currProgress = 0;
                if (InstallerUrlCache == null)
                {
                    Logger.Message("Start Download of installerUrl");
                    Newtonsoft.Json.Linq.JToken jsonData;
                    if (generalSettings.AllowPrerelases)
                    {
                        jsonData = await GetLatestPreRelease(settings);
                    }
                    else
                    {
                        jsonData = await GetLatestStableRelease(settings);
                    }
                    progress?.Report(0.30);
                    installerUrl = GetInstallerUrl(jsonData);
                    progress?.Report(0.35);
                    currProgress = 0.35;
                }
                else
                {
                    installerUrl = InstallerUrlCache;
                    currProgress = 0.05;
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                currProgress += 0.05;
                progress?.Report(currProgress);
                Logger.Message("Start Download of installer from " + installerUrl);
                using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    await client.DownloadAsync(installerUrl, fs, new Progress <double>(p => progress?.Report((p * (1 - currProgress)) + currProgress)), cancellationToken);
                }
            }
            progress?.Report(1);
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }
            return(path);
        }
Exemplo n.º 19
0
        static void AssertSystemProxySettings(IProxySettings proxySettings, bool hasCredentials)
        {
            var proxy = proxySettings.Should().BeOfType <UseSystemProxySettings>()
                        .Subject;

            if (hasCredentials)
            {
                proxy.Username.Should().Be(ProxyUserName);
                proxy.Password.Should().Be(ProxyPassword);
            }
            else
            {
                proxy.Username.Should().BeNull();
                proxy.Password.Should().BeNull();
            }
        }
Exemplo n.º 20
0
 internal static IEStyleProxySettingsBuilder Parse(IProxySettings settings)
 {
     return(new IEStyleProxySettingsBuilder()
     {
         Type = settings.Type,
         HttpHost = settings.HttpHost,
         HttpPort = settings.HttpPort,
         HttpsHost = settings.HttpsHost,
         HttpsPort = settings.HttpsPort,
         FtpHost = settings.FtpHost,
         FtpPort = settings.FtpPort,
         SocksHost = settings.SocksHost,
         SocksPort = settings.SocksPort,
         IsUseHttpProxyForAllProtocols = settings.IsUseHttpProxyForAllProtocols,
     });
 }
Exemplo n.º 21
0
        internal static HttpClient GetHttpClient(IProxySettings settings)
        {
            var httpClientHandler = new HttpClientHandler();

            if (settings.UseProxy)
            {
                SetProxyOfClientHandler(settings, httpClientHandler);
            }

            var httpClient = new HttpClient(httpClientHandler, true);

            //TODO default timeout??
            httpClient.Timeout = Timeout.InfiniteTimeSpan;

            return(httpClient);
        }
Exemplo n.º 22
0
        private static async Task InitEliteInsights(IEliteInsightsSettings settings, IProxySettings proxySettings, IProgress <ProgressMessage> progress = null, CancellationToken cancellationToken = default)
        {
            progress?.Report(new ProgressMessage(0, "Init"));
            EliteInsights.Init(settings);
            await EliteInsights.UpdateNewestVersion(proxySettings, new Progress <double>(p => progress?.Report(new ProgressMessage((p * 0.2) + 0.05, "Checking for Update"))));

            var newVersion = EliteInsights.UpdateAviable();

            if (EliteInsights.IsInstalled())
            {
                Logger.Message($"Installed EI Version: {EliteInsights.LocalVersion}");
            }
            else
            {
                Logger.Warn("EI not installed");
            }
            if (newVersion)
            {
                Logger.Message("EI update available. New version: " + EliteInsights.NewestVersion);
                Logger.Message("Auto update EI: " + settings.AutoUpdateEI);
                if (settings.AutoUpdateEI || MessageBox.Show("New Version of EliteInsights is aviable\nUpdate now?", "EliteInsights Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    progress?.Report(new ProgressMessage(0.25, "Starting Update"));
                    try
                    {
                        await EliteInsights.Update(proxySettings, new Progress <double>(p => progress?.Report(new ProgressMessage((p * 0.70) + 0.25, $"Updating {p*100:.}%"))), cancellationToken);

                        Logger.Message("Update EI completed");
                    }
                    catch (OperationCanceledException e)
                    {
                        Logger.Warn("EI update failed");
                        Logger.LogException(e);
                        if (!EliteInsights.IsInstalled())
                        {
                            MessageBox.Show("Faild to install EliteInsights", "Missing EliteInsights installation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            //TODO really crash here?
                            Exit(ExitCode.EI_UPDATE_FATAL_ERROR);
                        }
                    }

                    progress?.Report(new ProgressMessage(1, "Update Done"));
                }
            }
        }
Exemplo n.º 23
0
        void AssertCustomProxy(IProxySettings proxySettings, bool hasCredentials)
        {
            var proxy = proxySettings.Should().BeOfType <UseCustomProxySettings>()
                        .Subject;

            proxy.Host.Should().Be(proxyHost);
            proxy.Port.Should().Be(proxyPort);

            if (hasCredentials)
            {
                proxy.Username.Should().Be(ProxyUserName);
                proxy.Password.Should().Be(ProxyPassword);
            }
            else
            {
                proxy.Username.Should().BeNull();
                proxy.Password.Should().BeNull();
            }
        }
Exemplo n.º 24
0
        internal static TProxyInterface Create <TProxyInterface>(
            ITransceiverConnectionSettings connectionSettings,
            ITransceiver client,
            IAsyncCoupler <IMessage> asyncCoupler,
            ILogger logger,
            IProxySettings proxySettings) where TProxyInterface : class
        {
            var result = Create <TProxyInterface, Proxy>();

            var proxy = (result as Proxy);

            proxy._connectionSettings = connectionSettings ?? throw new ArgumentNullException(nameof(connectionSettings));
            proxy._client             = client ?? throw new ArgumentNullException(nameof(client));
            proxy._asyncCoupler       = asyncCoupler ?? throw new ArgumentNullException(nameof(asyncCoupler));
            proxy._logger             = logger ?? throw new ArgumentNullException(nameof(logger));
            proxy._proxySettings      = proxySettings ?? throw new ArgumentNullException(nameof(proxySettings));
            if (string.IsNullOrEmpty(proxySettings.OrganizationId))
            {
                throw new ArgumentNullException(nameof(proxySettings.OrganizationId));
            }

            if (string.IsNullOrEmpty(proxySettings.InstanceId))
            {
                throw new ArgumentNullException(nameof(proxySettings.InstanceId));
            }

            if (string.IsNullOrEmpty(connectionSettings.RpcClientReceiver.ResourceName))
            {
                throw new ArgumentNullException(nameof(connectionSettings.RpcClientReceiver.ResourceName));
            }

            proxy._replyPath = connectionSettings.RpcClientReceiver.ResourceName;
            if (connectionSettings.RpcClientTransmitter.TimeoutInSeconds == 0)
            {
                throw new ArgumentException("timeout must be  greater than zero", nameof(connectionSettings.RpcClientReceiver.TimeoutInSeconds));
            }

            proxy._requestTimeout = TimeSpan.FromSeconds(connectionSettings.RpcClientTransmitter.TimeoutInSeconds);

            return(result);
        }
Exemplo n.º 25
0
        public async Task <string> GetProxyAsync(Func <string, Task <bool> > proxyCheckerAsync)
        {
            var numTries = 0;

            while (numTries++ < _maxRetriesDefault &&
                   (_currentIndex >= _proxies.Count || !await IsProxyValidAsync(_proxies[_currentIndex], proxyCheckerAsync)))
            {
                if (_proxies == null || _proxies.Count == 0)
                {
                    _settings = _settingsProvider.GetSettings().Proxy;
                    _proxyRE  = new Regex(_settings.ProxyRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
                    await LoadProxiesAsync();
                }
                else
                {
                    _currentIndex++;
                }
            }

            return(_proxies.Count == 0 ? null : _proxies[_currentIndex].ToString());
        }
Exemplo n.º 26
0
        public static IWebProxy ToWebProxy(this IProxySettings proxy)
        {
            if (proxy != null)
            {
                if (string.IsNullOrEmpty(proxy.Server))
                {
                    throw new ArgumentOutOfRangeException(nameof(proxy),
                                                          "в параметрах подключения к proxy не указан адрес сервера");
                }

                var webProxy = proxy.Port < 0
                    ? new WebProxy(proxy.Server)
                    : new WebProxy(proxy.Server, proxy.Port);

                if (proxy.User != null)
                {
                    webProxy.Credentials = new NetworkCredential(proxy.User.Login, proxy.User.Password);
                }

                return(webProxy);
            }

            return(null);
        }
Exemplo n.º 27
0
        private static async Task <(Proxy[], int)> GetProxies(IProxySettings settings)
        {
            var client = new HttpClient();
            var req    = new HttpRequestMessage(HttpMethod.Post, settings.SourceUrl)
            {
                Content = new FormUrlEncodedContent(_proxyRequestData)
            };

            var resp = await client.SendAsync(req);

            if (resp.IsSuccessStatusCode)
            {
                var htmlDoc = new HtmlDocument();
                htmlDoc.Load(await resp.Content.ReadAsStreamAsync());

                var scriptNode = htmlDoc.DocumentNode.SelectSingleNode(settings.ScriptPath);
                var unpacked   = ScriptUnpacker.Unpack(scriptNode.InnerText);
                var calc       = new Calculator(unpacked);

                var nodes = htmlDoc.DocumentNode.SelectNodes(settings.ProxyPath);
                return(nodes.Select(n => ParseProxy(n.InnerText, calc, settings)).Take(_maxProxies).ToArray(), 0);
            }

            return(default);
Exemplo n.º 28
0
 public FtpProvider(IFtpServerConnection server, IProxySettings proxy = null)
     : this(server, proxy.ToWebProxy())
 {
 }
Exemplo n.º 29
0
 internal DPSReport(IProxySettings settings, string userToken) : this(settings)
 {
     UserToken = userToken;
 }
Exemplo n.º 30
0
 internal DPSReport(IProxySettings settings)
 {
     Settings = settings;
 }