Javascript to Coffeescript conversion doesn't work - coffeescript

I have the following function that works perfectly in Javascript
function graphite_get_data(target) {
return context.metric(function(start, stop, step, callback) {
var fetch_time = new Date().getTime();
if ((fetch_time-current_time) < 6000 && saved_data.length > 0) {
callback(null, graphite_parse(saved_data));
}
else {
// -------------- Begin Request New Data ------------------
d3.json(host + "/render?format=json"
+ "&target=" + encodeURIComponent(target)
+ "&from=" + graphite_format_date(start - 2 * step)
+ "&until=" + graphite_format_date(stop - 1000),
function(data) {
if (!data) return callback(new Error("unable to load data"));
current_time = fetch_time
saved_data = data;
callback(null, graphite_parse(data));
});
// -------------- End Request New Data --------------------
} // else
}); // return
}
When I try to convert this to coffeescript using http://js2coffee.org, it doesn't work and I'm not sure how to debug:
graphite_get_data = (target) ->
console.log(global_pod)
console.log("hi") #prints
context.metric (start, stop, step, callback) ->
console.log("hi") #doesn't print
fetch_time = new Date().getTime()
if (fetch_time - current_time) < 6000 and saved_data.length > 0
callback null, graphite_parse(saved_data) # will use global variable test_pod
else
# -------------- Begin Request New Data ------------------
d3.json host + "/render?format=json" + "&target=" + encodeURIComponent(target) + "&from=" + graphite_format_date(start - 2 * step) + "&until=" + graphite_format_date(stop - 1000), (data) ->
return callback(new Error("unable to load data")) unless data
current_time = fetch_time
saved_data = data
callback null, graphite_parse(data) #will use global variable test_pod
# -------------- End Request New Data --------------------
Can you advise me on how to debug coffee script?
EDIT: I checked the the javascript generated and saw this
graphite_get_data = function(target) {
var fetch_time;
console.log("hi");
context.metric(function(start, stop, step, callback) {});
fetch_time = new Date().getTime();
console.log("hi");
if ((fetch_time - current_time) < 6000 && saved_data.length > 0) {
callback(null, graphite_parse(saved_data));
return true;
}
else {
d3.json(host + "/render?format=json" + "&target=" + encodeURIComponent(target) + "&from=" + graphite_format_date(start - 2 * step) + "&until=" + graphite_format_date(stop - 1000), function(data) {
if (!data) {
return callback(new Error("unable to load data"));
} // end if
current_time = fetch_time;
saved_data = data;
callback(null, graphite_parse(data));
return true;
}); //end function(data)
return true;
} //end else
// missing });
};
graphite_format_date = function(time) {
return Math.floor(time / 1000);
};
return graphite_parse = function(data) {
var pod_data, pod_json_data;
pod_json_data = $.grep(data, function(e) { return e.target === test_pod; });
pod_data = pod_json_data[0]["datapoints"].slice(1).map(function(d) { return d[0]; });
return pod_data;
};
}
}); // what is this here?? it should be in missing
}).call(this);
and found the problem to be }); missing in one place and added in another wrong place
still working on how to fix it

Can you advise me on how to debug coffee script?
Sure: use sourcemaps in Chrome. Keep in mind that sometimes a step in Coffee is several steps in JS, so sometimes you'll see odd looking stepping behavior.
Regarding the conversion of your code, I think you may have copied or pasted something wrong, because it looks fine to me:
graphite_get_data = (target) ->
context.metric (start, stop, step, callback) ->
fetch_time = new Date().getTime()
if (fetch_time - current_time) < 6000 and saved_data.length > 0
callback null, graphite_parse(saved_data)
else
# -------------- Begin Request New Data ------------------
d3.json host + "/render?format=json" + "&target=" + encodeURIComponent(target) + "&from=" + graphite_format_date(start - 2 * step) + "&until=" + graphite_format_date(stop - 1000), (data) ->
return callback(new Error("unable to load data")) unless data
current_time = fetch_time
saved_data = data
callback null, graphite_parse(data)
I've found js2coffee to be pretty reliable.
The biggest problem with your code is here:
context.metric(function(start, stop, step, callback) {});
That line didn't come over right in your version, but was fine in my version. I'm not sure why, I suspect you're missing some indents in the coffee code. Indents in coffeescript are very important.
I'd also recommend trying CoffeeScript Enhanced in Chrome -- js2coffee is paying for that traffic and not getting anything for it.

Looks like there is an indentation problem at the start of the coffeescript.
This is what generates your 2nd javascript:
graphite_get_data = (target) ->
context.metric (start, stop, step, callback) ->
fetch_time = new Date().getTime()
My coffeescript starts:
graphite_get_data = (target) ->
context.metric( (start, stop, step, callback) ->
fetch_time = new Date().getTime()
if ...
else ...
)

Can you advise me on how to debug coffee script?
You can't. Debug the resulting JavaScript. CoffeeScript isn't run directly, it gets trans-compiled to JavaScript.

Related

protractor promises - querying an API using "request"

I am trying to use protractor to call an api - it will return some JSON to me and I want to assert against it. I thought I had this working, until I tried to take it further and realised I hadn't got it right, but having a bit of a time trying to work out why.
I have placed some console.logs in and expected the sequence to be 1,2,3 however it appears to be 3 (test finished) then 2 and 1. So I suspect a promise issue.
code below:
'use strict';
var request = require('request');
var path = require('path');
var info;
//var fname = null;
var fname = 'joe';
describe("Sample test", function() {
var request = require('request');
var options = {
method: 'GET',
url: 'URL here',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: '{ "pay_load": [] }'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
info = JSON.parse(body);
console.log('in the callback now');
//console.log('body :' + body);
//var count = Object.keys(info).length;
//console.log('body len:' + count);
//console.log('info :' + info);
fname = info.firstname;
console.log('firstname1 : ' + info.firstname);
console.log('firstname2 : ' + fname);
} else {
console.log('there was some error');
}
}
it("proves the API is alive - firstname is null", function() {
request(options, callback);
//expect(fname).toBe(null);
console.log('firstname3 : ' + fname);
//expect(fname).toBe(null);
//var common = new Common();
//common.checkForAPI();
});
So in my head I thought I would see "in the callback", then "firstname1", "firstname2" and finally "firstname3"
No, firstname3 will always get printed first, the way you have it. The reason for it as that all http requests in nodejs are async, so while your request is processing (or in flight), firstname3 will be printed. Then console.logs in your request callback.
Edit1 - Addressing the comment
Simple example which would print firstname1,2,3 in sequence (tested)
var request = function(cb) {
//basically call your request stuff and then when you are done call cb
console.log('firstname 1');
console.log('firstname 2');
cb();
};
request(function() {
console.log('firstname 3');
});
This prints
firstname 1
firstname 2
firstname 3
Or you can use a third party library called async and use async.tryEach to run tasks in series.
async.tryEach([
function getDataFromFirstWebsite(callback) {
// Try getting the data from the first website
callback(err, data);
},
function getDataFromSecondWebsite(callback) {
// First website failed,
// Try getting the data from the backup website
callback(err, data);
}
],
// optional callback
function(err, results) {
Now do something with the data.
});

401 when calling WLAuthorizationManager.login("scope")

I have implemented the new MFP 8 Beta security concept. The positive case, with valid credentials is working fine and the processSuccess method that I have defined is executed.
Unfortunately, the negative case doesn’t work.
After calling the WLAuthorizationManager.login("scope"), I am getting a 401 in the console:
2016-05-20 13:48:41.965 Inspector[98311:1660747] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper start] in WLAFHTTPSessionManagerWrapper.m:376 :: Starting the request with URL http://172.20.10.4:9080/mfp/api/preauth/v1/preauthorize
2016-05-20 13:48:41.983 Inspector[98311:1655477] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper requestFailed:responseObject:error:] in WLAFHTTPSessionManagerWrapper.m:419 :: Request Failed
2016-05-20 13:48:41.984 Inspector[98311:1655477] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper requestFailed:responseObject:error:] in WLAFHTTPSessionManagerWrapper.m:422 :: Response Status Code : 401
2016-05-20 13:48:41.984 Inspector[98311:1655477] [DEBUG] [WL_AFHTTPSessionManagerWrapper_PACKAGE] -[WLAFHTTPSessionManagerWrapper requestFailed:responseObject:error:] in WLAFHTTPSessionManagerWrapper.m:424 :: Response Error : Request failed: unauthorized (401)
Here is my implementation:
WLAuthorizationManager.login("UserLogin",{
'username':$scope.username,
'password':$scope.password
}).then( function () {
console.log(">> WLAuthorizationManager.login - onSuccess");
$scope.getInspectorDetails().then(
function(){
$scope.loginInProgress = false;
$state.go("inspectionList");
}
);
},
function (response) {
console.log(">> WLAuthorizationManager.login - onFailure: " + JSON.stringify(response));
$scope.loginInProgress = false;
if (!$scope.loginError){
$scope.loginError = "Could not connect to server. Please try again later.";
}
$scope.$apply();
});
}
And the Challenge handler:
$scope.registerChallengeHandler = function(){
console.log(">> in $scope.registerChllangeHandler ... ");
$scope.userLoginChallengeHandler = WL.Client.createWLChallengeHandler($scope.securityCheckName);
$scope.userLoginChallengeHandler.securityCheckName = $scope.securityCheckName;
$scope.userLoginChallengeHandler.handleChallenge = function(challenge) {
console.log(">> in UserLoginChallengeHandler - userLoginChallengeHandler.handleChallenge ...");
// When a session has expired, this will be our entry point into automatically logging back in
// (since the next server call the user tries to make will end up being flagged as a 'custom response'
// which will trigger the challenge hander. Thus, we need to turn on the progress spinner...
$scope.$apply(function(){
$scope.loginInProgress = true;
});
//show the login ...
$scope.user = { username: "", password: ""};
$scope.currentPath = $location.path();
console.log(">> $location.path(): " + $location.path());
if (!$state.is("login")){
$state.go("login");
}
$scope.isChallenged = true;
var statusMsg = "Remaining Attempts: " + challenge.remainingAttempts;
if (challenge.errorMsg !== null){
statusMsg = statusMsg + "<br/>" + challenge.errorMsg;
$timeout(function(){
//want to show only when submit user/pass not when token expired ...
if($scope.currentPath == "/"){
$scope.loginError = statusMsg;
}
}, 300);
}
console.log(">>> statusMsg : " + statusMsg);
};
$scope.userLoginChallengeHandler.processSuccess = function(data) {
console.log(">> in UserLoginChallengeHandler - userLoginChallengeHandler.processSuccess ...");
$scope.isChallenged = false;
$timeout(function(){
$scope.user = { username: "", password: ""};
}, 200);
$state.transitionTo("inspectionList");
};
$scope.userLoginChallengeHandler.handleFailure = function(error) {
console.log(">> in UserLoginChallengeHandler - userLoginChallengeHandler.handleFailure ...");
console.log(">> handleFailure: " + error.failure);
$scope.isChallenged = false;
if (error.failure !== null){
alert(error.failure);
} else {
alert("Failed to login.");
}
};
}
I would have expected that the handleFailure Method is called, but in the debugger I saw that it is not being executed. After the call of WLAuthorizationManager it just stops, so even the WLAuthorizationManager.login – onFailure is not called.
Edit:
Captured the traffic with Wireshark: https://ibm.box.com/s/7mtwsgea06i4bpdbdz0wvyhy3wpma58r
When using WLAuthorizationManager.login() with wrong credentials, the normal flow is that the challenge handler's handleChallenge will be called, to allow the user to try again.
In some cases, the security check might send a failure, such as "maximum attempt reached". In this case, the challenge handler's handleFailure is called.
WLAuthorizationManager.login() has its own failure scenarios. For example, let's say your server is down, there is no network, the security check does not exist, etc. In those cases, since there is no challenge involved, the login's failure will be called. That's when your then promise will come in handy.

Log in to Facebook with phantomjs - 302 issues?

I'm trying to write a phantomjs script to log in to my facebook account and take a screenshot.
Here's my code:
var page = require('webpage').create();
var system = require('system');
var stepIndex = 0;
var loadInProgress = false;
email = system.args[1];
password = system.args[2];
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
page.render('output.png');
});
},
function() {
console.log(document.documentElement.innerHTML);
},
function() {
phantom.exit();
}
]
setInterval(function() {
if (!loadInProgress && typeof steps[stepIndex] == "function") {
console.log("step " + (stepIndex + 1));
steps[stepIndex]();
stepIndex++;
}
if (typeof steps[stepIndex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 10000);
(Inspired by this answer, but note that I've upped the interval to 10s)
Called like so:
./phantomjs test.js <email> <password>
With output (filtering out the selfxss warnings from Facebook):
step 1
load started
load finished
Login submitted!
load started
load finished
step 2
<head></head><body></body>
step 3
test
complete!
(Note that the html output in step two is empty)
This answer suggests that there are problems with phantomjs' SSL options, but running with --ssl-protocol=any has no effect.
This appears to be a similar problem, but for caspar, not phantomjs (and on Windows, not Mac) - I've tried using --ignore-ssl-errors=yes, but that also had no effect.
I guessed that this might be a redirection problem (and, indeed, when I replicate this on Chrome, the response from clicking "Submit" was a 302 Found with location https://www.facebook.com/checkpoint/?next), but according to this documentation I can set a page.onNavigationRequested handler - when I do so in my script, it doesn't get called.
I think this issue is related, but it looks as if there's no fix there.

Strophe addHandler doesn't work

This is a relevant question to "Strophe.Connection.addHandler no works if call Strophe.Connection.sendIQ" but it doesn 't help me. I am trying to run a program of the book "Wrox Professional XMPP Programming with JavaScript and jQuery Book" which is a collaborative editor.
$(document).bind('connected', function () {
$('#disconnect').removeAttr('disabled');
NetPad.connection.addHandler(NetPad.on_message, null, "message");
if (NetPad.collaborator) {
NetPad.master = false;
$('#status')
.text('Checking feature support for ' + NetPad.collaborator + '.')
.attr('class', 'try-collab');
// check for feature support
NetPad.connection.sendIQ(
$iq({to: NetPad.collaborator, type: 'get'})
.c('query', {xmlns: Strophe.NS.DISCO_INFO}),
function (iq) {
console.log(iq);
var f = $(iq).find(
'feature[var="' + NetPad.NS_NETPAD + '"]');
if (f.length > 0) {
$('#status')
.text('Establishing session with ' +
NetPad.collaborator + '.')
.attr('class', 'try-collab');
NetPad.connection.send(
$pres({to: NetPad.collaborator})
.c('collaborate', {xmlns: NetPad.NS_NETPAD}));
} else {
$('#status')
.text('Collaboration not supported with ' +
NetPad.collaborator + '.')
.attr('class', 'no-collab');
NetPad.connection.disconnect();
}
});
} else {
NetPad.master = true;
$('#pad').removeAttr('disabled');
// handle incoming discovery and collaboration requests
**NetPad.connection.addHandler(NetPad.on_disco_info,
Strophe.NS.DISCO_INFO, "iq", "get");**
NetPad.connection.addHandler(NetPad.on_collaborate,
NetPad.NS_NETPAD, "presence");
NetPad.connection.addHandler(NetPad.on_unavailable,
null, "presence");
}
});
on_disco_info: function (iq) {
console.log("==> On_disco_info()...");
NetPad.connection.sendIQ(
$iq({to: $(iq).attr('from'),
id: $(iq).attr('id'),
type: "result"})
.c('query', {xmlns: Strophe.NS.DISCO_INFO})
.c('identity', {category: 'client',
type: 'pc'}).up()
.c('feature', {'var': NetPad.NS_NETPAD}));
return true;
},
The problem is that NetPad.on_disco_info(iq), isn't fired when a connection with another colloborator is made, though an iq stanza is sended. I omitted the rest of the addHandler's arguments, to get all iq but again nothing.
My server is ejabberd.
Please ask if something is not understandable.

phonegap - using external site as app - facebook login

I'm building a app site running through phone gap. Phone gap simply checks the user has internet connection and loads an external web app into the frame. I can navigat through the site fine with no blibs but as soon as I try the login to Facebook (either PHP redirect or javascript SDK) the app suddenly gets its navbar back or opens a new window (javascript SDK).
Is there anyway I can prevent this?
regards
It took some doing but using the ChildBrowser plugin, I've managed to login! (this is for android) I've used some code from a facebook connect plugin which didnt work for me, re wrote some stuffs so I could understand it and now works. Chears Juicy Scripter!
var fb_success = 'https://www.facebook.com/connect/login_success.html';
var fb_logout = 'https://www.facebook.com/connect/login_failed.html';
var fb_logout_ = 'http://m.facebook.com/logout.php?confirm=1&next=' + fb_logout;
var authorize_url = '';
var my_client_id = '##################';
var my_secret = '######################';
var my_type = 'user_agent';
var my_display = 'touch';
var token = false;
var fb_code = false;
var device_ready = false;
var ajax_url = '';
function logged_in(){
// alert('do what you need to do!');
}
function fb_force_logout(){
}
function fb_auth_check(){
console.log('fb_auth_check()');
if( fb_code !== false ) {
console.log('ajax test instigated...');
ajax_url = 'https://graph.facebook.com/oauth/access_token?client_id=' + encodeURIComponent(my_client_id) + '&client_secret=' + encodeURIComponent(my_secret) + '&code=' + encodeURIComponent(fb_code) + '&redirect_uri=' + fb_success;
$.ajax({
url: ajax_url,
type: 'POST',
success: function(html){
token = html.split("=")[1];
console.log('success! token = ' + token);
window.plugins.childBrowser.close();
fb_init();
},
error: function(error) {
console.log('there was an error...' + ajax_url);
window.plugins.childBrowser.close();
}
});
}
}
function fb_track_redirects(loc){
console.log('redirect tracked... ' + loc);
if ( loc.indexOf(fb_success) >= 0 || loc.indexOf(fb_success) > -1 ) {
fb_code = loc.match(/code=(.*)$/)[1]
console.log('success redirect... fb_code=' + fb_code);
fb_auth_check();
window.plugins.childBrowser.close();
} else if ( loc.indexOf(fb_logout) >= 0 || loc.indexOf(fb_logout) > -1 ) {
window.plugins.childBrowser.close();
}
}
function inner_init(){
console.log('inner_init()');
if( token === false ) {
console.log('token was false...');
authorize_url += "https://graph.facebook.com/oauth/authorize?";
authorize_url += "client_id=" + encodeURIComponent(my_client_id);
authorize_url += "&redirect_uri=" + encodeURIComponent(fb_success);
authorize_url += "&display=" + encodeURIComponent(my_display);
authorize_url += "&scope=publish_stream,offline_access";
console.log('instigated location change...');
window.plugins.childBrowser.onLocationChange = function(loc){
fb_track_redirects(loc);
}
console.log('open Facebbok login window');
window.plugins.childBrowser.showWebPage(authorize_url);
}else{
logged_in();
}
}
function fb_init(){
console.log('fb_init()');
if( device_ready === false ) {
console.log('first device run...');
document.addEventListener("deviceready", function(){
device_ready = true;
console.log('device ready...');
inner_init();
}, false);
}else{
inner_init();
}
}
$(document).ready(function(){
$('#login').bind('click', function(){
fb_init();
return false;
})
});
</script>
This is how it works for all apps native or web without patching the SDK code.
This is probably can be done, but will require digging into code. The question is do you really need it? This is a desired behavior.
You can try to use PhoneGap Facebook plugin and enable Single Sign On so native Facebook App if exists will be opened instead of browser to authenticate the user.
BTW,
Apps that are just external sites wrapped mostly rejected in app store.
Update:
Where is some points that may be also helpful in answer (by Facebook employee) to similar question How can I use an access token to circumvent FB.login().
Also have a look on ChildBrowser PhoneGap plugin (and Example).