Parse push notification shows empty geo-queries - javascript

This is similar to but it's a continuation to Parse geo-queries always empty
I have device installations working correctly, and i've created a customized class "test_users" that contains the location data. each instance in the "Installation" class holds a pointer to the "test_users" instance, with column name "test" below** you can see below, and when I clicked on the pointer value, it will go to that "test_user" instance.
and "test_users" class
I have the following javascript code to Query the channel and location to send push notification:
$http({
"url": "https://api.parse.com/1/push",
"method": "POST",
"data": {
"data": { "alert": "test!! ",
"sound": "beep.caf",
"badge": "Increment",
"uid":user_uid,
"date":date,
"time":time
},
"where": {
"channel": category,
"test": {
"$inQuery": {
"location": {
"$nearSphere": {
"__type": "GeoPoint",
"latitude": 37.7150 ,
"longitude": -117.1625
},
"$maxDistanceInMiles": 20
}
}
}
}
},
"headers": {
"X-Parse-Application-Id": "######",
"X-Parse-REST-API-Key": "#######",
"Content-Type": "application/json"
},
"params":
{
"uid" : user_uid,
"date": date,
"time": time
}
});
However, no push notification is created, and when i check the analytics, i see this
Any thoughts on where I made the query mistake? or anything wrong with "test_users" class? Update: On a different experiment, I also created a _User class just like the parse.com push notification doc did (and have "Installation" instance storing a pointer to the _User instance), and got same empty geo-query result.

Related

Axios PUT request -React

I want to send a put request to modify the command part of my JSON file. Here is my JSON;
{
"users": [
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password1",
"command": "command1",
"id": 1
},
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password2",
"command": "command2",
"id": 2
},
{
"hostname": "xxx.xx.xx.xxx",
"password": "password3",
"command": "command3",
"id": 3
}
]
}
In App.js I send put request like this;
stopPC(id){
axios.put('http://localhost:3002/users/'+id,{
command: 'stop'
})
}
And I have tried this;
axios({
method: 'put',
url: 'http://localhost:3002/users/'+ id,
data: {
hostname: id.hostname,
password: id.password,
command: 'stop'
}
});
In both, I got the following output in the JSON file.
{
"users": [
{
"command": "stop",
"id": 1
},
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password2",
"command": "command2",
"id": 2
},
{
"hostname": "xxx.xxx.xxx.xx",
"password": "password3",
"command": "command3",
"id": 3
}
]
}
I want to change only the command information while keeping the hostname and password information the same.
I'm not sure where I went wrong, I'd be glad if you could help.
If id is of type Number (which I think it is), id.hostname and id.password would be undefined, so basically
{
hostname: id.hostname,
password: id.password,
command: 'stop'
}
and
{
command: 'stop'
}
are the same to Javascript and you're effectively sending the same payload. I think that the best way of solving this would be changing how the backend handles the incoming payload by just changing the properties that came in the request. If you don't have access to changing the backend, you would have to get or read the current stored value and use that in the payload. Something like
user = axios.get('http://localhost:3002/users/'+id).then(r => r.data)
axios.put('http://localhost:3002/users/'+id,{
hostname: user.hostname,
password: user.password,
command: 'stop'
})
Also, PUT is meant to be used used to replace a record, and PATCH to update the existing one, which sounds more like what you want to do. Maybe just try axios.patch and it may work.
I did quite the same than #rodrigo-naranjo except I embedded the put call in the response of the get call:👇
axios.get("http://localhost:3002/users/" + id).then((r) => {
let user = r.data;
axios.put("http://localhost:3002/users/" + id, {
hostname: user.hostname,
password: user.password,
command: "stop",
});
});
with id an input value from your app context.

Google App Script - Save the sheet file Id created from my sheet file template

thank you for the time you will take to resolve my issue !
I am not sure that Google app script allows to do what I need.
Could you please tell me if it is possible?
If yes, do you have already a script code to do it?
I have created a file which I have shared it with others colleagues (in a shared drive), and it is used as a "template".
When a colleague creates a copy of it, I would like that the script to give me the new Google sheet id created from the model and saved this id in my Google sheet dashboard?
Is it possible with appscript?
Thanks a lot and have a good day !
Copy Spreadsheet and Save Id
function copySpreadsheetAndSaveId() {
const fileId = "fileid";
const ss = SpreadsheetApp.getActive():
const sh = ss.getSheetByName("Dashboard");
sh.getRange(sh.getLastRow() + 1, 1).setValue(DriveApp.getFileById(fileId).makeCopy().getId());//appends the id to the bottom of column one in the sheeet named Dashboard.
}
If you want users to be able to open the Spreadsheet then you can't restrict them copying it by script only
I can think of a couple of workarounds:
Workaround 1:
Make the Spreadsheet private, and create a web app which runs as you but is accessible by other users. On doGet(), create a copy of the Spreadsheet and share it with the email returned from Session.getActiveUser().getEmail():
function doGet() {
// Check if security policy gets email address:
const user = Session.getActiveUser()
if (!user.getEmail()) {
return ContentService.createTextOutput('Unable to retrieve user.')
}
const ss = DriveApp.getFileById("template-spreadsheet-id")
const newFile = ss.makeCopy().addEditor(user)
const html = `File copied, click here to open.`
return HtmlService.createHtmlOutput(html)
}
Pros:
Should work for anyone within the same domain as you
You can directly retrieve the ID on copy and save it to your database
Cons:
Security policy might stop you being able to get the user
What's to stop them from just copying the copy?
Workaround 2:
If you're an admin user, you could use the Drive Audit Activity API to check for domain-wide copy events of a given file ID. It's a bit more involved and assumes you have a client set up in GCP but will have a bigger catch-radius than the first workaround, and also doesn't involve restricting access to the template or creating a Web App:
function getAuditLog() {
const baseUrl = "https://admin.googleapis.com/admin/reports/v1/activity/users/all/applications/drive"
const apiKey = "api-key-obtained-from-gcp"
const params + `eventName=copy&key=${apiKey}`
const headers = {
"Authorization": `Bearer ${ScriptApp.getOAuthToken()}`,
"Accept": "application/json"
}
const response = UrlFetchApp.fetch(`${baseUrl}?${params}`, {
"method": "get",
"headers": headers"
})
const responseData = JSON.parse(response.getContentText())
}
You'll then have to process the response. responseData contains an items key which is an array of copy events in the audit report:
{
"kind": "admin#reports#activities",
"etag": "\"xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx\"",
"items": [
{
"kind": "admin#reports#activity",
"id": {
"time": "2022-01-21T10:03:12.793Z",
"uniqueQualifier": "-XXXXXXXXXXXXXX",
"applicationName": "drive",
"customerId": "xxxxxxx"
},
"etag": "\"xxxxxxxxxxxxx/xxxxxxxxxxx\"",
"actor": {
"email": "user#example.com",
"profileId": "XXXXXXXXXXXX"
},
"ipAddress": "0000:0000:0000:0000:0000:0000:0000:0000",
"events": [
{
"type": "access",
"name": "copy",
"parameters": [
{
"name": "primary_event",
"boolValue": false
},
{
"name": "billable",
"boolValue": true
},
{
"name": "old_value",
"multiValue": [
"Spreadsheet Template File Name"
]
},
{
"name": "new_value",
"multiValue": [
"Copy of Spreadsheet Template File Name"
]
},
{
"name": "doc_id",
"value": "new-spreadsheet-id"
},
{
"name": "doc_type",
"value": "spreadsheet"
},
{
"name": "is_encrypted",
"boolValue": false
},
{
"name": "doc_title",
"value": "Copy of Spreadsheet Template File Name"
},
{
"name": "visibility",
"value": "private"
},
{
"name": "actor_is_collaborator_account",
"boolValue": false
},
{
"name": "owner",
"value": "user#example.com"
},
{
"name": "owner_is_shared_drive",
"boolValue": false
},
{
"name": "owner_is_team_drive",
"boolValue": false
}
]
}
]
}
]
...
}
You will have to filter out the reponse from here, however. For each element in the items array, the events key contains the information you will need to look for:
old_value is the original template spreadsheet's name
doc_id is the ID of the new spreadsheet
items.actor is the email of the person that completed the action.
References:
Example Audit request using the Try this API feature

How to get JSON payload sent by the Slack action message?

I am trying to build a Slack bot with interactive buttons. I have set up a Google Apps Script to handle the action performed on the Slack message. I want the payload of the request sent by the Slack. I have tried to get the request object by doing
function doPost(e) {
return processComment(e);
}
function processComment(e) {
Logger.log(e);
}
{postData=FileUpload, queryString=method=slack, parameter={method=slack, payload={"type":"block_actions","user":{"id":"U01835Mxxxx","username":"ravsamteam","name":"ravsamteam","team_id":"T0160UQZZZZ"},"api_app_id":"A018MPZ2xxx","token":"NTNRCTPDz8mxxxzxxxxxxxxx","container":{"channel_id":"C0190D8L2AU","is_ephemeral":false,"message_ts":"1597154895.001500","type":"message"},"trigger_id":"1281039280903.1204976558018.aa1055f6900d7884d9cd4ac34ffzzzzz","team":{"id":"T0160UQGE0J","domain":"ravsamhq"},"channel":{"id":"C0190D8L2AU","name":"blogs"},"message":{"type":"message","subtype":"bot_message","text":"This content can't be displayed.","ts":"1597154895.001500","bot_id":"B019BNL08BS","blocks":[{"type":"section","block_id":"mNavk","text":{"type":"mrkdwn","text":" New comment on RavSam's blog by hello","verbatim":false}},{"type":"section","block_id":"v3Ip","text":{"type":"mrkdwn","text":"*Blog:*\nhello\n\n*Comment:*\nravgeet errorCannot read property 'payload' of undefined","verbatim":false}},{"type":"actions","block_id":"1maVO","elements":[{"type":"button","action_id":"WSo=","text":{"type":"plain_text","text":"Approve","emoji":true},"style":"primary","value":"approved"},{"type":"button","action_id":"Vek\/","text":{"type":"plain_text","text":"Deny","emoji":true},"style":"danger","value":"denied"}]}]},"response_url":"https:\/\/hooks.slack.com\/actions\/T0160Uxxxxx\/1301968xxxxxx\/Q3gZhbeUCUIxxxxxxxxxxxxx","actions":[{"action_id":"WSo=","block_id":"1maVO","text":{"type":"plain_text","text":"Approve","emoji":true},"type":"button","value":"approved","action_ts":"1597213837.152704"}]}}, contentLength=2391.0, parameters={payload=[Ljava.lang.Object;#53f2e9fa, method=[Ljava.lang.Object;#5793298b}, contextPath=}
How do I get the payload? Once I have the payload JSON, I can use the actions to determine what action was taken by the user?
Yes. The payload contains all the information you need to identify the action. And it also contains a response_url to respond back.
Slack payload should look like this.
{
"actions": [
{
"name": "channels_list",
"selected_options": [
{
"value": "C012AB3CD"
}
]
}
],
"callback_id": "select_simple_1234",
"team": {
"id": "T012AB0A1",
"domain": "pocket-calculator"
},
"channel": {
"id": "C012AB3CD",
"name": "general"
},
"user": {
"id": "U012A1BCD",
"name": "musik"
},
"action_ts": "1481579588.685999",
"message_ts": "1481579582.000003",
"attachment_id": "1",
"token": "iUeRJkkRC9RMMvSRTd8gdq2m",
"response_url": "https://hooks.slack.com/actions/T012AB0A1/123456789/JpmK0yzoZDeRiqfeduTBYXWQ",
"trigger_id": "13345224609.738474920.8088930838d88f008e0"
}
You can learn more here.

How to use API translate of SAP Leonardo?

I need help with API translation of SAP Leonardo. I building a translation app for studing, and following the documentation a create the method translate:
translate: function () {
//Create JSON Model with URL
var oModel = new sap.ui.model.json.JSONModel();
var langTo = this.getView().byId("idTo").getSelectedKey();
var langFrom = this.getView().byId("idFrom").getSelectedKey();
var textOld = this.getView().byId("idOldText").getValue();
//API Key for API Sandbox
var sHeaders = {
"Content-Type": "application/json",
"APIKey": "My api Key"
};
//Available Security Schemes for productive API Endpoints
//OAuth 2.0
//sending request
//API endpoint for API sandbox
var oData = {
"sourceLanguage": langTo,
"targetLanguages": [
langFrom
],
"units": [{
"value": textOld,
"key": "ANALYZE_SALES_DATA"
}]
};
oModel.loadData("https://sandbox.api.sap.com/ml/translation/translation", oData, true, "POST", null, false, sHeaders);
//Available API Endpoints
//https://mlfproduction-machine-translation.cfapps.eu10.hana.ondemand.com
//https://mlfproduction-machine-translation.cfapps.us10.hana.ondemand.com
//You can assign the created data model to a View and UI5 controls can be bound to it. Please refer documentation available at the below link for more information.
//https://sapui5.hana.ondemand.com/#docs/guide/96804e3315ff440aa0a50fd290805116.html#loio96804e3315ff440aa0a50fd290805116
//The below code snippet for printing on the console is for testing/demonstration purpose only. This must not be done in real UI5 applications.
oModel.attachRequestCompleted(function (oEvent) {
var oData = oEvent.getSource().oData;
// console.log(oData);
});
}
I used two selectBox for to get language keys both calls "idTo" and "idFrom". And I used too a input for get a text will be translate with id "idOldText". But nothing happen. the oData value always empty in the last instruction. I'm used SAP WEBIDE and I guess that it is not need configure IDE for to use the API.
Someone can help me?
it would be helpful if you provide the error from your console.
But I already have a feeling that this ends up in a cross site request, and thus will be blocked because of using a full qualified URL. Also your header whitelist is maybe missing.
Do it like this and it should work:
1) create a destination in SAP CP
2) create a new sapui5 project in SAP WebIDE and adapt neo-app.json by addin a new destination path and header whitelist your request headers
{
"welcomeFile": "/webapp/index.html",
"routes": [{
"path": "/resources",
"target": {
"type": "service",
"name": "sapui5",
"entryPath": "/resources"
},
"description": "SAPUI5 Resources"
}, {
"path": "/test-resources",
"target": {
"type": "service",
"name": "sapui5",
"entryPath": "/test-resources"
},
"description": "SAPUI5 Test Resources"
}, {
"path": "/ml-dest",
"target": {
"type": "destination",
"name": "sapui5ml-api"
},
"description": "ML API destination"
}],
"sendWelcomeFileRedirect": true,
"headerWhiteList": [
"APIKey", "Accept", "Content-Type"
]
}
3) add your method and post the request || possible issues in your version: JSON object and request headers
onInit: function () {
var oModel = new sap.ui.model.json.JSONModel();
var sHeaders = {
"Content-Type": "application/json",
"Accept": "application/json",
"APIKey": "<<yourAPIKey>>"
};
var oData = {
"sourceLanguage": "en",
"targetLanguages": [
"de"
],
"units": [{
"value": "I would like to analyze my sales data.",
"key": "ANALYZE_SALES_DATA"
}]
};
var ODataJSON = JSON.stringify(oData);
oModel.loadData("/ml-dest/translation/translation", ODataJSON, true, "POST", null, false, sHeaders);
oModel.attachRequestCompleted(function (oEvent) {
var oData = oEvent.getSource().oData;
console.log(oData.units[0].translations[0]);
});
}
4) get a successful response object when loading your app :-)
References used:
Destination creation (my own blog entry btw.) https://blogs.sap.com/2018/09/05/successfactors-extensions-with-sapui5-and-the-correct-usage-of-sap-cp-destination-services/
SAPUI5 examples for SAP ML Inference Services (see multiple examples) https://developers.sap.com/tutorials/ml-fs-sapui5-img-classification.html

Javascript facebook bot function

I used to program in C++ but I'm trying to program a facebook bot in Javascript.
I have a function Options that creates option buttons. The buttons are programmed like this (1):
"buttons": [{
"type": "web_url",
"url": "https://www.messenger.com",
"title": "Use"
}]
But since I have lots of them I would like to create a function to create buttons.
I've tried to create a Button function like that:
function PLButton(type, title, payload) {
"type": type,
"title": title,
"payload": payload
}
And then substitute the code above (1) by this:
"buttons": [{PLButton("postback", "Drop", "PRESS_CANCEL")}]
But it doesn't work.
The object literal syntax and function body syntax are not interchangeable, but you can next an object literal within a function. If you want to construct and return an object, you need to combine your two attempts:
function PLButton(type, title, payload) {
return {
"type": type,
"title": title,
"payload": payload
};
}
The object literal syntax ({x: 1}) does something akin to creating a map (a dict-mode object) which the function can then return. This sort of helper is pretty common, since an object is easier to extend later than a list of loose parameters.
var initialButtonList = {"buttons": [{
"type": "web_url",
"url": "https://www.messenger.com",
"title": "Use"
}]}
function PLButton(type, title, payload) {
var newButton={//create newButton as object that holds key-value pairs
"type": type,
"title": title,
"payload": payload
};
return newButton;
}
initialButtonList.buttons.push(PLButton("postback", "Drop", "PRESS_CANCEL"));
//initialButtonList will now have the newly added button as well;
Solved!
I've just created a function like that:
function PLButton(tipo, titulo, accao){
var Butt = {type:tipo, title: titulo, payload: accao};
return Butt;
}
And incede the funcion Options :
"buttons": [PLButton("postback", "Use", "PRESS_USE_SCISOR"), PLButton("postback", "Drop", "PRESS_DROP_SCISOR")],

Categories

Resources