# HG changeset patch
# User Matthew Wild <mwild1@gmail.com>
# Date 1409131838 -3600
# Node ID 04049524fcd1d6766b9b9180048b331c958552f8
# Parent  dfcc5a0f5c799191b117db188f27aceed1357b9b
plugins.smacks: Improve logic for sending <r/>

diff -r dfcc5a0f5c79 -r 04049524fcd1 plugins/smacks.lua
--- a/plugins/smacks.lua	Wed Aug 27 10:30:08 2014 +0100
+++ b/plugins/smacks.lua	Wed Aug 27 10:30:38 2014 +0100
@@ -1,4 +1,5 @@
 local verse = require "verse";
+local now = socket.gettime;
 
 local xmlns_sm = "urn:xmpp:sm:2";
 
@@ -6,6 +7,8 @@
 	-- State for outgoing stanzas
 	local outgoing_queue = {};
 	local last_ack = 0;
+	local last_stanza_time = now();
+	local timer_active;
 	
 	-- State for incoming stanzas
 	local handled_stanza_count = 0;
@@ -24,11 +27,24 @@
 		if stanza.name and not stanza.attr.xmlns then
 			-- serialize stanzas in order to bypass this on resumption
 			outgoing_queue[#outgoing_queue+1] = tostring(stanza);
-			verse.add_task(1, function()
-				if #outgoing_queue > 0 then
+			last_stanza_time = now();
+			if not timer_active then
+				timer_active = true;
+				stream:debug("Waiting to send ack request...");
+				verse.add_task(1, function()
+					if #outgoing_queue == 0 then
+						timer_active = false;
+						return;
+					end
+					local time_since_last_stanza = now() - last_stanza_time;
+					if time_since_last_stanza < 1 and #outgoing_queue < 10 then
+						return 1 - time_since_last_stanza;
+					end
+					stream:debug("Time up, sending <r>...");
+					timer_active = false;
 					stream:send(verse.stanza("r", { xmlns = xmlns_sm }));
-				end
-			end);
+				end);
+			end
 		end
 	end