public async Task ChangeProxySetting() { using (var context = Repository.GetEntityContext()) { var proxySetting = new ProxySetting(ProxySettingType.Manual); await context.Save(proxySetting).ConfigureAwait(false); var pseudoPluginType = typeof(ProxyTests); MangaSettingCache.Set(new MangaSettingCache(pseudoPluginType, proxySetting)); var cache = MangaSettingCache.Get(pseudoPluginType); var proxy = cache.Proxy; void AssertCacheEquals() { Assert.AreEqual(proxySetting.Id, cache.ProxySettingId); Assert.AreEqual(pseudoPluginType, cache.Plugin); Assert.AreEqual(ProxySettingType.Manual, cache.SettingType); } AssertCacheEquals(); Assert.AreEqual(proxy, cache.Proxy); proxySetting.UserName = "******"; await context.Save(proxySetting).ConfigureAwait(false); AssertCacheEquals(); Assert.AreNotEqual(proxy, cache.Proxy); await context.Delete(proxySetting).ConfigureAwait(false); } }
internal static void RevalidateSetting(Type pluginType, ProxySetting setting) { if (caches.Count == 0) { return; } var inCache = pluginType == null? caches.Values.Where(c => c.ProxySettingId == setting.Id).ToList() : caches.Values.Where(c => c.Plugin == pluginType).ToList(); foreach (var cache in inCache.OrderByDescending(c => c.IsParent)) { cache.RefreshProperties(setting); } Log.Add($"Applied {setting.SettingType} proxy to {string.Join(", ", inCache.Select(s => s.Plugin.Name))}"); // If any of setting cache is root - need recreate all 'child' caches. if (inCache.Any(r => r.IsParent)) { var childs = caches.Values.Where(c => c.SettingType == ProxySettingType.Parent).ToList(); foreach (var cache in childs) { cache.Proxy = setting.GetProxy(); } Log.Add($"Applied {setting.SettingType} proxy to childs {string.Join(", ", childs.Select(s => s.Plugin.Name))}"); } }
private static async Task <List <ProxySetting> > CreateDefaultProxySettings(RepositoryContext context) { var names = new[] { "Без прокси", "Cистемные настройки", "Общие настройки" }; var types = new[] { ProxySettingType.NoProxy, ProxySettingType.System, ProxySettingType.Parent }; var created = new List <ProxySetting>(); for (var index = 0; index < types.Length; index++) { var settingType = types[index]; var name = names[index]; var proxy = await context.Get <ProxySetting>().SingleOrDefaultAsync(s => s.SettingType == settingType).ConfigureAwait(false); if (proxy == null) { proxy = new ProxySetting(settingType) { Name = name }; await context.Save(proxy).ConfigureAwait(false); } created.Add(proxy); } return(created); }
public override async Task Execute(object parameter) { try { var selected = model.SelectedProxySettingModel; var address = model.TestAddress; var setting = new ProxySetting(selected.SettingType) { Address = selected.Address, UserName = selected.UserName, Password = selected.Password }; var proxy = setting.GetProxy(); var client = new TestCoockieClient() { Proxy = proxy }; await client.DownloadStringTaskAsync(address).ConfigureAwait(true); Dialogs.ShowInfo("Проверка прокси", "Успешно."); } catch (Exception e) { Dialogs.ShowInfo("Проверка прокси", "Произошла ошибка. \r\n" + e.Message); } }
public override async Task Execute(object parameter) { try { var selected = model.SelectedProxySettingModel; var address = new Uri(model.TestAddress); var setting = new ProxySetting(selected.SettingType) { Address = selected.Address, UserName = selected.UserName, Password = selected.Password }; var proxy = setting.GetProxy(); var client = SiteHttpClientFactory.Get(address, proxy, new CookieContainer()); var page = await client.GetPage(address).ConfigureAwait(true); if (page.HasContent) { Dialogs.ShowInfo("Проверка прокси", "Успешно."); } else { Dialogs.ShowInfo("Проверка прокси", "Не удалось получить страницу, проверьте настройки.\r\n" + page.Error); } } catch (Exception e) { Dialogs.ShowInfo("Проверка прокси", "Произошла ошибка. \r\n" + e.Message); } }
public string DownloadHtmlWithProxySettings(string url, ProxySetting proxySetting) { WebProxy proxy = new WebProxy($"{proxySetting.Host}:{proxySetting.Port}"); if (!string.IsNullOrWhiteSpace(proxySetting.UserName)) { proxy.Credentials = new NetworkCredential(proxySetting.UserName, proxySetting.Password); } HttpClientHandler httpClientHandler = new HttpClientHandler() { Proxy = proxy, UseDefaultCredentials = false, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, UseCookies = true, //CookieContainer = new CookieContainer(), UseProxy = true }; HttpClient wc = new HttpClient(httpClientHandler); //User-Agent: //https://techblog.willshouse.com/2012/01/03/most-common-user-agents/ wc.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml"); //wc.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate"); //This gets added above in the HttpClientHandler constructor wc.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", _userAgentString); wc.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1"); int tryCount = 0; string data = null; while (tryCount < proxySetting.FailureRetryCount) { try { HttpResponseMessage response = wc.GetAsync(new Uri(url)).Result; response.EnsureSuccessStatusCode(); using (Stream responseStream = response.Content.ReadAsStreamAsync().Result) using (StreamReader streamReader = new StreamReader(responseStream)) { data = streamReader.ReadToEnd(); } break; } catch (Exception ex) { Log.Warning(ex, "Proxy error encountered. try count = {tryCount} of {retryCount}", tryCount, proxySetting.FailureRetryCount); Extensions.SleepForRandomTime(true, 250, 1500); } tryCount++; } if (tryCount >= proxySetting.FailureRetryCount) { Log.Error("Proxy error encountered. Max tries exceeded.", tryCount, proxySetting.FailureRetryCount); } return(data); }
private void ResetAll() { settingsContainer = new Settings(EnvironmentManager.Settings); proxySettings = new ProxySetting(App.Kernel.Get <ProxyManager>().Settings); ProxySettings.DataContext = proxySettings; ComboBoxLanguage.SelectedIndex = CurrentLangIndex; BaseColorsList.SelectedItem = CurrentAppTheme; AccentColorsList.SelectedItem = CurrentAccent; UpdateCheck.DataContext = settingsContainer; }
public EdgeHttpProvider(ProxySetting proxy) { this.proxy = proxy; proxy.UseUpstream.ValueChanged += _ => UpdateProxy(); proxy.Upstream.ValueChanged += _ => UpdateProxy(); proxy.UpstreamPort.ValueChanged += _ => UpdateProxy(); UpdateProxy(); filter = new HttpBaseProtocolFilter(); client = new HttpClient(filter); }
public bool IsProxyWorking(ProxySetting proxySetting) { string nonProxyIp = GetIPAddress(IpCheckService.DynDns); string proxyIp = GetIPAddress(IpCheckService.DynDns, proxySetting); Log.Information("Non proxy IP {nonProxyIp}, proxy ip {proxyIp}", nonProxyIp, proxyIp); if (proxyIp == nonProxyIp) { return(false); } return(true); }
private void ValidateSettings(ProtectedSettings settings) { if (settings.Proxy == null) { settings.Proxy = new ProxySetting(); } ProxySetting proxy = settings.Proxy; if (Uri.CheckHostName(proxy.Host) == UriHostNameType.Unknown) { proxy.Host = string.Empty; } if (proxy.Port < 0 || proxy.Port > 65535) { proxy.Port = 8080; } if (settings.Profiles != null) { TwitterNameValidation twitterValidator = new TwitterNameValidation(); GuildNameValidationRule guildNameValidator = new GuildNameValidationRule(); foreach (var profile in settings.Profiles) { if (profile.News == null) { profile.News = new NewsData(); } if (profile.Login == null) { profile.Login = new LoginData(); } if (profile.Rotation == null) { profile.Rotation = new RotationData(); } if (profile.GameModel == null) { profile.GameModel = new GameModel(); } if (!twitterValidator.Validate(profile.News.TwitterUser, null).IsValid) { profile.News.TwitterUser = Utils.GetDefaultTwitter(); } if (profile.Rotation.Guild != null) { if (!guildNameValidator.Validate(profile.Rotation.Guild, null).IsValid) { profile.Rotation.Guild = string.Empty; } } } } }
public NekomimiProvider(ITimingService dateTime, ProxySetting setting) { this.dateTime = dateTime; this.setting = setting; server.AfterResponse += Server_AfterResponse; ListeningPort = setting.ListeningPort.InitialValue; setting.UseUpstream.ValueChanged += _ => UpdateUpstream(); setting.Upstream.ValueChanged += _ => UpdateUpstream(); setting.UpstreamPort.ValueChanged += _ => UpdateUpstream(); UpdateUpstream(); }
private Stream FetchData(string request, ProxySetting proxy) { this.Context.LogInform(this.Context.Localizer[$"Request execution '{request}'"]); HttpProviderModule httpProvider = new HttpProviderModule(); httpProvider.Context = this.Context; var config = new HttpProviderConfig(); return(httpProvider.Run(new HttpProviderRuntimeConfig() { Query = request }).GetContent()); }
protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_QUERYENDSESSION: Utils.SaveLog("Windows shutdown UnsetProxy"); CloseV2ray(); ProxySetting.UnsetProxy(); m.Result = (IntPtr)1; break; default: base.WndProc(ref m); break; } }
static void Main(string[] args) { ProxySetting setting = new ProxySetting(); setting.TransferSetting = TransferSettingGetter.Get; ProxyFactory factory = new ProxyFactory(setting, typeof(JsonTransferSerializer), typeof(HttpTransmitter)); var proxy = factory.CreateProxy <IExampleService>(); ConsoleHelper.ShowTextInfo("Any key to continue:"); Console.ReadLine(); var info = proxy.GetPlayerInfo("John Wang"); ConsoleHelper.ShowPlayerInfo(info); }
public static void UseProxy(this IApplicationBuilder app, ProxySetting setting) { var uri = new Uri(setting.Url); app.RunProxy(uri); // app.RunProxy(new ProxyOptions // { // Scheme = uri.Scheme, // Host = uri.Host, // // Port = uri.Port.ToString(), // BackChannelMessageHandler = new HttpClientHandler { // AllowAutoRedirect = false, // UseCookies = false, // ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator //} // }); }
protected override void WndProc(ref Message m) { switch (m.Msg) { case WM_QUERYENDSESSION: Utils.SaveLog("Windows shutdown UnsetProxy"); //CloseV2ray(); ConfigHandler.ToJsonFile(config); statistics?.SaveToFile(); ProxySetting.UnsetProxy(); m.Result = (IntPtr)1; break; default: base.WndProc(ref m); break; } }
public async Task CreateDelete() { using (var context = Repository.GetEntityContext()) { var proxy = new ProxySetting(ProxySettingType.Manual); await context.Save(proxy).ConfigureAwait(false); var proxyId = proxy.Id; proxy = await context.Get <ProxySetting>().SingleAsync(s => s.Id == proxyId).ConfigureAwait(false); Assert.NotNull(proxy); await context.Delete(proxy).ConfigureAwait(false); proxy = await context.Get <ProxySetting>().SingleOrDefaultAsync(s => s.Id == proxyId).ConfigureAwait(false); Assert.Null(proxy); } }
public async Task CreateUseAndBlockDelete() { var settingsId = 0; var proxyId = 0; using (var context = Repository.GetEntityContext()) { var proxy = new ProxySetting(ProxySettingType.Manual); await context.Save(proxy).ConfigureAwait(false); var setting = new MangaReader.Core.Services.MangaSetting() { Folder = AppConfig.DownloadFolder }; setting.ProxySetting = proxy; await context.Save(setting).ConfigureAwait(false); async Task DeleteProxy() { await context.Delete(proxy).ConfigureAwait(false); } settingsId = setting.Id; proxyId = proxy.Id; Assert.ThrowsAsync <EntityException <ProxySetting> >(DeleteProxy); } using (var context = Repository.GetEntityContext()) { var setting = await context.Get <MangaReader.Core.Services.MangaSetting>().SingleAsync(s => s.Id == settingsId).ConfigureAwait(false); var proxy = await context.Get <ProxySetting>().SingleAsync(s => s.Id == proxyId).ConfigureAwait(false); await context.Delete(setting).ConfigureAwait(false); await context.Delete(proxy).ConfigureAwait(false); } }
public async Task ChangeMangaSetting() { using (var context = Repository.GetEntityContext()) { var proxySetting = new ProxySetting(ProxySettingType.Manual); await context.Save(proxySetting).ConfigureAwait(false); var mangaSetting = await context.Get <MangaReader.Core.Services.MangaSetting>() .FirstOrDefaultAsync(s => s.ProxySetting.SettingType == ProxySettingType.Parent) .ConfigureAwait(false); var pluginType = MangaSettingCache.GetPluginType(mangaSetting); var cache = MangaSettingCache.Get(pluginType); var proxy = cache.Proxy; Assert.AreEqual(pluginType, cache.Plugin); Assert.AreNotEqual(proxySetting.Id, cache.ProxySettingId); Assert.AreNotEqual(ProxySettingType.Manual, cache.SettingType); Assert.AreEqual(proxy, cache.Proxy); var originalProxy = mangaSetting.ProxySetting; mangaSetting.ProxySetting = proxySetting; await context.Save(mangaSetting).ConfigureAwait(false); Assert.AreEqual(pluginType, cache.Plugin); Assert.AreEqual(proxySetting.Id, cache.ProxySettingId); Assert.AreEqual(ProxySettingType.Manual, cache.SettingType); Assert.AreNotEqual(proxy, cache.Proxy); mangaSetting.ProxySetting = originalProxy; await context.Save(mangaSetting).ConfigureAwait(false); Assert.AreEqual(pluginType, cache.Plugin); await context.Delete(proxySetting).ConfigureAwait(false); } }
public string GetIPAddress(IpCheckService ipService, ProxySetting proxySetting = null) { HtmlDocument doc = new HtmlDocument(); HtmlWeb web = new HtmlWeb(); if (ipService == IpCheckService.DynDns) { string checkUrl = "http://checkip.dyndns.com/"; if (proxySetting == null) { doc = web.Load(checkUrl); } else { string page = DownloadHtmlWithProxySettings(checkUrl, proxySetting); if (!string.IsNullOrWhiteSpace(page)) { doc.LoadHtml(page); } else { return(null); } } string searchString = "Current IP Address: "; int startIndexOfIp = doc.DocumentNode.InnerHtml.IndexOf(searchString); if (startIndexOfIp >= 0 && (startIndexOfIp - searchString.Length) >= 0) { int endOfIpAddress = doc.DocumentNode.InnerHtml.IndexOf("</body>"); int startIndex = startIndexOfIp + searchString.Length; string ipTemp = doc.DocumentNode.InnerHtml.Substring(startIndex, endOfIpAddress - startIndex); return(ipTemp); } } return(null); }
public async Task ChangeDatabaseConfig([Values] bool withParentSettingChange) { using (var context = Repository.GetEntityContext()) { var proxySetting = new ProxySetting(ProxySettingType.Parent); await context.Save(proxySetting).ConfigureAwait(false); var pseudoPluginType = typeof(Repository); MangaSettingCache.Set(new MangaSettingCache(pseudoPluginType, proxySetting)); var settingCache = MangaSettingCache.Get(pseudoPluginType); var settingCacheProxy = settingCache.Proxy; void AssertCacheEquals() { Assert.AreEqual(proxySetting.Id, settingCache.ProxySettingId); Assert.AreEqual(pseudoPluginType, settingCache.Plugin); Assert.AreEqual(ProxySettingType.Parent, settingCache.SettingType); } AssertCacheEquals(); Assert.AreEqual(settingCacheProxy, settingCache.Proxy); ProxySetting setting = null; if (withParentSettingChange) { var databaseConfig = await context.Get <DatabaseConfig>().SingleAsync().ConfigureAwait(false); setting = databaseConfig.ProxySetting; databaseConfig.ProxySetting = await context.Get <ProxySetting>().SingleAsync(p => p.SettingType == ProxySettingType.NoProxy).ConfigureAwait(false); await context.Save(databaseConfig).ConfigureAwait(false); } var parentCache = MangaSettingCache.Get(MangaSettingCache.RootPluginType); Assert.AreNotEqual(settingCache, parentCache); if (withParentSettingChange) { Assert.AreNotEqual(settingCacheProxy, parentCache.Proxy); Assert.AreEqual(settingCache.Proxy, parentCache.Proxy); Assert.AreNotEqual(settingCacheProxy, settingCache.Proxy); AssertCacheEquals(); } else { Assert.AreEqual(settingCacheProxy, parentCache.Proxy); Assert.AreEqual(settingCache.Proxy, parentCache.Proxy); } if (withParentSettingChange) { var databaseConfig = await context.Get <DatabaseConfig>().SingleAsync().ConfigureAwait(false); databaseConfig.ProxySetting = setting; await context.Save(databaseConfig).ConfigureAwait(false); AssertCacheEquals(); Assert.AreEqual(settingCache.Proxy, parentCache.Proxy); } await context.Delete(proxySetting).ConfigureAwait(false); } }
static void writeSampleSetting() { ProxySetting setting = new ProxySetting(); setting.logDirectory = "C:\\home\\develop\\tanuki-"; setting.engines = new EngineOption[] { new EngineOption( "doutanuki", "C:\\home\\develop\\tanuki-\\tanuki-\\x64\\Release\\tanuki-.exe", "", "C:\\home\\develop\\tanuki-\\bin", new[] { new Option("USI_Hash", "1024"), new Option("Book_File", "../bin/book-2016-02-01.bin"), new Option("Best_Book_Move", "true"), new Option("Max_Random_Score_Diff", "0"), new Option("Max_Random_Score_Diff_Ply", "0"), new Option("Threads", "1"), }), new EngineOption( "nighthawk", "ssh", "-vvv nighthawk tanuki-.bat", "C:\\home\\develop\\tanuki-\\bin", new[] { new Option("USI_Hash", "1024"), new Option("Book_File", "../bin/book-2016-02-01.bin"), new Option("Best_Book_Move", "true"), new Option("Max_Random_Score_Diff", "0"), new Option("Max_Random_Score_Diff_Ply", "0"), new Option("Threads", "4"), }), new EngineOption( "doutanuki", "C:\\home\\develop\\tanuki-\\tanuki-\\x64\\Release\\tanuki-.exe", "", "C:\\home\\develop\\tanuki-\\bin", new[] { new Option("USI_Hash", "1024"), new Option("Book_File", "../bin/book-2016-02-01.bin"), new Option("Best_Book_Move", "true"), new Option("Max_Random_Score_Diff", "0"), new Option("Max_Random_Score_Diff_Ply", "0"), new Option("Threads", "1"), }) }; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ProxySetting)); using (FileStream f = new FileStream("proxy-setting.sample.json", FileMode.Create)) { serializer.WriteObject(f, setting); } }
/// <summary> /// Sets the proxy setting. /// </summary> /// <param name="proxySetting">The proxy setting.</param> public void SetProxySetting([In, MarshalAs(UnmanagedType.Struct)] ProxySetting proxySetting) { m_managementObject.SetProxySetting(proxySetting); }
public static async Task Main(string[] args) { bool debugMode = false; #if DEBUG debugMode = true; #endif // proxy setting example ProxySetting proxy = new ProxySetting() { ip = "127.0.0.1", port = 7890, type = TDLibCore.Enum.ProxyType.HTTP }; // initializing api setting [without proxy] ApiSetting apiSetting = new ApiSetting(api_id, api_hash); // initializing api setting [with proxy] // ApiSetting apiSetting = new ApiSetting(api_id, api_hash, proxy); // initializing new instance Core core = new Core(debugMode, LoggerFunction, apiSetting); // task to show current authorization state and connection state in title every 1s _ = Task.Factory.StartNew(async() => { while (true) { Console.Title = "authorization state = " + core.api.authorizationState.ToString() + " | connection state = " + core.api.connectionState.ToString(); await Task.Delay(1000); } }); // function to call when phone number been asked core.api.onPhoneNumberRequired = () => { Logger.Info("write phone number : "); return(Console.ReadLine()); }; // function to call when verification code been asked core.api.onVerificationCodeRequired = () => { Logger.Info("write code sent to your number: "); return(Console.ReadLine()); }; // function to call when password been asked core.api.onPasswordRequired = () => { Logger.Info("write account password: "******"Authentication success"); // gathering mainchat chatslist var chats = await apiHandler.functions.getMainChatList(true); Logger.Info("loaded {0:n0} chats from main chatlist", chats.Count); // finding group with `APSoft Group` on it's title var chat = await apiHandler.functions.searchChat("APSoft Group", true); if (chat is null) { Logger.Error("process terminated because group not found"); return; } // gathering target group memebrs var users = await apiHandler.functions.getSuperGroupUsers(chat.Id); Logger.Info("gathered {0:n0} users", users.Count); // writing users to file System.IO.File.WriteAllText("users.json", users.JSONSerialize()); Logger.Success("all process finished successfully"); }; // running application core.Run(); await Task.Delay(-1); }
internal static void RevalidateSetting(ProxySetting setting) { RevalidateSetting(null, setting); }
private void RefreshProperties(ProxySetting setting) { this.ProxySettingId = setting.Id; this.Proxy = setting.GetProxy(); this.SettingType = setting.SettingType; }
/// <summary> /// Sets the proxy setting. /// </summary> /// <param name="proxySetting">The proxy setting.</param> public void SetProxySetting([In, MarshalAs(UnmanagedType.Struct)] ProxySetting proxySetting) { }
public UWPHttpProviderSelector(IShellContextService shell, BrowserSetting settings, ProxySetting proxy) { if (settings.Debug.InitialValue) { Current = new DebugHttpProvider(shell); } else { Current = new EdgeHttpProvider(proxy); } Settings = settings; }
/// <summary> /// generates a setting with proxy enabled /// </summary> /// <param name="api_id">application api_id</param> /// <param name="api_hash">application api_hash</param> /// <param name="proxy">proxy information to use</param> public ApiSetting(int api_id, string api_hash, ProxySetting proxy) : this(api_id, api_hash) { this.proxy = proxy; }
public ProxySettingView(ProxySetting instance) { Instance = instance; this.InitializeComponent(); }
public MangaSettingCache(Type pluginType, ProxySetting setting) { this.Plugin = pluginType; this.RefreshProperties(setting); this.IsParent = false; }