view mod_pubsub_eventsource/mod_pubsub_eventsource.lua @ 2491:5fbca7de2088

mod_smacks: Send out more ack requests where needed Under some circumstances it was possible that more than "max_unacked_stanzas" where left in the outgoing stanza queue without forcing an ack. This could happen, when more stanzas entered the queue while the last ack request was still unanswered. Now the test "#queue > max_unacked_stanzas" is done upon receiving an ack as well as when sending out stanzas, which fixes this bug.
author tmolitor <thilo@eightysoft.de>
date Sun, 12 Feb 2017 19:27:50 +0100
parents 7dbde05b48a9
children 0329cf8cdecb
line wrap: on
line source

module:depends("http");
module:depends("pubsub");

local streams = {};

local service = hosts[module.host].modules.pubsub.service;

function client_closed(response)
	local node = response._eventsource_node;
	module:log("debug", "Destroying client for %q", node);
	streams[node][response] = nil;
	if next(streams[node]) == nil then
		streams[node] = nil;
	end
end

function serve_stream(event, node)
	module:log("debug", "Client subscribed to: %s", node);

	local response = event.response;
	response.on_destroy = client_closed;
	response._eventsource_node = node;

	response.conn:write(table.concat({
		"HTTP/1.1 200 OK";
		"Content-Type: text/event-stream";
		"Access-Control-Allow-Origin: *";
		"Access-Control-Allow-Methods: GET";
		"Access-Control-Max-Age: 7200";
		"";
		"";
	}, "\r\n"));

	local clientlist = streams[node];
	if not clientlist then
		clientlist = {};
		streams[node] = clientlist;
	end
	clientlist[response] = response.conn;

	return true;
end

function handle_update(event)
	module:log("debug", "Item published: %q", event.node);
	local node = event.node;
	local clientlist = streams[node];
	local item = event.item;
	if (item.name == "json" and item.attr.xmlns == "urn:xmpp:json:0") or (item.name == "data" and item.attr.xmlns == "https://prosody.im/protocol/data") then
		item = item[1];
	end
	local data = "data: "..tostring(item):gsub("\n", "\ndata: \n").."\n\n";
	if not clientlist then module:log("debug", "No clients for %q", node); return; end
	for response, conn in pairs(clientlist) do
		conn:write(data);
	end
end

module:provides("http", {
	name = "eventsource";
	route = {
		["GET /*"] = serve_stream;
	};
});

module:hook_object_event(service.events, "item-published", handle_update);