const loki = require("lokijs");

let db = new loki("data.json");
let messages = db.addCollection("messages");
let sessions = db.addCollection("sessions");

let _exports = module.exports = {};

function clone(obj) {
	return JSON.parse( JSON.stringify(obj) );
}

function clean_message(msg) {
	msg = clone(msg);

	delete msg.secret;
	msg.timestamp = (new Date()).getTime() / 1000;
	return msg;
}

_exports.clean_object = function (obj) {
	obj = clone(obj);
	
	delete obj.meta;
	delete obj["$loki"];
	
	return obj;
}

_exports.store_message = function (msg) {
	let session = _exports.get_session(msg.token);

	if (session === false) {
		return false;
	}

	delete session.token;

	msg = Object.assign(session, msg);

	messages.insert( clean_message(msg) );
}

_exports.get_messages = function (timestamp) {
	return clone( messages.find( {"time" : {"$gte" : timestamp} } ) );
}

_exports.get_session = function (token) {
	let session = sessions.find( {"token" : token} );

	if ( session.length === 0 ) {
		return false;
	}

	session = clone(session[0])

	delete session.token;

	return _exports.clean_object(session);
}

_exports.generate_session = function (session) {
	token = require('crypto').randomBytes(64).toString('hex');
	
	if ( _exports.get_session(token).length > 0 ) {
		return _exports.generate_session(session);	
	}
	
	id = require('crypto').randomBytes(16).toString('hex');

	session.token = token;
	session.id = id;
	
	sessions.insert( session );

	return token;
}

@@ -384,24 +384,71 @@
 urn msg;%0A%7D%0A%0A
+function clean_messages(msg) %7B%0A%09return msg;%0A%7D%0A%0A
 _exports.cle
@@ -850,16 +850,32 @@
 %0A%09return
+ clean_messages(
  clone( 
@@ -923,16 +923,18 @@
 amp%7D %7D )
+ )
  );%0A%7D%0A%0A_

Add clean_messages()