Including JavaScript/jQuery libraries in .js functions - javascript

I'm trying to generate a token (partially random base 64 encoded string with a certain formatting) for use in a video chat application. To accomplish this, I am using Parse Cloud Code on my backend. I basically deploy a .js file that runs my server side scripts. The code I have now is below. I've been getting error code 141: "Uncaught ReferenceError: document is not defined" and another error saying that '$' is not defined. I suspect I am doing something like including jQuery wrong - probably something extremely noobish. Any ideas?
Parse.Cloud.define("generateToken", function(request, response) {
var script1 = document.createElement('script');
script1.src = 'http://code.jquery.com/jquery-1.8.3.min.js';
script1.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = 'https://raw.github.com/carlo/jquery-base64/master/ jquery.base64.min.js';
script2.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script2);
var script3 = document.createElement('script');
script3.src = 'http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha1.js';
script3.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script3);
var secondsInDay = 86400;
// Credentials - leaving these out for security purposes
var apiKey = <apiKey>;
var secret = <secret>;
var sessionId = request.params.sid;
// Token Params
var timeNow = Math.floor(Date.now()/1000);
var expire = timeNow+secondsInDay;
var role = "publisher";
var data = "whatever";
// Calculation
data = escape(data);
var rand = Math.floor(Math.random()*999999);
var dataString = "session_id="+sessionId+"&create_time="+timeNow+"&expire_time="+expire+"&role="+role+"&connection_data="+data+"&nonce="+rand;
// Encryption
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA1, secret);
hmac.update( dataString );
hash = hmac.finalize();
preCoded = "partner_id="+apiKey+"&sig="+hash+":"+dataString;
token = "T1=="+$.base64.encode( preCoded );
// Token Achieved. The End
response.success(token);
});

"document not defined" is generally a tell tale sign generally running a web worker. If you want to access the document don't use a webworker. This is because there should be only one thread accessing document so as to not cause clashes.

Related

Why do I get this error : Malformed UTF-8 data

const license = fs.readFileSync('./license').toString();
var bytes = CryptoJS.AES.decrypt(license, 'mysecretkey123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);
Last line throws an error : Malformed UTF-8 data
It works without error when I run this code in my Electron app before packaging it, but once its packaged in a exe file it throws an error here
The ./license file was created this way :
var licensedata = {license:licen.license, lastpayment:data.lastpayment, macAddress:getmac.default()};
var stringtoencrypt = JSON.stringify(licensedata);
var ciphertext = CryptoJS.AES.encrypt(stringtoencrypt, 'f8LNLIHdb9CT4KYTBF6Az9sNR2r1bMlUjqgCia0teIrg0lZ4iZ7sUSBt7cJqmYE3GrHe082eD9ajIry2');
var cptext = ciphertext.toString();
var fp = "./license";
var encdata = new Uint8Array(Buffer.from(cptext));
fs.writeFileSync(fp, encdata);

Disqus this.callbacks.onNewComment not working

I somehow cannot get the Disqus this.callbacks.onNewComment to work. What could be wrong? Im trying to alert('hey!') once a new comment is posted. Source
<script>
var disqus_config = function () {
this.page.url = PAGE_URL;
this.page.identifier = PAGE_IDENTIFIER;
this.callbacks.onNewComment = [function(comment) {
alert(comment.id);
alert(comment.text);
alert('hey!');
}];
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://example.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
PAGE_URL and PAGE_IDENTIFIER need to be specific to your site
This callback is for detecting a new post by this browser window. Not new posts arriving from other users (or even your own user in another browser windows)
That 2nd one threw me as I thought it was to indicate new post had arrived

Antlr4 Javascript Visitor

I'm currently trying to develope a JavaScript Compiler with the help of an Antlr4 Visitor. I've got this already implemented with Java but cannot figure out how to do this in JavaScript. Probably somebody can answer me a few questions?
1: In Java there is a Visitor.visit function. If im right this isn't possibile with Javascript. Is there a work around for this?
2: My Javascript Visitor got all the generated visiting functions but when I use console.log(ctx) the context is undefined. Any idea why?
Extract from the SimpleVisitor.js:
// Visit a parse tree produced by SimpleParser#parse.
SimpleVisitor.prototype.visitParse = function(ctx) {
console.log(ctx);
};
Main js file:
var antlr4 = require('lib/antlr4/index');
var SimpleLexer = require('antlr4/SimpleLexer');
var SimpleParser = require('antlr4/SimpleParser');
var SimpleVisitor = require('antlr4/SimpleVisitor');
var input = "double hallo = 1;";
var chars = new antlr4.InputStream(input);
var lexer = new SimpleLexer.SimpleLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new SimpleParser.SimpleParser(tokens);
var visitor = new SimpleVisitor.SimpleVisitor();
parser.buildParseTrees = true;
var tree = parser.parse();
visitor.visitParse();
This is probably enough to start with ...
Bruno
Edit:
Probably the context is undefined because I call the function without arguments but where do I get the "starting"-context?
Edit2:
So I think I get the idea how this should work out. One Question remaining how do I determine which rule to call next inside each visitor function?
The basic idea behind the visitor is that you have to handle all the logic by yourself. To do this I generated the visitor using antlr. My own visitor overrides all functions that I need to implement my logic.
create lexer, tokens, ...
var antlr4 = require('antlr4/index');
var SimpleJavaLexer = require('generated/GrammarLexer');
var SimpleJavaParser = require('generated/GrammarParser');
var SimpleJavaVisitor = require('generated/GrammarVisitor');
var Visitor = require('./Visitor');
var input = "TestInput";
var chars = new antlr4.InputStream(input);
var lexer = new GrammarLexer.GrammarLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new GrammarParser.GrammarParser(tokens);
var visitor = new Visitor.Visitor();
parser.buildParseTrees = true;
var tree = parser.parse();
and call your entry function
visitor.visitTest(tree);
inside your new visitor you need to implement your new logic to determine which function to call next (the right context as argument is important)
var GrammarVisitor = require('generated/GrammarVisitor').GrammarVisitor;
function Visitor () {
SimpleJavaVisitor.call(this);
return this;
};
Visitor.prototype = Object.create(GrammarVisitor.prototype);
Visitor.prototype.constructor = Visitor;
Visitor.prototype.visitTest = function(ctx) {
// implement logic to determine which function to visit
// then call next function and with the right context
this.visitBlock(ctx.block());
};
I hope you can understand my basic idea. If anybody got any questions just comment.

WebRTC in javascript

I am trying to make WebRTC an object in javascript for easier use.
Since javascript is executed on my side, i get an error saying Firebase is not defined.
So I called the script source using the following code;
///in this section I am trying to get the firebase.js
var head=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', "https://cdn.firebase.com/v0/firebase.js");
head.appendChild(script);
After that I try to get a reference to FireBase database and create my own
var dbRef = new Firebase("https://webrtcdemo.firebaseIO.com/");///this is the line i get the error
var roomRef = dbRef.child("rooms");
To sum up my question is it possible to use WebRTC(reference Firebase) in javascript? If so how is it possible?
Thanks
Since you're loading code from javascript, you need to wait for it to load before continuing:
// define onload handler
function onFirebaseLoad() {
var dbRef = new Firebase("https://webrtcdemo.firebaseIO.com/");
var roomRef = dbRef.child("rooms");
// ...
}
// load the code
var head=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
script.onload = onFirebaseLoad;
script.onreadystatechange = function() {
if(script.readyState == 'complete') onFirebaseLoad();
};
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', "https://cdn.firebase.com/v0/firebase.js");
head.appendChild(script);

Node.js - how to use external library (VersionOne JS SDK)?

I'm trying to use VersionOne JS SDK in Node.js (https://github.com/versionone/VersionOne.SDK.JavaScript). I'm simply downloading whole library, placing it alongside with my js file:
var v1 = require('./v1sdk/v1sdk.js');
var V1Server = v1.V1Server;
console.log(v1);
console.log(V1Server);
Unfortunately something seems wrong, the output I get after calling
node app.js
is:
{}
undefined
Can somebody point me what I'm doing wrong or check whether the sdk is valid.
Thanks!
You can see in the source where V1Server is defined, that it's a class with a constructor. So you need to use the new keyword and pass the arguments for your environment.
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/client.coffee#L37
var server = new V1Server('cloud'); //and more if you need
Can you try the sample.js script that I just updated from here:
https://github.com/versionone/VersionOne.SDK.JavaScript/blob/master/sample.js
It pulls in the two modules like this:
var V1Meta = require('./v1meta').V1Meta;
var V1Server = require('./client').V1Server;
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new V1Server(hostname, instance, username, password, port, protocol);
var v1 = new V1Meta(server);
v1.query({
from: "Member",
where: {
IsSelf: 'true'
},
select: ['Email', 'Username', 'ID'],
success: function(result) {
console.log(result.Email);
console.log(result.Username);
console.log(result.ID);
},
error: function(err) { // NOTE: this is not working correctly yet, not called...
console.log(err);
}
});
You might have to get the latest and build the JS from CoffeeScript.
I think I was trying out "browserify" last year and that's how the "v1sdk.js" file got generated. But I'm not sure if that's the best approach if you're using node. It's probably better just to do it the way the sample.js file is doing it.
However, I did also check in a change to v1sdk.coffee which property exports the two other modules, just as a convenience. With that, you can look at sample2.js. The only different part there is this, which is more like you were trying to do with your example:
var v1sdk = require('./v1sdk');
var hostname = "www14.v1host.com";
var instance = "v1sdktesting";
var username = "api";
var password = "api";
var port = "443";
var protocol = "https";
var server = new v1sdk.V1Server(hostname, instance, username, password, port, protocol);
var v1 = new v1sdk.V1Meta(server);

Categories

Resources