Welcome to mirror list, hosted at ThFree Co, Russian Federation.

contacts.py « common « src - dev.gajim.org/gajim/gajim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5a9df3499eddc5ab3ff0beaae511b44312735564 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# -*- coding:utf-8 -*-
## src/common/contacts.py
##
## Copyright (C) 2006 Dimitur Kirov <dkirov AT gmail.com>
##                    Travis Shirk <travis AT pobox.com>
##                    Nikos Kouremenos <kourem AT gmail.com>
## Copyright (C) 2006-2008 Yann Leboulanger <asterix AT lagaule.org>
##                         Jean-Marie Traissard <jim AT lapin.org>
## Copyright (C) 2007 Lukas Petrovicky <lukas AT petrovicky.net>
##                    Tomasz Melcer <liori AT exroot.org>
##                    Julien Pivotto <roidelapluie AT gmail.com>
## Copyright (C) 2007-2008 Stephan Erb <steve-e AT h3c.de>
## Copyright (C) 2008 Brendan Taylor <whateley AT gmail.com>
##                    Jonathan Schleifer <js-gajim AT webkeks.org>
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 3 only.
##
## Gajim is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
##

import common.gajim
import caps
from account import Account

class XMPPEntity(object):
	'''Base representation of entities in XMPP'''
	
	def __init__(self, jid, account, resource):
		self.jid = jid
		self.resource = resource
		self.account = account

class CommonContact(XMPPEntity):
	
	def __init__(self, jid, account, resource, show, status, name, our_chatstate,
	composing_xep, chatstate, client_caps=None):
		
		XMPPEntity.__init__(self, jid, account, resource)
		
		self.show = show
		self.status = status
		self.name = name
		
		self.client_caps = client_caps or caps.NullClientCaps()
		
		# please read xep-85 http://www.xmpp.org/extensions/xep-0085.html
		# we keep track of xep85 support with the peer by three extra states:
		# None, False and 'ask'
		# None if no info about peer
		# False if peer does not support xep85
		# 'ask' if we sent the first 'active' chatstate and are waiting for reply
		# this holds what WE SEND to contact (our current chatstate)
		self.our_chatstate = our_chatstate
		# tell which XEP we're using for composing state
		# None = have to ask, XEP-0022 = use this xep,
		# XEP-0085 = use this xep, False = no composing support
		self.composing_xep = composing_xep
		# this is contact's chatstate
		self.chatstate = chatstate
	
	def get_full_jid(self):
		raise NotImplementedError
	
	def get_shown_name(self):
		raise NotImplementedError

	def supports(self, requested_feature):
		'''
		Returns True if the contact has advertised to support the feature
		identified by the given namespace. False otherwise.
		'''
		if self.show == 'offline':
			# Unfortunately, if all resources are offline, the contact
			# includes the last resource that was online. Check for its
			# show, so we can be sure it's existant. Otherwise, we still
			# return caps for a contact that has no resources left.
			return False
		else:
			return caps.client_supports(self.client_caps, requested_feature)


class Contact(CommonContact):
	'''Information concerning each contact'''
	def __init__(self, jid, account, name='', groups=[], show='', status='', sub='',
	ask='', resource='', priority=0, keyID='', client_caps=None,
	our_chatstate=None, chatstate=None, last_status_time=None, msg_id = None,
	composing_xep=None):
		
		CommonContact.__init__(self, jid, account, resource, show, status, name, 
			our_chatstate, composing_xep, chatstate, client_caps=client_caps)
		
		self.contact_name = '' # nick choosen by contact
		self.groups = [i for i in set(groups)] # filter duplicate values

		self.sub = sub
		self.ask = ask
		
		self.priority = priority
		self.keyID = keyID
		self.msg_id = msg_id
		self.last_status_time = last_status_time
		
		self.pep = {}

	def get_full_jid(self):
		if self.resource:
			return self.jid + '/' + self.resource
		return self.jid

	def get_shown_name(self):
		if self.name:
			return self.name
		if self.contact_name:
			return self.contact_name
		return self.jid.split('@')[0]

	def get_shown_groups(self):
		if self.is_observer():
			return [_('Observers')]
		elif self.is_groupchat():
			return [_('Groupchats')]
		elif self.is_transport():
			return [_('Transports')]
		elif not self.groups:
			return [_('General')]
		else:
			return self.groups

	def is_hidden_from_roster(self):
		'''if contact should not be visible in roster'''
		# XEP-0162: http://www.xmpp.org/extensions/xep-0162.html
		if self.is_transport():
			return False
		if self.sub in ('both', 'to'):
			return False
		if self.sub in ('none', 'from') and self.ask == 'subscribe':
			return False
		if self.sub in ('none', 'from') and (self.name or len(self.groups)):
			return False
		if _('Not in Roster') in self.groups:
			return False
		return True

	def is_observer(self):
		# XEP-0162: http://www.xmpp.org/extensions/xep-0162.html
		is_observer = False
		if self.sub == 'from' and not self.is_transport()\
		and self.is_hidden_from_roster():
			is_observer = True
		return is_observer

	def is_groupchat(self):
		for account in common.gajim.gc_connected:
			if self.jid in common.gajim.gc_connected[account]:
				return True
		return False

	def is_transport(self):
		# if not '@' or '@' starts the jid then contact is transport
		if self.jid.find('@') <= 0:
			return True
		return False


class GC_Contact(CommonContact):
	'''Information concerning each groupchat contact'''
	def __init__(self, room_jid, account, name='', show='', status='', role='',
	affiliation='', jid='', resource='', our_chatstate=None,
	composing_xep=None, chatstate=None):
		
		CommonContact.__init__(self, jid, account, resource, show, status, name,
				our_chatstate, composing_xep, chatstate)
		
		self.room_jid = room_jid
		self.role = role
		self.affiliation = affiliation
		
	def get_full_jid(self):
		return self.room_jid + '/' + self.name

	def get_shown_name(self):
		return self.name
	
	def as_contact(self):
		'''Create a Contact instance from this GC_Contact instance'''
		return Contact(jid=self.get_full_jid(), account=self.account,
			resource=self.resource, name=self.name, groups=[], show=self.show,
			status=self.status, sub='none', client_caps=self.client_caps)
	

class Contacts:
	'''Information concerning all contacts and groupchat contacts'''
	def __init__(self):
		
		self._metacontact_manager = MetacontactManager(self)
		self._accounts = {}
		
	def change_account_name(self, old_name, new_name):		
		self._accounts[new_name] = self._accounts[old_name]
		self._accounts[new_name].name = new_name
		del self._accounts[old_name]
		
		self._metacontact_manager.change_account_name(old_name, new_name)

	def add_account(self, account_name):
		self._accounts[account_name] = Account(account_name,
				Contacts_New(), GC_Contacts())
		self._metacontact_manager.add_account(account_name)

	def get_accounts(self):
		return self._accounts.keys()

	def remove_account(self, account):
		del self._accounts[account]
		self._metacontact_manager.remove_account(account)

	def create_contact(self, jid, account, name='', groups=[], show='', status='',
		sub='', ask='', resource='', priority=0, keyID='', client_caps=None,
		our_chatstate=None, chatstate=None, last_status_time=None,
		composing_xep=None):
		account = self._accounts.get(account, account) # Use Account object if available
		return Contact(jid=jid, account=account, name=name, groups=groups,
			show=show, status=status, sub=sub, ask=ask, resource=resource, priority=priority,
			keyID=keyID, client_caps=client_caps, our_chatstate=our_chatstate,
			chatstate=chatstate, last_status_time=last_status_time,
			composing_xep=composing_xep)
		
	def create_self_contact(self, jid, account, resource, show, status, priority,
	name='', keyID=''):
		conn = common.gajim.connections[account]
		nick = name or common.gajim.nicks[account]
		account = self._accounts.get(account, account) # Use Account object if available
		self_contact = self.create_contact(jid=jid, account=account,
			name=nick, groups=['self_contact'], show=show, status=status,
			sub='both', ask='none',	priority=priority, keyID=keyID,
			resource=resource)
		self_contact.pep = conn.pep
		return self_contact
		
	def create_not_in_roster_contact(self, jid, account, resource='', name='', keyID=''):
		account = self._accounts.get(account, account) # Use Account object if available
		return self.create_contact(jid=jid, account=account, resource=resource,
				name=name, groups=[_('Not in Roster')], show='not in roster',
				status='', sub='none', keyID=keyID)

	def copy_contact(self, contact):
		return self.create_contact(jid=contact.jid, account=contact.account,
			name=contact.name, groups=contact.groups, show=contact.show, status=contact.status,
			sub=contact.sub, ask=contact.ask, resource=contact.resource,
			priority=contact.priority, keyID=contact.keyID,
			client_caps=contact.client_caps, our_chatstate=contact.our_chatstate,
			chatstate=contact.chatstate, last_status_time=contact.last_status_time)

	def add_contact(self, account, contact):
		if account not in self._accounts:
			self.add_account(account)
		return self._accounts[account].contacts.add_contact(contact)

	def remove_contact(self, account, contact):
		if account not in self._accounts:
			return
		return self._accounts[account].contacts.remove_contact(contact)

	def remove_jid(self, account, jid, remove_meta=True):
		self._accounts[account].contacts.remove_jid(jid)
		if remove_meta:
			self._metacontact_manager.remove_metacontact(account, jid)
		
	def get_contacts(self, account, jid):
		return self._accounts[account].contacts.get_contacts(jid)

	def get_contact(self, account, jid, resource=None):
		return self._accounts[account].contacts.get_contact(jid, resource=resource)

	def iter_contacts(self, account):
		for contact in self._accounts[account].contacts.iter_contacts():
			yield contact

	def get_contact_from_full_jid(self, account, fjid):
		return self._accounts[account].contacts.get_contact_from_full_jid(fjid)
	
	def get_first_contact_from_jid(self, account, jid):
		return self._accounts[account].contacts.get_first_contact_from_jid(jid)

	def get_contacts_from_group(self, account, group):
		return self._accounts[account].contacts.get_contacts_from_group(group)
	
	def get_jid_list(self, account):
		return self._accounts[account].contacts.get_jid_list()

	def change_contact_jid(self, old_jid, new_jid, account):
		return self._accounts[account].change_contact_jid(old_jid, new_jid)

	def get_highest_prio_contact_from_contacts(self, contacts):
		if not contacts:
			return None
		prim_contact = contacts[0]
		for contact in contacts[1:]:
			if int(contact.priority) > int(prim_contact.priority):
				prim_contact = contact
		return prim_contact

	def get_contact_with_highest_priority(self, account, jid):
		contacts = self.get_contacts(account, jid)
		if not contacts and '/' in jid:
			# jid may be a fake jid, try it
			room, nick = jid.split('/', 1)
			contact = self.get_gc_contact(account, room, nick)
			return contact
		return self.get_highest_prio_contact_from_contacts(contacts)
	
	def get_nb_online_total_contacts(self, accounts=[], groups=[]):
		'''Returns the number of online contacts and the total number of
		contacts'''
		if accounts == []:
			accounts = self.get_accounts()
		nbr_online = 0
		nbr_total = 0
		for account in accounts:
			our_jid = common.gajim.get_jid_from_account(account)
			for jid in self.get_jid_list(account):
				if jid == our_jid:
					continue
				if common.gajim.jid_is_transport(jid) and not \
				_('Transports') in groups:
					# do not count transports
					continue
				if self.has_brother(account, jid, accounts) and not \
				self.is_big_brother(account, jid, accounts):
					# count metacontacts only once
					continue
				contact = self.get_contact_with_highest_priority(account, jid)
				if _('Not in roster') in contact.groups:
					continue
				in_groups = False
				if groups == []:
					in_groups = True
				else:
					for group in groups:
						if group in contact.get_shown_groups():
							in_groups = True
							break

				if in_groups:
					if contact.show not in ('offline', 'error'):
						nbr_online += 1
					nbr_total += 1
		return nbr_online, nbr_total

	def is_pm_from_jid(self, account, jid):
		'''Returns True if the given jid is a private message jid'''
		if jid in self._contacts[account]:
			return False
		return True

	def is_pm_from_contact(self, account, contact):
		'''Returns True if the given contact is a private message contact'''
		if isinstance(contact, Contact):
			return False
		return True
	
	def __getattr__(self, attr_name):
		# Only called if self has no attr_name
		if hasattr(self._metacontact_manager, attr_name):
			return getattr(self._metacontact_manager, attr_name)
		else:
			raise AttributeError(attr_name)
	
	def create_gc_contact(self, room_jid, account, name='', show='', status='',
		role='', affiliation='', jid='', resource=''):
		account = self._accounts.get(account, account) # Use Account object if available
		return GC_Contact(room_jid, account, name, show, status, role, affiliation, jid,
			resource)

	def add_gc_contact(self, account, gc_contact):
		return self._accounts[account].gc_contacts.add_gc_contact(gc_contact)

	def remove_gc_contact(self, account, gc_contact):
		return self._accounts[account].gc_contacts.remove_gc_contact(gc_contact)

	def remove_room(self, account, room_jid):
		return self._accounts[account].gc_contacts.remove_room(room_jid)

	def get_gc_list(self, account):
		return self._accounts[account].gc_contacts.get_gc_list()

	def get_nick_list(self, account, room_jid):
		return self._accounts[account].gc_contacts.get_nick_list(room_jid)

	def get_gc_contact(self, account, room_jid, nick):
		return self._accounts[account].gc_contacts.get_gc_contact(room_jid, nick)

	def get_nb_role_total_gc_contacts(self, account, room_jid, role):
		return self._accounts[account].gc_contacts.get_nb_role_total_gc_contacts(room_jid, role)
		
		
class Contacts_New():
	
	def __init__(self):
		# list of contacts  {jid1: [C1, C2]}, } one Contact per resource
		self._contacts = {}
		
	def add_contact(self, contact):		
		if contact.jid not in self._contacts:
			self._contacts[contact.jid] = [contact]
			return
		contacts = self._contacts[contact.jid]
		# We had only one that was offline, remove it
		if len(contacts) == 1 and contacts[0].show == 'offline':
			# Do not use self.remove_contact: it deteles
			# self._contacts[account][contact.jid]
			contacts.remove(contacts[0])
		# If same JID with same resource already exists, use the new one
		for c in contacts:
			if c.resource == contact.resource:
				self.remove_contact(c)
				break
		contacts.append(contact)
		
	def remove_contact(self, contact):
		if contact.jid not in self._contacts:
			return
		if contact in self._contacts[contact.jid]:
			self._contacts[contact.jid].remove(contact)
		if len(self._contacts[contact.jid]) == 0:
			del self._contacts[contact.jid]
			
	def remove_jid(self, jid):
		'''Removes all contacts for a given jid'''
		if jid not in self._contacts:
			return
		del self._contacts[jid]
			
	def get_contacts(self, jid):
		'''Returns the list of contact instances for this jid.'''
		if jid in self._contacts:
			return self._contacts[jid]
		else:
			return []
		
	def get_contact(self, jid, resource=None):
		### WARNING ###
		# This function returns a *RANDOM* resource if resource = None!
		# Do *NOT* use if you need to get the contact to which you
		# send a message for example, as a bare JID in Jabber means
		# highest available resource, which this function ignores!
		'''Returns the contact instance for the given resource if it's given else
		the first contact is no resource is given or None if there is not'''
		if jid in self._contacts:
			if not resource:
				return self._contacts[jid][0]
			for c in self._contacts[jid]:
				if c.resource == resource:
					return c
		return None

	def iter_contacts(self):
		for jid in self._contacts.keys():
			for contact in self._contacts[jid][:]:
				yield contact
				
	def get_jid_list(self):
		return self._contacts.keys()
				
	def get_contact_from_full_jid(self, fjid):
		''' Get Contact object for specific resource of given jid'''
		barejid, resource = common.gajim.get_room_and_nick_from_fjid(fjid)
		return self.get_contact(barejid, resource)
	
	def get_first_contact_from_jid(self, jid):
		if jid in self._contacts:
			return self._contacts[jid][0]
		return None

	def get_contacts_from_group(self, group):
		'''Returns all contacts in the given group'''
		group_contacts = []
		for jid in self._contacts:
			contacts = self.get_contacts(jid)
			if group in contacts[0].groups:
				group_contacts += contacts
		return group_contacts

	def change_contact_jid(self, old_jid, new_jid):
		if old_jid not in self._contacts:
			return
		self._contacts[new_jid] = []
		for _contact in self._contacts[old_jid]:
			_contact.jid = new_jid
			self._contacts[new_jid].append(_contact)
			del self._contacts[old_jid]


class GC_Contacts():
	
	def __init__(self):
		# list of contacts that are in gc {room_jid: {nick: C}}}
		self._rooms = {}
	
	def add_gc_contact(self, gc_contact):
		if gc_contact.room_jid not in self._rooms:
			self._rooms[gc_contact.room_jid] = {gc_contact.name: gc_contact}
		else:
			self._rooms[gc_contact.room_jid][gc_contact.name] = gc_contact

	def remove_gc_contact(self, gc_contact):
		if gc_contact.room_jid not in self._rooms:
			return
		if gc_contact.name not in self._rooms[gc_contact.room_jid]:
			return
		del self._rooms[gc_contact.room_jid][gc_contact.name]
		# It was the last nick in room ?
		if not len(self._rooms[gc_contact.room_jid]):
			del self._rooms[gc_contact.room_jid]

	def remove_room(self, room_jid):
		if room_jid not in self._rooms:
			return
		del self._rooms[room_jid]

	def get_gc_list(self):
		return self._rooms.keys()

	def get_nick_list(self, room_jid):
		gc_list = self.get_gc_list()
		if not room_jid in gc_list:
			return []
		return self._rooms[room_jid].keys()

	def get_gc_contact(self, room_jid, nick):
		nick_list = self.get_nick_list(room_jid)
		if not nick in nick_list:
			return None
		return self._rooms[room_jid][nick]

	def get_nb_role_total_gc_contacts(self, room_jid, role):
		'''Returns the number of group chat contacts for the given role and the
		total number of group chat contacts'''
		if room_jid not in self._rooms:
			return 0, 0
		nb_role = nb_total = 0
		for nick in self._rooms[room_jid]:
			if self._rooms[room_jid][nick].role == role:
				nb_role += 1
			nb_total += 1
		return nb_role, nb_total
		

class MetacontactManager():
	
	def __init__(self, contacts):
		self._metacontacts_tags = {}
		self._contacts = contacts
	
	def change_account_name(self, old_name, new_name):
		self._metacontacts_tags[new_name] = self._metacontacts_tags[old_name]
		del self._metacontacts_tags[old_name]
		
	def add_account(self, account):
		if account not in self._metacontacts_tags:
			self._metacontacts_tags[account] = {}
	
	def remove_account(self, account):
		del self._metacontacts_tags[account]
		
	def define_metacontacts(self, account, tags_list):
		self._metacontacts_tags[account] = tags_list

	def _get_new_metacontacts_tag(self, jid):
		if not jid in self._metacontacts_tags:
			return jid
		#FIXME: can this append ?
		assert False

	def iter_metacontacts_families(self, account):		
		for tag in self._metacontacts_tags[account]:
			family = self._get_metacontacts_family_from_tag(account, tag)
			yield family

	def _get_metacontacts_tag(self, account, jid):
		'''Returns the tag of a jid'''
		if not account in self._metacontacts_tags:
			return None
		for tag in self._metacontacts_tags[account]:
			for data in self._metacontacts_tags[account][tag]:
				if data['jid'] == jid:
					return tag
		return None

	def add_metacontact(self, brother_account, brother_jid, account, jid, order=None):
		tag = self._get_metacontacts_tag(brother_account, brother_jid)
		if not tag:
			tag = self._get_new_metacontacts_tag(brother_jid)
			self._metacontacts_tags[brother_account][tag] = [{'jid': brother_jid,
				'tag': tag}]
			if brother_account != account:
				common.gajim.connections[brother_account].store_metacontacts(
					self._metacontacts_tags[brother_account])
		# be sure jid has no other tag
		old_tag = self._get_metacontacts_tag(account, jid)
		while old_tag:
			self.remove_metacontact(account, jid)
			old_tag = self._get_metacontacts_tag(account, jid)
		if tag not in self._metacontacts_tags[account]:
			self._metacontacts_tags[account][tag] = [{'jid': jid, 'tag': tag}]
		else:
			if order:
				self._metacontacts_tags[account][tag].append({'jid': jid,
					'tag': tag, 'order': order})
			else:
				self._metacontacts_tags[account][tag].append({'jid': jid,
					'tag': tag})
		common.gajim.connections[account].store_metacontacts(
			self._metacontacts_tags[account])

	def remove_metacontact(self, account, jid):
		if not account in self._metacontacts_tags:
			return None
		
		found = None
		for tag in self._metacontacts_tags[account]:
			for data in self._metacontacts_tags[account][tag]:
				if data['jid'] == jid:
					found = data
					break
			if found:
				self._metacontacts_tags[account][tag].remove(found)
				common.gajim.connections[account].store_metacontacts(
					self._metacontacts_tags[account])
				break

	def has_brother(self, account, jid, accounts):
		tag = self._get_metacontacts_tag(account, jid)
		if not tag:
			return False
		meta_jids = self._get_metacontacts_jids(tag, accounts)
		return len(meta_jids) > 1 or len(meta_jids[account]) > 1

	def is_big_brother(self, account, jid, accounts):
		family = self.get_metacontacts_family(account, jid)
		if family:
			nearby_family = [data for data in family
				if account in accounts]
			bb_data = self._get_metacontacts_big_brother(nearby_family)
			if bb_data['jid'] == jid and bb_data['account'] == account:
				return True
		return False

	def _get_metacontacts_jids(self, tag, accounts):
		'''Returns all jid for the given tag in the form {acct: [jid1, jid2],.}'''
		answers = {}
		for account in self._metacontacts_tags:
			if tag in self._metacontacts_tags[account]:
				if account not in accounts:
					continue
				answers[account] = []
				for data in self._metacontacts_tags[account][tag]:
					answers[account].append(data['jid'])
		return answers

	def get_metacontacts_family(self, account, jid):
		'''return the family of the given jid, including jid in the form:
		[{'account': acct, 'jid': jid, 'order': order}, ]
		'order' is optional'''
		tag = self._get_metacontacts_tag(account, jid)
		return self._get_metacontacts_family_from_tag(account, tag)

	def _get_metacontacts_family_from_tag(self, account, tag):
		if not tag:
			return []
		answers = []
		for account in self._metacontacts_tags:
			if tag in self._metacontacts_tags[account]:
				for data in self._metacontacts_tags[account][tag]:
					data['account'] = account
					answers.append(data)
		return answers

	def _compare_metacontacts(self, data1, data2):
		'''compare 2 metacontacts.
		Data is {'jid': jid, 'account': account, 'order': order}
		order is optional'''
		jid1 = data1['jid']
		jid2 = data2['jid']
		account1 = data1['account']
		account2 = data2['account']
		contact1 = self._contacts.get_contact_with_highest_priority(account1, jid1)
		contact2 = self._contacts.get_contact_with_highest_priority(account2, jid2)
		show_list = ['not in roster', 'error', 'offline', 'invisible', 'dnd',
			'xa', 'away', 'chat', 'online', 'requested', 'message']
		# contact can be null when a jid listed in the metacontact data
		# is not in our roster
		if not contact1:
			if contact2:
				return -1 # prefer the known contact
			else:
				show1 = 0
				priority1 = 0
		else:
			show1 = show_list.index(contact1.show)
			priority1 = contact1.priority
		if not contact2:
			if contact1:
				return 1 # prefer the known contact
			else:
				show2 = 0
				priority2 = 0
		else:
			show2 = show_list.index(contact2.show)
			priority2 = contact2.priority
		# If only one is offline, it's always second
		if show1 > 2 and show2 < 3:
			return 1
		if show2 > 2 and show1 < 3:
			return -1
		if 'order' in data1 and 'order' in data2:
			if data1['order'] > data2['order']:
				return 1
			if data1['order'] < data2['order']:
				return -1
		if 'order' in data1:
			return 1
		if 'order' in data2:
			return -1
		transport1 = common.gajim.get_transport_name_from_jid(jid1)
		transport2 = common.gajim.get_transport_name_from_jid(jid2)
		if transport2 and not transport1:
			return 1
		if transport1 and not transport2:
			return -1
		if show1 > show2:
			return 1
		if show2 > show1:
			return -1
		if priority1 > priority2:
			return 1
		if priority2 > priority1:
			return -1
		server1 = common.gajim.get_server_from_jid(jid1)
		server2 = common.gajim.get_server_from_jid(jid2)
		myserver1 = common.gajim.config.get_per('accounts', account1, 'hostname')
		myserver2 = common.gajim.config.get_per('accounts', account2, 'hostname')
		if server1 == myserver1:
			if server2 != myserver2:
				return 1
		elif server2 == myserver2:
			return -1
		if jid1 > jid2:
			return 1
		if jid2 > jid1:
			return -1
		# If all is the same, compare accounts, they can't be the same
		if account1 > account2:
			return 1
		if account2 > account1:
			return -1
		return 0
	
	def get_nearby_family_and_big_brother(self, family, account):
		'''Return the nearby family and its Big Brother

		Nearby family is the part of the family that is grouped with the metacontact.
		A metacontact may be over different accounts. If accounts are not merged
		then the given family is split account wise.

		(nearby_family, big_brother_jid, big_brother_account)
		'''
		if common.gajim.config.get('mergeaccounts'):
			# group all together
			nearby_family = family
		else:
			# we want one nearby_family per account
			nearby_family = [data for data in family if account == data['account']]

		big_brother_data = self._get_metacontacts_big_brother(nearby_family)
		big_brother_jid = big_brother_data['jid']
		big_brother_account = big_brother_data['account']

		return (nearby_family, big_brother_jid, big_brother_account)

	def _get_metacontacts_big_brother(self, family):
		'''which of the family will be the big brother under wich all
		others will be ?'''
		family.sort(cmp=self._compare_metacontacts)
		return family[-1]
	
# vim: se ts=3: