Ejemplo n.º 1
0
        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);
            }
        }
Ejemplo n.º 2
0
        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));
        }
Ejemplo n.º 4
0
        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;
            }
        }
Ejemplo n.º 6
0
        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();
        }
Ejemplo n.º 7
0
        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)));
        }
Ejemplo n.º 8
0
        /// <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"));
        }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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));
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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)));
        }
Ejemplo n.º 14
0
        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>());
        }
Ejemplo n.º 15
0
        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);
        }
Ejemplo n.º 16
0
        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();
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        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);
            }
        }
Ejemplo n.º 19
0
        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);
        }
Ejemplo n.º 20
0
 public Task DeleteWorksheet(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO)
 {
     return(Task.Run(() => DeleteWorksheetImpl(spreadsheetUri, worksheetUri, authDTO)));
 }
Ejemplo n.º 21
0
        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>());
        }
Ejemplo n.º 22
0
 public Task <IEnumerable <TableRowDTO> > GetData(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO)
 {
     return(Task.Run(() => GetDataImpl(spreadsheetUri, worksheetUri, authDTO).ToArray() as IEnumerable <TableRowDTO>));
 }
Ejemplo n.º 23
0
 public Task <Dictionary <string, string> > GetWorksheetHeaders(string spreadsheetUri, string worksheetUri, GoogleAuthDTO authDTO)
 {
     return(Task.Run(() => EnumerateColumnHeaders(spreadsheetUri, worksheetUri, authDTO)));
 }
Ejemplo n.º 24
0
 public Task <Dictionary <string, string> > GetWorksheets(string spreadsheetUri, GoogleAuthDTO authDTO)
 {
     return(Task.Run(() => GetWorksheetsImpl(spreadsheetUri, authDTO)));
 }
Ejemplo n.º 25
0
 public Task <Dictionary <string, string> > GetSpreadsheets(GoogleAuthDTO authDTO)
 {
     return(Task.Run(() => GetSpreadsheetsImpl(authDTO).ToDictionary(x => x.Id.AbsoluteUri, x => x.Title.Text)));
 }
Ejemplo n.º 26
0
        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));
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public async Task DeleteSpreadSheet(string spreadSheetId, GoogleAuthDTO authDTO)
        {
            var driveService = await _googleDrive.CreateDriveService(authDTO);

            driveService.Files.Delete(spreadSheetId).Execute();
        }
Ejemplo n.º 28
0
        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));
        }
Ejemplo n.º 29
0
 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()
         });
     }
 }
Ejemplo n.º 30
0
 public Task WriteData(string spreadsheetUri, string worksheetUri, StandardTableDataCM data, GoogleAuthDTO authDTO)
 {
     return(Task.Run(() => WriteDataImpl(spreadsheetUri, worksheetUri, data, authDTO)));
 }