Strophe MAM how to display the messages? - javascript

I have managed to use Strophe MAM to get the archived messages into the RAWInput, and display the last message(but only the last one). How do i display all the messages from the RAWInput?? But not just the last one?
And how do i extract who the message is from?
I have limited the messages to the last 5.
connection.mam.query("test3#macbook-pro.local", {
"with": "test4#macbook-pro.local","before": '',"max":"5",
onMessage: function(message) {
console.log( $(message).text());
},
onComplete: function(response) {
console.log("Got all the messages");
}
});

You can get all the messages using the `strophe.mam.js plugin
Here is my working code:
// Retrives the messages between two particular users.
var archive = [];
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0])
};
archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q, response:response});
}
};
$(document).ready(function)(){
archive = $("#archive-messages");
archive.val("");
$("#to-jid").change(function() {
$("#archive-messages").val("");
var to = {"with": $(this).val()};
$.extend(q, to, before, max);
// It takes around 800ms to auto login. So after this timeout we have to retrieve the messages of particular User.
setTimeout(function(){
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}, 1000);
});
});

connection.mam.query("Your_Id", {
"with": "partner_id","before": '',"max":'',
onMessage: function(message) {
console.log("Message from ", $(message).find("forwarded message").attr("from"),
": ", $(message).find("forwarded message body").text());
return true;
},
onComplete: function(response) {
console.log("Got all the messages");
}
});
This will fetch all History for a user. If you want to limit, then provide max value.
Don't download strophe.mam.js(https://github.com/metajack/strophejs-plugins/tree/master/mam) from github. Its not working. Please copy below strophe.mam.js file.
**strophe.mam.js**
/* XEP-0313: Message Archive Management
* Copyright (C) 2012 Kim Alvefur
*
* This file is MIT/X11 licensed. Please see the
* LICENSE.txt file in the source package for more information.
*
* TODO:
* Get RSM from the reply
* Clean remove onMessage handler afterwards
* queryid?
*
*/
Strophe.addConnectionPlugin('mam', {
_c: null,
_p: [ "with", "start", "end" ],
init: function (conn) {
this._c = conn;
Strophe.addNamespace('MAM', 'urn:xmpp:mam:0');
},
query: function (jid, options) {
var _p = this._p;
var attr = {
type:"set",
id:jid
};
var mamAttr = {xmlns: Strophe.NS.MAM};
var iq = $iq(attr).c("query", mamAttr).c('x',{xmlns:'jabber:x:data'});
iq.c('field',{var:"FORM_TYPE"}).c('value').t("urn:xmpp:mam:0").up().up();
for (i = 0; i < this._p.length; i++) {
var pn = _p[i];
var p = options[pn];
delete options[pn];
if (!!p) {
var f
iq.c('field',{var:pn}).c('value').t(p).up().up();
}
}
iq.up();
var onMessage = options["onMessage"];
delete options['onMessage'];
var onComplete = options["onComplete"];
delete options['onComplete'];
iq.cnode(new Strophe.RSM(options).toXML());
this._c.addHandler(onMessage, Strophe.NS.MAM, "message", null);
return this._c.sendIQ(iq, onComplete);
}
});

The easiest way to retrieve all the messages is to include this line at the end of the onMessage() function:
return true;
I think the reason is that if a handler does not return true, it will be destroyed after the first time it is called.

Related

Word Web-Addin: getSliceAsync() only return First Slice of data

I am developing an office 365 word web addin, wherein I need to upload the currently opened document to my server. For which I am trying to get the file data using following code.
The method getSliceAsync() is returning only first slice of data.
On debugging it gives "Addin Error: Sorry, we had to restart because this addin wasn't responding" while getting second slice.
I am using this link for reference : [https://learn.microsoft.com/en-us/office/dev/add-ins/word/get-the-whole-document-from-an-add-in-for-word][1]
Here is my code:
Office.context.document.getFileAsync(Office.FileType.Compressed, { sliceSize: 65536 }, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then result.value will return a valid File Object
var myFile = result.value;
var filename1 = myFile.name;
console.log(filename1);
var sliceCount = myFile.sliceCount;
var slicesReceived = 0, isAllSlicesSuccess = true, docdataSlices = [];
// document.getElementById("result").innerText = "File size:" + myFile.size + "#Slices: " + sliceCount;
console.log(" File size:" + myFile.size + " #Slices: " + sliceCount, "");
makeProgress(20);
// Iterate over the file slices
for (var i = 0; i < sliceCount && isAllSlicesSuccess; i++) {
var diffPercent = ((i / sliceCount) * 100);
myFile.getSliceAsync(i, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!isAllSlicesSuccess) { // Some slice has failed to get, no need to continue
console.log("Error", "One slice failed to get");
return;
console.log(sliceResult);
}
console.log('sliceResult', sliceResult);
console.log("Success", "i: " + i);
console.log("++slicesReceived ",slicesReceived );
console.log(" sliceCount",sliceCount );
console.log("++slicesReceived == sliceCount",slicesReceived == sliceCount);
// One chunk was got, store it in a temporal array
// ++slicesReceived;
// or you can do something with the chunk, such as sent it to a third party server
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
getAllSlicesTime = Date.now();
var performance = (getAllSlicesTime - startTime) / 1000.0;
console.log("Success", "All slices has been get, Seconds: " + performance);
// All slices have been received
myFile.closeAsync(function (closeRes) {
if (closeRes.status == "succeeded") {
console.log("Close Success", "Success");
// DUClick();
}
else {
console.log("Close Error", closeRes.error.message);
}
});
onGetAllSlicesSucceeded(docdataSlices, false);
}
}
else {
isAllSlicesSuccess = false;
myFile.closeAsync(function (closeRes) {
if (closeRes.status == "succeeded") {
console.log("Close Success", "Success");
// DUClick();
}
else {
console.log("Close Error", closeRes.error.message);
}
});
console.log("Get Slice Error:", sliceResult.error.message);
}
});
}
}
else {
getFileTime = Date.now();
var performance = (getFileTime - startTime) / 1000.0;
console.log('Get File Error:', "Seconds: " + performance + " " + result.error.message);
}
});
Please suggest! Thanks in advance!
[1]: https://learn.microsoft.com/en-us/office/dev/add-ins/word/get-the-whole-document-from-an-add-in-for-word

Missing ) after argument list (Node)

I'm using Node to run this program, where is my error(s)? It's saying I'm missing ) after argument list. I can't find where this error is, I've tried putting the ) in various places. I'm using Node v5
var Twit = require('twit');
var T = new Twit(require('./config.js'));
var stream = T.stream('statuses/filter', {
track: 'xoxo, oi, i\m fine,'
});
(stream.on('tweet', function(tweet) {
console.log('#' + tweet.user.screen_name + ': ' + tweet.text);
if (tweet.text.indexOf('RT') > -1) {
return;
}
var replyString;
if (tweet.user.utc_offset === null) {
replyString = ' Ok';
} else {
replyString = ' Okay';
}
})
(T.post('statuses/update', {
status: '#' + tweet.user.screen_name + replyString,
in_reply_to_status_id: tweet.id_str
}, function(err, data, response) {
if (err) {
console.log(err);
return;
}
}
tweet.botReplyId = data.id_str);
db.tweets.insert(tweet);
});
(end)
})
setInterval(stream, 60000);
The code seems to be a bit all over the place with regards to scope and it makes it a bit difficult to follow.
Try using something like the following which annotates it a bit and should help avoid issues like this (as it seems to validate without any errors) :
// Define your variables
var Twit = require('twit');
var T = new Twit(require('./config.js'));
var stream = T.stream('statuses/filter', { track: 'xoxo, oi, i\'m fine,'});
// When a tweet occurs
(stream.on('tweet', function(tweet) {
// Log it
console.log('#' + tweet.user.screen_name + ': ' + tweet.text);
// Determine if it is a retweet and ignore
if (tweet.text.indexOf('RT') > -1) { return; }
// Set your reply
var replyString = (tweet.user.utc_offset === null) ? ' Ok' : ' Okay';
// Post your reply
T.post('statuses/update', { status: '#' + tweet.user.screen_name + replyString, in_reply_to_status_id: tweet.id_str}, function(err, data, response) {
// If an error occurs, log it
if (err) {
console.log(err);
return;
}
// Otherwise store your response and store it
tweet.botReplyId = data.id_str;
db.tweets.insert(tweet);
});
}));
// Check your stream every 10 minutes
setInterval(stream, 60000);

Wrong Instagram Feed Bug

I am using this plugin:http://www.jqueryscript.net/social-media/jQuery-Plugin-To-Display-Instagram-Photos-On-Your-Web-Page-Instagram-Lite.html
When I set up my username and client-ID, it pulls photos from the wrong feed, for which I don't even have access (it pulls from helaspamexico, but instead it should be pulling from helaspa -> I am logged in to this and have generated client-ID for this)... Has anyone experienced something similar?
/*!
Name: Instagram Lite
Dependencies: jQuery
Author: Michael Lynch
Author URL: http://michaelynch.com
Date Created: January 14, 2014
Licensed under the MIT license
*/
;(function($) {
$.fn.instagramLite = function(options) {
// return if no element was bound
// so chained events can continue
if(!this.length) {
return this;
}
// define plugin
plugin = this;
// define default parameters
plugin.defaults = {
username: null,
clientID: null,
limit: null,
list: true,
videos: false,
urls: false,
captions: false,
date: false,
likes: false,
comments_count: false,
max_id: null,
load_more: null,
error: function() {},
success: function() {}
}
// vars
var s = $.extend({}, plugin.defaults, options),
el = $(this);
var getMaxId = function(items) {
// return id of last item
return items[items.length-1].id;
};
var formatCaption = function(caption) {
var words = caption.split(' '),
newCaption = '';
for(var i = 0; i < words.length; i++) {
var word;
if(words[i][0] == '#') {
var a = ''+words[i]+'';
word = a;
} else if(words[i][0] == '#') {
var a = ''+words[i]+'';
word = a;
} else {
word = words[i]
}
newCaption += word + ' ';
}
return newCaption;
};
var loadContent = function() {
// if client ID and username were provided
if(s.clientID && s.username) {
// for each element
el.each(function() {
var el = $(this);
// search the user
// to get user ID
$.ajax({
type: 'GET',
url: 'https://api.instagram.com/v1/users/search?q='+s.username+'&client_id='+s.clientID+'&callback=?',
dataType: 'jsonp',
success: function(data) {
if(data.data.length) {
// define user namespace
var thisUser = data.data[0];
// construct API endpoint
var url = 'https://api.instagram.com/v1/users/'+thisUser.id+'/media/recent/?client_id='+s.clientID+'&count='+s.limit+'&callback=?';
// concat max id if max id is set
url += (s.max_id) ? '&max_id='+s.max_id : '';
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function(data) {
// if success status
if(data.meta.code === 200 && data.data.length) {
// for each piece of media returned
for(var i = 0; i < data.data.length; i++) {
// define media namespace
var thisMedia = data.data[i],
item;
// if media type is image or videos is set to false
if(thisMedia.type === 'image' || !s.videos) {
// construct image
item = '<img class="il-photo__img" src="'+thisMedia.images.standard_resolution.url+'" alt="Instagram Image" data-filter="'+thisMedia.filter+'" />';
// if url setting is true
if(s.urls) {
item = ''+item+'';
}
if(s.captions || s.date || s.likes || s.comments_count) {
item += '<div class="il-photo__meta">';
}
// if caption setting is true
if(s.captions && thisMedia.caption) {
item += '<div class="il-photo__caption" data-caption-id="'+thisMedia.caption.id+'">'+formatCaption(thisMedia.caption.text)+'</div>';
}
// if date setting is true
if(s.date) {
var date = new Date(thisMedia.created_time * 1000),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
date = month +'/'+ day +'/'+ year;
item += '<div class="il-photo__date">'+date+'</div>';
}
// if likes setting is true
if(s.likes) {
item += '<div class="il-photo__likes">'+thisMedia.likes.count+'</div>';
}
// if caption setting is true
if(s.comments_count && thisMedia.comments) {
item += '<div class="il-photo__comments">'+thisMedia.comments.count+'</div>';
}
if(s.captions || s.date || s.likes || s.comments_count) {
item += '</div>';
}
}
if(thisMedia.type === 'video' && s.videos) {
if(thisMedia.videos) {
var src;
if(thisMedia.videos.standard_resolution) {
src = thisMedia.videos.standard_resolution.url;
} else if(thisMedia.videos.low_resolution) {
src = thisMedia.videos.low_resolution.url;
} else if(thisMedia.videos.low_bandwidth) {
src = thisMedia.videos.low_bandwidth.url;
}
item = '<video poster="'+thisMedia.images.standard_resolution.url+'" controls>';
item += '<source src="'+src+'" type="video/mp4;"></source>';
item += '</video>';
}
}
// if list setting is true
if(s.list && item) {
// redefine item with wrapping list item
item = '<li class="il-item" data-instagram-id="'+thisMedia.id+'">'+item+'</li>';
}
// append image / video
if(item !== '') {
el.append(item);
}
}
// set new max id
s.max_id = getMaxId(data.data);
// execute success callback
s.success.call(this);
} else {
// execute error callback
s.error.call(this, data.meta.code, data.meta.error_message);
}
},
error: function() {
// recent media ajax request failed
// execute error callback
s.error.call(this);
}
});
} else {
// error finding username
// execute error callback
s.error.call(this);
}
},
error: function() {
// search username ajax request failed
// execute error callback
s.error.call(this);
}
});
});
} else {
// username or client ID were not provided
// execute error callback
s.error.call(this);
};
}
// bind load more click event
if(s.load_more){
$(s.load_more).on('click', function(e) {
e.preventDefault();
loadContent();
});
}
// init
loadContent();
}
})(jQuery);
<ul class="instagram"></ul>
Load more
<br clear="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Wait untill everything loads
$(window).load(function(){
$('.instagram').instagramLite({
username: 'helaspa',
clientID: 'ecdadd6520c04f5b8ae8bfdc888dd59c',
urls: true,
limit: 10,
load_more: '.instagram-more',
captions: false,
likes: false,
comments_count: false,
success: function() {
console.log('The request was successful!');
},
error: function(errorCode, errorMessage) {
console.log('There was an error');
if(errorCode && errorMessage) {
alert(errorCode +': '+ errorMessage);
}
}
});
});
</script>
If you are looking for a bad but quick solution, just put a '$' on the end of your username. The result of the API call will have your result first (by dumb luck) so the library will work.
The library you are using is not parsing the result of the query API correctly. The query API returns results for usernames similar to your query and doesn't filter results that are the wrong username.
Really, you should submit a patch to the library to use an API other than search: https://instagram.com/developer/endpoints/users/
Here is the bad the function:
https://github.com/michael-lynch/instagram-lite/blob/master/src/instagramLite.js#L95

Retrieve messages on Page load Strophe js

I am trying to retrieve the messages whenever Uses logs in and the page loads. Right now I can able to retrieve the messages whenever the User sends the message to other User i.e., with the onMessage function.
Here is my code:
var archive = [];
// Retrives the messages whenever User sends the messages to Other User.
// TODO: Should be better when User logins and page loads
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0]),
avatar:'images/default_avatar_image.png'
};
archive.val(archive.val() + msg_data.from + ":" + msg_data.message + "\n" + msg_data.to + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q,data:data,response:response});
}
};
console.log('xmpp.history.start',{query:q});
function onMessage(msg) {
// Calls whenever User receives the messages
// and shows the received message in messagebox
var fromJid = msg.getAttribute("from"),
bareFromJid = Strophe.getBareJidFromJid(fromJid),
type = msg.getAttribute("type"),
elems = msg.getElementsByTagName("body");
if (type == "chat" && elems.length > 0) {
var body = elems[0],
message = Strophe.getText(body);
showMessage(bareFromJid + ": " + message);
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}
return true;
}
function send() {
// Calls whenever User sends the messages
// and shows the message in messagebox
var to = $('#to-jid').get(0).value,
myBareJid = Strophe.getBareJidFromJid(connection.jid);
message = $('#message').val(),
reply = $msg({to: to, type: 'chat'})
.c("body")
.t(message);
connection.send(reply.tree());
showMessage(myBareJid + ": " + message);
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
archive = $("#archive-messages");
archive.val("");
connection.rawInput = function (data) { log('RECV: ' + data); };
connection.rawOutput = function (data) { log('SEND: ' + data); };
Strophe.log = function (level, msg) { log('LOG: ' + msg); };
$("#send").bind('click', send);
});
So what happens in my code is whenever User receives the message, then all the messages be retrieved between those two Users.
How can I retrieve the messages in the chat box when I clicked on the particular User??
There were two issues in this. One is when I perform auto login with login() method when scripts loads, it at least takes 800ms to login and perform other actions. At this point I was facing the issue and also bit jQuery part.
Here is my code:
// Retrives the messages between two particular users.
var q = {
onMessage: function(message) {
try {
var id = message.querySelector('result').getAttribute('id');
var fwd = message.querySelector('forwarded');
var d = fwd.querySelector('delay').getAttribute('stamp');
var msg = fwd.querySelector('message');
var msg_data = {
id:id,
with: Strophe.getBareJidFromJid(msg.getAttribute('to')),
timestamp: (new Date(d)),
timestamp_orig: d,
from: Strophe.getBareJidFromJid(msg.getAttribute('from')),
to: Strophe.getBareJidFromJid(msg.getAttribute('to')),
type: msg.getAttribute('type'),
body: msg.getAttribute('body'),
message: Strophe.getText(msg.getElementsByTagName('body')[0])
};
var login_user = connection.jid.split('#')[0];
var username = msg_data.from.split('#')[0];
if(login_user == username) {
archive.val(archive.val() + "me:".capitalizeFirstLetter() + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
else {
archive.val(archive.val() + username.capitalizeFirstLetter() + ":" + msg_data.message + "\n");
archive.scrollTop(archive[0].scrollHeight - archive.height());
}
console.log('xmpp.history.message',msg_data.message);
} catch(err){
if(typeof(err) == 'TypeError'){
try {
console.log(err.stack)
} catch(err2){
console.log(err,err2);
}
}
}
return true;
},
onComplete: function(response) {
console.log('xmpp.history.end',{query:q, response:response});
}
};
$("#to-jid").change(function() {
$("#archive-messages").val("");
var to = {"with": $(this).val()};
$.extend(q, to);
// It takes around 800ms to login. So after this timeout we have to retrieve the messages of particular User.
setTimeout(function(){
connection.mam.query(Strophe.getBareJidFromJid(connection.jid), q);
}, 1000);
});

How Jasmine handles errors

I can't get jasmine testing working smoothly on nodejs. What I mean is that there are situations when the test just stops in the middle of the run, does not notify anything, but silently fails in error. One example I got a few moments ago is this:
In the validater.validateIDs. There is a callback "isOkFunc" that get sent to another modules function to a custom mongoose.find-function
validateIDs = function (data, dbFunc) {
data = data || selfData;
var
isOkFunc = (function () {
var ret = {};
ret.thisData = void 0;
ret.setData = function (data) {
ret.thisData = (data === undefined) ? true : data;
};
return ret;
})(),
findData = {
playerID: data.playerID,
gameID: data.gameID,
turnID: data.turnID,
objectID: data.objectID
};
dbFunc.find(findData, isOkFunc.setData);
return isOkFunc.thisData;
};
The callback get called in the custom find-function:
this.find = function (data, cb) {
models.Order.find(data,function (err, orders) {
if (err) {
console.log("error in getting orders");
cb(void 0);
} else {
console.log(orders);
cb(orders);
}
});
};
Now since I forgot to point the thisData to ret.thisData, it errored, since the variable did not exist. But the problem is that jasmine doesn't notify anything about this, it just silently fails and stops execution. How should this be done for better debugging? Or more like how it should be for ANY realistic debugging?
The actual part in spec-file that caused the problem was this:
isOk = validater.validateIDs(data, orderReceive);
After stripping few unrelated descibe-sections, here is the whole spec-file:
"use strict";
/* This is for making jasmine testing work in windows with netbeans. If this
* causes trouble for you, then try to find a better solution. I need this in
* windows enviroment */
if(process.platform.match(/^win/)) {
require("jasmine-node");
};
var uuid = require('node-uuid'),
orders = require("../../databases/modules/orders.js"),
orderReceive = orders.ordersAtDatabase("../testDB"),
data, UUID = uuid.v4();;
/* Counts the amount of finished-class received. When it reaches given point.
* Executes all functions. This is supposed to be executed last to remove database entries
*
* Without this we can not test the database ID validation fully, since we need
* to have data in database for this */
var toExecuteLast = (function toExecuteLast() {
var funcs = [], ret = {}, i,
count = 0,
max = 5;
ret.add = function(func) {
funcs.push(func);
};
ret.finished = function() {
count++;
};
ret.do = function() {
console.log("gogogo");
if(count >= max) {
console.log("gogogo2222");
for(i = 0; i < funcs.length; i++) {
funcs[i]();
}
clearInterval(toExecuteLast.do);
}
};
return ret;
})();
beforeEach(function() {
data =
{
"playerID": 1,
"gameID": 1,
"turnID": 1,
"objectID": UUID,
"type": "unit",
"action": "move",
"exec": {
"x": 10,
"y": 10
}
};
});
describe("Testing data validation from data, that would come from frontend", function() {
var validater;
validater = orders.orderValidation();
describe(". User is sending fishy data: ", function(){
it(". Test that everything works fine", function() {
expect(helper).not.toThrow();
});
it(". Something fishy with playerID", function() {
data.playerID = "kjdf ss";
expect(helper).toThrow(new Error("playerID was not an integer"));
data.playerID = 12322.33;
expect(helper).toThrow();
});
it(". Something fishy with gameID", function() {
data.gameID = "kjfkj";
expect(helper).toThrow(new Error("gameID was not an integer"));
});
it(". Something fishy with turnID", function() {
data.turnID = "| rm -r";
expect(helper).toThrow(new Error("turnID was not an integer"));
});
it(". Something fishy with objectID", function() {
data.objectID = "| rm -r";
expect(helper).toThrow(new Error("objectID was not an UUIDv4"));
});
it(". Something fishy with type", function() {
data.type = "| rm -r";
expect(helper).toThrow();
});
it(". Something fishy with action", function() {
data.action = "| rm -r";
expect(helper).toThrow(new Error("Action contains illegal character only a-z,A-Z,0-9,_ are allowed"));
});
it(". Something fishy with exec", function() {
data.exec = "| rm -r";
expect(helper).toThrow(new Error("Action was move, but exec.x was not an integer"));
});
toExecuteLast.finished();
});
describe(". Do a database check if the IDs that are given (player, game, turn, object) are correct? ", function(){
/* Remeber that the playerID is fetched from inner data / cookies / auth
* so it is supposed to be correct. We need it to be correct in the
* database too, so we can test the game, turn and object ID validations */
it(". Everything ok with ID validation?", function() {
var isOk;
isOk = validater.validateIDs(data, orderReceive);
waitsFor(function() {
return isOk !== 'undefined' ? true : false;
});
runs(function() {
expect(isOk).not.toBeTruthy();
isOk = false;
data.gameID = 10;
isOk = validater.validateIDs(data, orderReceive);
waitsFor(function() {
return (isOk !== 'undefined') ? true : false;
}, "", 1000);
runs(function() {
// THIS doesn't seem to work, why?
expect(true).toBeTruthy();
toExecuteLast.finished();
});
});
});
toExecuteLast.finished();
});
function helper() {
validater.validateRequest(data);
}
});
setInterval(toExecuteLast.do, 400);
orderReceive.showAll();
//orderReceive.removeAll();

Categories