What is the difference between "responseHeaders", "blocking", "asyncBlocking" in onAuthRequiredOptions? - google-chrome

I am working on a project in which I have to login a BasicAuth website. I come across the document of webRequest and realize there are three different onAuthRequiredOptions: namely "responseHeaders", "blocking", "asyncBlocking".
I have tried them and the only thing I found out is that with "asyncBlocking", Chrome will let the extension has a chance to fire a callback, which can authenticate the BasicAuth, change the request header, e.t.c..
chrome.webRequest.onAuthRequired.addListener(
function(details, callback) {
callback({
authCredentials: {username: "login", password: "login"}
});
},
{urls: ['<all_urls>']},
['asyncBlocking']
);
But with "responseHeaders", "blocking", their behaviors seems to be the same, they both DO NOT have callback, but then I couldn't figure out the other differences.
I believe there is a reason for separating into three values. So I would like to know what is the philosophy behind them?
Thank you.

The responseHeaders permission is used to populate the optional property of details and is available in a couple of the methods. Without this permission, the headers that are received aren't available to the webRequest handler. As for blocking and asyncBlocking they are the same except one is synchronous and the other is not. asyncBlocking allows you to specify a callback like in your example, while blocking expects a return in the handler itself like so:
chrome.webRequest.onAuthRequired.addListener(function(details) {
return {authCredentials: {username: "login", password: "login"}};
},
{urls: ['<all_urls>']},['blocking']);

Related

VSCode JSON language server unhandled method

I posted this last week and have made progress since, where I've discovered the packages that VSCode's JSON support is delivered via extensions:
https://github.com/vscode-langservers/vscode-json-languageserver
https://github.com/Microsoft/vscode-json-languageservice
and all the rest. I'm trying to reuse this in an Electron (NodeJS) app. I'm able to fork a process starting the language server and initialize it:
lspProcess = child_process.fork("node_modules/vscode-json-languageserver/out/jsonServerMain.js", [ "--node-ipc" ]);
function initialize() {
send("initialize", {
rootPath: process.cwd(),
processId: process.pid,
capabilities: {
textDocument: true
}
});
}
lspProcess.on('message', function (json) {
console.log(json);
});
and I see that console.log firing and showing it seems to be up correctly.
My thoughts are that I just want to send a textDocument/didChange event as per the LSP:
send('textDocument/didChange', {
textDocument: TextDocument.create('foo://bar/file.json', 'json', 0, JSON.stringify(data))
});
where data is a JSON object representing a file.
When I send that message and other attempts at it I get
error: {code: -32601, message: "Unhandled method textDocument/didChange"}
id: 2
jsonrpc: "2.0"
Any idea what I'm doing wrong here? My main goal is to allow edits through my Electron app and then send the updated JSON to the language server to get schema validation done.
EDIT: I'm even seeing unhandled method initialized when I implement connection.onInitialized() in the jsonServerMain.js.
EDIT2: Update, I figured out where I was going wrong with some of this. initialized and textDocument/didChange are notifications, not requests.
EDIT2: Update, I figured out where I was going wrong with some of this. According to the LSP, initialized and textDocument/didChange are notifications, not requests. Requests have an id field that notifications don't, so when sending a notification, remove the ID field.

Customize Loopback response after save

I have a loopback 2.x app, in which I have a model Conversation and a model Message, with a relationship "Conversation has many messages". I want to customize the response for POST conversations/:id/messages with a json response different than the default, say {status: 'success'}. I tried to use remote hook for the method __create__messages, but it did not work:
Conversation.afterRemote('__create__messages', function(ctx, next) {
ctx.result.data = {
success: 'yes'
};
next();
});
This still returns the default response. How can I return a custom json for a remote method? I have seen examples only for all models, or for all methods: multiple models, multiple methods
Maybe you can try a version of following code below. Also, I think you are meaning to to manipulate data before the method finishes, not after. If you wait, the response will already be created, preventing your intended goal. Let me know if this works (replace with methods that will work for your use case).
Conversation.observe('before save', function(context, next) {
var instance = context.instance || context.data;
if (!instance) return next();
// Your code here
next();
});

How to use Smooch postbacks?

I can't seem to find any documentation on how to actually use the postabck feature. Does it call functions on the server? What does ti do with the pasees value?
%[Button label here](postback:PAYLOAD_HERE) // What is the payload?
The payload is actually whatever you want!
Postback buttons can be used as triggers to your webhook. When a user taps on your postback button, a payload will be sent to your webhook with the following data:
{
"trigger": "postback",
"postbacks":[{
...
"action": {
"_id": "571530ee4fae94c32b78b170",
"type": "postback",
"text": "Read more",
"payload": "YOUR_PAYLOAD_HERE" // <---- your payload!
}
}],
...
}
For complete payload see this reference: http://docs.smooch.io/rest/#webhooks-payload
On your side, you could have automated messages, event scheduling or anything you want.
A simple payload could be TELL_ME_JOKE and on your backend, you could fetch your database for a joke, then send a message through the Smooch API to reply back.
Another payload could be RESERVE_MONDAY. When the user taps that button, your webhook receives RESERVE_MONDAY. Then you could use that value to know what to do next (call into your application to reserve that time slot).
Here's a simple Node.js implementation:
const express = require('express');
const SmoochCore = require('smooch-core');
const smoochApi = new SmoochCore({
keyId: 'some-key',
secret: 'some-secret',
scope: 'app'
});
express.Router().post('/smooch/webhooks', (req, res) => {
const smoochPayload = req.body.postbacks[0].action.payload;
const userId = req.body.appUser._id;
if (smoochPayload === 'TELL_ME_JOKE') {
smoochApi.conversations.sendMessage(userId, {
text: 'A cow walks into a bar...',
role: 'appMaker'
});
} else if (smoochPayload === 'RESERVE_MONDAY') {
CalendarController.reserve(userId, 'monday');
}
res.end();
});
Using the payload also allows you to use different button labels, but keep the same payload (ie. different translations).
Note: it could be anything even JSON if you want!
I hope this can help you!
The payload is what you want your bot to return. I'm not sure if my way of describing it is the best since I'm new at this. Think of it this way - If you have a button labeled %[Yes](postback:YES), then when the user clicks on the button that says yes, it will be just like they typed the word "yes."

REST not working on bluemix due to CORS

I am new to bluemix, I have simple Rest service with few functions and called from angular js.
Here is below in Rest service class:
#POST
#Path("getTest")
#Produces("application/json")
public Response getTest(#QueryParam("accountId") String accountId) throws Exception, IOException {
System.out.println("HelloResource.getTest() "+accountId);
...
...
return Response.ok(dbData).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods","POST, HEAD, GET, DELETE, PUT, OPTIONS")
.build();
}
Further, in client angular js is invoking this rest service in
$scope.searchcall = function(acctid)
{
$http({
method: 'POST',
url: 'http://javarestapi61.mybluemix.net/api/hello/getTest',
headers: {'Content-Type': 'application/json','Access-Control-Allow-Origin': '*'},
data: {"accountId": $scope.accountId}
}).success(function (data)
{
//never been successful onblue mix
}).error(function(data) {
alert("failure1"); //always landing here..
});
};
Looks like this is best solution which i tried. I am not sure, what i can try further to allow explicit permission on bluemix Rest application. BTW above app when deployed on local liberty, it works well.
Also i can access the same Rest service on bluemix, if i change return type as String and access via browser..(without even any additional permission)
Further, I saw that Chrome network details shows that, Preflight request go and returns with 200 (OPTIONS) then second request is actual POST which never succeeds.
What you can do is modify the method to :
public Response getTest(#QueryParam("accountId") String accountId, HttpServletRequest req) throws Exception, IOException{
//then your code
}
Now after that add the following:
since the browser looks for http://127.0.0.1:8080 in the Allow Origin Header, you need to make sure this is getting added in the following line:
response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
To get the http://127.0.0.1:8080 you can use :
request.getRemoteAddr() + ":" + request.getRemotePort();
But if the browser looks for localhost then go for the :
request.getRemoteHost().
Avoid adding * because some browsers will not still allow that.
Hope that solves your problem.
And of course add this to the header:
response.setHeader("Access-Control-Allow-Methods","POST, HEAD, GET, DELETE, PUT, OPTIONS")
Finally when everything else that i tried did not work, below solution worked for me..
I have just added another separate url in my rest service class..
#Path("/getTest")
#OPTIONS
public Response getOptions() {
return Response.ok().header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS").header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
}
Basically response of options have the "allowed" methods given by service..

How to create microsoft/google translate button for each div separately?

How to create microsoft or google translate button for each div?
Each div has content in different language and I would like to add a translate button for each div and make it respond to only that div like the button in the following link.
http://www.bing.com/widget/translator
But when I use the code mentioned in the link above, it translates the whole webpage. I would like to translate each div separately by clicking on the respective translate button.
Can the same thing be done easily using google translate?
Any translator is fine with me. Kindly help. Thanks.
This how the users' post appear on my website.
I would like to have a translate button for each of the divs so that the users can translate each div into any language they want.
Each of my div has an id.
Below I'm explaining how to get started with Microsoft Translator API. The very same functionality can be implemented via Google Translate API however it was somehow easier for me with MS as they offer 2M characters/monthly translation for free whereas Google charges minimum of 1$ for testing.
Prerequisites:
Sign up for free subscription on Microsoft Translator. For that you will be asked to create new MS account or login with existing one.
Register your application on Azure Datamarket.
Registration example. Note: There are two important fields here Client ID and Client secret you will need them for access token requests.
Implementation:
First things first, every request to the API should include access token. Expiration time is 10 minutes so you will have to renew them before they expire. Ideally the process should be done on the back-end side to protect your Client secret and result (token + expiration time) send back to web application.
Node.js example:
var request = require("request");
var options = {
method: 'POST',
url: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/',
form: {
// Client ID & Client secret values (see screenshot)
client_id: 'translator_3000',
client_secret: 'ZP8LzjZkKuFAb2qa05+3nNq+uOcqzWK7e3J6qCN1mtg=',
scope: 'http://api.microsofttranslator.com',
grant_type: 'client_credentials'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Response contains few fields including access_token, use its value for further requests.
{
"token_type": "http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0",
"access_token": "http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=translator_3000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1435405881&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=st9LJ0F8CKSa6Ls59gQN0EqMWLFed5ftkJiOCVXE4ns%3d",
"expires_in": "600",
"scope": "http://api.microsofttranslator.com"
}
Now when we have access token it's time for translation request. Note: These are JSONP requests and access token is supplied using query string parameter appId in the format Bearer <token> (separated by space). Query string also includes text parameter - text of your post and to parameter - language code selected by user, list of all supported codes and language friendly names you can get from API as well.
Here is example:
var settings = {
"url": "https://api.microsofttranslator.com/v2/Ajax.svc/Translate",
"method": "GET",
"dataType": "jsonp",
"jsonp" : "oncomplete",
"data" : {
"text" : "Good Morning StackOverflow",
"to" : "uk",
"appId" : "Bearer http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=translator_3000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1435405881&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=st9LJ0F8CKSa6Ls59gQN0EqMWLFed5ftkJiOCVXE4ns%3d"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Response is translated string to be replaced with post original text:
"Доброго ранку StackOverflow"
And lastly, all language codes:
http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguagesForTranslate
and friendly names for selected codes:
http://api.microsofttranslator.com/V2/Ajax.svc/GetLanguageNames?locale=en&languageCodes=["en", "de", "es", "uk"]
Official documentation included.
Use the Class element <div class="micropost293"> shown below.
<div class="micropost293"><p>Тестирование</p>
<div class="micropost293_control" lang="en"></div>
<script>
function googleSectionalElementInit() {
new google.translate.SectionalElement({
sectionalNodeClassName: 'micropost293',
controlNodeClassName: 'micropost293_control',
background: '#f4fa58'
}, 'google_sectional_element');
}
</script>
</div>
//Place this Script at bottom of page.
<script src="//translate.google.com/translate_a/element.js?cb=googleSectionalElementInit&ug=section&hl=en"></script>