public async Task CreateFr8TriggerForDocument(GoogleAuthDTO authDTO, string formId, string email) { try { //allow edit permissions to our main google account on current form in Google Drive await AllowPermissionsForGoogleDriveFile(authDTO, formId); // run apps script deployed as web app to create trigger for this form _googleAuth.CreateFlowMetadata(authDTO, "", CloudConfigurationManager.GetSetting("GoogleRedirectUri")); var appScriptUrl = CloudConfigurationManager.GetSetting("GoogleAppScriptWebApp"); var formEventWebServerUrl = CloudConfigurationManager.GetSetting("GoogleFormEventWebServerUrl"); appScriptUrl = string.Format(appScriptUrl + "?formId={0}&endpoint={1}&email={2}", formId, formEventWebServerUrl, email); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authDTO.AccessToken); var responseMessage = await client.GetAsync(new Uri(appScriptUrl)); await responseMessage.Content.ReadAsStringAsync(); } catch (Exception e) { //in case of error generate script link for user throw new Exception(e.Message); } }
public AppFlowMetadata(GoogleAuthDTO googleToken, string email = null, string callbackUrl = null) { _googleAuth = googleToken; _email = email; _authCallbackUrl = callbackUrl; }
public GOAuth2RequestFactory CreateRequestFactory(GoogleAuthDTO authDTO) { var parameters = CreateOAuth2Parameters(accessToken: authDTO.AccessToken, refreshToken: authDTO.RefreshToken); // Initialize the variables needed to make the request return(new GOAuth2RequestFactory(null, "fr8", parameters)); }
public async Task <GmailService> CreateGmailService(GoogleAuthDTO authDTO) { var flowData = _googleAuth.CreateFlowMetadata(authDTO, "", CloudConfigurationManager.GetSetting("GoogleRedirectUri")); TokenResponse tokenResponse = new TokenResponse(); tokenResponse.AccessToken = authDTO.AccessToken; tokenResponse.RefreshToken = authDTO.RefreshToken; tokenResponse.Scope = CloudConfigurationManager.GetSetting("GoogleScope"); UserCredential userCredential; try { userCredential = new UserCredential(flowData.Flow, authDTO.AccessToken, tokenResponse); } catch (Exception ex) { throw new Exception(ex.Message); } var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = userCredential, ApplicationName = "Fr8", }); return(service); }
/// <summary> /// Checks google token validity /// </summary> /// <param name="googleAuthDTO"></param> /// <returns></returns> public async Task <bool> IsTokenInfoValid(GoogleAuthDTO googleAuthDTO) { try { // Checks token for expiration local if (googleAuthDTO.Expires - DateTime.Now < TimeSpan.FromMinutes(5) && string.IsNullOrEmpty(googleAuthDTO.RefreshToken)) { var message = "Google access token is expired. Token refresh will be executed"; //EventManager.TokenValidationFailed(JsonConvert.SerializeObject(googleAuthDTO), message); Logger.GetLogger().Error(message); return(false); } // To validate token, we just need to make a get request to the GoogleTokenInfo url. // We don't need result of this response, because if token is valid, there are no useful info for us; // if token is invalid, request fails with error code 400 and we catches this error below. var url = CloudConfigurationManager.GetSetting("GoogleTokenInfo"); url = url.Replace("%TOKEN%", googleAuthDTO.AccessToken); await _client.GetAsync(new Uri(url)); return(true); } catch (Exception exception) { if (exception is RestfulServiceException || exception is WebException) { var message = "Google token validation fails with error: " + exception.Message; //EventManager.TokenValidationFailed(JsonConvert.SerializeObject(googleAuthDTO), message); Logger.GetLogger().Error(message); return(false); } throw; } }
private async Task AllowPermissionsForGoogleDriveFile(GoogleAuthDTO authDTO, string fileId) { //create google drive service for file manipulation var driveService = await _googleDrive.CreateDriveService(authDTO); var batch = new BatchRequest(driveService); //bach service callback for successfull permission set BatchRequest.OnResponse <Permission> callback = delegate( Permission permission, RequestError error, int index, HttpResponseMessage message){ if (error != null) { // Handle error throw new ApplicationException($"Problem with Google Drive Permissions: {error.Message}"); } }; var userPermission = new Permission { Type = "user", Role = "writer", EmailAddress = CloudConfigurationManager.GetSetting("GoogleMailAccount") }; var request = driveService.Permissions.Create(userPermission, fileId); request.Fields = "id"; batch.Queue(request, callback); await batch.ExecuteAsync(); }
private SpreadsheetEntry FindSpreadsheet(string spreadsheetUri, GoogleAuthDTO authDTO) { var spreadsheets = GetSpreadsheetsImpl(authDTO); return(spreadsheetUri.ToLower().Contains("http") ? spreadsheets.SingleOrDefault(ae => string.Equals(ae.Id.AbsoluteUri, spreadsheetUri)) : spreadsheets.SingleOrDefault(ae => ae.Id.AbsoluteUri.Contains(spreadsheetUri))); }
/// <summary> /// This is manual approach for creating Fr8 trigger for some document, mainly used as backup plan for automatic apps script run /// </summary> /// <param name="authDTO"></param> /// <param name="formId"></param> /// <param name="desription"></param> /// <returns></returns> public async Task <string> CreateManualFr8TriggerForDocument(GoogleAuthDTO authDTO, string formId, string desription = "Script uploaded from Fr8 application") { string response = ""; try { var driveService = await _googleDrive.CreateDriveService(authDTO); var formFilename = FormFilename(driveService, formId); Google.Apis.Drive.v3.Data.File scriptFile = new Google.Apis.Drive.v3.Data.File(); scriptFile.Name = "Script for: " + formFilename; scriptFile.Description = desription; scriptFile.MimeType = "application/vnd.google-apps.script+json"; // Create a memory stream using (MemoryStream memoryStream = new MemoryStream()) { //load template file and replace specific formID var assembly = Assembly.GetExecutingAssembly(); var resourceName = "terminalGoogle.Template.googleAppScriptFormResponse.json"; string content; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { content = reader.ReadToEnd(); } content = content.Replace("@ID", formId); content = content.Replace("@ENDPOINT", CloudConfigurationManager.GetSetting("GoogleFormEventWebServerUrl")); byte[] contentAsBytes = Encoding.UTF8.GetBytes(content); memoryStream.Write(contentAsBytes, 0, contentAsBytes.Length); // Set the position to the beginning of the stream. memoryStream.Seek(0, SeekOrigin.Begin); //upload file to google drive string existingFileLink = ""; if (!_googleDrive.FileExist(driveService, scriptFile.Name, out existingFileLink)) { FilesResource.CreateMediaUpload request = driveService.Files.Create(scriptFile, memoryStream, "application/vnd.google-apps.script+json"); request.Upload(); response = request.ResponseBody.WebViewLink; } else { response = existingFileLink; } } } catch (Exception e) { throw new Exception(e.Message); } return(await Task.FromResult(response)); }
public async Task <string> GetExternalUserId(GoogleAuthDTO googleAuthDTO) { var url = CloudConfigurationManager.GetSetting("GoogleUserProfileUrl"); url = url.Replace("%TOKEN%", googleAuthDTO.AccessToken); var jsonObj = await _client.GetAsync <JObject>(new Uri(url)); return(jsonObj.Value <string>("email")); }
public GoogleAuthDTO RefreshToken(GoogleAuthDTO googleAuthDTO) { var parameters = CreateOAuth2Parameters( accessToken: googleAuthDTO.AccessToken, refreshToken: googleAuthDTO.RefreshToken); OAuthUtil.RefreshAccessToken(parameters); googleAuthDTO.AccessToken = parameters.AccessToken; googleAuthDTO.Expires = parameters.TokenExpiry; return(googleAuthDTO); }
private Dictionary <string, string> GetWorksheetsImpl(string spreadsheetUri, GoogleAuthDTO authDTO) { var spreadsheet = FindSpreadsheet(spreadsheetUri, authDTO); if (spreadsheet == null) { throw new ArgumentException("Cannot find a spreadsheet", nameof(spreadsheetUri)); } var wsFeed = spreadsheet.Worksheets; return(wsFeed.Entries.ToDictionary(item => item.Id.AbsoluteUri, item => item.Title.Text)); }
public async Task <string> CreateGoogleForm(GoogleAuthDTO authDTO, string title) { var driveService = await CreateDriveService(authDTO); var file = new Google.Apis.Drive.v3.Data.File(); file.Name = title; file.MimeType = "application/vnd.google-apps.form"; var request = driveService.Files.Create(file); var result = request.Execute(); return(result.Id); }
public async Task <Dictionary <string, string> > GetGoogleForms(GoogleAuthDTO authDTO) { var driveService = await CreateDriveService(authDTO); // Define parameters of request. FilesResource.ListRequest listRequest = driveService.Files.List(); listRequest.Q = "mimeType = 'application/vnd.google-apps.form' and trashed = false"; // List files. FileList fileList = listRequest.Execute(); IList <Google.Apis.Drive.v3.Data.File> files = fileList.Files; return(await Task.FromResult(files.ToDictionary(a => a.Id, a => a.Name))); }
private IEnumerable <SpreadsheetEntry> GetSpreadsheetsImpl(GoogleAuthDTO authDTO) { GOAuth2RequestFactory requestFactory = _googleIntegration.CreateRequestFactory(authDTO); SpreadsheetsService service = new SpreadsheetsService("fr8"); service.RequestFactory = requestFactory; // Instantiate a SpreadsheetQuery object to retrieve spreadsheets. SpreadsheetQuery query = new SpreadsheetQuery(); // Make a request to the API and get all spreadsheets. SpreadsheetFeed feed = service.Query(query); return(feed.Entries.Cast <SpreadsheetEntry>()); }
public async Task <string> CreateSpreadsheet(string spreadsheetname, GoogleAuthDTO authDTO) { var driveService = await _googleDrive.CreateDriveService(authDTO); var file = new Google.Apis.Drive.v3.Data.File(); file.Name = spreadsheetname; file.Description = $"Created via Fr8 at {DateTime.Now}"; file.MimeType = "application/vnd.google-apps.spreadsheet"; var request = driveService.Files.Create(file); var result = request.Execute(); return(result.Id); }
private void DeleteWorksheetImpl(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { var spreadsheet = FindSpreadsheet(spreadsheetUri, authDTO); if (spreadsheet == null) { throw new ArgumentException("Cannot find a spreadsheet", nameof(spreadsheetUri)); } var worksheet = spreadsheet.Worksheets.Entries.FindById(new AtomId(worksheetUri)); if (worksheet == null) { throw new ArgumentException("Cannot find a worksheet", nameof(worksheetUri)); } worksheet.Delete(); }
public async Task <string> DownloadFile(string fileId, GoogleAuthDTO authDTO) { var driveService = await CreateDriveService(authDTO); var getRequest = driveService.Files.Get(fileId); var file = await getRequest.ExecuteAsync(); var downloadUlr = string.Format("https://www.googleapis.com/drive/v3/files/{0}", file.Id); string fileContent; using (var httpClient = new HttpClient()) { fileContent = await httpClient.GetStringAsync(downloadUlr); } return(fileContent); }
public async Task <List <GoogleFormField> > GetGoogleFormFields(GoogleAuthDTO authDTO, string formId) { try { //allow edit permissions to our main google account on current form in Google Drive await AllowPermissionsForGoogleDriveFile(authDTO, formId); // run apps script deployed as web app to return form fields as json object _googleAuth.CreateFlowMetadata(authDTO, "", CloudConfigurationManager.GetSetting("GoogleRedirectUri")); var appScriptUrl = CloudConfigurationManager.GetSetting("GoogleAppScriptWebApp"); appScriptUrl = string.Format(appScriptUrl + "?formId={0}&action={1}", formId, "getFormFields"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authDTO.AccessToken); //check received response var responseMessage = await client.GetAsync(new Uri(appScriptUrl)); var contents = await responseMessage.Content.ReadAsStringAsync(); var googleForm = new GoogleForm(); JsonConvert.PopulateObject(contents, googleForm); var result = new List <GoogleFormField>(); foreach (var item in googleForm.FormFields) { result.Add(new GoogleFormField() { Id = item.Id, Title = item.Title, Index = item.Index, Type = item.Type, }); } return(await Task.FromResult(result)); } catch (Exception e) { //in case of error generate script link for user throw new Exception(e.Message); } }
private string CreateWorksheetImpl(string spreadsheetUri, GoogleAuthDTO authDTO, string worksheetname) { var spreadsheet = FindSpreadsheet(spreadsheetUri, authDTO); if (spreadsheet == null) { throw new ArgumentException("Cannot find a spreadsheet", nameof(spreadsheetUri)); } var service = (SpreadsheetsService)spreadsheet.Service; var newWorksheet = new WorksheetEntry(2000, 100, worksheetname); var wfeed = spreadsheet.Worksheets; newWorksheet = service.Insert(wfeed, newWorksheet); return(newWorksheet.Id.AbsoluteUri); }
public Task DeleteWorksheet(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { return(Task.Run(() => DeleteWorksheetImpl(spreadsheetUri, worksheetUri, authDTO))); }
private IEnumerable <ListEntry> EnumerateRows(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { var spreadsheet = FindSpreadsheet(spreadsheetUri, authDTO); if (spreadsheet == null) { throw new ArgumentException("Cannot find a spreadsheet", nameof(spreadsheetUri)); } var service = (SpreadsheetsService)spreadsheet.Service; // Get the first worksheet of the spreadsheet. var wsFeed = spreadsheet.Worksheets; var worksheet = string.IsNullOrEmpty(worksheetUri) ? (WorksheetEntry)wsFeed.Entries[0] : (WorksheetEntry)wsFeed.Entries.FindById(new AtomId(worksheetUri)); worksheet = worksheet ?? (WorksheetEntry)wsFeed.Entries[0]; // Define the URL to request the list feed of the worksheet. var listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); // Fetch the list feed of the worksheet. var listQuery = new ListQuery(listFeedLink.HRef.ToString()); var listFeed = service.Query(listQuery); return(listFeed.Entries.Cast <ListEntry>()); }
public Task <IEnumerable <TableRowDTO> > GetData(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { return(Task.Run(() => GetDataImpl(spreadsheetUri, worksheetUri, authDTO).ToArray() as IEnumerable <TableRowDTO>)); }
public Task <Dictionary <string, string> > GetWorksheetHeaders(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { return(Task.Run(() => EnumerateColumnHeaders(spreadsheetUri, worksheetUri, authDTO))); }
public Task <Dictionary <string, string> > GetWorksheets(string spreadsheetUri, GoogleAuthDTO authDTO) { return(Task.Run(() => GetWorksheetsImpl(spreadsheetUri, authDTO))); }
public Task <Dictionary <string, string> > GetSpreadsheets(GoogleAuthDTO authDTO) { return(Task.Run(() => GetSpreadsheetsImpl(authDTO).ToDictionary(x => x.Id.AbsoluteUri, x => x.Title.Text))); }
private void WriteDataImpl(string spreadsheetUri, string worksheetUri, StandardTableDataCM data, GoogleAuthDTO authDTO) { if (String.IsNullOrEmpty(spreadsheetUri)) { throw new ArgumentNullException("Spreadsheet Uri parameter is required."); } if (string.IsNullOrEmpty(worksheetUri)) { throw new ArgumentNullException("Worksheet Uri parameter is required."); } if (data != null && data.Table.Count > 0) { int MAX_ROWS = data.Table.Count; int MAX_COLS = data.Table[0].Row.Count; SpreadsheetEntry spreadsheet = FindSpreadsheet(spreadsheetUri, authDTO); if (spreadsheet == null) { throw new ArgumentException("Cannot find a spreadsheet", "spreadsheetUri"); } SpreadsheetsService service = (SpreadsheetsService)spreadsheet.Service; string worksheetId = worksheetUri.Substring(worksheetUri.LastIndexOf('/') + 1, worksheetUri.Length - (worksheetUri.LastIndexOf('/') + 1)); string spreadSheetId = spreadsheetUri; if (spreadSheetId.ToLower().Contains("http"))//remove http url { spreadSheetId = spreadSheetId.Substring(spreadSheetId.LastIndexOf('/') + 1, spreadSheetId.Length - (spreadSheetId.LastIndexOf('/') + 1)); } CellQuery cellQuery = new CellQuery(spreadSheetId, worksheetId, "private", "full"); CellFeed cellFeed = service.Query(cellQuery); // Build list of cell addresses to be filled in List <CellAddress> cellAddrs = new List <CellAddress>(); for (int row = 0; row < MAX_ROWS; row++) { for (int col = 0; col < MAX_COLS; col++) { cellAddrs.Add(new CellAddress(row + 1, col + 1, data.Table[row].Row[col].Cell.Value)); } } // Prepare the update // GetCellEntryMap is what makes the update fast. Dictionary <String, CellEntry> cellEntries = GetCellEntryMap(service, cellFeed, cellAddrs); CellFeed batchRequest = new CellFeed(cellQuery.Uri, service); foreach (CellAddress cellAddr in cellAddrs) { CellEntry batchEntry = cellEntries[cellAddr.IdString]; batchEntry.InputValue = cellAddr.InputValue; batchEntry.BatchData = new GDataBatchEntryData(cellAddr.IdString, GDataBatchOperationType.update); batchRequest.Entries.Add(batchEntry); } // Submit the update CellFeed batchResponse = (CellFeed)service.Batch(batchRequest, new Uri(cellFeed.Batch)); // Check the results foreach (CellEntry entry in batchResponse.Entries) { string batchId = entry.BatchData.Id; if (entry.BatchData.Status.Code != 200) { GDataBatchStatus status = entry.BatchData.Status; throw new Exception(string.Format("{0} failed ({1})", batchId, status.Reason)); } } } }
public async Task DeleteSpreadSheet(string spreadSheetId, GoogleAuthDTO authDTO) { var driveService = await _googleDrive.CreateDriveService(authDTO); driveService.Files.Delete(spreadSheetId).Execute(); }
private Dictionary <string, string> EnumerateColumnHeaders(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { var firstRow = EnumerateRows(spreadsheetUri, worksheetUri, authDTO).FirstOrDefault(); if (firstRow == null) { return(new Dictionary <string, string>()); } return(firstRow.Elements.Cast <ListEntry.Custom>().ToDictionary(e => e.LocalName, e => e.Value)); }
private IEnumerable <TableRowDTO> GetDataImpl(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO) { foreach (var row in EnumerateRows(spreadsheetUri, worksheetUri, authDTO)) { yield return(new TableRowDTO { Row = row.Elements .Cast <ListEntry.Custom>() .Select(c => new TableCellDTO { Cell = new KeyValueDTO(c.LocalName, c.Value) }) .ToList() }); } }
public Task WriteData(string spreadsheetUri, string worksheetUri, StandardTableDataCM data, GoogleAuthDTO authDTO) { return(Task.Run(() => WriteDataImpl(spreadsheetUri, worksheetUri, data, authDTO))); }