Ruby on Rails get body object from fcm response - ruby-on-rails

I have implemented fcm for push notification in windows ruby on rails. but I'm getting response of send() that is in following format. I need only body attribute's value.I'm pretty new to ruby on rails. please guide how can i achieve it.
fcm = FCM.new(server_key)
options = {
priority: "high",
# collapse_key: "updated_score",
notification: {
title: "Hi Android",
body: "Hi, Worked perfectly"
}
}
response = fcm.send([device_token], options)
This is my response
{
"success": true,
"data": {
"body": "{\"multicast_id\":8218758506962978728,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1514875371230492%ebb60861ebb60861\"}]}",
"headers": {
"content-type": [
"application/json; charset=UTF-8"
],
"date": [
"Tue, 02 Jan 2018 06:42:51 GMT"
],
"expires": [
"Tue, 02 Jan 2018 06:42:51 GMT"
],
"cache-control": [
"private, max-age=0"
],
"x-content-type-options": [
"nosniff"
],
"x-frame-options": [
"SAMEORIGIN"
],
"x-xss-protection": [
"1; mode=block"
],
"server": [
"GSE"
],
"alt-svc": [
"hq=\":443\"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=\":443\"; ma=2592000; v=\"41,39,38,37,35\""
],
"accept-ranges": [
"none"
],
"vary": [
"Accept-Encoding"
],
"connection": [
"close"
]
},
"status_code": 200,
"response": "success",
"canonical_ids": [],
"not_registered_ids": []
}
}

You can follow ruby OpenStruct library, it's something like this
object = JSON.parse(response, object_class: OpenStruct)
Then you can find based on object value and very nicely explain here
Hope to help

suppose your response is hash
body = hash[:data][:body].gsub(/[\"]/,"")
and out put will be like this: -
"{multicast_id:8218758506962978728,success:1,failure:0,canonical_ids:0,results:[{message_id:0:1514875371230492%ebb60861ebb60861}]}"

Related

Bad Request "ErrorExecuteSearchStaleData" in Microsoft Graph API - Search for Mails

We are using Microsoft Graph Search API to search through our O365 emails. Since the search only allows 25 results per request for mails. (see https://learn.microsoft.com/en-us/graph/api/resources/search-api-overview?view=graph-rest-beta#page-search-results)
We figured to work around this by batching our search request like this:
POST https://graph.microsoft.com/beta/$batch
{
"requests": [
{
"url": "/search/query",
"method": "POST",
"id": "MyMails-0",
"body":
{
"requests": [
{
"entityTypes": ["message"],
"query":
{
"query_string":
{
"query": "some search text"
}
},
"from": 0,
"size": 25
}
]
},
"headers":
{
"Content-Type": "application/json"
}
},
{
"url": "/search/query",
"method": "POST",
"id": "MyMails-1",
"body":
{
"requests": [
{
"entityTypes": ["message"],
"query":
{
"query_string":
{
"query": "some search text"
}
},
"from": 25,
"size": 25
}
]
},
"headers":
{
"Content-Type": "application/json"
}
},
{
"url": "/search/query",
"method": "POST",
"id": "MyMails-2",
"body":
{
"requests": [
{
"entityTypes": ["message"],
"query":
{
"query_string":
{
"query": "some search text"
}
},
"from": 50,
"size": 25
}
]
},
"headers":
{
"Content-Type": "application/json"
}
},
{
"url": "/search/query",
"method": "POST",
"id": "MyMails-3",
"body":
{
"requests": [
{
"entityTypes": ["message"],
"query":
{
"query_string":
{
"query": "some search text"
}
},
"from": 75,
"size": 25
}
]
},
"headers":
{
"Content-Type": "application/json"
}
}
]
}
This works usually well, but in some cases the API returns something like this:
{
"id": "MyMails-2",
"status": 400,
"headers":
{
"Link": "<https://developer.microsoft-tst.com/en-us/graph/changes?$filterby=beta,RemoveDeprecatedUnderscoreProperty&from=2021-12-01&to=2022-01-01>;rel=\"deprecation\";type=\"text/html\",<https://developer.microsoft-tst.com/en-us/graph/changes?$filterby=beta,RemoveDeprecatedUnderscoreProperty&from=2021-12-01&to=2022-01-01>;rel=\"deprecation\";type=\"text/html\",<https://developer.microsoft-tst.com/en-us/graph/changes?$filterby=beta,RemoveDeprecatedUnderscoreProperty&from=2021-12-01&to=2022-01-01>;rel=\"deprecation\";type=\"text/html\"",
"Deprecation": "Tue, 14 Dec 2021 23:59:59 GMT",
"Sunset": "Sat, 31 Dec 2022 23:59:59 GMT",
"Cache-Control": "no-cache",
"Content-Type": "application/json"
},
"body":
{
"error":
{
"code": "BadRequest",
"message": "\r\n An exception occurred\r\n Lss call failed with status code 400. \"Exchange service returned error ErrorExecuteSearchStaleData: Please reissue the query with rowOffset = 0. The specified rowoffset is '50', but the results are stale.\".",
"innerError":
{
"date": "2022-01-25T09:58:53",
"request-id": "75def95f-a857-427d-a8b4-ee2792329e87",
"client-request-id": "75def95f-a857-427d-a8b4-ee2792329e87"
}
}
}
}
I noticed the deprecation note in the header, however I can't find anything about it. Neither about the actual exception.
What am I missing?
[workaround]
Thanks for the hint #user2250152.
This heavily reduced the issue by splitting the request into two requests, while the second is able to request more than 25 mails at a time:
POST https://graph.microsoft.com/beta/$batch
{
"requests": [
{
"url": "/search/query",
"method": "POST",
"id": "MyMails-0",
"body": {
"requests": [
{
"entityTypes": [
"message"
],
"query": {
"query_string": {
"query": "some search text"
}
},
"from": 0,
"size": 25
}
]
},
"headers": {
"Content-Type": "application/json"
}
},
{
"url": "/search/query",
"method": "POST",
"id": "MyMails-1",
"body": {
"requests": [
{
"entityTypes": [
"message"
],
"query": {
"query_string": {
"query": "some search text"
}
},
"from": 25,
"size": 200
}
]
},
"headers": {
"Content-Type": "application/json"
}
}
]
}
The error with stale results can happen time to time.
You can decrease the number of batch requests to reduce a chance that the error with stale results will occur.
For the first page "from": 0 the max size is 25. But for the next page "from": 25 you can increase the page size to 200.
I've tested the search query with "from": 25 and "size": 200 and it returns 200 results.
Resources:
Page search results

Power Automate / Twilio : HTTP POST Error

I'm not sure what I've messed up, but I'm receiving this error when attempting to send a POST request from Power Automate to a Twilio Flow.
Was able to trigger the Twilio Flow from PowerShell, but cannot replicate on Power Automate.
{
"code": 20001,
"message": "Missing required parameter To in the post body",
"more_info": "https://www.twilio.com/docs/errors/20001",
"status": 400
}
input
output
http request post
This ended up working for me.
Change Content-Type value to
application/x-www-form-urlencoded; charset=utf-8
Change Body value to
To=%2B12223334444&From=%2B15556667777
12223334444 = Send To #
15556667777 = Send From # (Twilio Phone # assigned the Flow)
Re: Using HTTP POST with Twilio
INPUT
{
"uri": "https://studio.twilio.com/v2/Flows/##################################/Executions",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
"authentication": {
"username": "**********************************",
"password": "*sanitized*",
"type": "Basic"
},
"body": "To=%2B12223334444&From=%2B15556667777"
}
OUTPUT
{
"statusCode": 201,
"headers": {
"Connection": "keep-alive",
"Twilio-Concurrent-Requests": "1",
"Twilio-Request-Id": "##################################",
"Twilio-Request-Duration": "0.055",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Accept, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since",
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
"Access-Control-Expose-Headers": "ETag",
"Access-Control-Allow-Credentials": "true",
"X-Shenanigans": "none",
"X-Home-Region": "us1",
"X-API-Domain": "studio.twilio.com",
"Strict-Transport-Security": "max-age=31536000",
"Date": "Tue, 08 Jun 2021 14:04:24 GMT",
"X-Powered-By": "AT-5000",
"Content-Length": "707",
"Content-Type": "application/json"
},
"body": {
"status": "active",
"date_updated": null,
"contact_channel_address": "+12223334444",
"account_sid": ""**********************************",",
"url": "https://studio.twilio.com/v2/Flows/##################################/Executions/##################################",
"context": {},
"sid": "##################################",
"date_created": "2021-06-08T14:04:23Z",
"flow_sid": "##################################",
"links": {
"steps": "https://studio.twilio.com/v2/Flows/##################################/Executions/##################################/Steps",
"execution_context": "https://studio.twilio.com/v2/Flows/##################################/Executions/##################################/Context"
}
}
}

How can I post request json body in swift using Alamofire?

I need to make a POST request in the json body for my app backend but the response returns a failure. I assume my json formatting or encoding is wrong but I can't figure out what the problem is. I have attempted a lot of different solutions but I haven't been able to find one that works. Can anyone see which part of my code is responsible for the failure?
let headers: HTTPHeaders = [
"accept": "application/json",
"content-type": "application/json",
"authorization": self.authValue,
"x-iyzi-rnd": self.randomString,
"cache-control": "no-cache"
]
let parameters: [String: Any] = [
"price": "1.0",
"paidPrice": "1.1",
"paymentChannel": "mobile_ios",
"paymentCard": [
"cardHolderName": "card_name",
"cardNumber": "card_no",
"expireYear": "2030",
"expireMonth": "09",
"cvc": "123"
],
"buyer": [
"id": "123123123",
"name": "john",
"surname": "doe",
"identityNumber": "12345678902",
"email": "johndoe#gmail.com",
"registrationAddress": "nidakulegöztepemerdivenköymahborasokno1",
"city": "istanbul",
"country": "turkey",
"ip": "192.168.1.82"
],
"shippingAddress": [
"address": "nidakulegöztepemerdivenköymahborasokno1",
"contactName": "janedoe",
"city": "istanbul",
"country": "turkey"
],
"billingAddress": [
"address": "nidakulegöztepemerdivenköymahborasokno1",
"contactName": "janedoe",
"city": "istanbul",
"country": "turkey"
],
"basketItems": [
[
"id": "321",
"price": "0.3",
"name": "binocular",
"category1": "collectibles",
"itemType": "physical"
],
[
"id": "432",
"price": "0.5",
"name": "gamecode",
"category1": "game",
"itemType": "virtual"
],
[
"id": "543",
"price": "0.2",
"name": "usb",
"category1": "electronics",
"itemType": "physical"
]
],
"currency": "try"
]
Alamofire.request("https://api.iyzipay.com/payment/auth", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
print(jsonResponse)
})
Is there any different way to post request json body?

Reply sent email by Gmail API

Currently I'm trying to create send and reply using gmail api, in documentation here
Refernces and In-Reply-To must be set in compliance with the RFC 2822 standard, the problem is when I try to get References and In-Reply-To from specified id like below:
`{
"id": "16183e0822247c79",
"threadId": "16183e0822247c79",
"labelIds": [
"SENT"
],
"snippet": "terkait",
"historyId": "1640387",
"internalDate": "1518335984000",
"payload": {
"partId": "",
"mimeType": "multipart/mixed",
"filename": "",
"headers": [
{
"name": "Received",
"value": "from 1059028371380 named unknown by gmailapi.google.com with HTTPREST; Sat, 10 Feb 2018 23:59:44 -0800"
},
{
"name": "Date",
"value": "Sat, 10 Feb 2018 23:59:44 -0800"
},
{
"name": "From",
"value": "jaisanas2#gmail.com"
},
{
"name": "To",
"value": "jaisanas3#gmail.com"
},
{
"name": "Message-Id",
"value": "\u003cCA+8aSZeXMOETdH8NYtd18UWk5eiQnvT0oEnEWy_1HL6mJPuKjw#mail.gmail.com\u003e"
},
{
"name": "Subject",
"value": "terkait"
},
{
"name": "Mime-Version",
"value": "1.0"
},
{
"name": "Content-Type",
"value": "multipart/mixed; boundary=\"--==_mimepart_5a7ff7f050e3_3263ffa0ceb1cc020ea\"; charset=UTF-8"
},
{
"name": "Content-Transfer-Encoding",
"value": "7bit"
}
],
"body": {
"size": 0
},
"parts": [
{
"partId": "0",
"mimeType": "multipart/alternative",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "multipart/alternative; boundary=\"--==_mimepart_5a7ff7f05063_3263ffa0ceb1cc01916\"; charset=UTF-8"
},
{
"name": "Content-Transfer-Encoding",
"value": "7bit"
}
],
"body": {
"size": 0
},
"parts": [
{
"partId": "0.0",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
},
{
"name": "Content-Transfer-Encoding",
"value": "7bit"
}
],
"body": {
"size": 14,
"data": "PHA-dGVya2FpdDwvcD4="
}
}
]
}
]
},
"sizeEstimate": 929
}`
When you see the result there are no headers In-Reply-To and Refernces, my questions is it is possible to reply email using API ?
Here is my code in ruby:
client = google_client user_id
token = Token.find_by_user_id(user_id)
access_token = token.access_token
gmail = Google::Apis::GmailV1::GmailService.new
gmail.authorization = client
message = Mail.new
message.date = Time.now
message.subject = "Re: #{subject}"
message.from = token.email
message.to = "#{to}"
# message.thread_id = "#{thread_id}"
message.message_id = "\u003cCA+8aSZeXMOETdH8NYtd18UWk5eiQnvT0oEnEWy_1HL6mJPuKjw#mail.gmail.com\u003e"
message.part content_type: 'multipart/alternative' do |part|
part.html_part = Mail::Part.new(body: "#{body}", content_type: 'text/html; charset=UTF-8')
end
msg = message.encoded
message_object = Google::Apis::GmailV1::Message.new(raw:message.to_s, thread_id: thread_id, content_type: 'message/rfc822')
gmail.send_user_message('me', message_object)
This code successfully send email in the same thread, but not reply email, here is what looks like inside my gmail sent emails:
As you can see, message with body lauv does not reply message terkait instead I just sent email lauv, my question is how to reply email?
Here you need to set In-Reply-To and References headers. If there is only one email in the thread use the message_id as In-Reply-To and References

How do I get browsermob-proxy to record ALL response bodies

I'm having trouble with browsermob-proxy and its har exporting feature. Some response bodies are not logged (the entire "text" field is missing)
My setup (using browsermob-proxy 2.1.4)
curl -X POST http://localhost:8080/proxy?port=9091
curl -X PUT "http://localhost:8080/proxy/9091/har?captureHeaders=true&captureCookies=true&captureContent=true"
Some responses are fine:
"response": {
"status": 201,
"statusText": "Created",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "Cache-Control",
"value": "max-age=0, no-cache, no-store"
}, {
"name": "Content-Type",
"value": "application/json"
}, {
"name": "Date",
"value": "Thu, 15 Feb 2018 13:07:39 GMT"
}, {
"name": "Location",
"value": ...
}, {
"name": "Pragma",
"value": "no-cache"
}, {
"name": "Render-Time",
"value": "8"
}, {
"name": "Server",
"value": "openresty"
}, {
"name": "Strict-Transport-Security",
"value": "max-age=31536000; includeSubDomains"
}, {
"name": "transfer-encoding",
"value": "chunked"
}, {
"name": "Connection",
"value": "keep-alive"
}],
"content": {
"size": 8607,
"mimeType": "application/json",
"text": "{ <actual json body> }",
"comment": ""
}, ...
But some are not (maybe it is the special content/mime type? or maybe it is the gzip content encoding?)
"response": {
"status": 200,
"statusText": "OK",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "Cache-Control",
"value": "max-age=0, no-cache, no-store"
}, {
"name": "Content-Encoding",
"value": "gzip"
}, {
"name": "Content-Type",
"value": "application/some.custom.type-v1+json"
}, {
"name": "Date",
"value": "Thu, 15 Feb 2018 13:07:39 GMT"
}, {
"name": "Pragma",
"value": "no-cache"
}, {
"name": "Render-Time",
"value": "92"
}, {
"name": "Server",
"value": "openresty"
}, {
"name": "Strict-Transport-Security",
"value": "max-age=31536000; includeSubDomains"
}, {
"name": "Vary",
"value": "Accept-Encoding"
}, {
"name": "Content-Length",
"value": "1978"
}, {
"name": "Connection",
"value": "keep-alive"
}],
"content": {
"size": 7429,
"mimeType": "application/some.custom.type-v1+json",
"comment": ""
< there's nothing else here!! >
},
"redirectURL": "",
"headersSize": 444,
"bodySize": 1978,
"comment": ""
}, ...
Oh yea, both requests are over https, using MITM.
I think I found the answer to my own question
In BrowserMobHttpClient.java I found the following:
private boolean hasTextualContent(String contentType) {
return contentType != null && contentType.startsWith("text/") ||
contentType.startsWith("application/x-javascript") ||
contentType.startsWith("application/javascript") ||
contentType.startsWith("application/json") ||
contentType.startsWith("application/xml") ||
contentType.startsWith("application/xhtml+xml");
}
Looks like I'll have go make a custom build of browsermob-proxy to make it work.

Resources