Ping
authorMyhailo Danylenko <isbear@ukrpost.net>
Mon, 23 Mar 2009 02:01:16 +0200
changeset 55 9e32b6288c86
parent 54 b53355736057
child 56 8561e55e0662
Ping
examples/ping.lua
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/ping.lua	Mon Mar 23 02:01:16 2009 +0200
@@ -0,0 +1,69 @@
+
+-- XMPP PING (XEP-0199)
+
+-- library
+
+require 'lm'
+require 'iq'
+
+-- public
+
+ping = { }
+
+function ping.send ( conn, to, success, fail )
+	iq.send ( conn, to, 'get', success, fail )
+end
+
+-- private
+
+local ping_incoming_iq_handler = lm.message_handler.new (
+	function ( conn, mess )
+		local mtype, smtype = mess:type ()
+		if smtype == 'get' then
+			local p = mess:child ( 'ping' )
+			if p and p:attribute ( 'xmlns' ) == 'urn:xmpp:ping' then
+				conn:send ( lm.message.create { mtype = 'iq-result', to = mess:attribute ( 'from' ), id = mess:attribute ( 'id' ) } )
+				return true
+			end
+		end
+		return false
+	end )
+
+-- mcabber
+
+main.command ( 'ping',
+	function ( args )
+		local who
+		if args[1] then
+			who = args[1]
+		else
+			who = main.full_jid ()
+		end
+		local time = os.time ()
+		ping.send ( lm.connection.bless ( main.connection () ), who,
+			function ()
+				main.print_info ( ('Pong: %d seconds'):format ( os.time () - time ) )
+			end,
+			function ( mesg )
+				main.print_info ( 'Ping failed: ' .. mesg )
+			end )
+	end, true, 'jid' )
+
+local ping_handler_registered = false
+
+hooks_d['hook-post-connect'].ping =
+	function ( args )
+		lm.connection.bless( main.connection () ):handler ( ping_incoming_iq_handler, 'iq', 'normal' )
+		ping_handler_registered = true
+		hooks_d['hook-post-connect'].ping = nil
+		hooks_d['hook-quit'].ping =
+			function ( args )
+				if ping_handler_registered then
+					lm.connection.bless( main.connection () ):handler ( ping_incoming_iq_handler, 'iq' )
+				end
+			end
+	end
+
+main.add_feature ( 'urn:xmpp:ping' )
+
+-- vim: se ts=4: --