examples/vcard.lua
author Myhailo Danylenko <isbear@ukrpost.net>
Fri, 27 Mar 2009 12:06:19 +0200
changeset 66 542f61e113cb
parent 64 bf7521ed96eb
child 67 d33ca5572e91
permissions -rw-r--r--
Modularization, I * activity * attention * avatar * disco * evil * geoloc * ibb * iq * mood * oob * ping * pubsub * tune * mpd * pep


-- VCARD-TEMP (XEP-0054)

-- library

local lm = require 'lm'
local iq = require 'iq'
require 'x_data'

-- public

vcard = { }

local function vcard_parse ( node, path, ret )
	local item = node:child ()
	if item then
		while item do
			vcard_parse ( item, ( path and path .. '/' or '' ) .. item:name (), ret )
			item = item:next ()
		end
	elseif path then
		table.insert ( ret, { var = path, type = 'text-single', value = node:value () } )
	end
end

function vcard.parse ( card )
	local form = { xmlns = 'vcard-temp', type = 'form' }
	vcard_parse ( card, nil, form )
	form.format =
		function ( form, root )
			root.vCard = { xmlns = 'vcard-temp' }
			for k, field in ipairs ( form ) do
				local el = root.vCard
				for k in field.var:gmatch ( '[^/]+' ) do
					if not el[k] then
						el[k] = { }
					end
					el = el[k]
				end
				el[1] = field.value
			end
			return root
		end
	return form
end

function vcard.get ( conn, from, success, fail )
	iq.send ( conn, from, 'get',
		{
			vCard = { xmlns = 'vcard-temp' },
		},
		function ( mess )
			local card = mess:child ( 'vCard' )
			if card and card:attribute ( 'xmlns' ) == 'vcard-temp' then
				success ( vcard.parse ( mess:child ( 'vCard' ) ),
					function ( form, success, fail )
						form.type = 'submit' -- :)
						iq.send ( conn, from, 'set', form.format ( form, { } ), success, fail )
					end,
					function ( form, success, fail )
						success ()
					end )
			else
				fail ( mess:xml () ) -- XXX
			end
		end, fail )
end

-- mcabber

main.command ( 'vcard-temp',
	function ( args )
		vcard.get ( lm.connection.bless ( main.connection () ), args[1],
			function ( form, submit, reject )
				local id = #forms + 1
				forms[id] = {
					form = form,
					submit =
						function ( form )
							submit ( form,
								function ()
									print ( 'Vcard changed' )
								end,
								function ( mesg )
									print ( 'Vcard changing error: ' .. mesg )
								end )
						end,
					reject =
						function ( form )
							reject ( form,
								function ()
									print ( 'Vcard changing cancelled' )
								end,
								function ( mesg )
									print ( 'Vcard changing cancellation error: ' .. mesg )
								end )
						end,
				}
				print ( 'You have new form ' .. id )
			end,
			function ( mesg )
				print ( 'Vcard obtaining error: ' .. mesg )
			end )
	end, true, 'jid' )

-- vim: se ts=4: --