Commit de5bd188 authored by Andrew Price's avatar Andrew Price
Browse files

duktape: Implement wholist()

parent d011ca37
Loading
Loading
Loading
Loading
Loading
+59 −0
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <jansson.h>
#include <duktape.h>

#include "js.h"
@@ -13,6 +14,7 @@
#include "alias.h"
#include "user.h"
#include "alarm.h"
#include "who.h"

extern struct user * const user;
struct alarm *timeout_event = NULL;
@@ -119,6 +121,62 @@ static duk_ret_t js_say(duk_context *cx)
	return 0;
}

static duk_ret_t js_wholist(duk_context *cx)
{
	duk_idx_t arr_idx;
	json_t * wlist;
	json_t *entry;
	time_t now;
	size_t wi;
	int i = 0;

	wlist = grab_wholist();
	if (wlist == NULL) {
		fprintf(stderr, "Could not grab who list, try again\n");
		return 0;
	}
	arr_idx = duk_push_array(cx);
	now = time(0);
	json_array_foreach(wlist, wi, entry) {
		json_t * perms = json_object_get(entry, "perms");
		duk_idx_t obj_idx;
		const char *prot;
		int dowhen;

		obj_idx = duk_push_bare_object(cx);
		/* user name */
		duk_push_string(cx, json_getstring(entry, "name"));
		duk_put_prop_string(cx, obj_idx, "username");
		/* room number */
		duk_push_int(cx, json_getint(entry, "channel"));
		duk_put_prop_string(cx, obj_idx, "room");
		/* idle time */
		duk_push_int(cx, now - json_getint(entry, "idletime"));
		duk_put_prop_string(cx, obj_idx, "idle");
		/* chat modes */
		duk_push_string(cx, json_getstring(entry, "chatmode"));
		duk_put_prop_string(cx, obj_idx, "chatmodes");
		/* protection level */
		prot = json_getstring(perms, "protection");
		duk_push_int(cx, prot[0] - '0');
		duk_put_prop_string(cx, obj_idx, "protection_level");
		duk_push_int(cx, prot[2] - '0');
		duk_put_prop_string(cx, obj_idx, "protection_power");
		/* chat perms */
		duk_push_string(cx, json_getstring(perms, "chatprivs"));
		duk_put_prop_string(cx, obj_idx, "chatprivs");
		/* status string */
		duk_push_string(cx, json_getstring(entry, "doing"));
		duk_put_prop_string(cx, obj_idx, "doing");
		dowhen = json_getint(entry, "dowhen");
		duk_push_int(cx, dowhen ? now - dowhen : 0);
		duk_put_prop_string(cx, obj_idx, "since");
		/* stick line into array */
		duk_put_prop_index(ctx, arr_idx, i++);
	}
	return 1; /* Array is returned at top of stack */
}

static duk_ret_t js_bind(duk_context *cx)
{
	const char *bind_name = NULL;
@@ -379,6 +437,7 @@ int setup_js(void)
	define_func("print", js_print, DUK_VARARGS);
	define_func("exec", js_mwexec, 1);
	define_func("say", js_say, 1);
	define_func("wholist", js_wholist, 0);
	define_func("bind", js_bind, 3);
	define_func("unbind", js_unbind, 2);
	duk_pop(ctx);