private List <MetricDataPoint> GAReports(ExternalApiAuth externalApiAuth, AuthorizationCodeWebApp.AuthResult authResult, IEnumerable <MetricDataPoint> metricDataPoints) { var resultantDataPoints = new List <MetricDataPoint>(); if (metricDataPoints != null) { // Initiate GA Reporting Service var service = new AnalyticsReportingService(new BaseClientService.Initializer { HttpClientInitializer = authResult.Credential, ApplicationName = "Supdate" }); // Get a list of each date we need data for var dataPoints = metricDataPoints as IList <MetricDataPoint> ?? metricDataPoints.ToList(); var dateList = dataPoints.Select(d => d.Date).Distinct(); var reportMetrics = GAReportMetrics(); foreach (var date in dateList) { // Get a report request var reportsRequest = PrepareGAReportRequest(date, reportMetrics, externalApiAuth.ConfigData); // Execute the request var reportResponse = service.Reports.BatchGet(reportsRequest).Execute(); // Extract the resultant report data resultantDataPoints.AddRange(ParseResults(date, reportResponse.Reports[0], dataPoints)); } } // Return the results of all report requests return(resultantDataPoints); }
public async Task <MetricDataImport> GetData(int companyId, ExternalApiAuth externalApiAuth, AuthorizationCodeWebApp.AuthResult authResult, IEnumerable <MetricDataPoint> metricDataPoints) { var metricDataImport = new MetricDataImport { success = true }; if (externalApiAuth == null) { // user is not connected to this API return(metricDataImport); } if (authResult.Credential == null) { // should be connected, but Google says we're not metricDataImport.errors.Add(new JsonError { ErrorMessage = "Google Analytics authorization revoked - unable to get data" }); return(metricDataImport); } metricDataImport.results = GAReports(externalApiAuth, authResult, metricDataPoints); return(metricDataImport); }
public async Task <ActionResult> Connect(Guid uniqueId, int externalApiId) { var externalApi = ExternalApi.ChartMogul.GetById(externalApiId); var externalApiAuth = new ExternalApiAuth { ExternalApiId = externalApiId }; // Replace with requested object if (uniqueId != Guid.Empty) { externalApiAuth = _externalApiAuthManager.GetExternalApiAuth(CompanyId, uniqueId); } switch (externalApi.ApiAuthorizationType) { case ExternalApiAuthorizationType.OAuth20: // Hard coded to Google for now var company = _companyManager.Get(CompanyId); Session["CompanyGuid"] = company.UniqueId.ToString(); var authResult = await _googleAuthorizer.Authorize(company.UniqueId, externalApiAuth, Url.Action("SetGoogleAnalyticsSiteId"), CancellationToken.None); if (authResult.Credential == null) { return(View("_startOAuth", new OAuthStartAuthorisation { ExternalApi = externalApi, StartUrl = authResult.RedirectUri })); } try { var accountSummaries = await _googleAuthorizer.GetAccountSummaries(authResult); if (string.IsNullOrWhiteSpace(externalApiAuth.ConfigData)) { // Default to first profile externalApiAuth.ConfigData = accountSummaries.items[0].webProperties[0].profiles[0].id; _externalApiAuthManager.Update(externalApiAuth); } return(View("_manageOAuth", new GoogleOAuthConfigView { ExternalApi = externalApi, ExternalApiAuth = externalApiAuth, Accounts = accountSummaries })); } catch { _externalApiAuthManager.Delete(externalApiAuth.Id); return(Content("We couldn't retrieve your Google Analytics site list.\nTry refreshing the page and re-connecting to Google Analytics")); } default: return(View("_connect", externalApiAuth)); } }
public ActionResult Credentials(ExternalApiAuth externalApiAuth, Guid uniqueId = default(Guid)) { var x = ExternalApi.ChartMogul; if (ModelState.IsValid) { externalApiAuth.CompanyId = CompanyId; _externalApiAuthManager.SaveExternalApiAuth(externalApiAuth); this.SetNotificationMessage(NotificationType.Success, "Configuration successfully saved."); return(Json(new { success = true })); } return(Json(new { success = false })); }
private static ExternalApiAuth StoreValue(string key, string value, ExternalApiAuth externalApiAuth) { var useKeyField = key.StartsWith("oauth_"); if (useKeyField) { externalApiAuth.Key = value; } else { externalApiAuth.Token = value; } return(externalApiAuth); }
public HttpClient GetHttpClient(ExternalApi externalApi, ExternalApiAuth externalApiAuth) { var client = new HttpClient { BaseAddress = new Uri(externalApi.BaseUrl) }; var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", externalApiAuth.Token, externalApiAuth.Key)); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return(client); }
public async Task <bool> TestCredentials(string token, string key, int externalApiId) { var externalApiAuth = new ExternalApiAuth { Token = token, Key = key }; var client = GetHttpClient(_externalApi, externalApiAuth); HttpResponseMessage response = await client.GetAsync(_externalApi.TestUrl); if (response.IsSuccessStatusCode) { return(true); } return(false); }
public Task StoreAsync <T>(string key, T value) { var companyGuid = ExtractCompanyGuid(key); var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value); var typeParameterType = typeof(T); Debug.WriteLine("GETASYNC"); Debug.WriteLine("Key is:" + key); Debug.WriteLine("T is:" + typeParameterType.FullName); Debug.WriteLine("value is:" + value); // Check the serialized data can be converted back, // if not then it wasn't a valid value and shouldn't be saved try { var check = NewtonsoftJsonSerializer.Instance.Deserialize <T>(serialized); } catch (Exception ex) { return(Task.Delay(0)); } var externalApiAuth = _externalApiAuthManager.GetByCompanyGuid(companyGuid, ExternalApi.GoogleAnalytics.Id); if (externalApiAuth == null) { // New User we insert it into the database externalApiAuth = new ExternalApiAuth { ExternalApiId = ExternalApi.GoogleAnalytics.Id }; externalApiAuth = StoreValue(key, serialized, externalApiAuth); _externalApiAuthManager.SaveWithCompanyGuid(companyGuid, externalApiAuth); } else { // Existing User We update it externalApiAuth = StoreValue(key, serialized, externalApiAuth); _externalApiAuthManager.Update(externalApiAuth); } return(Task.Delay(0)); }
public async Task <AuthorizationCodeWebApp.AuthResult> Authorize(Guid companyGuid, ExternalApiAuth externalApiAuth, string state, CancellationToken token) { var appFlowMetaData = GetAppFlowMetaData(companyGuid); var callbackUrl = string.Format("{0}{1}", ConfigUtil.BaseAppUrl, appFlowMetaData.AuthCallback.Substring(1)); var result = await new AuthorizationCodeWebApp(appFlowMetaData.Flow, callbackUrl, state).AuthorizeAsync(companyGuid.ToString(), token); // Check if token has expired if (result.Credential != null) { if (result.Credential.Token.IsExpired(SystemClock.Default)) { // token has expired we should refresh it var refresh = result.Credential.RefreshTokenAsync(CancellationToken.None).Result; } } return(result); }
public async Task <MetricDataImport> GetData(int companyId, ExternalApiAuth externalApiAuth, IEnumerable <MetricDataPoint> metricDataPoints) { var metricDataImport = new MetricDataImport { success = true }; if (externalApiAuth == null) { // user is not connected to this API return(metricDataImport); } var resultantDataPoints = new List <MetricDataPoint>(); var dataPoints = metricDataPoints as IList <MetricDataPoint> ?? metricDataPoints.ToList(); var dateList = dataPoints.Select(d => d.Date).Distinct(); try { // Loop for each distinct date provided in the MetricDataPoints foreach (var date in dateList) { // We want data for the last day of the month specified var dataDate = date.AddMonths(1).AddDays(-1); // Unless that puts us in the future, in which case get today's data if (dataDate > DateTime.Today) { dataDate = DateTime.Today; } var metricsChartMogul = dataPoints.Where(m => m.DataSourceId.HasValue && m.DataSourceId > 0 && m.DataSourceId < 9); if (metricsChartMogul.Any()) { // Setup objects for API call var client = GetHttpClient(_externalApi, externalApiAuth); // Call API to get all ChartMogul numbers. They can't take a range of a single day so we need to ask for two even though we only need one : / var response = await client.GetAsync(string.Format(_dataUrl, dataDate.AddDays(-1).ToString("yyyy-MM-dd"), dataDate.ToString("yyyy-MM-dd"))); if (response.IsSuccessStatusCode) { // Process resultant JSON string json = await response.Content.ReadAsStringAsync(); ChartMogulResponse results = JsonConvert.DeserializeObject <ChartMogulResponse>(json); resultantDataPoints.AddRange(ParseResults(results, dataDate, date, dataPoints)); } else { var errMsg = string.Format("{0}: {1}", _externalApi.Name, response.StatusCode); // Don't add the same error multiple times if (!metricDataImport.errors.Any(e => e.ErrorMessage == errMsg)) { var err = new JsonError { ErrorMessage = errMsg }; metricDataImport.errors.Add(err); } } } } } catch (Exception e) { metricDataImport.errors.Add(new JsonError { ErrorMessage = string.Format("{0}: {1}", _externalApi.Name, e.Message) }); } metricDataImport.results = resultantDataPoints; return(metricDataImport); }
public Task <MetricDataImport> GetData(int companyId, ExternalApiAuth externalApiAuth, AuthorizationCodeWebApp.AuthResult authResult, IEnumerable <MetricDataPoint> metricDataPoints) { throw new BusinessException("Not Implemented"); }
public async Task <MetricDataImport> GetData(int companyId, ExternalApiAuth externalApiAuth, IEnumerable <MetricDataPoint> metricDataPoints) { throw new BusinessException("Not Implemented"); }