Sending Onesignal/gamethrive push by JSON network request - json

I am trying to send a JSON request to send a push notification using the following code but I get an error message for the network response saying "app_id not found". I am using Corona but this shouldnt matter as long as JSON format is right.
local json = require "json"
local function networkListener( event )
if ( event.isError ) then
print( "Network error!" )
else
print ( "RESPONSE: " .. event.response )
end
end
headers = {}
headers["app_id"] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
headers["Authorization"] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
headers["Content-Type"] = "application/json"
local params = {}
commands_json =
{
["contents"] = "English Message"
}
postData = json.encode(commands_json)
local params = {}
params.header = headers
params.body = postData
network.request( "https://onesignal.com/api/v1/notifications","POST",networkListener,params)

I could work it out.
function SendJson(url, action, in_json, callback)
local json = require ( "json" )
local headers = {}
headers["Content-Type"] = "application/json"
headers["Accept-Language"] = "en-US"
headers["Authorization"] = "Basic 12121321313123" -- put your Rest API
local params = {}
params.headers = headers
params.body = json.encode( in_json )
network.request ( url, action, callback, params )
end
local function networkListener( event )
if ( event.isError ) then
print( "Network error!")
else
print ( "RESPONSE: " .. event.response )
end
end
local jsonToSend = {["app_id"] = "aaaaaa-222-222-33-3333333333", --put yours App ID
["contents"] = {["en"] = "George challenged you to beat his score!"},
["included_segments"] = "All",
["isAndroid"] = true,
["isIos"] = true,}
--["include_player_ids"] = ["(RECIPIENT_PLAYER_ID_HERE)"]}
SendJson("https://gamethrive.com/api/v1/notifications", "POST", jsonToSend, networkListener)

Do you have both Android and Apple setup on your app on the OneSignal dashboard? Platforms(isAndroid and isIos) are not required parameters when you use include_player_ids.
Also make sure you don't use the Authorization header in your production app as someone can easily disassemble your app and get the REST API key. When you use the include_player_ids field the Authorization header is not required.
See the OneSignal create notification POST call for the full documentation.
Also I recommend you switch to using "https://onesignal.com/api/v1/notifications" as the URL in your code to save on redirects.

Related

Unable to stream data from twitter using Pyspark

I am new to Twitter stream analytics
I was unable to use the tweepy streaming as there was a change in the API version 2.0. So I am currently trying to stream it using a bearer token.
I am facing two issues:
Getting error- The content for this response was already consumed
How to send the JSON response to the Spark stream
I am streaming the JSON response by using stream=True
Any pointers/alternatives would be great!
import requests
import os
import json
bearer_token = 'your bearer token'
query = "fifa"
tweet_fields = "tweet.fields=id,created_at,text"
expansions = "expansions=author_id"
headers = {"Authorization": "Bearer {}".format(bearer_token)}
def create_url(query, tweet_fields, expansions):
url = "https://api.twitter.com/2/tweets/search/recent?query={}&{}".format(
query, tweet_fields, expansions
)
return url
def bearer_oauth(r):
"""
Method required by bearer token authentication.
"""
r.headers["Authorization"] = f"Bearer {bearer_token}"
r.headers["User-Agent"] = "v2SampledStreamPython"
return r
def connect_to_endpoint(url):
response = requests.request("GET", url, auth=bearer_oauth, stream=True)
#print(response.status_code)
for response_line in response.iter_lines():
if response_line:
json_response = json.loads(response_line)
t=json.dumps(json_response, indent=4, sort_keys=True)
if response.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(
response.status_code, response.text
)
)
def main():
url = create_url(query, tweet_fields, expansions)
timeout = 0
while True:
connect_to_endpoint(url)
timeout += 1
if __name__ == "__main__":
main()

How to fetch a JSON with SparkAR networking module

I want to fetch data from an URL with SparkAR's networking module
and display it.
I tried the example found in the Spark AR documentation but it doesn't do much: https://developers.facebook.com/docs/ar-studio/reference/classes/networkingmodule/
Don't forget to add "jsonplaceholder.typicode.com"
to Spark AR's whitelisted domains first. :)
// Load in the required modules
const Diagnostics = require('Diagnostics');
const Networking = require('Networking');
//==============================================================================
// Create the request
//==============================================================================
// Store the URL we're sending the request to
const url = 'https://jsonplaceholder.typicode.com/posts';
// Create a request object
const request = {
// The HTTP Method of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
method: 'POST',
// The HTTP Headers of the request
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)
headers: {'Content-type': 'application/json; charset=UTF-8'},
// The data to send, in string format
body: JSON.stringify({title: 'Networking Module'})
};
//==============================================================================
// Send the request and log the results
//==============================================================================
// Send the request to the url
Networking.fetch(url, request).then(function(result) {
// Check the status of the result
// (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
if ((result.status >= 200) && (result.status < 300)) {
// If the request was successful, chain the JSON forward
return result.json();
}
// If the request was not successful, throw an error
throw new Error('HTTP status code - ' + result.status);
}).then(function(json) {
// Log the JSON obtained by the successful request
Diagnostics.log('Successfully sent - ' + json.title);
}).catch(function(error) {
// Log any errors that may have happened with the request
Diagnostics.log('Error - ' + error.message);
});
All I get is : ">> Successfully sent - Networking Module"
Does anybody know how I could get the json content to be displayed in the console I want to store it and use it in a text object afterwards.
In my case a have a url that give me a random item in json format.
URL: https://gabby-airbus.glitch.me/random
Result: {"item":"Item 14"}
In the code, replace the line:
Diagnostics.log('Successfully sent - ' + json.title);
with this:
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
First line shows the json data in console.
Second line asign the json data to a text object in the scene, in this case the "itemText" text object.
Full code:
const Diagnostics = require('Diagnostics');
const Scene = require('Scene');
const Networking = require('Networking');
const URL = 'https://gabby-airbus.glitch.me/random';
var itemText = Scene.root.find('itemText');
Networking.fetch(URL).then(function(result){
if( (result.status >=200) && (result.status < 300)){ return result.json(); }
else { throw new Error('HTTP Status Code: ' + result.status); }
}).then(function(json){
// show json data in console
Diagnostics.log(json.item);
// Asign json data to text object
itemText.text = json.item;
}).catch(function(error){
itemText = 'Failed to start';
Diagnostics.log(result.status + error);
});

When I get JSON data through AJAX, Where does the data get stored?

I want to know the place where certain JSON data get stored when it's sent from server to client which exists in the different directory.
I am trying to build simple API which send JSON data from server side(port number:5001) to client side(port number:3000).
What I noticed doing this project is that http header and body is not the place where the JSON to be contained.
If so, how does JSON data get delivered to client side?
I want to know what happen in code-behind.
Following is the code that I wrote to build simple API:
Client side code:
componentDidMount() {
axios.get('localhost:5001')
.then((result) => console.log(result))
.catch((err) => console.log('Error ocurred'));
}
Server side code(ASP.NET Core 2.0):
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json;
charset=utf-8";
await context.Response.WriteAsync(json);
I expected that the JSON data named 'result' will be attached to HTTP header or body but it was not. When I checked the raw data of http body on the console, it was just html content. This is the content displayed on the browser:
{"id":1,"Name":"jay","Password":"1004","Content":"This is text from the server"}
as I wrote in the code, I want this data on the console not on the browser view page.
That seems you get error returned form server side . You should firstly Enable Cross-Origin Requests (CORS) in ASP.NET Core
Add CORS to your web api in ConfigureServices :
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
And enable that in Configure function :
app.UseCors("MyPolicy");
If you have middleware to modify the response in your web api :
app.Run(async (context) =>
{
UserPosts result = new UserPosts();
result.id = 1;
result.Name = "jay";
result.Password = "1004";
result.Content = "This is text from the server";
string json = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json; charset = utf - 8";
await context.Response.WriteAsync(json);
});
In client , you could get the result by accessing .data in response :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function test(){
axios.get('http://localhost:5001/api/values')
.then(
(result) => console.log(result.data)
)
.catch(
(err) => console.log('Error ocurred')
);
}
</script>

Get the token and send it as value for Authorization header for the rest of the steps

After I get a token from a Post request as shown below:
{ "access_token": "12345", "expires_in": 3600, "token_type": "Bearer" }
I want to use this token in different TestSteps Headers values.
For example I have to make a GET request after I received this token and it have in the header -> Authentification : Bearer + token_value.
So can I write a GroovyScript or something to make this automatically? I'm using ReadyApi.
Regards,
Adrian
Add Script Assertion for the same step where you receive the mentioned response:
Script Assertion this fetches the values from response and creates a project property and set the retrieved value.
//Check if the response is empty or null
assert context.response, "Response is null or empty"
def json = new groovy.json.JsonSlurper().parseText(context.response)
def token = "${json.token_type} ${json.access_token}" as String
log.info "Token will be: ${token}"
//Assing the value at project level property TOKEN
context.testCase.testSuite.project.setPropertyValue('TOKEN', token)
Now the value needs to be set as header to each outgoing request dynamically. i.e., Add Authorization header and its value for the SOAP or REST request type steps. For this, Events feature is going to be used.
Add a SubmitListener.beforeSubmit event and add the below script into it. Please follow the comments inline.
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
import com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep
//Please edit the header name as you wanted
def headerName = 'Authorization'
//a method which sets the headers
def setHttpHeaders(def headers) {
def step = context.getProperty("wsdlRequest").testStep
if (step instanceof RestTestRequestStep || step instanceof WsdlTestRequestStep) {
def currentRequest = step.httpRequest
def existingHeaders = currentRequest.requestHeaders
headers.each {
existingHeaders[it.key] = it.value
}
currentRequest.requestHeaders = existingHeaders
} else {
log.info 'not adding headers to the current step as it is not request type step'
}
}
//read the token from project properties
def token = context.expand('${#Project#TOKEN}')
//assert the value of token
assert token, "Token is null or empty"
//UPDATE from the comment to add the header to next request
if (token) {
def headerValue = [(token)]
def headers = [(headerName) : (headerValue)]
setHttpHeaders(headers)
}
import groovy.json.JsonSlurper
import groovy.json.*
def tokens=testRunner.runStepByname("Token")
def response = context.expand( '${Token#Response}' )
def JsonSlurperjsonSlurper = newJsonSlurper()
def Objectresult = jsonSlurper.parseText(response)
def access_token= result.access_token
def authorization = "Bearer "+access_token
testRunner.testCase.setPropertyValue("access_token", authorization)

jQuery ajax callback receiving incorrect json result

In my asp.net mvc 4 web app my action in the controller seems to return a invalid data to the jquery ajax callback... The action is doing a ping to an IP and it is called several times from several ajax calls in order to do pings to several IPs.
A piece of my action in the controller (below what is returned):
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = (int)(packetsLost < 4 ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return new JsonResult()
{
ContentType = "application/json;charset=utf-8",
Data = new
{
sent = 4,
received = 4 - packetsLost,
lost = packetsLost,
percentLost = (int) (packetsLost / 4 * 100),
responseStatus01 = statuses[0],
responseStatus02 = statuses[1],
responseStatus03 = statuses[2],
responseStatus04 = statuses[3],
responseMessage01 = responseStatuses[0],
responseMessage02 = responseStatuses[1],
responseMessage03 = responseStatuses[2],
responseMessage04 = responseStatuses[3],
rtt01 = rtt[0],
rtt02 = rtt[1],
rtt03 = rtt[2],
rtt04 = rtt[3],
ttl01 = ttl[0],
ttl02 = ttl[1],
ttl03 = ttl[2],
ttl04 = ttl[3],
minRtt = roundTripTimes.Count == 0 ? "0" : string.Format("{0}ms", roundTripTimes.Min()),
maxRtt = roundTripTimes.Count == 0 ? "0" : string.Format("{0}ms", roundTripTimes.Max()),
avgRtt = roundTripTimes.Count == 0 ? "0" : string.Format("{0}ms", roundTripTimes.Average())
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
and jquery ajax call:
ajax({
url: '/Controller/Action/',
type: 'POST'
}).then(function (data) {
var _data;
try {
_data = $.parseJSON(data);
}
catch (err) {
alert("Something went bad!!!");
}
}, function (data) {
var _data;
try {
_var = $.parseJSON(data.responseText);
}
catch (err) {
alert("Something went bad!!!");
}
});
1) When action returns http status code OK (200) data.responseText in the jquery ajax callback is empty so I convert data instead (that contains correct data) but for some reason it is crashing when converting using parseJSON(data): error catched says invalid character... I do not know why...
2) When action return http status code NotFound (404) data.responseText sometimes (not always) is empty and statusText within data is "error" so neither I do not understand it....
Action in the controller always is returning the correct data....
Could someone help me to detect this error? or right me in the right direction....
UPDATED:
From ie dev tools, in network, I have observed that some pings are cancelled and then when trying to process them it returns empty responseText to the ajax callback so when trying to parse it, it crashes. I have observed that If I set the timeout for ping to a lower value, for example, 750ms, it is working but if i use the default timeout for ping, that is, 5sec, then it does not work: some pings are cancelled and when trying to serve them they are returning empty responseText that cause it to crash when trying to parse in ajax callback.