Error making listNotebooks request using Evernote's Javascript SDK - javascript

I am creating a Cordova/Phonegap mobile app using the Ionic framework. I'm using Evernote's Javascript SDK and successfully got the OAuth process working.
I'm stuck at the very last step. I am trying to list my notebooks and keep generating an error. Everything seems to be working fine up until this point:
noteStore.listNotebooks(authTokenEvernote, function (notebooks)
At that point, I get an error that reads "{"position":0,"totalSize":0}". I've looked all over the forum and can't figure out what it means, or how to fix it.
Here is my code.
// authTokenEvernote can now be used to send request to the Evernote Cloud API
console.log('got access token:', authTokenEvernote)
console.log('got notestore url:', noteStoreURL)
// Here, we connect to the Evernote Cloud API and get a list of all of the
// notebooks in the authenticated user's account:
var noteStoreTransport = new Thrift.BinaryHttpTransport("noteStoreURL");
var noteStoreProtocol = new Thrift.BinaryProtocol(noteStoreTransport);
var noteStore = new NoteStoreClient(noteStoreProtocol);
noteStore.listNotebooks(authTokenEvernote, function (notebooks) {
console.log('success!! : ');
console.log(notebooks);
}, function onerror(error) {
console.log('error:')
console.log(error);
});
};

The listNotebooks method (like most Evernote methods) returns a err object first, then the object containing the notebooks.
Here is an example of how the listNotebooks method could be called:
var notebooks = noteStore.listNotebooks(function(err, notebooks) {
console.log("Found " + notebooks.length + " notebooks:");
for (var i in notebooks) {
console.log(" * " + notebooks[i].name);
}
console.log(notebooks)
});

Related

Integrate Salesforce registration page with VanillaJS oidc-client-js, getting the error - No matching state found in storage

Integrate Salesforce registration page with VanillaJS, getting the error - No matching state found in storage
We are redirecting the user to Salesforce registration page when Create Account button is created.
Once the User registers in Salesforce, the user is redirected to our site but we are getting this error. ('No matching state found in storage').
We tried the below solution but still getting the same error.
As I stated in my answer, the oidc client maintains state information
in the local storage so that it can verify that it got the response
back from the intended server. You can mimic this by generating a
secure random string and saving it in localStorage. Do this before
sending a request to your auth server to register a new user.
Reference- Integrate third party login in from my registration page with IdentityServer4 and Angular 6 - 'No matching state found in storage'
Is there a function related to creating registration? How to fix this issue?
Thanks.
Appreciate your help.
After spending days on this issue. Finally found the workaround as registration is not a feature of OIDC.
To overcome this issue, need to follow the Sign In process same as for Sign Up process, created the startSignupMainWindow method same as startSigninMainWindow and passing the signUpFlag:true as shown below in code.
/* This function is written to mimic the oidc library sign in process flow */
function startSignupMainWindow() {
var someState = {
message: window.location.href,
signUpFlag: true
};
mgr.signinRedirect({
state: someState,
useReplaceToNavigate: true
}).then(function() {
log("signinRedirect done");
}).catch(function(err) {
log(err);
});
}
Reading the signUpFlag:true in UserManager.js and swapping the Salesforce Sign In page Url with Sign Up page url and calling the Register function in Code.
UserManager.js(oidc - client - dev - js / src / UserManager.js)
//UserManager Customised Code :
return this.createSigninRequest(args).then(signinRequest => {
Log.debug("UserManager._signinStart: got signin request");
navigatorParams.url = signinRequest.url;
navigatorParams.id = signinRequest.state.id;
if (signinRequest.state._data.signUpFlag) {
register(signinRequest.state._id, signinRequest.state._code_challenge);
} else {
return handle.navigate(navigatorParams);
}
})
The below code is Register function written in code.
/* This function is written to send the code_challenge to salesforce server so that
salesforce server holds the code challenge and used to verify the further requests(token-request)
against the code_challenge it received initially.*/
//Customised register function written outside the library (Inside our App):
function register(_id, code_challenge) {
var date = new Date();
var baseUrl = "SALESFORCE_URL/login/SelfRegister?expid=id";
var expId = "id";
var userPage = encodeURIComponent(window.location.href);
var appDetails = "response_type=code&" +
"client_id=CLIENT_ID" +
"client_secret=CLIENT_SECRET&" +
"redirect_uri=CALLBACK_URL&" +
"state=" + _id + "&code_challenge=" + code_challenge + "&code_challenge_method=S256&response_mode=query";
var encodedapp = encodeURIComponent(appDetails);
var startUrl = "/services/oauth2/authorize/expid?" + encodedapp;
var signUpUrl = baseUrl + "&startURL=" + startUrl;
window.open(signUpUrl, "_self");
};

How to inspect Node.JS AWS Lambda data?

I am new to both Lambda and Node.JS. I originally wanted to write the function in Python, but boss says he'd like it in Node. I am writing an AWS Lambda function to turn off specified EC2 instances at the end of the day. I am having trouble inspecting if describeInstances is grabbing the correct data.
Right now the code shows return String(instances); but I've tried numerous different things such as return instances.response.data; which gives an error about trying to stringify the data or something.
var AWS = require('aws-sdk');
var ec2 = new AWS.EC2();
AWS.config.update({region: 'us-west-2'});
exports.handler = async (event) => {
var params = {
Filters: [
{
Name: "tag:Parking",
Values: [
"true"
]
}
]
};
var instances = ec2.describeInstances(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else return data; // successful response
});
//return Object.getOwnPropertyNames(instances);
//return instances.response.httpResponse;
return String(instances);
};
I just want to be able to view a list of the returned EC2 instances to see if I have the correct instances before turning them off.
describeInstances returns an AWS.Request object not the actual results of the operation, which are returned in the callback handler you passed to the describeInstances function.
You can do it like this using async/await syntax
const data = await ec2.describeInstances(params).promise();
return data
You should be able to view the logs in the AWS Console. The easiest way is to go to the Lambda console, select the function in question, click "Monitoring" near the top left, and then "View logs in CloudWatch" just below that to the right.

YouTube Search Node.js with Google API

I am trying to do a YouTube search with the Google APIs within Node.
I am using this as somewhat of a tutorial:
https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client
I have some of the basics working:
var google = require('googleapis');
var YOUTUBE_API_KEY = "--YOUR_API_KEY";
var youtube = google.youtube('v3');
var requests = youtube.search.list({part:'snippet', q: 'cats', maxResults: 10});
When I call this I get this message:
Error: Daily limit for Unauthenticated Used Exceeded.
Now, this is obviously because I'm not using my API key. However, I cannot find any resource out there that shows you how the API key is used for Node.
Anything I find tells me to do something like this:
var YOUTUBE_CLIENT_KEY = '';
var CLIENT_SECRET = '';
var REDIRECT_URL = '/';
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
google.options({auth: oauth2Client});
Followed by my "youtube.search.list...".
The issue with this approach is I have NO idea where to get:
CLIENT_ID
CLIENT_SECRET
REDIRECT_URL
I cannot find any of these anywhere online. I have tried to just follow Javascript tutorials, since Node obviously uses Javascript, although it always requires the oAuth2... which requires the three things above.
Any helps/hints?
You should input api key in the auth parameter. This is the right way of doing it as per the https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client sample docs.
var google = require('googleapis');
var youtube = google.youtube({
version: 'v3',
auth: "your-api-key"
});
youtube.search.list({
part: 'snippet',
q: 'your search query'
}, function (err, data) {
if (err) {
console.error('Error: ' + err);
}
if (data) {
console.log(data)
}
});
Thanks
It took me a while to find this point but I am a beginner on node.js and googleapis, so if someone else would like to expand this answer they can.
I believe to set simply using the Simple API key, just warning that you should only keep this key on the server side. Never give this key out, or it can be abused!
var googleapis = require('googleapis');
googleapis.client.setApiKey('YOUR API KEY');
Found this via https://developers.google.com/api-client-library/javascript/features/authentication
under Simple access using the API key

Error when sending message with realtime.co - Boolean is not a function

I am using realtime.co for realtime messaging in my .NET 4.5/Javascript webapp.
I created a connection using the code:
xRTML.ready(function () {
xRTML.Config.debug = true;
globalRealtimeConnectionId = generateUUID();
globalRealtimeToken = getRealtimeToken();
globalMyConnection = xRTML.ConnectionManager.create(
{
id: globalRealtimeConnectionId,
appkey: 'xxxx',
authToken: globalRealtimeToken, // insert token
url: 'http://ortc-developers.realtime.co/server/2.1'
});
globalMyConnection.bind(
{
// When we get a message, process it
message: function (e) {
var user = e.message; // the use that just joined
}
});
globalMyConnection.active = true;
});
On the server I gave permissions to "main:*" (all sub channels) and returned a token.
When I send a message to the user from the server using the following code:
OrtcClient client = (OrtcClient)Application["realtime"]; // get reference to client, which initialized in global.asax
client.Send(channel, user); // send message
user is a string with the username, channel is the channel name (e.g. main:12_323_34_. I get the following error in xrtml-custom-3.2.0-min.js:1
Uncaught TypeError: boolean is not a function xrtml-custom-3.2.0-min.js:1
c.Connection.process
(anonymous function)
f.proxy
IbtRealTimeSJ.d.sockjs.d.sockjs.onmessage
x.dispatchEvent
m._dispatchMessage
m._didMessage
m.websocket.d.ws.onmessage
From what I can tell, the client is subscribed because it triggers something when a message is sent to it from the server. But I can't understand the source of the error. Because of the error, the function binded to "message:" is not triggered.
For debugging purposes, if I were you, I would include the non-minified version so you can see exactly what function is causing the error. Once you've done that, it should be easier to track down.
One other quick note is when making RESTful calls you should try to do this in the back end so your api key is not exposed to the public. This would obviously only be an issue when you are creating a public facing website, so if this is an organizational (internal) application you can disregard.

Dashboard data with Good data SDK

I need to consume my company 'Target Social R3 V3' dashboard data with Good data Javascript SDK. First I'm trying to get pinterest data as start but I'm receiving error 400 Bad request. I'm newbie to good data api and following methods given in good data examples in Java script SDK.
$('#root').append('<div class="login-loader">Logging in...</div>');
gooddata.user.login(user, passwd).then(function() {
// Loged in
$('div.login-loader').remove();
$('#root').append('<div class="loading">Logged in... Loading metrics</div>');
// Do your stuff here
// ...
gooddata.md.getMetrics(projectId).then(function(dataSets) {
$('div.loading').remove();
$('#root').append('<div class="dataLoading">Laoding data...</div>');
$('#root').append('<p>Total number of metrics ' + dataSets.length + '</p>');
elements=[];
dataSets.forEach(function(ds) {
var dstr = JSON.stringify(ds.title);
if(dstr.toLowerCase().indexOf("pinterest account followers") > 0)
{
var did = JSON.stringify(ds.identifier);
$('#datasets').append('<li>'+did+'</li>');
elements.push(did);
}
});
$('#root').append('<p>Total number of choosen metrics '+elements.length + ' and element '+elements[0] +'</p>');
gooddata.execution.getData(projectId, elements).then(function(dataResult)
{
$('div.dataLoading').remove();
console.log('Social Data:\n'+ JSON.stringify(dataResult));
});
});
});
I'd appreciate if some one could explain about attributes and metrics passed here as parameters.
Make sure your sample is under gooddata-js/examples/ folder (let's assume is named 'mysample') and it has index.html file in that directory. Set user and passwd variables in your script file to your real GoodData user name and password. Run grunt dev and access your sample at https://localhost:8443/mysample/index.html. It should work.
If it does not work, please provide the details (message body) of the 400 error you are getting.

Categories