Exemple #1
0
        // POST /api/Register - Register User
        public async Task <bool> PostRegisterUserAsync()
        {
            loggerService.StartMethod();
            try
            {
                await serverConfigurationRepository.LoadAsync();

                string url     = serverConfigurationRepository.UserRegisterApiEndpoint;
                var    content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                var    result  = await PostAsync(url, content);

                if (result != null)
                {
                    loggerService.EndMethod();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed to register user.", ex);
            }

            loggerService.EndMethod();
            return(false);
        }
Exemple #2
0
        public EditServerConfigurationPageViewModel(
            INavigationService navigationService,
            IServerConfigurationRepository serverConfigurationRepository
            ) : base(navigationService)
        {
            Title = "Edit ServerConfiguration";
            _serverConfigurationRepository = serverConfigurationRepository;

            Task.Run(async() =>
            {
                await _serverConfigurationRepository.LoadAsync();

                UserRegisterApiEndpoint = _serverConfigurationRepository.UserRegisterApiEndpoint;
                Regions = string.Join(",", _serverConfigurationRepository.Regions);
                DiagnosisKeyRegisterApiEndpoint       = _serverConfigurationRepository.DiagnosisKeyRegisterApiEndpoint;
                DiagnosisKeyListProvideServerEndpoint = _serverConfigurationRepository.DiagnosisKeyListProvideServerEndpoint;
                InquiryLogApiUrl         = _serverConfigurationRepository.InquiryLogApiUrl;
                LogStorageEndpoint       = _serverConfigurationRepository.LogStorageEndpoint;
                ExposureConfigurationUrl = _serverConfigurationRepository.ExposureConfigurationUrl;
                ExposureRiskCalculationConfigurationUrl = _serverConfigurationRepository.ExposureRiskCalculationConfigurationUrl;
                ExposureDataCollectServerEndpoint       = _serverConfigurationRepository.ExposureDataCollectServerEndpoint;
                EventLogApiEndpoint = _serverConfigurationRepository.EventLogApiEndpoint;

                UpdateUrls();
            });
        }
        public async Task UploadExposureDataAsync(
            ExposureRequest exposureRequest
            )
        {
            await _serverConfigurationRepository.LoadAsync();

            foreach (var url in _serverConfigurationRepository.ExposureDataCollectServerUrls)
            {
                await UploadExposureDataAsync(exposureRequest, url);
            }
        }
Exemple #4
0
        // POST /api/Register - Register User
        public async Task <HttpStatusCode> PostRegisterUserAsync()
        {
            loggerService.StartMethod();
            try
            {
                await serverConfigurationRepository.LoadAsync();

                string url     = serverConfigurationRepository.UserRegisterApiEndpoint;
                var    content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

                HttpResponseMessage result = await httpClient.PostAsync(url, content);

                loggerService.EndMethod();
                return(result.StatusCode);
            }
            catch (Exception ex)
            {
                loggerService.Exception("Failed to register user.", ex);
                loggerService.EndMethod();
                throw;
            }
        }
Exemple #5
0
        private async Task SendExposureDataAsync(
            string idempotencyKey,
            ExposureData exposureData
            )
        {
            _loggerService.StartMethod();

            SendEventLogState sendEventLogState = _userDataRepository.GetSendEventLogState();
            bool isEnabled = sendEventLogState == SendEventLogState.Enable;

            if (!isEnabled)
            {
                _loggerService.Debug($"Send event-log function is not enabled.");
                _loggerService.EndMethod();
                return;
            }

            await _serverConfigurationRepository.LoadAsync();

            string exposureDataCollectServerEndpoint = _serverConfigurationRepository.EventLogApiEndpoint;

            _loggerService.Debug($"exposureDataCollectServerEndpoint: {exposureDataCollectServerEndpoint}");

            try
            {
                var contentJson = exposureData.ToJsonString();

                var eventLog = new V1EventLogRequest.EventLog()
                {
                    HasConsent = isEnabled,
                    Epoch      = _dateTimeUtility.UtcNow.ToUnixEpoch(),
                    Type       = "ExposureData",
                    Subtype    = "Debug",
                    Content    = contentJson,
                };
                var eventLogs = new[] { eventLog };

                var request = new V1EventLogRequest()
                {
                    IdempotencyKey = idempotencyKey,
                    Platform       = _essentialsService.Platform,
                    AppPackageName = _essentialsService.AppPackageName,
                    EventLogs      = eventLogs,
                };

                request.DeviceVerificationPayload = await _deviceVerifier.VerifyAsync(request);

                var requestJson = request.ToJsonString();

                var httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");

                Uri uri = new Uri(exposureDataCollectServerEndpoint);

                HttpResponseMessage response = await _httpClient.PutAsync(uri, httpContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();

                    _loggerService.Debug($"{responseJson}");
                }
                else
                {
                    _loggerService.Info($"UploadExposureDataAsync {response.StatusCode}");
                }
            }
            finally
            {
                _loggerService.EndMethod();
            }
        }
        private async Task <ExposureConfiguration> GetExposureConfigurationInternalAsync()
        {
            _loggerService.StartMethod();

            ExposureConfiguration currentExposureConfiguration = null;

            if (File.Exists(_currentExposureConfigurationPath))
            {
                _loggerService.Debug("ExposureConfiguration file is found.");

                try
                {
                    string exposureConfigurationAsJson = await LoadAsync(_currentExposureConfigurationPath);

                    currentExposureConfiguration = JsonConvert.DeserializeObject <ExposureConfiguration>(exposureConfigurationAsJson);

                    _loggerService.Info("Cached:" + exposureConfigurationAsJson);

                    if (!IsDownloadedExposureConfigurationOutdated(AppConstants.ExposureConfigurationFileDownloadCacheRetentionDays))
                    {
                        _loggerService.EndMethod();
                        return(currentExposureConfiguration);
                    }
                    else
                    {
                        _loggerService.Info($"ExposureConfiguration is found but the file is outdated.");
                    }
                }
                catch (IOException exception)
                {
                    _loggerService.Exception("IOException. ExposureConfiguration file has been deleted.", exception);
                    RemoveExposureConfigurationInternal();
                }
                catch (JsonException exception)
                {
                    _loggerService.Exception("JsonException. ExposureConfiguration file has been deleted.", exception);
                    RemoveExposureConfigurationInternal();
                }
            }

            // Cache not exist (first time. probably...)
            if (currentExposureConfiguration is null)
            {
                currentExposureConfiguration = CreateDefaultConfiguration();
                SetExposureConfigurationDownloadedDateTime(_dateTimeUtility.UtcNow);
                SetIsDiagnosisKeysDataMappingConfigurationUpdated(true);
            }

            await _serverConfigurationRepository.LoadAsync();

            string url = _serverConfigurationRepository.ExposureConfigurationUrl;

            ExposureConfiguration newExposureConfiguration = null;

            var response = await _httpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string exposureConfigurationAsJson = await response.Content.ReadAsStringAsync();

                try
                {
                    newExposureConfiguration = JsonConvert.DeserializeObject <ExposureConfiguration>(exposureConfigurationAsJson);

                    _loggerService.Info("Downloaded:" + exposureConfigurationAsJson);

                    SetExposureConfigurationDownloadedDateTime(_dateTimeUtility.UtcNow);
                }
                catch (JsonException exception)
                {
                    _loggerService.Exception("JsonException.", exception);
                }
            }
            else
            {
                _loggerService.Warning($"Download ExposureConfiguration failed from {url}");
            }

            if (newExposureConfiguration is null)
            {
                _loggerService.EndMethod();
                return(currentExposureConfiguration);
            }

            if (IsUpdatedDiagnosisKeysDataMapping(currentExposureConfiguration, newExposureConfiguration))
            {
                if (IsExposureConfigurationOutdated(AppConstants.MinimumDiagnosisKeysDataMappingApplyIntervalDays))
                {
                    currentExposureConfiguration = newExposureConfiguration;
                    SetIsDiagnosisKeysDataMappingConfigurationUpdated(true);
                }
                else
                {
                    _loggerService.Info($"DiagnosisKeysDataMappingConfig has been changed but not updated, because current configuration is updated in {AppConstants.MinimumDiagnosisKeysDataMappingApplyIntervalDays} days.");
                }
            }
            else
            {
                currentExposureConfiguration = newExposureConfiguration;
            }

            string tmpFilePath = Path.Combine(_configDir, Guid.NewGuid().ToString());

            try
            {
                await SaveAsync(
                    JsonConvert.SerializeObject(currentExposureConfiguration, Formatting.Indented),
                    tmpFilePath
                    );

                Swap(tmpFilePath, _currentExposureConfigurationPath);

                return(currentExposureConfiguration);
            }
            finally
            {
                File.Delete(tmpFilePath);

                _loggerService.EndMethod();
            }
        }
        private async Task InternalExposureDetectionAsync(CancellationTokenSource cancellationTokenSource = null)
        {
            bool isEnabled = await _exposureNotificationApiService.IsEnabledAsync();

            if (!isEnabled)
            {
                _loggerService.Info($"EN API is not enabled.");
                return;
            }

            IEnumerable <int> statuseCodes = await _exposureNotificationApiService.GetStatusCodesAsync();

            bool isActivated = statuseCodes.Contains(ExposureNotificationStatus.Code_Android.ACTIVATED)
                               | statuseCodes.Contains(ExposureNotificationStatus.Code_iOS.Active);

            if (!isActivated)
            {
                _loggerService.Info($"EN API is not ACTIVATED.");
                return;
            }

            var cancellationToken = cancellationTokenSource?.Token ?? default(CancellationToken);

            await _serverConfigurationRepository.LoadAsync();

            bool canConfirmExposure = true;
            bool isMaxPerDayExposureDetectionAPILimitReached = false;

            foreach (var region in _serverConfigurationRepository.Regions)
            {
                _loggerService.Info($"Region: {region}");

                var diagnosisKeyListProvideServerUrl = _serverConfigurationRepository.GetDiagnosisKeyListProvideServerUrl(region);

                _loggerService.Info($"diagnosisKeyListProvideServerUrl: {diagnosisKeyListProvideServerUrl}");

                List <string> downloadedFileNameList = new List <string>();
                try
                {
                    var tmpDir = PrepareDir(region);

                    var(httpStatus, diagnosisKeyEntryList) = await _diagnosisKeyRepository.GetDiagnosisKeysListAsync(
                        diagnosisKeyListProvideServerUrl,
                        cancellationToken
                        );

                    if (httpStatus != HttpStatusCode.OK)
                    {
                        _loggerService.Info($"URL: {diagnosisKeyListProvideServerUrl}, Response StatusCode: {httpStatus}");
                        canConfirmExposure = false;
                        continue;
                    }

                    var lastProcessTimestamp = await _userDataRepository.GetLastProcessDiagnosisKeyTimestampAsync(region);

                    _loggerService.Info($"Region: {region}, lastProcessTimestamp: {lastProcessTimestamp}");

                    var targetDiagnosisKeyEntryList = FilterDiagnosisKeysAfterLastProcessTimestamp(diagnosisKeyEntryList, lastProcessTimestamp);

                    if (targetDiagnosisKeyEntryList.Count() == 0)
                    {
                        _loggerService.Info($"No new diagnosis-key found on {diagnosisKeyListProvideServerUrl}");
                        continue;
                    }

                    _loggerService.Info($"{targetDiagnosisKeyEntryList.Count()} new keys found.");

                    foreach (var diagnosisKeyEntry in targetDiagnosisKeyEntryList)
                    {
                        string filePath = await _diagnosisKeyRepository.DownloadDiagnosisKeysAsync(diagnosisKeyEntry, tmpDir, cancellationToken);

                        _loggerService.Info($"URL {diagnosisKeyEntry.Url} have been downloaded.");

                        downloadedFileNameList.Add(filePath);
                    }

                    var downloadedFileNames = string.Join("\n", downloadedFileNameList);
                    _loggerService.Debug(downloadedFileNames);

                    await _exposureNotificationApiService.ProvideDiagnosisKeysAsync(
                        downloadedFileNameList,
                        cancellationTokenSource
                        );

                    // Save LastProcessDiagnosisKeyTimestamp after ProvideDiagnosisKeysAsync was succeeded.
                    var latestProcessTimestamp = targetDiagnosisKeyEntryList
                                                 .Select(diagnosisKeyEntry => diagnosisKeyEntry.Created)
                                                 .Max();
                    await _userDataRepository.SetLastProcessDiagnosisKeyTimestampAsync(region, latestProcessTimestamp);

                    _userDataRepository.SetLastConfirmedDate(_dateTimeUtility.UtcNow);
                    _userDataRepository.SetCanConfirmExposure(true);
                    _userDataRepository.SetIsMaxPerDayExposureDetectionAPILimitReached(isMaxPerDayExposureDetectionAPILimitReached);
                }
                catch (ENException exception)
                {
                    canConfirmExposure = false;
                    isMaxPerDayExposureDetectionAPILimitReached = CheckMaxPerDayExposureDetectionAPILimitReached(exception);
                    _loggerService.Exception($"ENExcepiton occurred, Code:{exception.Code}, Message:{exception.Message}", exception);
                    throw;
                }
                catch (Exception exception)
                {
                    canConfirmExposure = false;
                    _loggerService.Exception($"Exception occurred: {region}", exception);
                    throw;
                }
                finally
                {
                    RemoveFiles(downloadedFileNameList);
                    _userDataRepository.SetCanConfirmExposure(canConfirmExposure);
                    _userDataRepository.SetIsMaxPerDayExposureDetectionAPILimitReached(isMaxPerDayExposureDetectionAPILimitReached);
                }
            }
        }
        private async Task <V1ExposureRiskCalculationConfiguration> GetExposureRiskCalculationConfigurationInternalAsync(bool preferCache)
        {
            _loggerService.StartMethod();

            V1ExposureRiskCalculationConfiguration currentConfiguration = null;

            if (File.Exists(_currentPath))
            {
                _loggerService.Debug("ExposureConfiguration file is found.");

                try
                {
                    string exposureRiskCalculationConfigurationAsJson = await LoadAsync(_currentPath);

                    currentConfiguration = JsonConvert.DeserializeObject <V1ExposureRiskCalculationConfiguration>(exposureRiskCalculationConfigurationAsJson);
                }
                catch (IOException exception)
                {
                    _loggerService.Exception("IOException. ExposureRiskCalculationConfiguration file has been deleted.", exception);
                    RemoveExposureRiskCalculationConfiguration();
                }
                catch (JsonException exception)
                {
                    _loggerService.Exception("JsonException. ExposureRiskCalculationConfiguration file has been deleted.", exception);
                    RemoveExposureRiskCalculationConfiguration();
                }
            }

            if (currentConfiguration is null)
            {
                currentConfiguration = CreateDefaultConfiguration();
            }
            else if (preferCache)
            {
                _loggerService.EndMethod();
                return(currentConfiguration);
            }

            await _serverConfigurationRepository.LoadAsync();

            string url = _serverConfigurationRepository.ExposureRiskCalculationConfigurationUrl;

            V1ExposureRiskCalculationConfiguration newExposureRiskCalculationConfiguration = null;

            try
            {
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    string exposureRiskCalculationConfigurationAsJson = await response.Content.ReadAsStringAsync();

                    _loggerService.Debug(exposureRiskCalculationConfigurationAsJson);
                    newExposureRiskCalculationConfiguration
                        = JsonConvert.DeserializeObject <V1ExposureRiskCalculationConfiguration>(exposureRiskCalculationConfigurationAsJson);
                }
                else
                {
                    _loggerService.Warning($"Download ExposureRiskCalculationConfiguration failed from {url}");
                }
            }
            catch (JsonException exception)
            {
                _loggerService.Exception("JsonException.", exception);
            }
            catch (HttpRequestException exception)
            {
                _loggerService.Exception("HttpRequestException.", exception);
            }

            if (newExposureRiskCalculationConfiguration is null)
            {
                _loggerService.EndMethod();
                return(currentConfiguration);
            }

            if (newExposureRiskCalculationConfiguration.Equals(currentConfiguration))
            {
                _loggerService.Info("ExposureRiskCalculationConfiguration have not been changed.");
                _loggerService.EndMethod();

                return(currentConfiguration);
            }

            _loggerService.Info("ExposureRiskCalculationConfiguration have been changed.");

            string tmpFilePath = Path.Combine(_configDir, Guid.NewGuid().ToString());

            try
            {
                await SaveAsync(
                    JsonConvert.SerializeObject(newExposureRiskCalculationConfiguration, Formatting.Indented),
                    tmpFilePath
                    );

                Swap(tmpFilePath, _currentPath);

                return(newExposureRiskCalculationConfiguration);
            }
            finally
            {
                File.Delete(tmpFilePath);

                _loggerService.EndMethod();
            }
        }