Google gmail api list messages by labelId error 400 - javascript

I am working on a domain-wide delegation app to pull attachments from a user's email with a specific label. When trying to get their messages, I get this exception:
{
error={
code=400.0,
message='raw' RFC822 payload message string or uploading message via /upload/* URL required,
status=INVALID_ARGUMENT,
errors=[
{reason=invalidArgument, message='raw' RFC822 payload message string or uploading message via /upload/* URL required, domain=global}
]
}
}
The Gmail API documentation suggests to me that the labelIds property is an array of label ids.
From Resolve errors documentation these would cause a 400 exception.
A required field or parameter hasn't been provided.
The value supplied or a combination of provided fields is invalid.
Invalid attachment.
I don't think its 1, no parameter is mandatory based on the docs.
Number 3 is out because theres no attachment.
So thats leaves 2. what field am I messing up?
Things I don't know: 'raw' and RFC822 from the following exception
Here is the exception "message='raw' RFC822 payload message string or uploading message via /upload/* URL required"
function getMessages(oAuth,userEmail,labels){
let labels = ['Label_718766733436502667']
if (oAuth.hasAccess()) {
let url = 'https://gmail.googleapis.com/gmail/v1/users/' + userEmail + '/messages'
let token = service.getAccessToken();
let payload = JSON.stringify({labelIds:labels})
let options = {
headers: {
Authorization: "Bearer " + token,
"content-type": "application/json"
},
method: "GET",
payload:payload,
//muteHttpExceptions: true
};
let response = UrlFetchApp.fetch(url, options);
//Logger.log(response.getContentText());
let result = JSON.parse(response.getContentText());
Logger.log(result)
return result
//Logger.log(JSON.stringify(result, null, 2));
} else {
Logger.log(service.getLastError());
}
}

Related

MemberOf in Graph Me api azure AD

I am trying to get the member groups of the user to whom user belongs using azure graph api but it is not returning memberof in the api. I am using auth0 for the authentication.
Here is the java script code which I am using.
function(accessToken, ctx, cb) {
const jwt = require('jsonwebtoken#7.1.9');
console.log('azure - retrieve user profile');
// Retrieve the profile from Azure
request.get(
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf', {
headers: {
'Authorization': 'Bearer ' + accessToken,
},
json: true
},
function(e, r, profile) {
if (e) {
console.log('azure - error while retrieving user profile:');
console.log(e);
return cb(e)
}
if (r.statusCode !== 200) {
console.log('azure - error while retrieving user profile: ' + r.statusCode);
return cb(new Error('StatusCode: ' + r.statusCode));
}
console.log('azure - retrieved user profile.');
// Get the tenant id from the access token
let decodedToken = jwt.decode(accessToken);
let auth0Profile = {
user_id: profile.id,
given_name: profile.givenName,
family_name: profile.surname,
email: profile.mail || profile.otherMails[0] || profile.userPrincipalName,
email_verified: true,
name: profile.givenName + ' ' + profile.surname,
tenant_id: decodedToken.tid,
identification_value: decodedToken.tid,
user_principal_name: profile.userPrincipalName,
user_department: profile.department,
user_member: profile.memberOf
};
cb(null, auth0Profile);
}
);
}
I have added scope (User.Read Directory.Read.All) in Auth0 for the api call.
Can some one let me know why I am not getting memberOf?
If you want to get member groups of the user, along with multiple attributes, the query will not return the expected results.
I tried checking the same query in Microsoft Graph Explorer.
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf'
Even
for that, except memberOf, all objects displayed:
For getting memberOf, you have to query separately like below:
https://graph.microsoft.com/v1.0/me/memberOf
So, for the workaround, you can make use of the above query by giving it separately without querying with other attributes.
Also please make sure to add GroupMember.Read.All permissions in the scope as mentioned in this Microsoft Doc.
Please find below links if they are helpful: Ref1, Ref2

Twilio Autopilot's custom channel Memory payload

I'm creating a web chat and I need to integrate an assistant using Twilio Autopilot, I use Autopilot's custom channels as follows:
I send a POST request to https://channels.autopilot.twilio.com/v2/{AccountSid}/{AssistantSid}/custom/webchat
I fill in these fields in the request data (Language=en-US, UserId=user123, Text=Something)
I add a Memory parameter in the Assistant URL
My backend code:
// Assistant URL Memory parameter
const context = JSON.stringify({
accountHolder: "foo bar",
balance: 123
}, null, "");
// Request params
const urlencoded = new URLSearchParams();
urlencoded.append("Language", "en-US");
urlencoded.append("UserId", message.Author);
urlencoded.append("Text", message.Body);
const requestConfig: AxiosRequestConfig = {
headers: {
"content-type": "application/x-www-form-urlencoded",
"accept": "application/json",
"authorization" : "Basic " + Buffer.from(accountSid + ":" + authToken).toString("base64")
},
method: "POST",
url: `https://channels.autopilot.twilio.com/v2/${accountSid}/${assistantSid}/custom/webchat?Memory=${context}`,
data: urlencoded
};
// Trigger the bot
const twilioResponse = this.httpService.request(requestConfig);
const result = await lastValueFrom(twilioResponse.pipe(map((response) => response.data)));
Twilio function:
exports.handler = async function(context, event, callback) {
console.log(event.Memory);
const userData = JSON.parse(event.Memory); // Memory does not contains my payload !
return callback(null, {
"actions": [
{
"say": `Hello ${userData.accountHolder}, your balance is ${userData.balance}`
},
{
"listen": true
}
]
});
};
My problem is, The Memory parameter is not sent to the function
I had a similar problem trying to pass the payload in and reached out to a Twilio support.
The answer I received was:
"As per the present update from our engineering team, they are not looking at implementing the Memory parameter on V2 endpoint as there are very less users consuming it. You will have to use V1 endpoint for Autopilot if you are looking to use URL Parameter "Memory" for your use case. "
Therefore the URL will need to look like so:
https://channels.autopilot.twilio.com/v1/ACxxx/UAxxx/custom/chat?Memory={"CarModel":"Diablo","CarMake":"Lamborghini","CarYear":"2019"}'
Twilio developer evangelist here.
I would have thought you might want to URL encode the JSON memory when you add it to the URL. Try this:
const context = encodeURIComponent(
JSON.stringify({
accountHolder: "foo bar",
balance: 123
}, null, "")
);

After using Fetch I still Got Multipart Boundary in react.js when send formData

I seriously confused how to solve this multipart boundary when using Axios, react.js and multipart/formdata. I already stuck for 2 weeks to try to solve this but I feel like I getting closer to solved it but it still stuck no matter what solution I try.
I read and trysome solution from this topic:
how-to-post-multipart-formdata-using-fetch-in-react-native
how-to-send-multipart-form-data-with-antd-upload-react
how-to-send-a-multipart-form-data-from-react-js-with-an-image
this is my create Order function in orderAction.js :
function createOrder(data) {
return dispatch => {
let apiEndpoint = 'order';
let payload = new FormData();
// payload.append('orderImage', data.orderImage);
// console.log("Cek Image : ", data.orderImage);
for (const file of data.orderImage) {
payload.append('orderImage', file)
}
payload.append('userId', data.userId);
payload.append('materialId', data.materialId);
// payload.append('materialId', '5d79930c8c4a882f44b1b0fb');
payload.append('color', data.color);
payload.append('description', data.description);
payload.append('quantity', data.quantity);
payload.append('city', data.city);
payload.append('detailAddress', data.detailAddress);
console.log("Cek Data : ", payload);
fetch(config.baseUrl + apiEndpoint, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Content-Type' : 'multipart/form-data; boundary=----WebKitFormBoundaryHl8DZV3dBSj0qBVe'
},
body: payload
})
// orderService.post(apiEndpoint, payload)
// .then(res => {
// if(res.data.status === 200) {
// alert(res.data.Message);
// dispatch(createOrderSuccess(res.data));
// history.push('/user-order');
// } else {
// dispatch(createOrderFailed());
// alert(res.data.Message);
// }
// })
};
}
can someone help me to solve this? I'm quite confused with this problem
Edit 1
after try using #narasimha solution finally I got rid the multipart boundary but I got weird behaviour where The data succesfully got encoded like this:
but When I trying check the response the photoUrl return null or `` like this:
and when I try using insomnia or postman it successfully generated the photoUrl like this:
where did I wrong in here?
I had the same problem yesterday. The problem was with content type. I had used the same content type header as you are using. The thing is I removed content type and allowed the fetch () API to handle it automatically. It worked!!

Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body in react-admin

I am using react-adminframework, and I have written my own DataProvider. I am trying to accomplish that when an User is created, an instance of UserPossession is created as well. My code bellow accomplishes that, but react-admin Front-end just displays the warning message:
Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body
I checked the Network tab in Developer Tools and every request to server is correct, there is no error. Which leaves me confused and stuck with this, because I have no idea what that warning means or why is it even occuring.
My code is a part of convertDataRequestToHTTP constant and looks like this:
if (resource === 'User') {
url = `${apiUrl}/${resource}`;
options.body = params.data;
httpClient(url, {
method: 'POST',
body: JSON.stringify(options.body),
})
.then(response => (
url = `${apiUrl}/Location`,
options.method = 'POST',
options.body = JSON.stringify({
"odata.type": "HardwareDatabase.UserPossession",
"Name": response.json.Login,
"UserId": response.json.Id
}),
httpClient(url, {
method: options.method,
body: options.body
})
));
}
If you have any questions regarding the code I can clarify.
Thank you for any ideas in advance.
Since you are stating that this code snippet is a part of convertDataRequestToHTTP I might see the issue. httpClient cannot be used in this constant since it creates duplicit calls to API or in your case, this Warning. Correct way would be to only state the options constant.
url = `${apiUrl}/${resource}`;
options.body = JSON.stringifiy(params.data);
options.method = 'POST';
Later in the constant that converts response from OData to mandatory React Admin format, state the httpClient.
params.data = {
"odata.type": "HardwareDatabase.UserPossession",
"Name": response.json.Login,
"UserId": response.json.Id
};
httpClient(`${apiUrl}/Location`, {
method: 'POST',
body: JSON.stringify(params.data),
})
Unfortunately, the GET method for XMLHttpRequest and fetch don't support request bodies.
A temporary work around I found was to use the axios library, which does let you send GET with request bodies.
const res = await axios.get("/api/devices", {
data: { deviceName: 'name' }
})

How to POST an XML with Angular http?

I'm having trouble using JavaScript to send xml. I've tried to emulate what many others have done, but I'm not getting success. I'm getting a XML Syntax Error: Please check the XML request to see if it can be parsed. with the code 80040B19.
Here's my code. I'm trying to use the USPS Address Validation API. On page 4 of this doc, there's more info.
const apiUrl = 'http://production.shippingapis.com/ShippingAPI.dll?API=Verify';
validate(address: Object): any {
const payload = this.xmlBuilder.buildObject({
AddressValidateRequest: {
$: { USERID: 'XXXXXXXXX' }, // api key hidden
Address: {
$: { ID: '0'},
FirmName: null,
Address1: address['address2'],
Address2: address['address1'], // NOT A TYPO, they swap it
City: address['city'],
State: 'NY',
Zip5: address['postal_code'],
Zip4: null
}
}
});
console.log(payload); // SEE BELOW
const headers = new Headers({ 'Content-Type': 'text/xml' });
const options = new RequestOptions({ headers: headers });
return this.http.post(this.apiUrl, { 'XML': payload }, options)
.map((res) => {
this.parseXMLStringToObject(res.text(), (err, result) => {
console.log(result);
});
});
}
Here's what my console.log on the payload reads. I've verified this to the letter, from the order of the xml tags, to what is required tag but optional value. I'm positive the payload is correct.
<AddressValidateRequest USERID="XXXXXXXXX">
<Address ID="0">
<FirmName/>
<Address1/>
<Address2>620 Eighth Avenue</Address2>
<City>New York</City>
<State>NY</State>
<Zip5>10018</Zip5>
<Zip4/>
</Address>
</AddressValidateRequest>
One thing that I can think of is I'm somehow not using the http correctly, and I'm sending a blank xml somehow.
On their docs, they have this listed:
https://servername/ShippingAPI.dll?API=Verify&XML=……..
I noticed I'm not doing a XML in the url, but I'm assuming that when I input the Content-Type: text/xml, that it get converted. I've also tried application/xml which give the same error.
From the documentation on USPS website it seems that the call isn't a POST with the XML as payload but a GET with XML (I suppose urlencoded) in the URL XML parameter.

Categories

Resources