XMPP/Ext/VCard.pm untested

filter: Statementstmt 0.0% 0 / 167 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 18 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 279 CC 24 SCAR 30.0
CC
24
Cov
0%
encode_vcard
56.0
hook_on
42.0
_retrieve
20.0
CRAP 20.0
1 package AnyEvent::XMPP::Ext::VCard;
2 use AnyEvent::XMPP::Ext;
3 no warnings;
4 use strict;
5  
6 use MIME::Base64;
7 use Digest::SHA qw/sha1_hex/;
8 use Scalar::Util;
9 use AnyEvent::XMPP::Namespaces qw/xmpp_ns/;
10 use AnyEvent::XMPP::Util qw/prep_bare_jid/;
11  
12 our @ISA = qw/AnyEvent::XMPP::Ext/;
13  
14 =head1 NAME
15  
16 AnyEvent::XMPP::Ext::VCard - VCards (XEP-0054 & XEP-0084)
17  
18 =head1 SYNOPSIS
19  
20 use AnyEvent::XMPP::Ext::VCard;
21  
22 my $vcard = AnyEvent::XMPP::Ext::VCard->new;
23 $con->reg_cb (
24 stream_ready => sub { $vcard->hook_on ($con) }
25 );
26  
27 $vcard->retrieve ($con, 'elmex@jabber.org', sub {
28 my ($jid, $vcard, $error) = @_;
29  
30 if ($error) {
31 warn "couldn't get vcard for elmex@jabber.org: " . $error->string . "\n";
32 } else {
33 print "vCard nick for elmex@jabber.org: ".$vcard->{NICKNAME}."\n";
34 print "Avatar hash for elmex@jabber.org: ".$vcard->{_avatar_hash}."\n";
35 }
36 });
37  
38 $vcard->store ($con, undef, { NICKNAME => 'net-xmpp2' }, sub {
39 my ($error) = @_;
40 if ($error) {
41 warn "upload failed: " . $error->string . "\n";
42 } else {
43 print "upload successful\n";
44 }
45 });
46  
47 $disco->enable_feature ($vcard->disco_feature);
48  
49  
50 =head1 DESCRIPTION
51  
52 This extension handles setting and retrieval of the VCard and the
53 VCard based avatars.
54  
55 For example see the test suite of L<AnyEvent::XMPP>.
56  
57 =head1 METHODS
58  
59 =over 4
60  
61 =item B<new (%args)>
62  
63 Creates a new vcard extension.
64 It can take a C<cache> argument, which should be a tied hash
65 which should be able to save the retrieved vcards.
66 If no C<cache> is set a internal hash will be used and the
67 vcards will be retrieved everytime the program is restarted.
68 The keys will be the stringprepped bare JIDs of the people we
69 got a vcard from and the value will be a non-cyclic hash/array datastructure
70 representing the vcard.
71  
72 About this datastructure see below at B<VCARD STRUCTURE>.
73  
74 If you want to support avatars correctly make sure you hook up the connection
75 via the C<hook_on> method.
76  
77 =cut
78  
79 sub new {
80 my $this = shift;
81 my $class = ref($this) || $this;
82 my $self = bless { @_ }, $class;
83 $self->init;
84 $self
85 }
86  
87 sub init {
88 my ($self) = @_;
89  
90 $self->{cb_id} =
91 $self->reg_cb (
92 ext_before_vcard => sub {
93 my ($self, $jid, $vcard) = @_;
94 my $vc = $self->{cache}->{prep_bare_jid ($jid)} = $vcard;
95 }
96 );
97 }
98  
99 sub disco_feature { xmpp_ns ('vcard') }
100  
101 =item B<hook_on ($con, $dont_retrieve_vcard)>
102  
103 C<$con> must be an object of the class L<AnyEvent::XMPP::Connection> (or derived).
104 Once the vCard extension has been hooked up on a connection it will add
105 the avatar information to all outgoing presence stanzas.
106  
107 IMPORTANT: You need to hook on the connection B<BEFORE> it was connected. The
108 initial presence stanza needs to contain the information that we support
109 avatars. The vcard will automatically retrieved if the session wasn't already
110 started. Otherwise you will have to retrieve the vcard manually if you hook it
111 up after the C<session_ready> event was received. You can prevent the automatic
112 retrieval by giving a true value in C<$dont_retrieve_vcard>. However, just
113 make sure to hook up on any connection before it is connected if you want to
114 offer avatar support on it.
115  
116 Best is probably to do it like this:
117  
118 my $vcard = AnyEvent::XMPP::Ext::VCard->new;
119 $con->reg_cb (
120 stream_ready => sub { $vcard->hook_on ($con) }
121 );
122  
123 =cut
124  
125 sub hook_on {
126 my ($self, $con, $dont_retrieve_vcard) = @_;
127  
128 Scalar::Util::weaken $self;
129  
130 my $rid =
131 $con->reg_cb (
132 ext_before_send_presence_hook => sub {
133 my ($con, $id, $type, $attrs, $create_cb) = @_;
134  
135 my $chlds;
136  
137 my $vc = $self->my_vcard ($con);
138  
139 if ($vc && !$vc->{_avatar}) {
140 push @$chlds, { ns => xmpp_ns ('vcard_upd'), name => 'photo' }
141  
142 } elsif ($vc && $vc->{_avatar}) {
143 push @$chlds, {
144 ns => xmpp_ns ('vcard_upd'),
145 name => 'photo',
146 childs => [ $vc->{_avatar_hash} ]
147 }
148 }
149  
150 push @$create_cb, {
151 defns => xmpp_ns ('vcard_upd'),
152 node => {
153 ns => xmpp_ns ('vcard_upd'),
154 name => 'x',
155 ($chlds ? (childs => [ @$chlds ]) : ()),
156 }
157 };
158 },
159 ext_after_session_ready => sub {
160 my ($con) = @_;
161  
162 if (not $dont_retrieve_vcard) {
163 $self->retrieve ($con, undef, sub {
164 my ($jid, $vc, $error) = @_;
165  
166 if ($error) {
167 $self->event (retrieve_vcard_error => $error);
168 }
169  
170 # the own vcard was already set by retrieve
171 # this will push out an updated presence
172 $self->_publish_avatar;
173 });
174 }
175 }
176 );
177  
178 my $ar = [$con, $rid];
179 Scalar::Util::weaken $ar->[0];
180 push @{$self->{hooked}}, $ar;
181 }
182  
183 sub _publish_avatar {
184 my ($self) = @_;
185  
186 for (@{$self->{hooked}}) {
187 if ($_->[0]) { $_->[0]->send_presence () }
188 }
189 }
190  
191 =item B<my_vcard ($con)>
192  
193 This method returns the vcard for the account connected by C<$con>.
194 This only works if vcard was (successfully) retrieved. If the connection was
195 hoooked up the vcard was automatically retrieved.
196  
197 Alternatively C<$con> can also be a string reprensenting the JID of an
198 account.
199  
200 =cut
201  
202 sub my_vcard {
203 my ($self, $con) = @_;
204 $self->{own_vcards}->{prep_bare_jid (ref ($con) ? $con->jid : $con)}
205 }
206  
207 =item B<cache ([$newcache])>
208  
209 See also C<new> about the meaning of cache hashes.
210 If no argument is given the current cache is returned.
211  
212 =cut
213  
214 sub cache {
215 my ($self, $cache_hash) = @_;
216 $self->{cache} = $cache_hash if defined $cache_hash;
217 $self->{cache}
218 }
219  
220 sub _store {
221 my ($self, $con, $vcard_cb, $cb) = @_;
222  
223 $con->send_iq (
224 set => sub {
225 my ($w) = @_;
226 $w->addPrefix (xmpp_ns ('vcard'), '');
227 $w->startTag ([xmpp_ns ('vcard'), 'vCard']);
228 $vcard_cb->($w);
229 $w->endTag;
230  
231 }, sub {
232 my ($xmlnode, $error) = @_;
233  
234 if ($error) {
235 $cb->($error);
236 } else {
237 $cb->();
238 }
239 }
240 );
241 }
242  
243 =item B<store ($con, $vcard, $cb)>
244  
245 This method will store your C<$vcard> on the connected server.
246 C<$cb> is called when either an error occured or the storage was successful.
247 If an error occured the first argument is not undefined and contains an
248 L<AnyEvent::XMPP::Error::IQ> object.
249  
250 C<$con> should be a L<AnyEvent::XMPP::Connection> or an object from some derived class.
251  
252 C<$vcard> has a datastructure as described below in B<VCARD STRUCTURE>.
253  
254 =cut
255  
256 sub store {
257 my ($self, $con, $vcard, $cb) = @_;
258  
259 $self->_store ($con, sub {
260 my ($w) = @_;
261 $self->encode_vcard ($vcard, $w);
262 }, sub {
263 $cb->(@_);
264 });
265 }
266  
267 sub _retrieve {
268 my ($self, $con, $dest, $cb) = @_;
269  
270  
271 $con->send_iq (
272 get => { defns => 'vcard', node => { ns => 'vcard', name => 'vCard' } },
273 sub {
274 my ($xmlnode, $error) = @_;
275  
276 if ($error) {
277 $cb->(undef, undef, $error);
278  
279 } else {
280 my ($vcard) = $xmlnode->find_all ([qw/vcard vCard/]);
281 my $jid = $dest || prep_bare_jid ($con->jid);
282 $vcard = $self->decode_vcard ($vcard);
283 if (prep_bare_jid ($jid) eq prep_bare_jid ($con->jid)) {
284 $self->{own_vcards}->{prep_bare_jid $con->jid} = $vcard;
285 }
286 $self->event (vcard => $jid, $vcard);
287 $cb->($jid, $vcard, $error);
288 }
289 },
290 (defined $dest ? (to => $dest) : ())
291 );
292 }
293  
294 =item B<retrieve ($con, $jid, $cb)>
295  
296 This method will retrieve the vCard for C<$jid> via the connection C<$con>.
297 If C<$jid> is undefined the vCard of yourself is retrieved.
298 The callback C<$cb> is called when an error occured or the vcard was retrieved.
299 The first argument of the callback will be the JID to which the vCard belongs,
300 the second argument is the vCard itself (as described in B<VCARD STRUCTURE> below)
301 and the thrid argument is the error, if an error occured (undef otherwise).
302  
303 =cut
304  
305 sub retrieve {
306 my ($self, $con, $dest, $cb) = @_;
307  
308 $self->_retrieve ($con, $dest, sub {
309 my ($jid, $vc, $error) = @_;
310  
311 if ($error) { $cb->(undef, $error); return }
312 else {
313 $cb->($jid, $vc);
314 }
315 });
316 }
317  
318 sub decode_vcard {
319 my ($self, $vcard) = @_;
320 my $ocard = {};
321  
322 for my $cn ($vcard->nodes) {
323 if ($cn->nodes) {
324 my $sub = {};
325 for ($cn->nodes) {
326 $sub->{$_->name} = $_->text
327 }
328 push @{$ocard->{$cn->name}}, $sub;
329 } else {
330 push @{$ocard->{$cn->name}}, $cn->text;
331 }
332 }
333  
334 if (my $p = $ocard->{PHOTO}) {
335 my $first = $p->[0];
336  
337 if ($first->{BINVAL} ne '') {
338 $ocard->{_avatar} = decode_base64 ($first->{BINVAL});
339 $ocard->{_avatar_hash} = sha1_hex ($ocard->{_avatar});
340 $ocard->{_avatar_type} = $first->{TYPE};
341 }
342 }
343  
344 $ocard
345 }
346  
347 sub encode_vcard {
348 my ($self, $vcardh, $w) = @_;
349  
350 if ($vcardh->{_avatar}) {
351 $vcardh->{PHOTO} = [
352 {
353 BINVAL => encode_base64 ($vcardh->{_avatar}),
354 TYPE => $vcardh->{_avatar_type}
355 }
356 ];
357 }
358  
359 for my $ve (keys %$vcardh) {
360 next if substr ($ve, 0, 1) eq '_';
361  
362 for my $el (@{ref ($vcardh->{$ve}) eq 'ARRAY' ? $vcardh->{$ve} : [$vcardh->{$ve}]}) {
363  
364 if (ref $el) {
365 $w->startTag ([xmpp_ns ('vcard'), $ve]);
366  
367 for (keys %$el) {
368 if ((not defined $el->{$_}) || $el->{$_} eq '') {
369 $w->emptyTag ([xmpp_ns ('vcard'), $_]);
370  
371 } else {
372 $w->startTag ([xmpp_ns ('vcard'), $_]);
373 $w->characters ($el->{$_});
374 $w->endTag;
375 }
376 }
377 $w->endTag;
378  
379 } elsif ((not defined $el) || $el eq '') {
380 $w->emptyTag ([xmpp_ns ('vcard'), $ve]);
381  
382 } else {
383 $w->startTag ([xmpp_ns ('vcard'), $ve]);
384 $w->characters ($el);
385 $w->endTag;
386 }
387 }
388 }
389 }
390  
391 sub DESTROY {
392 my ($self) = @_;
393 $self->unreg_cb ($self->{cb_id});
394 for (@{$self->{hooked}}) {
395 $_->[0]->unreg_cb ($_->[1]) if defined $_->[0];
396 }
397 }
398  
399 =back
400  
401 =head1 VCARD STRUCTURE
402  
403 As there are currently no nice DOM implementations in Perl and I strongly
404 dislike the DOM API in general this module has a simple Perl datastructure
405 without cycles to represent the vCard.
406  
407 First an example: A fetched vCard hash may look like this:
408  
409 {
410 'URL' => ['http://www.ta-sa.org/'],
411 'ORG' => [{
412 'ORGNAME' => 'nethype GmbH'
413 }],
414 'N' => [{
415 'FAMILY' => 'Redeker'
416 }],
417 'EMAIL' => ['elmex@ta-sa.org'],
418 'BDAY' => ['1984-06-01'],
419 'FN' => ['Robin'],
420 'ADR' => [
421 {
422 HOME => undef,
423 'COUNTRY' => 'Germany'
424 },
425 {
426 WORK => undef,
427 COUNTRY => 'Germany',
428 LOCALITY => 'Karlsruhe'
429 }
430 ],
431 'NICKNAME' => ['elmex'],
432 'ROLE' => ['Programmer']
433 }
434  
435 The keys represent the toplevel element of a vCard, the values are always array
436 references containig one or more values for the key. If the value is a
437 hash reference again it's value will not be an array reference but either undef
438 or plain values.
439  
440 The values of the toplevel keys are all array references because fields
441 like C<ADR> may occur multiple times.
442  
443 Consult XEP-0054 for an explanation what these fields mean or contain.
444  
445 There are special fields in this structure for handling avatars:
446 C<_avatar> contains the binary data for the avatar image.
447 C<_avatar_hash> contains the sha1 hexencoded hash of the binary image data.
448 C<_avatar_type> contains the mime type of the avatar.
449  
450 If you want to store the vcard you only have to set C<_avatar> and C<_avatar_type>
451 if you want to store an avatar.
452  
453 =head1 EVENTS
454  
455 The vcard extension will emit these events:
456  
457 =head1 TODO
458  
459 Implement caching, the cache stuff is just a storage hash at the moment.
460 Or maybe drop it completly and let the application handle caching.
461  
462 =over 4
463  
464 =item retrieve_vcard_error => $iq_error
465  
466 When a vCard retrieval was not successful, this event is emitted.
467 This is neccessary as some retrievals may happen automatically.
468  
469 =item vcard => $jid, $vcard
470  
471 Whenever a vCard is retrieved, either automatically or manually,
472 this event is emitted with the retrieved vCard.
473  
474 =back
475  
476 =head1 AUTHOR
477  
478 Robin Redeker, C<< <elmex at ta-sa.org> >>, JID: C<< <elmex at jabber.org> >>
479  
480 =head1 COPYRIGHT & LICENSE
481  
482 Copyright 2007, 2008 Robin Redeker, all rights reserved.
483  
484 This program is free software; you can redistribute it and/or modify it
485 under the same terms as Perl itself.
486  
487 =cut
488  
489 1;