Retrieve inline images from gmail api? - gmail-api

I'm retrieving messages from my Gmail using Gmail API. specifically, the email with Hangouts conversations using this url: https://www.googleapis.com/gmail/v1/users/me/messages?q=in:chats
When I enter in a message, I see this structure
{
"id": "1555561f7b8e1sdf56b",
"threadId": "155552511dfsd83ce98",
"labelIds": [
"CHAT"
],
"snippet": "df",
"historyId": "270812",
"internalDate": "1466016331704",
"payload": {
"partId": "",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "From",
"value": "\"Oscar J. Irún\" <Oscarjiv91#gmail.com>"
}
],
"body": {
"size": 2,
"data": "ZGY="
}
},
"sizeEstimate": 100
}
as you can see, the body message is "df". Everything it's ok so far.
The problem comes when the Hangout message is an image. The snippet field is empty, and it doesnt show any attachment in the message. This is an example:
{
"id": "155558233274d78c91",
"threadId": "15fd5552511d83ce98",
"labelIds": [
"CHAT"
],
"snippet": "",
"historyId": "27sd0827",
"internalDate": "1466018445133",
"payload": {
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "From",
"value": "\"Oscar J. Irún\" <Oscarjiv91#gmail.com>"
}
],
"body": {
"size": 0,
"data": ""
}
},
"sizeEstimate": 100
}
I need to retrieve this inline images. Any help will be appreciated!

You can retrieve attachments by using Users.messages.attachments:get. Take note that this request requires authorization. All requests to the Gmail API must be authorized by an authenticated user. Gmail uses the OAuth 2.0 protocol for authenticating a Google account and authorizing access to user data.
HTTP request
GET https://www.googleapis.com/gmail/v1/users/userId/messages/messageId/attachments/id
public static void getAttachments(Gmail service, String userId, String messageId)
throws IOException {
Message message = service.users().messages().get(userId, messageId).execute();
List<MessagePart> parts = message.getPayload().getParts();
for (MessagePart part : parts) {
if (part.getFilename() != null && part.getFilename().length() > 0) {
String filename = part.getFilename();
String attId = part.getBody().getAttachmentId();
MessagePartBody attachPart = service.users().messages().attachment().
get(userId, messageId, attId).execute();
byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
FileOutputStream fileOutFile =
new FileOutputStream("directory_to_store_attachments" + filename);
fileOutFile.write(fileByteArray);
file OutFile.close();
}
}
}

JUST FYI for PHP the solution is something similar to this:
base64_decode(strtr($gmail->service->users_messages_attachments->get('me', $message->id, $arrPart['body']['attachmentId'])->data,'-_', '+/'));

Related

Graph API User delta query not returning Manager following a change to the user

When I run this initial query:
https://graph.microsoft.com/beta/users/delta?$select=id,displayName,manager,jobTitle&$filter=id+eq+'87fa2ed7-5e58-4ff5-85ca-42a973e103e7'
I get the following response (as expected):
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#users(id,displayName,jobTitle,manager)",
"#odata.nextLink": "https://graph.microsoft.com/beta/users/delta?$skiptoken=<removed>",
"value": [
{
"displayName": "Jane Doe",
"jobTitle": "Super Administrator",
"id": "87fa2ed7-5e58-4ff5-85ca-42a973e103e7",
"manager#delta": [
{
"#odata.type": "#microsoft.graph.user",
"id": "1ab00b74-6f7e-45ca-8629-22d64632501d"
}
]
}
]
}
I follow the #odata.nextLink URL, which returns:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#users",
"#odata.deltaLink": "https://graph.microsoft.com/beta/users/delta?$deltatoken=<removed>",
"value": []
}
I don't really understand why it doesn't just give me the deltaLink in the first call, but that isn't the issue. At this point, I make a change to the user's job title in Azure AD (outside of Graph API) and then follow the #odata.deltaLink, which returns:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#users",
"#odata.deltaLink": "https://graph.microsoft.com/beta/users/delta?$deltatoken=<removed>",
"value": [
{
"displayName": "Jane Doe",
"jobTitle": "Administrator",
"id": "87fa2ed7-5e58-4ff5-85ca-42a973e103e7"
}
]
}
No manager!!
The only attribute changed was the job title; Manager is unchanged. This behavior is the same in both the v1.0 and beta endpoints. Also, I am not using the "prefer:return=minimal" header (or any additional headers for that matter).
Can anyone provide some insight into this?

Reading message from Service bus

I have a logic app with started when there is a message in serviceBus queue. The message is being published to the service bus from the DevOps pipeline using "PublishToAzureServiceBus" as a JSON message or from the pipeline webhook.
But getting an issue while converting a message from service bus to original JSON format, not able to get valid JSON object. It's getting append with some Serialization object.
I have tried with base64 decode, and JSON converts but have not been able to get success.
Below is the content of the message it looks like.
Any pointer on how can solve this?
Sample message sent
{
"id": "76a187f3-c154-4e60-b8bc-c0b754e54191",
"eventType": "build.complete",
"publisherId": "tfs",
"message": {
"text": "Build 20220605.8 succeeded"
},
"detailedMessage": {
"text": "Build 20220605.8 succeeded"
},
"resource": {
"uri": "vstfs:///Build/Build/288",
"id": 288,
"buildNumber": "20220605.8",
"url": "https://dev.azure.com/*******/_apis/build/Builds/288",
"startTime": "2022-06-05T14:47:01.1846966Z",
"finishTime": "2022-06-05T14:47:16.7602096Z",
"reason": "manual",
"status": "succeeded",
"drop": {},
"log": {},
"sourceGetVersion": "LG:refs/heads/main:********",
"lastChangedBy": {
"displayName": "Microsoft.VisualStudio.Services.TFS",
"id": "00000000-0000-0000-0000-000000000000",
"uniqueName": "***************"
},
"retainIndefinitely": false,
"definition": {
"definitionType": "xaml",
"id": 20,
"name": "getReleaseFile",
"url": "https://dev.azure.com/************/_apis/build/Definitions/20"
},
"requests": [
{
"id": 288,
"url": "https://dev.azure.com/B*****/**********/_apis/build/Requests/288",
"requestedFor": {
"displayName": "B*****.sag",
"id": "*******",
"uniqueName": "B**********"
}
}
]
},
"resourceVersion": "1.0",
"resourceContainers": {
"collection": {
"id": "*******",
"baseUrl": "https://dev.azure.com/B*****/"
},
"account": {
"id": "******",
"baseUrl": "https://dev.azure.com/B*****/"
},
"project": {
"id": "**********",
"baseUrl": "https://dev.azure.com/B*****/"
}
},
"createdDate": "2022-06-05T14:47:28.6089499Z"
}
Message received
#string3http://schemas.microsoft.com/2003/10/Serialization/�q{"id":"****","eventType":"build.complete","publisherId":"tfs","message":{"text":"Build 20220605.8 succeeded"},"detailedMessage":{"text":"Build 20220605.8 succeeded"},"resource":{"uri":"vstfs:///Build/Build/288","id":288,"buildNumber":"20220605.8","url":"https://dev.azure.com/*****/********/_apis/build/Builds/288","startTime":"2022-06-05T14:47:01.1846966Z","finishTime":"2022-06-05T14:47:16.7602096Z","reason":"manual","status":"succeeded","drop":{},"log":{},"sourceGetVersion":"LG:refs/heads/main:f0b1a1d2bd047454066cf21dc4d4c710bca4e1d7","lastChangedBy":{"displayName":"Microsoft.VisualStudio.Services.TFS","id":"00000000-0000-0000-0000-000000000000","uniqueName":"******"},"retainIndefinitely":false,"definition":{"definitionType":"xaml","id":20,"name":"getReleaseFile","url":"https://dev.azure.com/******/_apis/build/Definitions/20"},"requests":[{"id":288,"url":"https://dev.azure.com/*****/******/_apis/build/Requests/288","requestedFor":{"displayName":"baharul.sag","id":"******","uniqueName":"baharul.*****"}}]},"resourceVersion":"1.0","resourceContainers":{"collection":{"id":"3*****","baseUrl":"https://dev.azure.com/*****/"},"account":{"id":"******","baseUrl":"https://dev.azure.com/*****/"},"project":{"id":"*******","baseUrl":"https://dev.azure.com/*****/"}},"createdDate":"2022-06-05T14:47:28.6089499Z"}
When reading message from service bus in peek mode can see as below where <#string3http://schemas.microsoft.com/2003/10/Serialization/��> is appended to json string
Publish using PublishToAzureServiceBus from Azure pipeline.
Publish from Azure DevOps project webhook
I believe what is happening is that you have two different types of serialisation in the body of the brokered message created by the PublishToAzureServiceBus task. This is because the brokered message only supports binary content.
So the json is initially serialised as a binary string using the data contract serialiser.
How to solve this? Do the following before passing to your json deserialiser - unfortunately the logic app isn't doing this:
byte[] messageContent = brokeredMessage.GetBody<byte[]>();
string messageContentStr = Encoding.UTF8.GetString(messageContent);
I probably wouldn't use a logic app to do the reading of the message because to insert c# like I suggest you're gonna need to call an azure function or similar. I'd create an azure function to read your messages as above.

Is there a way to get Gmail Chat recipient details?

I'm trying to find the recipient info in the Gmail with the label CHAT. Normally with other Gmail messages, the payload header should return the sender, recipient, cc and bcc information. But the recipient info is missing in the payload header when I try to get the Gmail Chat. I've tried the metadataHeader and wasn't not able to return the recipient format. Is there a way to get the recipient info?
I've been using this page to test the API.
https://developers.google.com/gmail/api/v1/reference/users/messages/get
Example -
When I sent a chat message to User B, I would like to get the message recipient from the api. The returned json below only shows that I send the message, but not who received the message.
Returned Json -
"id": "xxxx",
"threadId": "xxxx",
"labelIds": [
"CHAT"
],
"snippet": "asdfasdfasdf",
"historyId": "171386",
"internalDate": "1586440732637",
"payload": {
"partId": "",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "From",
"value": "Admin Admin \u003cxxx#xxx.com\u003e"
}
],
"body": {
"size": 12,
"data": "YXNkZmFzZGZhc2Rm"
}
},
"sizeEstimate": 100
}
Thanks

Internal Server Error when creating Conditional Access Policy

I referred to this documentation to make a POST request.
Below is the error while making a POST request to create a conditional access policy
{
"message": "There was an internal server error while processing the request. Error ID: 2dbb1530-4ce6-44f5-9c63-08de28d7218a",
"innerError": {
"request-id": "2dbb1530-4ce6-44f5-9c63-08de28d7218a"
}
}
Payload being passed with the request is below:
{
"displayName": "Test Policy",
"state": "enabled",
"conditions": {
"clientAppTypes": ["modern", "browser"],
"applications": {
"includeApplications": ["None"]
},
"users": {
"includeUsers": [
"08290005-23ba-46b4-a377-b381d651a2fb"
]
},
"locations": {
"includeLocations": ["All"],
"excludeLocations": ["AllTrusted"]
}
},
"grantControls": {
"operator": "OR",
"builtInControls": ["approvedApplication"]
}
}
I've tried using this endpoint to get a policy:
https://graph.microsoft.com/beta/{tenant_id}/conditionalAccess/policies
Which successfully returns an existing policy. However, the above POST request is not working.
The "approvedApplication" requirement only supports the iOS and Android for device platform condition. See details here.
You need to add "includePlatforms" iOS and android into the json body.
{
"displayName": "Test Policy",
"state": "enabled",
"conditions": {
"clientAppTypes": ["modern", "browser"],
"applications": {
"includeApplications": ["None"]
},
"users": {
"includeUsers": [
"08290005-23ba-46b4-a377-b381d651a2fb"
]
},
"platforms": {
"includePlatforms": [
"iOS", "android"
]
},
"locations": {
"includeLocations": ["All"],
"excludeLocations": ["AllTrusted"]
}
},
"grantControls": {
"operator": "OR",
"builtInControls": ["approvedApplication"]
}
}

what is 'code' parameter in django-rest-social-auth?

I am new in Django and working on django-rest-social-auth.
I want to implement social login in my app.(frontend- angular, Backend- Django)
but I am not getting what is the code parameter below request.
POST /api/login/social/token/
input:
{
"provider": "facebook",
"code": "AQBPBBTjbdnehj51"
}
output:
{
"token": "68ded41d89f6a28da050f882998b2ea1decebbe0"
}
POST /api/login/social/token_user/
input:
{
"provider": "facebook",
"code": "AQBPBBTjbdnehj51"
}
output:
{
"username": "Alex",
"email": "user#email.com",
// other user data
"token": "68ded41d89f6a28da050f882998b2ea1decebbe0"
}

Resources