examples/lm/vcard.lua
changeset 68 742878c74b8e
child 70 e43e386c8a33
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/lm/vcard.lua	Tue Mar 31 18:35:34 2009 +0300
@@ -0,0 +1,108 @@
+
+-- VCARD-TEMP (XEP-0054)
+
+-- library
+
+local iq         = require 'lm.iq'
+local form_field = require 'lm.form_field'
+
+--
+
+local F = { }
+local M = { }
+M.__index = M
+
+function F.new ( args )
+	local form = {
+		xmlns        = 'vcard-temp',
+		ftype        = args.type or 'form',
+		title        = args.title,
+		instructions = args.instructions,
+		f            = { },
+	}
+	setmetatable ( form, M )
+	return form
+end
+
+local function vcard_parse ( node, path, form )
+	local item = node:child ()
+	if item then
+		while item do
+			vcard_parse ( item, ( path and path .. '/' or '' ) .. item:name (), form )
+			item = item:next ()
+		end
+	elseif path then
+		form:add ( path, { type = 'text-single', value = node:value () } )
+	end
+end
+
+function F.parse ( card )
+	local form = F.new { type = 'form' }
+	vcard_parse ( card, nil, form )
+	return form
+end
+
+function M.type ( form )
+	return form.ftype
+end
+
+function M.desc ( form )
+	return form.title, form.instructions
+end
+
+function M.format ( form, root, format_as )
+	root.vCard = { xmlns = 'vcard-temp' }
+	for k, field in form:fields () do
+		local el = root.vCard
+		for k in field:name():gmatch ( '[^/]+' ) do
+			if not el[k] then
+				el[k] = { }
+			end
+			el = el[k]
+		end
+		el[1] = field:value ()
+	end
+	return root
+end
+
+function M.fields ( form )
+	return ipairs ( form.f )
+end
+
+function M.add ( form, name, fld )
+	fld.var   = name
+	fld.index = #form.f + 1
+	local obj = form_field.new ( fld )
+	table.insert ( form.f, obj )
+	form.f[name] = obj
+	return obj
+end
+
+function M.field ( form, name )
+	return form.f[name]
+end
+
+function F.retrieve ( 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 ( F.parse ( mess:child ( 'vCard' ) ),
+					function ( form, success, fail )
+						iq.send ( conn, from, 'set', form:format ( form, { }, 'submit' ), success, fail )
+					end,
+					function ( form, success, fail )
+						success ()
+					end )
+			else
+				fail ( mess:xml () ) -- XXX
+			end
+		end, fail )
+end
+
+return F
+
+-- vim: se ts=4: --