Пример #1
0
 public TeamsController(
     ITeamUseCase useCase,
     IOptions <UrlSettings> optionsAccessor)
 {
     this.useCase = useCase;
     this.Options = optionsAccessor.Value;
 }
        public void GivenInternalLink_WhenGetValueWithUseAbsoluteUrlsSetToFalse_ThenReturnsCorrectRelativeLink()
        {
            var value = "random-internallink";
            var linkItemCollection = new LinkItemCollection();
            var expected           = "/my-pretty-url/?anyQuery=hej";
            var settings           = new UrlSettings {
                UseAbsoluteUrls = false
            };

            this._urlHelper.ContentUrl(Arg.Any <Url>(), settings)
            .Returns(expected);
            var linkItem = Substitute.For <EPiServer.SpecializedProperties.LinkItem>();

            linkItem.Href.Returns(value);
            linkItem.Text.Returns("any text");
            linkItem.Title.Returns("any title");
            linkItem.Target.Returns("_blank");
            linkItem.ReferencedPermanentLinkIds.Returns(new List <Guid>
            {
                Guid.NewGuid()
            });
            linkItemCollection.Add(linkItem);

            var result = ((IEnumerable <LinkItem>) this._sut.GetValue(linkItemCollection, settings)).ToList();

            result.Count.ShouldBe(1);
            result.ShouldContain(x => x.Href == expected);
            result.ShouldContain(x => x.Text == "any text");
            result.ShouldContain(x => x.Title == "any title");
            result.ShouldContain(x => x.Target == "_blank");
        }
Пример #3
0
 public AuthController(IAuthService authService, IMapper mapper, IConfiguration configuration)
 {
     _authService   = authService;
     _mapper        = mapper;
     _configuration = configuration;
     _urlSettings   = configuration.GetSection("UrlSettings").Get <UrlSettings>();
 }
Пример #4
0
 public PlayersController(
     IPlayerUseCase playerUseCase,
     IOptions <UrlSettings> optionsAccessor)
 {
     this.playerUseCase = playerUseCase;
     this.Options       = optionsAccessor.Value;
 }
Пример #5
0
        internal static string GetNewsUrl()
        {
            var JSON           = "";
            var sFile          = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var configFile     = @"Configuration\websettings.json";
            var configLocation = Path.Combine(sFile, configFile);

            if (!File.Exists(configLocation))
            {
                Log.Error($"{configLocation} does not exist");
            }
            try
            {
                using (var stream = new FileStream(configLocation, FileMode.Open, FileAccess.Read))
                    using (var readSettings = new StreamReader(stream))
                    {
                        JSON = readSettings.ReadToEnd();
                    }
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.Logger.Error(ex, $"Error reading websettings.json ({configLocation}");
                throw;
            }

            UrlSettings settings = JsonConvert.DeserializeObject <UrlSettings>(JSON);
            var         url      = "";

            WebSettings.NewsUrl = settings.newsUrl;
            url = WebSettings.NewsUrl;
            return(url);
        }
Пример #6
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            string setupBasePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            if (e.Args.Length == 0)
            {
                return;
            }
            if (e.Args[0].Split(':')[0] == "doh" || e.Args[0].Split(':')[0] == "dns-over-https")
            {
                MessageBoxResult msgResult =
                    MessageBox.Show(
                        $"您确定要将主 DNS over HTTPS 服务器设为 https:{e.Args[0].Split(':')[1]} 吗?" +
                        $"{Environment.NewLine}请确认这是可信的服务器,来源不明的服务器可能将会窃取您的个人隐私,或篡改网页植入恶意软件。请谨慎操作!",
                        "设置 DNS over HTTPS 服务器", MessageBoxButton.OKCancel);
                if (msgResult != MessageBoxResult.OK)
                {
                    return;
                }

                if (File.Exists($"{setupBasePath}config.json"))
                {
                    DnsSettings.ReadConfig($"{setupBasePath}config.json");
                }
                DnsSettings.HttpsDnsUrl = e.Args[0].Replace("dns-over-https:", "https:").Replace("doh:", "https:");
                new SettingsWindow().ButtonSave_OnClick(sender, null);
            }
            else if (e.Args[0].Split(':')[0] == "aurora-doh-list")
            {
                MessageBoxResult msgResult =
                    MessageBox.Show(
                        $"您确定要将 DNS over HTTPS 服务器列表设为 https:{e.Args[0].Split(':')[1]} 吗?" +
                        $"{Environment.NewLine}请确认这是可信的服务器列表,来源不明的服务器可能将会窃取您的个人隐私,或篡改网页植入恶意软件。请谨慎操作!",
                        "设置 DNS over HTTPS 服务器列表", MessageBoxButton.OKCancel);
                if (msgResult != MessageBoxResult.OK)
                {
                    return;
                }

                if (File.Exists($"{setupBasePath}url.json"))
                {
                    UrlSettings.ReadConfig($"{setupBasePath}url.json");
                }
                UrlSettings.MDohList = e.Args[0].Replace("aurora-doh-list:", "https:");
                new ListL10NWindow().ButtonSave_OnClick(sender, null);
            }

            foreach (var item in Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName))
            {
                if (item.Id != Process.GetCurrentProcess().Id)
                {
                    item.Kill();
                }
            }
            Process.Start(new ProcessStartInfo {
                FileName = GetType().Assembly.Location
            });
            Shutdown();
        }
Пример #7
0
        //switch (System)
        //{
        //    case "xbox":
        //        switch (Trigger)
        //        {
        //            case "playerstats":
        //            case "goaliestats":
        //                WebSettings.XboxPlayerStatsURL = settings.xboxPlayerStatsURL;
        //                WebSettings.PSNPlayerStatsURL = settings.psnPlayerStatsURL;
        //                xboxURL = WebSettings.XboxPlayerStatsURL + WebSettings.XboxSeasonId;
        //                psnURL = WebSettings.PSNPlayerStatsURL + WebSettings.PSNSeasonID;
        //                break;
        //            case "draftlist":
        //                WebSettings.XboxDraftListURL = settings.xboxDraftListURL;
        //                WebSettings.PSNDraftListURL = settings.psnDraftListURL;
        //                xboxURL = WebSettings.XboxDraftListURL + WebSettings.XboxSeasonId;
        //                psnURL = WebSettings.PSNDraftListURL + WebSettings.PSNSeasonID;
        //                break;
        //            case "teamstats":
        //                WebSettings.XboxTeamStandingsURL = settings.xboxStandingsURL;
        //                WebSettings.PSNTeamStandingsURL = settings.psnStandingsURL;
        //                xboxURL = WebSettings.XboxTeamStandingsURL + WebSettings.XboxSeasonId;
        //                psnURL = WebSettings.PSNTeamStandingsURL + WebSettings.PSNSeasonID;
        //                break;
        //        }
        //        return xboxURL;
        //}
        #endregion

        public static string GetNumberOfPlayersUrl(string system)
        {
            string JSON = "";

            var sFile          = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var configFile     = @"Configuration\websettings.json";
            var configLocation = Path.Combine(sFile, configFile);

            if (!File.Exists(configLocation))
            {
                Log.Error($"GetNumberOfPlayersURL Method: {configLocation} does not exist");
            }
            try
            {
                using (var stream = new FileStream(configLocation, FileMode.Open, FileAccess.Read))
                    using (var readSettings = new StreamReader(stream))
                    {
                        JSON = readSettings.ReadToEnd();
                    }
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.Error(ex, $"Error reading websettings.json ({configLocation}");
                throw;
            }

            UrlSettings settings = JsonConvert.DeserializeObject <UrlSettings>(JSON);

            var url = "";

            if (system == "xbox")
            {
                WebSettings.XboxSeasonId     = settings.xboxSeasonId;
                WebSettings.XboxDraftListURL = settings.xboxDraftListURL;
                url = WebSettings.XboxDraftListURL + WebSettings.XboxSeasonId;
            }
            else if (system == "psn")
            {
                WebSettings.PSNSeasonID     = settings.psnSeasonId;
                WebSettings.PSNDraftListURL = settings.psnDraftListURL;
                url = WebSettings.PSNDraftListURL + WebSettings.PSNSeasonID;
            }
            #region Switch2
            //switch (system)
            //{
            //    case "xbox":
            //        WebSettings.XboxSeasonId = settings.xboxSeasonId;
            //        WebSettings.XboxDraftListURL = settings.xboxDraftListURL;
            //        var xboxURL = WebSettings.XboxDraftListURL + WebSettings.XboxSeasonId;
            //        return xboxURL;
            //    case "psn":
            //        WebSettings.XboxSeasonId = settings.xboxSeasonId;
            //        WebSettings.XboxDraftListURL = settings.xboxDraftListURL;
            //        var psnURL = WebSettings.XboxDraftListURL + WebSettings.XboxSeasonId;
            //        return psnURL;
            //}
            #endregion
            return(url);
        }
Пример #8
0
        internal HttpWebRequest Build(UrlSettings urlSettings, HttpWebRequestHeadersSettings headersSettings)
        {
            var url = UrlBuilder.BuildUri(urlSettings);

            return(((HttpWebRequest)WebRequest.Create(url))
                   .BuildGeneralValues()
                   .BuildHeaders(headersSettings));
            //.BuildBody();
        }
        public static UrlSettingsModel ToModel(this UrlSettings urlSettings)
        {
            var model = new UrlSettingsModel()
            {
                ActivationPageUrl = urlSettings.ActivationPageUrl
            };

            return(model);
        }
Пример #10
0
        private string Execute(Url url, UrlSettings urlSettings)
        {
            var prettyUrl = this._urlHelper.ContentUrl(url);

            if (urlSettings.UseAbsoluteUrls)
            {
                return(CreateAbsoluteUrl(prettyUrl, urlSettings.FallbackToWildcard));
            }

            return(prettyUrl);
        }
Пример #11
0
        public IHttpActionResult Post(UrlSettingsModel entityModel)
        {
            var thirdPartySettings = new UrlSettings()
            {
                ActivationPageUrl = entityModel.ActivationPageUrl
            };

            _settingService.Save(thirdPartySettings);
            VerboseReporter.ReportSuccess("Settings saved successfully", "post_setting");
            return(RespondSuccess(new { ThirdPartySettings = thirdPartySettings.ToModel() }));
        }
Пример #12
0
 public AccountController(CustomUserManager userManager, IProfileRepository profileRepository, UrlSettings urlSettings, IFileService fileService, IUserOnlineSignalService userOnlineSignalService, INotificationService notificationService, IUserMailer mailer, IOAuthClientsRepository oAuthClientsRepository)
 {
     _userManager             = userManager;
     _profileRepository       = profileRepository;
     _urlSettings             = urlSettings;
     _fileService             = fileService;
     _userOnlineSignalService = userOnlineSignalService;
     _notificationService     = notificationService;
     _mailer = mailer;
     _oAuthClientsRepository = oAuthClientsRepository;
 }
        public void GivenEpiserverPage_WhenGetValue_ThenReturnsRewrittenPrettyAbsoluteUrl()
        {
            var siteUrl    = "https://example.com";
            var prettyPath = "/rewritten/pretty-url/";
            var value      = "/link/d40d0056ede847d5a2f3b4a02778d15b.aspx";
            var url        = new Url(value);
            var settings   = new UrlSettings();

            this._urlHelper.ContentUrl(Arg.Any <Url>(), settings).Returns($"{siteUrl}{prettyPath}");

            var result = this._sut.GetValue(url, settings);

            result.ShouldBe($"{siteUrl}{prettyPath}");
        }
        public void GivenEpiserverPage_WhenGetValueWithAbsoluteUrlSetToFalse_ThenReturnsRewrittenPrettyRelativeUrl()
        {
            var prettyPath = "/rewritten/pretty-url/";
            var value      = "/link/d40d0056ede847d5a2f3b4a02778d15b.aspx";
            var url        = new Url(value);
            var settings   = new UrlSettings {
                UseAbsoluteUrls = false
            };

            this._urlHelper.ContentUrl(Arg.Any <Url>(), settings).Returns(prettyPath);

            var result = this._sut.GetValue(url, settings);

            result.ShouldBe(prettyPath);
        }
Пример #15
0
        public void BuildRequest()
        {
            var urlSettings = new UrlSettings
            {
                Scheme = Uri.UriSchemeHttps,
                Host   = "dictation.nuancemobility.net",
                Path   = "/NMDPAsrCmdServlet/dictation",
                AppId  = "MY_APP",
                AppKey = "777",
                Id     = "111"
            };
            var requestSettingsProvider = new ChunkedRequestSettingsProvider();
            var headersSettings         = requestSettingsProvider.Provide();

            request = new HttpWebRequestBuilder().Build(urlSettings, headersSettings);
        }
Пример #16
0
        internal static Uri BuildUri(UrlSettings urlSettings)
        {
            var uriBuilder = new UriBuilder
            {
                Scheme = urlSettings.Scheme,
                Host   = urlSettings.Host,
                Path   = urlSettings.Path,
                Query  = BuildUrlQuery(new
                {
                    appId  = urlSettings.AppId,
                    appKey = urlSettings.AppKey,
                    id     = urlSettings.Id
                })
            };

            return(uriBuilder.Uri);
        }
Пример #17
0
        public static string GetSeasonID(string System)
        {
            string JSON           = "";
            var    sFile          = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var    configFile     = @"Configuration\websettings.json";
            var    configLocation = Path.Combine(sFile, configFile);

            if (!File.Exists(configLocation))
            {
                Log.Error($"GetSeasonID Method: {configLocation} does not exist");
            }
            try
            {
                using (var stream = new FileStream(configLocation, FileMode.Open, FileAccess.Read))
                    using (var readSettings = new StreamReader(stream))
                    {
                        JSON = readSettings.ReadToEnd();
                    }
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.Error(ex, $"Error reading websettings.json ({configLocation}");
                throw;
            }

            UrlSettings seasonID      = JsonConvert.DeserializeObject <UrlSettings>(JSON);
            var         CurrentSeason = WebSettings.XboxSeasonId;

            if (System == "xbox")
            {
                WebSettings.XboxSeasonId = seasonID.xboxSeasonId;
                CurrentSeason            = WebSettings.XboxSeasonId;
            }
            else if (System == "psn")
            {
                WebSettings.PSNSeasonID = seasonID.psnSeasonId;
                CurrentSeason           = WebSettings.PSNSeasonID;
            }
            else
            {
                Log.Warning("Unable to fetch current season from websettings.json.  Please check that the file exists or has a seasonid entry");
                CurrentSeason = "Error";
            }
            return(CurrentSeason);
        }
Пример #18
0
 public AuthenticationController(IUserService userService,
                                 ICryptographyService cryptographyService, IMediaService mediaService, MediaSettings mediaSettings, IFollowService followService, IFriendService friendService, IUserRegistrationService userRegistrationService, SecuritySettings securitySettings, UserSettings userSettings, IRoleService roleService, IEmailSender emailSender, UrlSettings urlSettings, IEntityPropertyService entityPropertyService, INotificationService notificationService)
 {
     _userService             = userService;
     _cryptographyService     = cryptographyService;
     _mediaService            = mediaService;
     _mediaSettings           = mediaSettings;
     _followService           = followService;
     _friendService           = friendService;
     _userRegistrationService = userRegistrationService;
     _securitySettings        = securitySettings;
     _userSettings            = userSettings;
     _roleService             = roleService;
     _emailSender             = emailSender;
     _urlSettings             = urlSettings;
     _entityPropertyService   = entityPropertyService;
     _notificationService     = notificationService;
 }
Пример #19
0
 public AccountsController(
     IAccountsUseCase accountsUseCase,
     IAuthorizationUseCase authorizationUseCase,
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     ILoggerFactory loggerFactory,
     IOptions <UrlSettings> optionsAccessor)
 {
     this.accountsUseCase      = accountsUseCase;
     this.authorizationUseCase = authorizationUseCase;
     this.userManager          = userManager;
     this.logger         = loggerFactory.CreateLogger <AccountsController>();
     this.signInManager  = signInManager;
     this.Options        = optionsAccessor.Value;
     this.accountService = new AccountService(
         this.signInManager,
         accountsUseCase,
         authorizationUseCase);
 }
        private string Execute(Url url, UrlSettings urlSettings)
        {
            if (url.Scheme == "mailto")
            {
                return(url.OriginalString);
            }

            if (url.IsAbsoluteUri)
            {
                if (urlSettings.UseAbsoluteUrls)
                {
                    return(url.OriginalString);
                }

                return(url.PathAndQuery);
            }

            return(this._urlHelper.ContentUrl(url, urlSettings));
        }
Пример #21
0
        private static void ConfigureServiceSettings(IServiceCollection services, AppSettings appSettings)
        {
            AuthSettings    auth    = appSettings.Auth;
            MembersSettings members = appSettings.Members;
            PathSettings    paths   = appSettings.Paths;
            UrlSettings     urls    = appSettings.Urls;

            services.AddSingleton(new AuthenticationServiceSettings
            {
                AccessTokenLifetimeMinutes = auth.AccessTokenLifetimeMinutes,
                EventsUrl = $"{urls.AppBase}{urls.Events}",
                PasswordResetTokenLifetimeMinutes = auth.PasswordResetTokenLifetimeMinutes,
                PasswordResetUrl         = $"{urls.AppBase}{urls.PasswordReset}",
                RefreshTokenLifetimeDays = auth.RefreshTokenLifetimeDays
            });

            services.AddSingleton(new AuthenticationTokenFactorySettings
            {
                Key = auth.Key
            });

            services.AddSingleton(new EventAdminServiceSettings
            {
                BaseUrl              = urls.AppBase,
                EventRsvpUrlFormat   = urls.EventRsvp,
                EventUrlFormat       = urls.Event,
                UnsubscribeUrlFormat = urls.Unsubscribe
            });

            services.AddSingleton(new MemberServiceSettings
            {
                ActivateAccountUrl           = $"{urls.AppBase}{urls.ActivateAccount}",
                ConfirmEmailAddressUpdateUrl = $"{urls.AppBase}{urls.ConfirmEmailAddressUpdate}",
                MaxImageSize = members.MaxImageSize
            });

            services.AddSingleton(new MediaFileProviderSettings
            {
                RootMediaPath = paths.MediaRoot,
                RootMediaUrl  = $"{urls.ApiBase}{urls.Media}"
            });
        }
Пример #22
0
        internal void CreateTab(UrlSettings urlsettings)
        {
            var browser = new ChromiumWebBrowser();

            _form.RootGrid.Children.Add(browser);
            browser.VerticalAlignment   = VerticalAlignment.Stretch;
            browser.HorizontalAlignment = HorizontalAlignment.Stretch;
            browser.Visibility          = Visibility.Hidden;

            browser.IsBrowserInitializedChanged += OnBrowserInitialized;
            browser.LoadingStateChanged         += OnBrowserLoadingStateChanged;

            lock (_browserLock)
            {
                var id = _browserCounter++;
                browser.Uid = id.ToString();

                _browsers.Add(id, browser);
                _browserSettings.Add(id, urlsettings);
            }
        }
Пример #23
0
        public static string GetSeasonID()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Async(a => a.Console(theme: AnsiConsoleTheme.Code))
                         .CreateLogger();
            string JSON           = "";
            string seasonSettings = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(@"bin\Debug", @"Configuration\Settings\websettings.json");

            if (!File.Exists(seasonSettings))
            {
                Log.Warning($"{seasonSettings} does not exist.");
            }
            using (var stream = new FileStream(seasonSettings, FileMode.Open, FileAccess.Read))
                using (var readSeason = new StreamReader(stream)) { JSON = readSeason.ReadToEnd(); }
            UrlSettings seasonID = JsonConvert.DeserializeObject <UrlSettings>(JSON);

            WebSettings.XboxSeasonId = seasonID.xboxSeasonId;
            WebSettings.PSNSeasonID  = seasonID.xboxSeasonId;
            var CurrentSeason = WebSettings.XboxSeasonId;

            return(CurrentSeason);
        }
Пример #24
0
        private IEnumerable <object> Execute(LinkItemCollection linkItemCollection, UrlSettings urlSettings)
        {
            var links = new List <LinkItem>();

            foreach (var link in linkItemCollection)
            {
                string prettyUrl = null;
                if (link.ReferencedPermanentLinkIds.Any())
                {
                    var url = new Url(link.Href);
                    prettyUrl = this._urlHelper.ContentUrl(url, urlSettings);
                }
                links.Add(new LinkItem
                {
                    Text   = link.Text,
                    Target = link.Target,
                    Title  = link.Title,
                    Href   = prettyUrl ?? link.Href
                });
            }

            return(links);
        }
Пример #25
0
        public MainWindow()
        {
            InitializeComponent();

            WindowStyle = WindowStyle.SingleBorderWindow;
            Grid.Effect = new BlurEffect {
                Radius = 5, RenderingBias = RenderingBias.Performance
            };

            if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45)
            {
                //Mainland China PRC
                DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29");
                DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list";
                UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/";
            }
            else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237)
            {
                //Taiwan ROC
                DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101");
                DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list";
            }
            else if (RegionInfo.CurrentRegion.GeoId == 104)
            {
                //HongKong SAR
                UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list";
            }

            if (!File.Exists($"{SetupBasePath}config.json"))
            {
                if (MyTools.IsBadSoftExist())
                {
                    MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!");
                }
                if (!MyTools.IsNslookupLocDns())
                {
                    var msgResult =
                        MessageBox.Show(
                            "Question: 初次启动,是否要将您的系统默认 DNS 服务器设为 AuroraDNS?"
                            , "Question", MessageBoxButton.OKCancel);
                    if (msgResult == MessageBoxResult.OK)
                    {
                        IsSysDns_OnClick(null, null);
                    }
                }
            }

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"))
            {
                try
                {
                    UrlReg.Reg("doh");
                    UrlReg.Reg("dns-over-https");
                    UrlReg.Reg("aurora-doh-list");

                    File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                "\\AuroraDNS.UrlReged");
                    File.SetAttributes(
                        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                        "\\AuroraDNS.UrlReged", FileAttributes.Hidden);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            try
            {
                if (File.Exists($"{SetupBasePath}url.json"))
                {
                    UrlSettings.ReadConfig($"{SetupBasePath}url.json");
                }
                if (File.Exists($"{SetupBasePath}config.json"))
                {
                    DnsSettings.ReadConfig($"{SetupBasePath}config.json");
                }
                if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list"))
                {
                    DnsSettings.ReadBlackList($"{SetupBasePath}black.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(SetupBasePath + "china.list");
                }
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBoxResult msgResult =
                    MessageBox.Show(
                        "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" +
                        $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel);
                if (msgResult == MessageBoxResult.OK)
                {
                    RunAsAdmin();
                }
                else
                {
                    Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}");
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
            if (DnsSettings.AllowSelfSignedCert)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, cert, chain, sslPolicyErrors) => true;
            }

//            switch (0.0)
//            {
//                case 1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
//                    break;
//                case 1.1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
//                    break;
//                case 1.2:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//                    break;
//                default:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
//                    break;
//            }

            MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10);
            MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived;
            //MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start();
            //MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop();

            using (BackgroundWorker worker = new BackgroundWorker())
            {
                worker.DoWork += (a, s) =>
                {
                    LocIPAddr = IPAddress.Parse(IpTools.GetLocIp());
                    if (!(Equals(DnsSettings.EDnsIp, IPAddress.Any) && DnsSettings.EDnsCustomize))
                    {
                        IntIPAddr = IPAddress.Parse(IpTools.GetIntIp());
                        var local = IpTools.GeoIpLocal(IntIPAddr.ToString());
                        Dispatcher?.Invoke(() => { TitleTextItem.Header = $"{IntIPAddr}{Environment.NewLine}{local}"; });
                    }

                    try
                    {
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list");
                        }
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list");
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}");
                    }

                    MemoryCache.Default.Trim(100);
                };
                worker.RunWorkerAsync();
            }

            IsSysDns.IsChecked = MyTools.IsNslookupLocDns();
        }
Пример #26
0
        public MainWindow()
        {
            InitializeComponent();

            WindowStyle = WindowStyle.SingleBorderWindow;
            Grid.Effect = new BlurEffect {
                Radius = 5, RenderingBias = RenderingBias.Performance
            };

            if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45)
            {
                //Mainland China PRC
                DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29");
                DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list";
                UrlSettings.WhatMyIpApi = "https://myip.ustclug.org/";
            }
            else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237)
            {
                //Taiwan ROC
                DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101");
                DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query";
                UrlSettings.MDnsList    = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list";
            }
            else if (RegionInfo.CurrentRegion.GeoId == 104)
            {
                //HongKong SAR
                UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list";
            }

            if (!File.Exists($"{SetupBasePath}config.json"))
            {
                if (MyTools.IsBadSoftExist())
                {
                    MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!");
                }
                if (!MyTools.IsNslookupLocDns())
                {
                    MessageBoxResult msgResult =
                        MessageBox.Show(
                            "Question: 初次启动,是否要将您的系统默认 DNS 服务器设为 AuroraDNS?"
                            , "Question", MessageBoxButton.OKCancel);
                    if (msgResult == MessageBoxResult.OK)
                    {
                        IsSysDns_OnClick(null, null);
                    }
                }
            }

            if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"))
            {
                try
                {
                    UrlReg.Reg("doh");
                    UrlReg.Reg("dns-over-https");
                    UrlReg.Reg("aurora-doh-list");

                    File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                "\\AuroraDNS.UrlReged");
                    File.SetAttributes(
                        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                        "\\AuroraDNS.UrlReged", FileAttributes.Hidden);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            try
            {
                if (File.Exists($"{SetupBasePath}url.json"))
                {
                    UrlSettings.ReadConfig($"{SetupBasePath}url.json");
                }
                if (File.Exists($"{SetupBasePath}config.json"))
                {
                    DnsSettings.ReadConfig($"{SetupBasePath}config.json");
                }
                if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list"))
                {
                    DnsSettings.ReadBlackList($"{SetupBasePath}black.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}white.list");
                }
                if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list"))
                {
                    DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list");
                }
                if (DnsSettings.ChinaListEnable && File.Exists("china.list"))
                {
                    DnsSettings.ReadChinaList(SetupBasePath + "china.list");
                }
            }
            catch (UnauthorizedAccessException e)
            {
                MessageBoxResult msgResult =
                    MessageBox.Show(
                        "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" +
                        $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel);
                if (msgResult == MessageBoxResult.OK)
                {
                    RunAsAdmin();
                }
                else
                {
                    Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}");
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
            if (DnsSettings.AllowSelfSignedCert)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, cert, chain, sslPolicyErrors) => true;
            }

//            switch (0.0)
//            {
//                case 1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
//                    break;
//                case 1.1:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
//                    break;
//                case 1.2:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//                    break;
//                default:
//                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
//                    break;
//            }

            MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10);
            MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived;
            MDnsSvrWorker.DoWork     += (sender, args) => MDnsServer.Start();
            MDnsSvrWorker.Disposed   += (sender, args) => MDnsServer.Stop();

            using (BackgroundWorker worker = new BackgroundWorker())
            {
                worker.DoWork += (sender, args) =>
                {
                    LocIPAddr = IPAddress.Parse(IpTools.GetLocIp());
                    if (!Equals(DnsSettings.EDnsIp, IPAddress.Loopback))
                    {
                        IntIPAddr = IPAddress.Parse(IpTools.GetIntIp());
                    }

                    try
                    {
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list");
                        }
                        if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list"))
                        {
                            DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list");
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}");
                    }

                    MemoryCache.Default.Trim(100);
                };
                worker.RunWorkerAsync();
            }

            NotifyIcon = new NotifyIcon()
            {
                Text = @"AuroraDNS", Visible = false,
                Icon = Properties.Resources.AuroraWhite
            };
            WinFormMenuItem showItem    = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal);
            WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) =>
            {
                if (MDnsSvrWorker.IsBusy)
                {
                    MDnsSvrWorker.Dispose();
                }
                Process.Start(new ProcessStartInfo {
                    FileName = GetType().Assembly.Location
                });
                Environment.Exit(Environment.ExitCode);
            });
            WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) =>
            {
                if (File.Exists(
                        $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log"))
                {
                    Process.Start(new ProcessStartInfo(
                                      $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log"));
                }
                else
                {
                    MessageBox.Show("找不到当前日志文件,或当前未产生日志文件。");
                }
            });
            WinFormMenuItem abootItem    = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().Show());
            WinFormMenuItem updateItem   = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location));
            WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().Show());
            WinFormMenuItem exitItem     = new WinFormMenuItem("退出", (sender, args) =>
            {
                try
                {
                    UrlReg.UnReg("doh");
                    UrlReg.UnReg("dns-over-https");
                    UrlReg.UnReg("aurora-doh-list");
                    File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                                "\\AuroraDNS.UrlReged");
                    if (!DnsSettings.AutoCleanLogEnable)
                    {
                        return;
                    }
                    foreach (var item in Directory.GetFiles($"{SetupBasePath}Log"))
                    {
                        if (item != $"{SetupBasePath}Log" +
                            $"\\{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")
                        {
                            File.Delete(item);
                        }
                    }
                    if (File.Exists(Path.GetTempPath() + "setdns.cmd"))
                    {
                        File.Delete(Path.GetTempPath() + "setdns.cmd");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                Close();
                Environment.Exit(Environment.ExitCode);
            });

            NotifyIcon.ContextMenu =
                new WinFormContextMenu(new[]
            {
                showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem
            });

            NotifyIcon.DoubleClick += MinimizedNormal;

            IsSysDns.IsChecked = MyTools.IsNslookupLocDns();
            if (IsSysDns.IsChecked == true)
            {
                IsSysDns.ToolTip = "已设为系统 DNS";
            }
        }
Пример #27
0
        public static string GetURL(string System, string Trigger, int SeasonId, string SeasonType)
        {
            string JSON    = "";
            var    xboxURL = "";
            var    psnURL  = "";

            var sFile          = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var configFile     = @"Configuration\websettings.json";
            var configLocation = Path.Combine(sFile, configFile);

            if (!File.Exists(configLocation))
            {
                Log.Error($"{configLocation} does not exist");
            }
            try
            {
                using (var stream = new FileStream(configLocation, FileMode.Open, FileAccess.Read))
                    using (var readSettings = new StreamReader(stream))
                    {
                        JSON = readSettings.ReadToEnd();
                    }
            }
            catch (UnauthorizedAccessException ex)
            {
                Log.Logger.Error(ex, $"Error reading websettings.json ({configLocation}");
                throw;
            }
            //convert Season Type from int to string
            UrlSettings settings = JsonConvert.DeserializeObject <UrlSettings>(JSON);

            if (SeasonType == "pre")
            {
                SeasonType = "0";
            }
            else if (SeasonType == "reg")
            {
                SeasonType = "1";
            }
            var url          = "";
            var sTypeTemp    = "&seasontypeid=";
            var seasonTypeId = string.Concat(String.Empty, sTypeTemp, SeasonType);

            switch (System)
            {
            case "xbox":
                switch (Trigger)
                {
                case "playerstats":
                case "goaliestats":
                    WebSettings.XboxPlayerStatsURL = settings.xboxPlayerStatsURL;
                    //var urlTemp = WebSettings.XboxPlayerStatsURL;
                    url = WebSettings.XboxPlayerStatsURL + SeasonId + seasonTypeId;
                    break;

                case "draftlist":
                    url = WebSettings.XboxDraftListURL + SeasonId;
                    break;

                case "teamstats":
                    WebSettings.XboxTeamStandingsURL = settings.xboxStandingsURL;
                    url = WebSettings.XboxTeamStandingsURL + SeasonId + seasonTypeId;
                    break;
                }
                return(url);

            case "psn":
                switch (Trigger)
                {
                case "playerstats":
                case "goaliestats":
                    WebSettings.PSNPlayerStatsURL = settings.psnPlayerStatsURL;
                    url = WebSettings.PSNPlayerStatsURL + SeasonId + seasonTypeId;
                    break;

                case "draftlist":
                    url = WebSettings.PSNDraftListURL + SeasonId;
                    break;

                case "teamstats":
                    WebSettings.PSNTeamStandingsURL = settings.psnStandingsURL;
                    url = WebSettings.PSNTeamStandingsURL + SeasonId + seasonTypeId;
                    break;
                }
                return(url);
            }
            return(null);
        }
Пример #28
0
 public MerchantSetting(UrlSettings urlSettings = default, string mastheadBackgroundColor = default, string communicationConfiguration = default)
 {
     UrlSettings                = urlSettings;
     MastheadBackgroundColor    = mastheadBackgroundColor;
     CommunicationConfiguration = communicationConfiguration;
 }
Пример #29
0
        public static void AddAuthentictionAndAuthorisation(this IServiceCollection services, UrlSettings settings)
        {
            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority            = settings.Authority;
                options.RequireHttpsMetadata = false;
                options.Audience             = "admin-api";
            });

            services.AddAuthorization(options =>
            {
                // options.AddPolicy("UserManagement", policy => policy.RequireClaim("scope", "admin_users"));
                options.AddPolicy("UserManagement", policy => policy.RequireClaim("admin_users", "true"));
                options.AddPolicy("RoleManagement", policy => policy.RequireClaim("admin_roles", "true"));
                options.AddPolicy("ApiManagement", policy => policy.RequireClaim("admin_api_resource", "true"));
                options.AddPolicy("IdentityManagement", policy => policy.RequireClaim("admin_identity_resource", "true"));
                options.AddPolicy("ClientManagement", policy => policy.RequireClaim("admin_clients", "true"));


                // options.AddPolicy("Consumer", policy => policy.RequireClaim(ClaimTypes.Role, "consumer"));
            });
        }
Пример #30
0
 public IEnumerable <object> GetValue(LinkItemCollection linkItemCollection, UrlSettings urlSettings)
 {
     return(Execute(linkItemCollection, urlSettings));
 }
Пример #31
0
 public HttpService(UrlSettings settings)
 {
     _settings = settings;
 }