Get Gmail User Profile Picture and Name with Google API client - ruby

The Google API client has Class: Google::Apis::PeopleV1::Name and Google::Apis::PeopleV1::Photo how do I hit these endpoints? I tried
p = Google::Apis::PeopleV1::Photo.new
response = p.url
But it returns nil. Opposed to this GmailService has instance methods like get_user_message which I can call like this
#service = Google::Apis::GmailV1::GmailService.new
# authorization is done
response = #service.get_user_message(user_id, message_id)
It returns a response object which has the message, now I want to fetch the User's name and Photo, but I did not find any method to access this information. How do I retrieve the User's name and photo using the API client?

I think that the value retrieved with the method of users.messages.get in Gmail API doesn't include "User Profile Picture". Ref So for example, in order to retrieve the URL of user's profile photo, how about using the method of people.connections.list in People API? The sample script is as follows.
Sample script:
service = Google::Apis::PeopleV1::PeopleServiceService.new
service.authorization = authorize
response = service.list_person_connections(
'people/me',
'page_size': 1000,
'person_fields': "names,emailAddresses,photos"
)
puts "No connections" if response.connections.empty?
result = response.connections.map {|person| {
'resourceName': person.resource_name,
'email': person.email_addresses[0].value,
'photos': person.photos.map {|e| e.url}
}}
puts result
Result:
When above script is run, the following result is returned.
[
{"resourceName": "people/###", "email": "###", "photos": ["https://###"]},
{"resourceName": "people/###", "email": "###", "photos": ["https://###", "https://###"]},
,
,
,
]
The URLs of phtots are the URLs of the user's photo images.
Note:
In this case, it seems that the method of otherContacts.list doesn't return the user's photo data.
Reference:
Method: people.connections.list

Related

Freebusy google API not getting returned with or w/o a key

As can be seen, Ihave read/write access to google calendar (sensitive scope). I want to also have access to freebusy scope of google calendar (not sensitive).
I followed the same steps but just provided a written justification instead of video as it's not sensitive as only sensitive scopes require one. Nonetheless, I am not getting granted permission nor are there any signs that's even being processed as it's been weeks. What shall I do?
I only see this on my dashboard which is for the other scope & feel like is the reason why the new scope is not getting reviewed despite my resubmission.
I know I have not been approved as the green check isn't displayed beside freebusy unlike auth/calendar
Currently, when I call the API:
Code:
def busyTimes():
"""
returns busy time of the user in a day
"""
body = {
"timeMin":datetime.now(timezone.utc).astimezone().isoformat(),
"timeMax": '2021-03-27T21:27:58.945714-04:00',
"items": [
{
"id": "....#group.calendar.google.com"
}
]
}
req = requests.post(url='https://www.googleapis.com/calendar/v3/freeBusy', data = body)
req_ = req.json()
return str(req_)
I would get:
{'error': {'code': 403, 'message': 'The request is missing a valid API key.', 'errors': [{'message': 'The request is missing a valid API key.', 'domain': 'global', 'reason': 'forbidden'}], 'status': 'PERMISSION_DENIED'}}
& if I were to include API key along the request.post() parameter I would get:
TypeError: request() got an unexpected keyword argument 'key'
and if I include it after the link like:
https://www.googleapis.com/calendar/v3/freeBusy?<apiKey>
I would get:
{'error': {'errors': [{'domain': 'global', 'reason': 'badRequest', 'message': 'Bad Request'}], 'code': 400, 'message': 'Bad Request'}}
P.S: the doc didn't doc even mention to include API.

Speed up Ruby class to avoid requests to JIRA and Slack API

My, pure Ruby, class pull out user names from Jira API to convert it into email address and pass these email addresses to another class based on which Slack ID is extracted.
module Request
class GetUser
def call
setup_email
end
private
def setup_email
devops_email = dev_role['actors'].map { |user| "#{user['name']}#example.com" }
devops_email.each do |email|
::Slack::GetUserId.new(email: email).call
end
end
def dev_role
HTTParty.get('https://company_name.atlassian.net/rest/api/3/project/1234/role/1234',
basic_auth: { username: 'user', password: 'pass' },
headers: { 'content-type' => 'application/json' })
end
end
end
Because above class will be called every day (AWS Lambda schedule), I want to speed up the class. What should I use to achieve that? Should I use some database (Dynamodb probably?) to save user data (userID and user email) and make a query to check if the data (e.g. user name) has changed?
Or maybe should I change some implementation and leave these requests without saving data to the database?

How to authenticate GitHub with HTTParty to scrape a page?

I'm trying to scrape this page:
https://github.com/search?p=1&q=https%3A%2F%2Fsonarcloud.io%2Fdashboard&type=Code
and I need to authenticate with my email and password.
I have tried to do that:
auth = {:usarname => "username", :password => "password"}
a = HTTParty.get(url, :basic_auth)
but this didn't authenticate me as expected.
Why isn't this working, and how can I fix it?
I want retrive that information, and isn't available on the Github API:
Don't scrape GitHub. Scraping is fragile, and very awkward with sites that make heavy use of JavaScript.
Use its API instead:
https://api.github.com/search/code?q=https%3A%2F%2Fsonarcloud.io%2Fdashboard
To search across all repositories you'll still need to authenticate, though. You need to pass your auth hash into HTTParty.get():
auth = {:username => "username", :password => "password"}
a = HTTParty.get(url, :basic_auth => auth)
# ^ Here
More idiomatically, this might look like
auth = {username: "username", password: "password"}
a = HTTParty.get(url, basic_auth: auth)
You also have a typo—usarname instead of username—which I've fixed in my version.
Edit: If you want to retrieve the specific matched text, file, and lines you still don't have to scrape their HTML. Instead, you can set your Accept header to application/vnd.github.v3.text-match+json:
url = "https://api.github.com/search/code"
query = {q: "https://sonarcloud.io/dashboard"}
auth = {username: "username", password: "password"}
headers = {"Accept" => "application/vnd.github.v3.text-match+json"}
a = HTTParty.get(url, query: query, basic_auth: auth, headers: headers)
The response should now give a text_matches key containing hashes with fragments showing the matched text as well as object_types (e.g. "FileContent"), object_urls, and indices.
This is also mentioned in the search code link I already provided:
When searching for code, you can get text match metadata for the file content and file path fields when you pass the text-match media type. For more details about how to receive highlighted search results, see Text match metadata.

How to pass the validation code to the Lambda function

I'm trying to customize the email that AWS Cognito sends if a user has forgotten their password.
It requires {####} placeholder for the verification code in the email message. For example, if you do
event['response']['emailMessage'] = "Your code is {####}", you'll receive a message Your code is 123456.
Here's an example of my AWS Lambda function:
def custom_message_handler(event, context):
event['response']['emailSubject'] = 'Custom subject'
event['response']['emailMessage'] = 'Custom email'
# verification_code = event[...] ???
return event
It seems like Cognito generates the verification code after your lambda returned the message with the placeholder. Is it possible to get the verification code inside your lambda to use it?
Amazon Cognito's Custom Message Lambda Trigger's Event JSON does not get the numerical verification code. The data of the Event available to the trigger, as stated in the official documentation is stated as follows:
{
"version": 1,
"triggerSource": "CustomMessage_AdminCreateUser",
"region": "<region>",
"userPoolId": "<userPoolId>",
"userName": "<userName>",
"callerContext": {
"awsSdk": "<calling aws sdk with version>",
"clientId": "<apps client id>",
...
},
"request": {
"userAttributes": {
"phone_number_verified": false,
"email_verified": true,
...
},
"codeParameter": "####",
"usernameParameter": "username"
},
"response": {
"smsMessage": "<custom message to be sent in the message with code parameter and username parameter>"
"emailMessage": "<custom message to be sent in the message with code parameter and username parameter>"
"emailSubject": "<custom email subject>"
}
}
You would be able to use Cognito data in a Lambda trigger only if it is available in an Event, or if there is a separate API call for the same. But given Amazon Cognito's design, this does not seem to be possible.

Google plus's access_token integration

I followed :
http://developers.google.com/+/api/oauth
and :
http://developers.google.com/+/api/latest/people/get#examples
After I acquired the access token I didn't understand how to get the user's ID? How do I use it to get the user's data?
With the access token, you can make a people.get request with the userId me:
GET https://www.googleapis.com/plus/v1/people/me?access_token=1234567890
↑
The returned person resource has an Id property that contains the userId of the user:
{
"kind": "plus#person",
"id": "108189587050871927619",
... ↑
}

Resources