public Uri GetOAuthCalculatedAuthorizationUri(Uri callbackUri) { var apiSecret = ConfigurationManager.AppSettings["VideoApiSecret"] ?? "nnb4e_-c3TSKzf8kmwrgp5wr"; var parameters = new OAuth2Parameters { ClientId = _apiKey, ClientSecret = apiSecret, Scope = "http://gdata.youtube.com", }; var authenticator = new OAuth2Authenticator("BandApp", parameters); return authenticator.ApplyAuthenticationToUri(callbackUri); }
public void DoWorkbookUpload(object in_instance) { var instance = in_instance as Google2uData; if (instance == null) return; if (!string.IsNullOrEmpty(instance.WorkbookUploadPath)) { try { // We need a DocumentService var service = new DocumentsService("Google2Unity"); var mimeType = Google2uMimeType.GetMimeType(instance.WorkbookUploadPath); var authenticator = new OAuth2Authenticator("Google2Unity", _authParameters); // Instantiate a DocumentEntry object to be inserted. var entry = new DocumentEntry { MediaSource = new MediaFileSource(instance.WorkbookUploadPath, mimeType) }; // Define the resumable upload link var createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); var link = new AtomLink(createUploadUrl.AbsoluteUri) { Rel = ResumableUploader.CreateMediaRelation }; entry.Links.Add(link); // Set the service to be used to parse the returned entry entry.Service = service; // Instantiate the ResumableUploader component. var uploader = new ResumableUploader(); // Set the handlers for the completion and progress events uploader.AsyncOperationCompleted += OnSpreadsheetUploadDone; uploader.AsyncOperationProgress += OnSpreadsheetUploadProgress; // Start the upload process uploader.InsertAsync(authenticator, entry, instance); } catch (Exception) { PushNotification( "There is a problem with your credentials. Clear the credentials and Re-Authorize G2U"); //instance.Messages.Add(new G2GUIMessage(GFGUIMessageType.InvalidLogin, ex.Message)); instance.Commands.Remove(GFCommand.WaitingForUpload); } } }
public static void CreateGoogleNote(/*Document parentFolder, */Document googleNote, object UserData, DocumentsRequest documentsRequest, ResumableUploader uploader, OAuth2Authenticator authenticator) { // Define the resumable upload link Uri createUploadUrl = new Uri("https://docs.google.com/feeds/upload/create-session/default/private/full"); //Uri createUploadUrl = new Uri(GoogleNotesFolder.AtomEntry.EditUri.ToString()); AtomLink link = new AtomLink(createUploadUrl.AbsoluteUri); link.Rel = ResumableUploader.CreateMediaRelation; googleNote.DocumentEntry.Links.Add(link); //if (parentFolder != null) // googleNote.DocumentEntry.ParentFolders.Add(new AtomLink(parentFolder.DocumentEntry.SelfUri.ToString())); // Set the service to be used to parse the returned entry googleNote.DocumentEntry.Service = documentsRequest.Service; // Start the upload process //uploader.InsertAsync(_authenticator, match.GoogleNote.DocumentEntry, new object()); uploader.InsertAsync(authenticator, googleNote.DocumentEntry, UserData); }
public void LoginToGoogle(string username) { Logger.Log("Connecting to Google...", EventType.Information); if (ContactsRequest == null && SyncContacts || DocumentsRequest == null && SyncNotes || EventRequest == null & SyncAppointments) { //OAuth2 for all services List<String> scopes = new List<string>(); //Contacts-Scope scopes.Add("https://www.google.com/m8/feeds"); //Notes-Scope scopes.Add("https://docs.google.com/feeds/"); //scopes.Add("https://docs.googleusercontent.com/"); //scopes.Add("https://spreadsheets.google.com/feeds/"); //Calendar-Scope //scopes.Add("https://www.googleapis.com/auth/calendar"); scopes.Add(CalendarService.Scope.Calendar); //take user credentials UserCredential credential; //load client secret from ressources byte[] jsonSecrets = Properties.Resources.client_secrets; //using (var stream = new FileStream(Application.StartupPath + "\\client_secrets.json", FileMode.Open, FileAccess.Read)) using (var stream = new MemoryStream(jsonSecrets)) { FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true); GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream); credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync( clientSecrets.Secrets, scopes.ToArray(), username, CancellationToken.None, fDS). Result; var initializer = new Google.Apis.Services.BaseClientService.Initializer(); initializer.HttpClientInitializer = credential; OAuth2Parameters parameters = new OAuth2Parameters { ClientId = clientSecrets.Secrets.ClientId, ClientSecret = clientSecrets.Secrets.ClientSecret, // Note: AccessToken is valid only for 60 minutes AccessToken = credential.Token.AccessToken, RefreshToken = credential.Token.RefreshToken }; Logger.Log(Application.ProductName, EventType.Information); RequestSettings settings = new RequestSettings( Application.ProductName, parameters); if (SyncContacts) { //ContactsRequest = new ContactsRequest(rs); ContactsRequest = new ContactsRequest(settings); } if (SyncNotes) { //DocumentsRequest = new DocumentsRequest(rs); DocumentsRequest = new DocumentsRequest(settings); //Instantiate an Authenticator object according to your authentication, to use ResumableUploader //GDataCredentials cred = new GDataCredentials(credential.Token.AccessToken); //GOAuth2RequestFactory rf = new GOAuth2RequestFactory(null, Application.ProductName, parameters); //DocumentsRequest.Service.RequestFactory = rf; authenticator = new OAuth2Authenticator(Application.ProductName, parameters); } if (SyncAppointments) { //ContactsRequest = new Google.Contacts.ContactsRequest() var CalendarRequest = new CalendarService(initializer); //CalendarRequest.setUserCredentials(username, password); calendarList = CalendarRequest.CalendarList.List().Execute().Items; //Get Primary Calendar, if not set from outside if (string.IsNullOrEmpty(SyncAppointmentsGoogleFolder)) foreach (var calendar in calendarList) { if (calendar.Primary != null && calendar.Primary.Value) { SyncAppointmentsGoogleFolder = calendar.Id; break; } } if (SyncAppointmentsGoogleFolder == null) throw new Exception("Google Calendar not defined (primary not found)"); //EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full"); //Old v2 approach: EventQuery query = new EventQuery("https://www.googleapis.com/calendar/v3/calendars/default/events"); EventRequest = CalendarRequest.Events; } } } Synchronizer.UserName = username; int maxUserIdLength = Synchronizer.OutlookUserPropertyMaxLength - (Synchronizer.OutlookUserPropertyTemplate.Length - 3 + 2);//-3 = to remove {0}, +2 = to add length for "id" or "up" string userId = username; if (userId.Length > maxUserIdLength) userId = userId.GetHashCode().ToString("X"); //if a user id would overflow UserProperty name, then use that user id hash code as id. //Remove characters not allowed for Outlook user property names: []_# userId = userId.Replace("#", "").Replace("[", "").Replace("]", "").Replace("_", ""); OutlookPropertyPrefix = string.Format(Synchronizer.OutlookUserPropertyTemplate, userId); }
public void CreateNewNote() { string gmailUsername; string syncProfile; GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile); DocumentsRequest service; var scopes = new List<string>(); //Contacts-Scope scopes.Add("https://www.google.com/m8/feeds"); //Notes-Scope scopes.Add("https://docs.google.com/feeds/"); //scopes.Add("https://docs.googleusercontent.com/"); //scopes.Add("https://spreadsheets.google.com/feeds/"); //Calendar-Scope //scopes.Add("https://www.googleapis.com/auth/calendar"); scopes.Add(CalendarService.Scope.Calendar); UserCredential credential; byte[] jsonSecrets = Properties.Resources.client_secrets; using (var stream = new MemoryStream(jsonSecrets)) { FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true); GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream); credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync( clientSecrets.Secrets, scopes.ToArray(), gmailUsername, CancellationToken.None, fDS). Result; OAuth2Parameters parameters = new OAuth2Parameters { ClientId = clientSecrets.Secrets.ClientId, ClientSecret = clientSecrets.Secrets.ClientSecret, // Note: AccessToken is valid only for 60 minutes AccessToken = credential.Token.AccessToken, RefreshToken = credential.Token.RefreshToken }; RequestSettings settings = new RequestSettings("GoContactSyncMod", parameters); service = new DocumentsRequest(settings); //Instantiate an Authenticator object according to your authentication, to use ResumableUploader _authenticator = new OAuth2Authenticator("GCSM Unit Tests", parameters); } //Delete previously created test note. DeleteTestNote(service); Document newEntry = new Document(); newEntry.Type = Document.DocumentType.Document; newEntry.Title = "AN_OUTLOOK_TEST_NOTE"; string file = NotePropertiesUtils.CreateNoteFile("AN_OUTLOOK_TEST_NOTE", "This is just a test note to test GoContactSyncMod", null); newEntry.MediaSource = new MediaFileSource(file, MediaFileSource.GetContentTypeForFileName(file)); #region normal flow, only working to create documents without content (metadata only), e.g. for Notes folder Document createdEntry = Synchronizer.SaveGoogleNote(null, newEntry, service); Assert.IsNotNull(createdEntry.DocumentEntry.Id.Uri); Logger.Log("Created Google note", EventType.Information); //Wait 5 seconds to give the testcase the chance to finish System.Threading.Thread.Sleep(5000); //delete test note DeleteTestNote(service); #endregion #region workaround flow to use UploadDocument, not needed anymore because of new approach to use ResumableUploader //Google.GData.Documents.DocumentEntry createdEntry2 = service.Service.UploadDocument(file, newEntry.Title); //Assert.IsNotNull(createdEntry2.Id.Uri); ////delete test note //DeleteTestNote(service); #endregion #region New approach how to update an existing document: https://developers.google.com/google-apps/documents-list/#updatingchanging_documents_and_files //Instantiate the ResumableUploader component. ResumableUploader uploader = new ResumableUploader(); uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnGoogleNoteCreated); Synchronizer.CreateGoogleNote(newEntry, file, service, uploader, _authenticator); #endregion //Wait 5 seconds to give the testcase the chance to finish the Async events System.Threading.Thread.Sleep(5000); DeleteTestNote(service); }