/// <summary> /// List all of the people in the specified collection /// documentation: https://developers.google.com/+/api/latest/people/list /// </summary> /// <param name="service"></param> /// <param name="_userId">Get the collection of people for the person identified. Use "me" to indicate the authenticated user.</param> /// <returns></returns> public static IList<Person> GetAllPeople(PlusService service, string _userId) { PeopleResource.ListRequest list = service.People.List(_userId, PeopleResource.ListRequest.CollectionEnum.Visible); list.MaxResults = 50; PeopleFeed peopleFeed = list.Execute(); IList<Person> people = new List<Person>(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null) { // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null) { break; } // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = list.Execute(); } return people; }
public static IList<Person> SearchPeopleLimitedPaging(PlusService service, string _query, int NumberOfPages, int ItemsPerPage, string NextPageToken) { PeopleFeed peopleFeed = null; PeopleResource.SearchRequest list = service.People.Search(_query); int count = 0; int max = ItemsPerPage; int iterate = NumberOfPages; list.PageToken = NextPageToken; list.MaxResults = max; try { peopleFeed = list.Execute(); count++; } catch { } IList<Person> people = new List<Person>(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null || count < iterate) { // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null || count >= iterate) { break; } // Execute and process the next page request peopleFeed = list.Execute(); count++; } Person token = new Person(); token.DisplayName = peopleFeed.NextPageToken; people.Add(token); return people; }
/// <summary> /// Creates friend edges within the model for each match between this user's visible people /// and others who already exist in the database. /// </summary> /// <param name="user">The user object to create friend edges for.</param> /// <param name="ps">The Google+ API client service.</param> /// <returns>None.</returns> static public void GenerateFriends(User user, PlusService ps) { // Get the PeopleFeed for the currently authenticated user using the Google+ API. PeopleResource.ListRequest lr = ps.People.List("me", PeopleResource.CollectionEnum.Visible); PeopleFeed pf = lr.Fetch(); PhotohuntContext db = new PhotohuntContext(); do { foreach (Person p in pf.Items) { // Check whether the friend has an account on PhotoHunt bool userExists = db.Users.Any(u => u.googleUserId.Equals(p.Id)); if (userExists) { // Check whether friend edge already exists. User friend = db.Users.First(f => f.googleUserId.Equals(p.Id)); bool edgeExists = db.Edges.Any(e => e.photohuntUserId == user.id && e.friendUserId == friend.id); // Only add new edges when the user exists on PhotoHunt and the edge doesn't // already exist if (!edgeExists && userExists && friend.id != user.id) { // Save the friend edges. DirectedUserToEdge fromFriendEdge = new DirectedUserToEdge(); fromFriendEdge.friendUserId = friend.id; fromFriendEdge.photohuntUserId = user.id; db.Edges.Add(fromFriendEdge); DirectedUserToEdge toFriendEdge = new DirectedUserToEdge(); toFriendEdge.friendUserId = user.id; toFriendEdge.photohuntUserId = friend.id; db.Edges.Add(toFriendEdge); db.SaveChanges(); } } } lr.PageToken = pf.NextPageToken; pf = lr.Fetch(); } while (pf.NextPageToken != null); }
public static IList<Person> PeopleListByActivityPaging(PlusService service, string _activityId, PeopleResource.ListByActivityRequest.CollectionEnum _type, int NumberOfPages, int ItemsPerPage, string NextPageToken) { int max = ItemsPerPage; int count = 0; int iterate = NumberOfPages; PeopleResource.ListByActivityRequest list = service.People.ListByActivity(_activityId, _type); list.MaxResults = max; PeopleFeed peopleFeed = list.Execute(); IList<Person> people = new List<Person>(); count++; //// Loop through until we arrive at an empty page while (peopleFeed.Items != null || count <= iterate) { // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null || count >= iterate) { break; } // Execute and process the next page request peopleFeed = list.Execute(); count++; } Person token = new Person(); token.DisplayName = peopleFeed.NextPageToken; people.Add(token); return people; }
/// <summary> /// Search all public profiles. /// Documentation: https://developers.google.com/+/api/latest/people/search /// </summary> /// <param name="service"></param> /// <param name="_query">Specify a query string for full text search of public text in all profiles.</param> /// <returns></returns> public static IList<Person> SearchPeople(PlusService service, string _query) { PeopleFeed peopleFeed = null; PeopleResource.SearchRequest list = service.People.Search(_query); list.MaxResults = 5; try { peopleFeed = list.Execute(); } catch { } IList<Person> people = new List<Person>(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null) { // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null) { break; } // Prepare the next page of results list.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = list.Execute(); } return people; }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.EndsWith("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.EndsWith("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Use the code exchange flow to get an access and refresh token. IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", CancellationToken.None).Result; // Create an authorization state from the returned token. context.Session["authState"] = token; // Get tokeninfo for the access token if you want to verify. Oauth2Service service = new Oauth2Service( new Google.Apis.Services.BaseClientService.Initializer()); Oauth2Service.TokeninfoRequest request = service.Tokeninfo(); request.AccessToken = token.AccessToken; Tokeninfo info = request.Execute(); string gplus_id = info.UserId; } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else if (context.Request.Path.Contains("/connect")) { // The user is already connected and credentials are cached. context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Write(JsonConvert.SerializeObject("Current user is already connected.")); return; } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. token = (TokenResponse)context.Session["authState"]; IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets, Scopes = SCOPES }); UserCredential credential = new UserCredential(flow, "me", token); bool success = credential.RefreshTokenAsync(CancellationToken.None).Result; token = credential.Token; ps = new PlusService( new Google.Apis.Services.BaseClientService.Initializer() { ApplicationName = ".NET Quickstart", HttpClientInitializer = credential }); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible).Execute(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. token = (TokenResponse)context.Session["authState"]; string tokenToRevoke = (token.RefreshToken != null) ? token.RefreshToken : token.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + token); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }
/// <summary> /// Processes the request based on the path. /// </summary> /// <param name="context">Contains the request and response.</param> public void ProcessRequest(HttpContext context) { // Redirect base path to signin. if (context.Request.Path.EndsWith("/")) { context.Response.RedirectPermanent("signin.ashx"); } // This is reached when the root document is passed. Return HTML // using index.html as a template. if (context.Request.Path.EndsWith("/signin.ashx")) { String state = (String)context.Session["state"]; // Store a random string in the session for verifying // the responses in our OAuth2 flow. if (state == null) { Random random = new Random((int)DateTime.Now.Ticks); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 13; i++) { builder.Append(Convert.ToChar( Convert.ToInt32(Math.Floor( 26 * random.NextDouble() + 65)))); } state = builder.ToString(); context.Session["state"] = state; } // Render the templated HTML. String templatedHTML = File.ReadAllText( context.Server.MapPath("index.html")); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID); templatedHTML = Regex.Replace(templatedHTML, "[{]{2}\\s*STATE\\s*[}]{2}", state); context.Response.ContentType = "text/html"; context.Response.Write(templatedHTML); return; } if (context.Session["authState"] == null) { // The connect action exchanges a code from the sign-in button, // verifies it, and creates OAuth2 credentials. if (context.Request.Path.Contains("/connect")) { // Get the code from the request POST body. StreamReader sr = new StreamReader( context.Request.InputStream); string code = sr.ReadToEnd(); string state = context.Request["state"]; // Test that the request state matches the session state. if (!state.Equals(context.Session["state"])) { context.Response.StatusCode = 401; return; } // Manually perform the OAuth2 flow for now. var authObject = ManualCodeExchanger.ExchangeCode(code); // Create an authorization state from the returned token. context.Session["authState"] = CreateState( authObject.access_token, authObject.refresh_token, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(authObject.expires_in)); string id_token = authObject.id_token; string[] segments = id_token.Split('.'); string base64EncoodedJsonBody = segments[1]; int mod4 = base64EncoodedJsonBody.Length % 4; if (mod4 > 0) { base64EncoodedJsonBody += new string( '=', 4 - mod4 ); } byte[] encodedBodyAsBytes = System.Convert.FromBase64String(base64EncoodedJsonBody); string json_body = System.Text.Encoding.UTF8.GetString(encodedBodyAsBytes); IDTokenJsonBodyObject bodyObject = JsonConvert.DeserializeObject <IDTokenJsonBodyObject>(json_body); string gplus_id = bodyObject.sub; } else { // No cached state and we are not connecting. context.Response.StatusCode = 400; return; } } else if (context.Request.Path.Contains("/connect")) { // The user is already connected and credentials are cached. context.Response.ContentType = "application/json"; context.Response.StatusCode = 200; context.Response.Write(JsonConvert.SerializeObject("Current user is already connected.")); return; } else { // Register the authenticator and construct the Plus service // for performing API calls on behalf of the user. _authState = (IAuthorizationState)context.Session["authState"]; AuthorizationServerDescription description = GoogleAuthenticationServer.Description; var provider = new WebServerClient(description); provider.ClientIdentifier = CLIENT_ID; provider.ClientSecret = CLIENT_SECRET; var authenticator = new OAuth2Authenticator <WebServerClient>( provider, GetAuthorization) { NoCaching = true }; ps = new PlusService(new BaseClientService.Initializer() { Authenticator = authenticator }); } // Perform an authenticated API request to retrieve the list of // people that the user has made visible to the app. if (context.Request.Path.Contains("/people")) { // Get the PeopleFeed for the currently authenticated user. PeopleFeed pf = ps.People.List("me", PeopleResource.CollectionEnum.Visible).Fetch(); // This JSON, representing the people feed, will later be // parsed by the JavaScript client. string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(pf); context.Response.ContentType = "application/json"; context.Response.Write(jsonContent); return; } // Disconnect the user from the application by revoking the tokens // and removing all locally stored data associated with the user. if (context.Request.Path.Contains("/disconnect")) { // Perform a get request to the token endpoint to revoke the // refresh token. _authState = (IAuthorizationState)context.Session["authState"]; string token = (_authState.RefreshToken != null) ? _authState.RefreshToken : _authState.AccessToken; WebRequest request = WebRequest.Create( "https://accounts.google.com/o/oauth2/revoke?token=" + token); WebResponse response = request.GetResponse(); // Remove the cached credentials. context.Session["authState"] = null; // You could reset the state in the session but you must also // reset the state on the client. // context.Session["state"] = null; context.Response.Write( response.GetResponseStream().ToString().ToCharArray()); return; } }