Unable to Get Contacts on FirefoxOS - mobile

I have a FirefoxOS device and I am trying to create an application to manage the contacts. I am unable to get the contacts both from the Device and the Simulator (both have 1.3 version)
Following is my code (taken from the help):
var cursor = navigator.mozContacts.getAll({});
cursor.onsuccess = function() {
if (cursor.result) {
console.log("Got contact with name: " + cursor.result.name.join(" "));
cursor.continue();
} else {
alert("Done!");
}
};
cursor.onerror = function() {
alert("Error getting contacts");
console.log( cursor );
};
Following is the segment from my manifest file:
...
"permissions": {
"storage": {
"description": "Required for storing data"
},
"contacts": {
"description": "Needed to access the contacts",
"access": "readonly"
}
},
...
It always falls to the onerror function. Need help.

Did you set in the manifest:
"type": "privileged",
?
Otherwise please post the the value of cursor.error when it fails.

Related

Github Login (oAuth ) from react- chrome extension

I am building a simple chrome extension which will make some simple API calls.
For this, I need the user to be logged in with a Github Account, however, if I set up a new oAuth app on github, I need to add Homepage URL and Authorization callback URL which, as far as I understand, we don't have from a Chrome Extension popup.
IMPORTANT: I don't want to use firebase. All I need is to be able to get the user code, which I can process in my backend after to get the token and all the rest.
Need you help here ! :-)
Here is my background file
const GITHUB_AUTHORIZATION_UL = "https://github.com/login/oauth/authorize";
const CLIENT_ID = encodeURIComponent("xxxx");
const SCOPE = encodeURIComponent("user:email");
let user_signed_in = false;
function create_auth_endpoint() {
let endpoint_url = `${GITHUB_AUTHORIZATION_UL}
?client_id=${CLIENT_ID}
&scope=${SCOPE}`;
return endpoint_url;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === 'login') {
chrome.identity.launchWebAuthFlow({
url: create_auth_endpoint(),
interactive: true
}, (response) => {
console.log(response)
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError)
console.log("Could not authenticate.");
sendResponse('fail');
} else {
user_signed_in = true;
sendResponse('success');
}
});
return true;
} else if (request.message === 'logout') {
user_signed_in = false;
sendResponse('success');
}
});
And my login handler from popup.tsx
const handleLogin = () => {
chrome.runtime.sendMessage({ message: 'login' }, function (response) {
console.log(response)
if (response === "success") {
window.close();
}
});
Manifest:
{
"name": "test ext",
"description": "test ext",
"version": "1.0.0",
"manifest_version": 3,
"icons": {
"16": "favicon-32.png",
"48": "favicon-32.png",
"128": "favicon-32.png"
},
"action": {
"default_popup": "popup.html",
"default_title": "test ext",
"default_icon": "favicon-32.png"
},
"permissions": ["storage", "identity"],
"options_page": "options.html",
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
]
}
I tried with various options for the requested url for github such as : http://chrome-extension://CHROME_ID/popup.html
=> This fails directly.
Interestingly, if I just input https://www.google.com, I have a popup with the github login, then I am directly to google and it fail.
However, the extension authorization is added as "accepted" in my github account.
Here is my log from the background for response :
{message: 'The user did not approve access.'}eventhough I approved it. Once I am redirected to the popup with www.google.com it fails

Can Facebook Messenger Webview access the LocalStorage API to store data on client side?

I want to store 6 booleans on the user side, if he reaches 6 sites in a city.
Can I use LocalStorage or even cookies, inside the Messenger Webview ?
If I close the Webview and open it again, will the data be still there ?
After test, yes it can.
So you can easily open a button to the Webview like that in your botfile app.js on the server :
function openWebview(sender_psid, text,button_text){
let button_response = {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": text,
"buttons": [
{
"type":"web_url",
"url":"<URL>",
"title":button_text,
"webview_height_ratio": "compact",
"messenger_extensions": "true",
"fallback_url": "<FB_URL>"
}
],
}
}
}
callSendAPI(sender_psid, button_response);
}
to be complete...
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
and on index.html on client side by example you can store simple data as easy as :
<div id='myDiv'>nothing for the moment</div>
<script>
localStorage.setItem('key1','myValue1')
var test = localStorage.getItem('key1')
document.getElementById('myDiv').innerHTML = test
</script>
You will now see 'myValue1' displayed on the Facebook Messenger Webview

Can't get my Facebook messenger bot to respond with response from my service

I have made an Api.Ai bot and integrated it with both Slack and Facebook Messenger. When I write to it, it answers with the responses set up in Api.Ai for both Slack and Facebook Messenger, but on the fulfillment part, when Api.Ai makes a call to my service, it works fine in Slack, but I get no response from Facebook Messenger.
The format of the message I return from my service:
{
"contextOut": [
{
"lifespan": 2,
"name": "weather",
"parameters": {
"city": "Rome"
}
}
],
"data": {
"facebook": {
"message": {
"text": "Great success!"
},
"recipient": {
"id": "1454102654663349"
}
},
"slack": {
"attachments": [
{
"color": "#00A399",
"title": "Hello world!",
"title_link": "https://www.mywebsite.se"
}
],
"text": "Horray! Great success! :)"
}
},
"displayText": "Whatever!!",
"followupEvent": {
"followupEvent": {
"data": {
"parameter": "<parameter_value>"
},
"name": "<event_name>"
}
},
"source": "mywebsite.se",
"speech": "Whatever!?"
}
The Facebook recipient id comes from the request made to my service.
request.result.contexts[0].parameters.Facebook_sender_id
I have verified my webhook under the product settings tab in the Facebook app.
I have subscribed my app to the page using my page access token.
I have checked the following events under webhooks: messages, messaging_postbacks
I'm logged in as the admin user of the app, when trying the bot in Facebook.
I'm out of ideas, there must be something I've missed?
EDIT:
I've set up an Azure Function as my webhook for testing purposes.
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
var request = await req.Content.ReadAsAsync<ApiAiMessage>();
log.Info($"Incoming: {JsonConvert.SerializeObject(request)}");
var slack_message = new {
text = $"Horray! Great success! :)",
attachments = new[] {
new {
title = "Hello world!",
title_link = "https://www.mywebsite.se",
color = "#00A399"
}
}
};
var facebook_message = new {
recipient = new {
id = $"{request.result.contexts[0].parameters.Facebook_sender_id}"
},
message = new {
text = "Great success!"
}
};
var response = new
{
data = new
{
facebook = facebook_message,
slack = slack_message
},
speech = "Whatever!?",
displayText = "Whatever!!",
contextOut = new[] {
new {
name = "weather",
lifespan = 2,
parameters = new {
city = "Rome"
}
}
},
source = "mywebsite.se",
followupEvent = new {
followupEvent = new {
name = "<event_name>",
data = new {
parameter = "<parameter_value>"
}
}
}
};
log.Info($"Outgoing: {JsonConvert.SerializeObject(response)}");
return req.CreateResponse(HttpStatusCode.OK, response, new MediaTypeHeaderValue("application/json"));
}
Where are you actually sending the API.ai response back to Facebook Messenger? This requires some FB specifics like the 'page token' and the fact it works for Slack but not FB makes me believe it's just something simple left out like this. Here's an example in javascript of what the call would look like
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: config.FB_PAGE_TOKEN
},
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
if (messageId) {
console.log("Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("Successfully called Send API for recipient %s",
recipientId);
}
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
}

Chrome Packaged App: Retrieving FileEntry in Dart from command line (LaunchData) parameter

Similarly to another post on this topic, I've been attempting to run my app from the command line with the file path of a local XML file so that my main.dart can parse this file in order to extract information relevant to program operation from it. I've been stumped as to how to appropriately access the FileEntry reference included in launchData -- the parameter for the onLaunched event.
Here's what I currently have:
manifest.json:
...
"permissions": [
"storage",
"fileSystem",
"*://*/*"
],
"file_handlers" : {
"any" : {
"types" : [ "*" ]
}
},
...
background.js:
chrome.app.runtime.onLaunched.addListener(function(launchData) {
chrome.app.window.create(
'htmlFile.html',
{...},
function(createdWindow) {
createdWindow.contentWindow.launchData = launchData;
});
});
At this point, I can't access launchData from main.dart because trying to do
FileEntry entry = (chrome.app.window.current().contentWindow.launchData as chrome.LaunchData).items.elementAt(0).entry;
to get the FileEntry results in an error for accessing launchData. I'm really confused about how I'm supposed to access the FileEntry that I want from my Dart code as a result.
I ended up with this as my solution:
manifest.json:
...
"file_handlers": {
"any": {
"extensions": [
"xml"
]
}
},
...
background.js:
chrome.app.runtime.onLaunched.addListener(function(launchData) {
chrome.app.window.create(
'htmlSource.html',
{
id: 'mainWindow',
state: "fullscreen"
},
function(createdWindow) {
if(launchData.items !== undefined) {
launchData.items[0].entry.file(
function(result) {
var reader = new FileReader();
var XML;
reader.onloadend = function(){
XML = reader.result;
chrome.storage.local.set({'XML': XML});
};
reader.readAsText(result);
},
function(){
console.log("Error reading XML file");
}
);
} else {
console.log("No file was detected.");
}
});
});
The dart code to retrieve the XML was simply:
String text = (await chrome.storage.local.get('XML'))['XML'];

400 response from GAE Cloud Endpoints

I'm trying the following api call to my GAE Cloud Endpoint:
gapi.client.myapp.foo.update({
"value": "foobar",
"key": "keyvaluefromlistoperation"
}).execute(function(resp) {
console.log(resp);
});
Which responds with the following:
[
{
"error": {
"code": 400,
"message": "Bad Request",
"data": [
{
"domain": "usageLimits",
"reason": "keyInvalid",
"message": "Bad Request"
}
]
},
"id": "gapiRpc"
}
]
Note, prior to this call I have authenticated, inserted several foo objects, then call list to have them returned to the client. The api's explorer update call works fine and running the jQuery snippet below works fine as well. Any suggestions? Or am I just in experimental bug land.
var token = gapi.auth.getToken();
$.ajax({
type:"POST",
beforeSend: function (request) {
request.setRequestHeader("Content-Type","application/json");
request.setRequestHeader("Authorization", token.token_type+" "+token.access_token);
},
url: "https://myappid.appspot.com/_ah/api/myapp/v1/foo/update",
data:JSON.stringify({
"value": "foobar",
"key": "keyvaluefromlistoperation"
}),
processData: false,
dataType: "json",
success: function(msg) {
console.log(msg);
},
failure: function(msg) {
console.log(msg);
}
});
Here is the Java code:
#Api(
name = "myapp",
description = "This is the myapp rest interface",
scopes = {"https://www.googleapis.com/auth/userinfo.email"},
version = "v1",
clientIds = {Ids.WEB_CLIENT_ID}
)
public class FooV1 {
private static PersistenceManager getPersistenceManager() {
return PMF.get().getPersistenceManager();
}
#ApiMethod(
name = "foo.update",
httpMethod = HttpMethod.POST
)
public Foo update(Foo foo, User user) throws OAuthRequestException, IOException, UnauthorizedUpdateException {
PersistenceManager pm = PMF.get().getPersistenceManager();
if (user != null) {
try {
Foo f = pm.getObjectById(Foo.class, foo.getId());
if ( Security.isUpdateAuthorized(f, user) ) {
if( foo.getValue() != null ) f.setValue(foo.getValue());
} else {
throw new UnauthorizedUpdateException("");
}
} finally {
pm.close();
}
} else {
throw new OAuthRequestException("Invalid user.");
}
return foo;
}
}
I had the same problem. Apparently you can't use "key" as a field once you deploy to GAE. Locally it worked fine.

Resources