riddim.plugins.pubsub2room: Add support for extracting data from JSON Containers (XEP-0335)

Thu, 31 May 2018 00:59:20 +0200

author
Kim Alvefur <zash@zash.se>
date
Thu, 31 May 2018 00:59:20 +0200
changeset 146
e545ba65c9ef
parent 145
565c0c43b063
child 147
7ab078186587

riddim.plugins.pubsub2room: Add support for extracting data from JSON Containers (XEP-0335)

plugins/pubsub2room.lua file | annotate | diff | comparison | revisions
--- a/plugins/pubsub2room.lua	Thu May 31 00:59:08 2018 +0200
+++ b/plugins/pubsub2room.lua	Thu May 31 00:59:20 2018 +0200
@@ -12,6 +12,7 @@
 
 local verse = require "verse";
 local st = require "util.stanza";
+local json = require "util.json";
 
 -- FIXME Should this really be here?
 local extractor_mt = {
@@ -36,8 +37,30 @@
 	end
 };
 
+local json_extractor_mt = {
+	__index = function (t, k)
+		if not k:find"%." then
+			return nil;
+		end
+		for x in k:gmatch("[^.]+") do
+			t = rawget(t, x) or rawget(t, tonumber(x));
+			if t == nil then return end
+		end
+		if type(t) == "table" then
+			return json.encode(t);
+		end
+		return tostring(t);
+	end
+};
+
 local function new_extractor(stanza, data)
 	if not stanza then return nil end
+	if stanza.attr.xmlns == "urn:xmpp:json:0" then
+		local payload = json.decode(stanza:get_text());
+		if type(payload) == "table" then
+			return setmetatable(payload, json_extractor_mt);
+		end
+	end
 	return setmetatable({ stanza = stanza, data = data }, extractor_mt);
 end
 

mercurial