1package eu.siacs.conversations.services;
2
3import java.text.ParseException;
4import java.text.SimpleDateFormat;
5import java.util.Collections;
6import java.util.Comparator;
7import java.util.Date;
8import java.util.Hashtable;
9import java.util.List;
10import java.util.Locale;
11import java.util.Random;
12
13import org.openintents.openpgp.util.OpenPgpApi;
14import org.openintents.openpgp.util.OpenPgpServiceConnection;
15
16import net.java.otr4j.OtrException;
17import net.java.otr4j.session.Session;
18import net.java.otr4j.session.SessionStatus;
19
20import eu.siacs.conversations.crypto.PgpEngine;
21import eu.siacs.conversations.crypto.PgpEngine.OpenPgpException;
22import eu.siacs.conversations.entities.Account;
23import eu.siacs.conversations.entities.Contact;
24import eu.siacs.conversations.entities.Conversation;
25import eu.siacs.conversations.entities.Message;
26import eu.siacs.conversations.entities.MucOptions;
27import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
28import eu.siacs.conversations.entities.Presences;
29import eu.siacs.conversations.persistance.DatabaseBackend;
30import eu.siacs.conversations.persistance.OnPhoneContactsMerged;
31import eu.siacs.conversations.ui.OnAccountListChangedListener;
32import eu.siacs.conversations.ui.OnConversationListChangedListener;
33import eu.siacs.conversations.ui.OnRosterFetchedListener;
34import eu.siacs.conversations.utils.ExceptionHelper;
35import eu.siacs.conversations.utils.MessageParser;
36import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
37import eu.siacs.conversations.utils.PhoneHelper;
38import eu.siacs.conversations.utils.UIHelper;
39import eu.siacs.conversations.xml.Element;
40import eu.siacs.conversations.xmpp.OnBindListener;
41import eu.siacs.conversations.xmpp.OnIqPacketReceived;
42import eu.siacs.conversations.xmpp.OnJinglePacketReceived;
43import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
44import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
45import eu.siacs.conversations.xmpp.OnStatusChanged;
46import eu.siacs.conversations.xmpp.OnTLSExceptionReceived;
47import eu.siacs.conversations.xmpp.XmppConnection;
48import eu.siacs.conversations.xmpp.stanzas.IqPacket;
49import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
50import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
51import eu.siacs.conversations.xmpp.stanzas.jingle.JinglePacket;
52import android.app.AlarmManager;
53import android.app.PendingIntent;
54import android.app.Service;
55import android.content.Context;
56import android.content.Intent;
57import android.content.SharedPreferences;
58import android.database.ContentObserver;
59import android.database.DatabaseUtils;
60import android.net.ConnectivityManager;
61import android.net.NetworkInfo;
62import android.os.Binder;
63import android.os.Bundle;
64import android.os.IBinder;
65import android.os.PowerManager;
66import android.os.PowerManager.WakeLock;
67import android.os.SystemClock;
68import android.preference.PreferenceManager;
69import android.provider.ContactsContract;
70import android.util.Log;
71
72public class XmppConnectionService extends Service {
73
74 protected static final String LOGTAG = "xmppService";
75 public DatabaseBackend databaseBackend;
76
77 public long startDate;
78
79 private static final int PING_MAX_INTERVAL = 300;
80 private static final int PING_MIN_INTERVAL = 10;
81 private static final int PING_TIMEOUT = 5;
82 private static final int CONNECT_TIMEOUT = 60;
83
84 private List<Account> accounts;
85 private List<Conversation> conversations = null;
86
87 public OnConversationListChangedListener convChangedListener = null;
88 private int convChangedListenerCount = 0;
89 private OnAccountListChangedListener accountChangedListener = null;
90 private OnTLSExceptionReceived tlsException = null;
91
92 public void setOnTLSExceptionReceivedListener(
93 OnTLSExceptionReceived listener) {
94 tlsException = listener;
95 }
96
97 private Random mRandom = new Random(System.currentTimeMillis());
98
99 private ContentObserver contactObserver = new ContentObserver(null) {
100 @Override
101 public void onChange(boolean selfChange) {
102 super.onChange(selfChange);
103 Log.d(LOGTAG, "contact list has changed");
104 mergePhoneContactsWithRoster(null);
105 }
106 };
107
108 private XmppConnectionService service = this;
109
110 private final IBinder mBinder = new XmppConnectionBinder();
111 private OnMessagePacketReceived messageListener = new OnMessagePacketReceived() {
112
113 @Override
114 public void onMessagePacketReceived(Account account,
115 MessagePacket packet) {
116 Message message = null;
117 boolean notify = true;
118 if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
119 String pgpBody = MessageParser.getPgpBody(packet);
120 if (pgpBody != null) {
121 message = MessageParser.parsePgpChat(pgpBody, packet,
122 account, service);
123 message.markUnread();
124 } else if (packet.hasChild("body")
125 && (packet.getBody().startsWith("?OTR"))) {
126 message = MessageParser.parseOtrChat(packet, account,
127 service);
128 if (message != null) {
129 message.markUnread();
130 }
131 } else if (packet.hasChild("body")) {
132 message = MessageParser.parsePlainTextChat(packet, account,
133 service);
134 message.markUnread();
135 } else if (packet.hasChild("received")
136 || (packet.hasChild("sent"))) {
137 message = MessageParser.parseCarbonMessage(packet, account,
138 service);
139 if (message != null) {
140 message.getConversation().markRead();
141 }
142 notify = false;
143 }
144
145 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
146 message = MessageParser
147 .parseGroupchat(packet, account, service);
148 if (message != null) {
149 if (message.getStatus() == Message.STATUS_RECIEVED) {
150 message.markUnread();
151 } else {
152 message.getConversation().markRead();
153 notify = false;
154 }
155 }
156 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
157 message = MessageParser.parseError(packet, account, service);
158 } else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
159 if (packet.hasChild("x")) {
160 Element x = packet.findChild("x");
161 if (x.hasChild("invite")) {
162 findOrCreateConversation(account, packet.getFrom(),
163 true);
164 if (convChangedListener != null) {
165 convChangedListener.onConversationListChanged();
166 }
167 Log.d(LOGTAG,
168 "invitation received to " + packet.getFrom());
169 }
170
171 } else {
172 // Log.d(LOGTAG, "unparsed message " + packet.toString());
173 }
174 }
175 if ((message == null) || (message.getBody() == null)) {
176 return;
177 }
178 if (packet.hasChild("delay")) {
179 try {
180 String stamp = packet.findChild("delay").getAttribute(
181 "stamp");
182 stamp = stamp.replace("Z", "+0000");
183 Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
184 .parse(stamp);
185 message.setTime(date.getTime());
186 } catch (ParseException e) {
187 Log.d(LOGTAG, "error trying to parse date" + e.getMessage());
188 }
189 }
190 Conversation conversation = message.getConversation();
191 conversation.getMessages().add(message);
192 if (packet.getType() != MessagePacket.TYPE_ERROR) {
193 databaseBackend.createMessage(message);
194 }
195 if (convChangedListener != null) {
196 convChangedListener.onConversationListChanged();
197 } else {
198 UIHelper.updateNotification(getApplicationContext(),
199 getConversations(), message.getConversation(), notify);
200 }
201 }
202 };
203 private OnStatusChanged statusListener = new OnStatusChanged() {
204
205 @Override
206 public void onStatusChanged(Account account) {
207 if (accountChangedListener != null) {
208 accountChangedListener.onAccountListChangedListener();
209 }
210 if (account.getStatus() == Account.STATUS_ONLINE) {
211 List<Conversation> conversations = getConversations();
212 for (int i = 0; i < conversations.size(); ++i) {
213 if (conversations.get(i).getAccount() == account) {
214 sendUnsendMessages(conversations.get(i));
215 }
216 }
217 scheduleWakeupCall(PING_MAX_INTERVAL, true);
218 } else if (account.getStatus() == Account.STATUS_OFFLINE) {
219 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
220 int timeToReconnect = mRandom.nextInt(50) + 10;
221 scheduleWakeupCall(timeToReconnect, false);
222 }
223
224 } else if (account.getStatus() == Account.STATUS_REGISTRATION_SUCCESSFULL) {
225 databaseBackend.updateAccount(account);
226 reconnectAccount(account, true);
227 } else {
228 UIHelper.showErrorNotification(getApplicationContext(), getAccounts());
229 }
230 }
231 };
232
233 private OnPresencePacketReceived presenceListener = new OnPresencePacketReceived() {
234
235 @Override
236 public void onPresencePacketReceived(Account account,
237 PresencePacket packet) {
238 if (packet.hasChild("x","http://jabber.org/protocol/muc#user")) {
239 Conversation muc = findMuc(
240 packet.getAttribute("from").split("/")[0], account);
241 if (muc != null) {
242 muc.getMucOptions().processPacket(packet);
243 } else {
244 Log.d(LOGTAG,account.getJid()+": could not find muc for received muc package "+packet.toString());
245 }
246 } else if (packet.hasChild("x","http://jabber.org/protocol/muc")) {
247 Conversation muc = findMuc(packet.getAttribute("from").split("/")[0], account);
248 if (muc != null) {
249 Log.d(LOGTAG,account.getJid()+": reading muc status packet "+packet.toString());
250 int error = muc.getMucOptions().getError();
251 muc.getMucOptions().processPacket(packet);
252 if ((muc.getMucOptions().getError() != error)
253 && (convChangedListener != null)) {
254 Log.d(LOGTAG, "muc error status changed");
255 convChangedListener.onConversationListChanged();
256 }
257 }
258 } else {
259 String[] fromParts = packet.getAttribute("from").split("/");
260 String type = packet.getAttribute("type");
261 if (fromParts[0].equals(account.getJid())) {
262 if (fromParts.length==2) {
263 if (type == null) {
264 account.updatePresence(fromParts[1],Presences.parseShow(packet.findChild("show")));
265 } else if (type.equals("unavailable")) {
266 account.removePresence(fromParts[1]);
267 }
268 }
269
270 } else {
271 Contact contact = findContact(account, fromParts[0]);
272 if (contact == null) {
273 // most likely roster not synced
274 return;
275 }
276 if (type == null) {
277 if (fromParts.length == 2) {
278 contact.updatePresence(fromParts[1], Presences.parseShow(packet.findChild("show")));
279 PgpEngine pgp = getPgpEngine();
280 if (pgp != null) {
281 Element x = packet.findChild("x","jabber:x:signed");
282 if (x != null) {
283 try {
284 Element status = packet.findChild("status");
285 String msg;
286 if (status!=null) {
287 msg = status.getContent();
288 } else {
289 msg = "";
290 }
291 contact.setPgpKeyId(pgp.fetchKeyId(msg, x
292 .getContent()));
293 } catch (OpenPgpException e) {
294 Log.d(LOGTAG, "faulty pgp. just ignore");
295 }
296 }
297 }
298 databaseBackend.updateContact(contact);
299 } else {
300 // Log.d(LOGTAG,"presence without resource "+packet.toString());
301 }
302 } else if (type.equals("unavailable")) {
303 if (fromParts.length != 2) {
304 // Log.d(LOGTAG,"received presence with no resource "+packet.toString());
305 } else {
306 contact.removePresence(fromParts[1]);
307 databaseBackend.updateContact(contact);
308 }
309 } else if (type.equals("subscribe")) {
310 if (contact
311 .getSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT)) {
312 sendPresenceUpdatesTo(contact);
313 contact.setSubscriptionOption(Contact.Subscription.FROM);
314 contact.resetSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
315 replaceContactInConversation(contact.getJid(),
316 contact);
317 databaseBackend.updateContact(contact);
318 if ((contact
319 .getSubscriptionOption(Contact.Subscription.ASKING))
320 && (!contact
321 .getSubscriptionOption(Contact.Subscription.TO))) {
322 requestPresenceUpdatesFrom(contact);
323 }
324 } else {
325 // TODO: ask user to handle it maybe
326 }
327 } else {
328 //Log.d(LOGTAG, packet.toString());
329 }
330 replaceContactInConversation(contact.getJid(), contact);
331 }
332 }
333 }
334 };
335
336 private OnIqPacketReceived unknownIqListener = new OnIqPacketReceived() {
337
338 @Override
339 public void onIqPacketReceived(Account account, IqPacket packet) {
340 if (packet.hasChild("query")) {
341 Element query = packet.findChild("query");
342 String xmlns = query.getAttribute("xmlns");
343 if ((xmlns != null) && (xmlns.equals("jabber:iq:roster"))) {
344 processRosterItems(account, query);
345 mergePhoneContactsWithRoster(null);
346 }
347 }
348 }
349 };
350
351 private OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
352
353 @Override
354 public void onJinglePacketReceived(Account account, JinglePacket packet) {
355 Log.d(LOGTAG,account.getJid()+": jingle packet received"+packet.toString());
356 }
357 };
358
359 private OpenPgpServiceConnection pgpServiceConnection;
360 private PgpEngine mPgpEngine = null;
361 private Intent pingIntent;
362 private PendingIntent pendingPingIntent = null;
363 private WakeLock wakeLock;
364 private PowerManager pm;
365
366 public PgpEngine getPgpEngine() {
367 if (pgpServiceConnection.isBound()) {
368 if (this.mPgpEngine == null) {
369 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
370 getApplicationContext(),
371 pgpServiceConnection.getService()));
372 }
373 return mPgpEngine;
374 } else {
375 return null;
376 }
377
378 }
379
380 protected Conversation findMuc(String name, Account account) {
381 for (Conversation conversation : this.conversations) {
382 if (conversation.getContactJid().split("/")[0].equals(name)
383 && (conversation.getAccount() == account)) {
384 return conversation;
385 }
386 }
387 return null;
388 }
389
390 private void processRosterItems(Account account, Element elements) {
391 String version = elements.getAttribute("ver");
392 if (version != null) {
393 account.setRosterVersion(version);
394 databaseBackend.updateAccount(account);
395 }
396 for (Element item : elements.getChildren()) {
397 if (item.getName().equals("item")) {
398 String jid = item.getAttribute("jid");
399 String subscription = item.getAttribute("subscription");
400 Contact contact = databaseBackend.findContact(account, jid);
401 if (contact == null) {
402 if (!subscription.equals("remove")) {
403 String name = item.getAttribute("name");
404 if (name == null) {
405 name = jid.split("@")[0];
406 }
407 contact = new Contact(account, name, jid, null);
408 contact.parseSubscriptionFromElement(item);
409 databaseBackend.createContact(contact);
410 }
411 } else {
412 if (subscription.equals("remove")) {
413 databaseBackend.deleteContact(contact);
414 replaceContactInConversation(contact.getJid(), null);
415 } else {
416 contact.parseSubscriptionFromElement(item);
417 databaseBackend.updateContact(contact);
418 replaceContactInConversation(contact.getJid(), contact);
419 }
420 }
421 }
422 }
423 }
424
425 private void replaceContactInConversation(String jid, Contact contact) {
426 List<Conversation> conversations = getConversations();
427 for (int i = 0; i < conversations.size(); ++i) {
428 if ((conversations.get(i).getContactJid().equals(jid))) {
429 conversations.get(i).setContact(contact);
430 break;
431 }
432 }
433 }
434
435 public class XmppConnectionBinder extends Binder {
436 public XmppConnectionService getService() {
437 return XmppConnectionService.this;
438 }
439 }
440
441 @Override
442 public int onStartCommand(Intent intent, int flags, int startId) {
443 this.wakeLock.acquire();
444 // Log.d(LOGTAG,"calling start service. caller was:"+intent.getAction());
445 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
446 .getSystemService(Context.CONNECTIVITY_SERVICE);
447 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
448 boolean isConnected = activeNetwork != null
449 && activeNetwork.isConnected();
450
451 for (Account account : accounts) {
452 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
453 if (!isConnected) {
454 account.setStatus(Account.STATUS_NO_INTERNET);
455 if (statusListener != null) {
456 statusListener.onStatusChanged(account);
457 }
458 } else {
459 if (account.getStatus() == Account.STATUS_NO_INTERNET) {
460 account.setStatus(Account.STATUS_OFFLINE);
461 if (statusListener != null) {
462 statusListener.onStatusChanged(account);
463 }
464 }
465
466 // TODO 3 remaining cases
467 if (account.getStatus() == Account.STATUS_ONLINE) {
468 long lastReceived = account.getXmppConnection().lastPaketReceived;
469 long lastSent = account.getXmppConnection().lastPingSent;
470 if (lastSent - lastReceived >= PING_TIMEOUT * 1000) {
471 Log.d(LOGTAG, account.getJid() + ": ping timeout");
472 this.reconnectAccount(account, true);
473 } else if (SystemClock.elapsedRealtime() - lastReceived >= PING_MIN_INTERVAL * 1000) {
474 account.getXmppConnection().sendPing();
475 account.getXmppConnection().lastPingSent = SystemClock
476 .elapsedRealtime();
477 this.scheduleWakeupCall(2, false);
478 }
479 } else if (account.getStatus() == Account.STATUS_OFFLINE) {
480 if (account.getXmppConnection() == null) {
481 account.setXmppConnection(this
482 .createConnection(account));
483 }
484 account.getXmppConnection().lastPingSent = SystemClock
485 .elapsedRealtime();
486 new Thread(account.getXmppConnection()).start();
487 } else if ((account.getStatus() == Account.STATUS_CONNECTING)
488 && ((SystemClock.elapsedRealtime() - account
489 .getXmppConnection().lastConnect) / 1000 >= CONNECT_TIMEOUT)) {
490 Log.d(LOGTAG, account.getJid()
491 + ": time out during connect reconnecting");
492 reconnectAccount(account, true);
493 } else {
494 Log.d(LOGTAG,
495 "seconds since last connect:"
496 + ((SystemClock.elapsedRealtime() - account
497 .getXmppConnection().lastConnect) / 1000));
498 Log.d(LOGTAG,
499 account.getJid() + ": status="
500 + account.getStatus());
501 // TODO notify user of ssl cert problem or auth problem
502 // or what ever
503 }
504 // in any case. reschedule wakup call
505 this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
506 }
507 if (accountChangedListener != null) {
508 accountChangedListener.onAccountListChangedListener();
509 }
510 }
511 }
512 if (wakeLock.isHeld()) {
513 wakeLock.release();
514 }
515 return START_STICKY;
516 }
517
518 @Override
519 public void onCreate() {
520 ExceptionHelper.init(getApplicationContext());
521 databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
522 this.accounts = databaseBackend.getAccounts();
523
524 this.getConversations();
525
526 getContentResolver().registerContentObserver(
527 ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
528 this.pgpServiceConnection = new OpenPgpServiceConnection(
529 getApplicationContext(), "org.sufficientlysecure.keychain");
530 this.pgpServiceConnection.bindToService();
531
532 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
533 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
534 "XmppConnectionService");
535 }
536
537 @Override
538 public void onDestroy() {
539 super.onDestroy();
540 for (Account account : accounts) {
541 if (account.getXmppConnection() != null) {
542 disconnect(account, true);
543 }
544 }
545 }
546
547 protected void scheduleWakeupCall(int seconds, boolean ping) {
548 long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
549 Context context = getApplicationContext();
550 AlarmManager alarmManager = (AlarmManager) context
551 .getSystemService(Context.ALARM_SERVICE);
552
553 if (ping) {
554 if (this.pingIntent == null) {
555 this.pingIntent = new Intent(context, EventReceiver.class);
556 this.pingIntent.setAction("ping");
557 this.pingIntent.putExtra("time", timeToWake);
558 this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
559 this.pingIntent, 0);
560 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
561 timeToWake, pendingPingIntent);
562 // Log.d(LOGTAG,"schedule ping in "+seconds+" seconds");
563 } else {
564 long scheduledTime = this.pingIntent.getLongExtra("time", 0);
565 if (scheduledTime < SystemClock.elapsedRealtime()
566 || (scheduledTime > timeToWake)) {
567 this.pingIntent.putExtra("time", timeToWake);
568 alarmManager.cancel(this.pendingPingIntent);
569 this.pendingPingIntent = PendingIntent.getBroadcast(
570 context, 0, this.pingIntent, 0);
571 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
572 timeToWake, pendingPingIntent);
573 // Log.d(LOGTAG,"reschedule old ping to ping in "+seconds+" seconds");
574 }
575 }
576 } else {
577 Intent intent = new Intent(context, EventReceiver.class);
578 intent.setAction("ping_check");
579 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
580 intent, 0);
581 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
582 alarmIntent);
583 }
584
585 }
586
587 public XmppConnection createConnection(Account account) {
588 SharedPreferences sharedPref = PreferenceManager
589 .getDefaultSharedPreferences(getApplicationContext());
590 account.setResource(sharedPref.getString("resource", "mobile").toLowerCase(Locale.getDefault()));
591 XmppConnection connection = new XmppConnection(account, this.pm);
592 connection.setOnMessagePacketReceivedListener(this.messageListener);
593 connection.setOnStatusChangedListener(this.statusListener);
594 connection.setOnPresencePacketReceivedListener(this.presenceListener);
595 connection
596 .setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
597 connection.setOnJinglePacketReceivedListener(this.jingleListener);
598 connection
599 .setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
600
601 @Override
602 public void onTLSExceptionReceived(String fingerprint,
603 Account account) {
604 Log.d(LOGTAG, "tls exception arrived in service");
605 if (tlsException != null) {
606 tlsException.onTLSExceptionReceived(fingerprint,
607 account);
608 }
609 }
610 });
611 connection.setOnBindListener(new OnBindListener() {
612
613 @Override
614 public void onBind(Account account) {
615 databaseBackend.clearPresences(account);
616 account.clearPresences(); // self presences
617 if (account.getXmppConnection().hasFeatureRosterManagment()) {
618 updateRoster(account, null);
619 }
620 connectMultiModeConversations(account);
621 if (convChangedListener != null) {
622 convChangedListener.onConversationListChanged();
623 }
624 }
625 });
626 return connection;
627 }
628
629 synchronized public void sendMessage(Message message, String presence) {
630 Account account = message.getConversation().getAccount();
631 Conversation conv = message.getConversation();
632 boolean saveInDb = false;
633 boolean addToConversation = false;
634 if (account.getStatus() == Account.STATUS_ONLINE) {
635 MessagePacket packet;
636 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
637 if (!conv.hasValidOtrSession()) {
638 // starting otr session. messages will be send later
639 conv.startOtrSession(getApplicationContext(), presence,true);
640 } else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
641 // otr session aleary exists, creating message packet
642 // accordingly
643 packet = prepareMessagePacket(account, message,
644 conv.getOtrSession());
645 account.getXmppConnection().sendMessagePacket(packet);
646 message.setStatus(Message.STATUS_SEND);
647 }
648 saveInDb = true;
649 addToConversation = true;
650 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
651 message.getConversation().endOtrIfNeeded();
652 long keyId = message.getConversation().getContact()
653 .getPgpKeyId();
654 packet = new MessagePacket();
655 packet.setType(MessagePacket.TYPE_CHAT);
656 packet.setFrom(message.getConversation().getAccount()
657 .getFullJid());
658 packet.setTo(message.getCounterpart());
659 packet.setBody("This is an XEP-0027 encryted message");
660 packet.addChild("x","jabber:x:encrypted").setContent(this.getPgpEngine().encrypt(keyId,
661 message.getBody()));
662 account.getXmppConnection().sendMessagePacket(packet);
663 message.setStatus(Message.STATUS_SEND);
664 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
665 saveInDb = true;
666 addToConversation = true;
667 } else {
668 message.getConversation().endOtrIfNeeded();
669 // don't encrypt
670 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
671 message.setStatus(Message.STATUS_SEND);
672 saveInDb = true;
673 addToConversation = true;
674 }
675
676 packet = prepareMessagePacket(account, message, null);
677 account.getXmppConnection().sendMessagePacket(packet);
678 }
679 } else {
680 // account is offline
681 saveInDb = true;
682 addToConversation = true;
683
684 }
685 if (saveInDb) {
686 databaseBackend.createMessage(message);
687 }
688 if (addToConversation) {
689 conv.getMessages().add(message);
690 if (convChangedListener != null) {
691 convChangedListener.onConversationListChanged();
692 }
693 }
694
695 }
696
697 private void sendUnsendMessages(Conversation conversation) {
698 for (int i = 0; i < conversation.getMessages().size(); ++i) {
699 if ((conversation.getMessages().get(i).getStatus() == Message.STATUS_UNSEND)&&(conversation.getMessages().get(i).getEncryption() == Message.ENCRYPTION_NONE)) {
700 Message message = conversation.getMessages().get(i);
701 MessagePacket packet = prepareMessagePacket(
702 conversation.getAccount(), message, null);
703 conversation.getAccount().getXmppConnection()
704 .sendMessagePacket(packet);
705 message.setStatus(Message.STATUS_SEND);
706 if (conversation.getMode() == Conversation.MODE_SINGLE) {
707 databaseBackend.updateMessage(message);
708 } else {
709 databaseBackend.deleteMessage(message);
710 conversation.getMessages().remove(i);
711 i--;
712 }
713 }
714 }
715 }
716
717 public MessagePacket prepareMessagePacket(Account account, Message message,
718 Session otrSession) {
719 MessagePacket packet = new MessagePacket();
720 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
721 packet.setType(MessagePacket.TYPE_CHAT);
722 if (otrSession != null) {
723 try {
724 packet.setBody(otrSession.transformSending(message
725 .getBody()));
726 } catch (OtrException e) {
727 Log.d(LOGTAG,
728 account.getJid()
729 + ": could not encrypt message to "
730 + message.getCounterpart());
731 }
732 packet.addChild("private","urn:xmpp:carbons:2");
733 packet.addChild("no-copy","urn:xmpp:hints");
734 packet.setTo(otrSession.getSessionID().getAccountID() + "/"
735 + otrSession.getSessionID().getUserID());
736 packet.setFrom(account.getFullJid());
737 } else {
738 packet.setBody(message.getBody());
739 packet.setTo(message.getCounterpart());
740 packet.setFrom(account.getJid());
741 }
742 } else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
743 packet.setType(MessagePacket.TYPE_GROUPCHAT);
744 packet.setBody(message.getBody());
745 packet.setTo(message.getCounterpart().split("/")[0]);
746 packet.setFrom(account.getJid());
747 }
748 return packet;
749 }
750
751 private void getRoster(Account account,
752 final OnRosterFetchedListener listener) {
753 List<Contact> contacts = databaseBackend.getContactsByAccount(account);
754 for (int i = 0; i < contacts.size(); ++i) {
755 contacts.get(i).setAccount(account);
756 }
757 if (listener != null) {
758 listener.onRosterFetched(contacts);
759 }
760 }
761
762 public List<Contact> getRoster(Account account) {
763 List<Contact> contacts = databaseBackend.getContactsByAccount(account);
764 for (int i = 0; i < contacts.size(); ++i) {
765 contacts.get(i).setAccount(account);
766 }
767 return contacts;
768 }
769
770 public void updateRoster(final Account account,
771 final OnRosterFetchedListener listener) {
772 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
773 if (!"".equals(account.getRosterVersion())) {
774 Log.d(LOGTAG, account.getJid() + ": fetching roster version "
775 + account.getRosterVersion());
776 } else {
777 Log.d(LOGTAG, account.getJid() + ": fetching roster");
778 }
779 iqPacket.query("jabber:iq:roster").setAttribute("ver", account.getRosterVersion());
780 account.getXmppConnection().sendIqPacket(iqPacket,
781 new OnIqPacketReceived() {
782
783 @Override
784 public void onIqPacketReceived(final Account account,
785 IqPacket packet) {
786 Element roster = packet.findChild("query");
787 if (roster != null) {
788 Log.d(LOGTAG, account.getJid()
789 + ": processing roster");
790 processRosterItems(account, roster);
791 StringBuilder mWhere = new StringBuilder();
792 mWhere.append("jid NOT IN(");
793 List<Element> items = roster.getChildren();
794 for (int i = 0; i < items.size(); ++i) {
795 mWhere.append(DatabaseUtils
796 .sqlEscapeString(items.get(i)
797 .getAttribute("jid")));
798 if (i != items.size() - 1) {
799 mWhere.append(",");
800 }
801 }
802 mWhere.append(") and accountUuid = \"");
803 mWhere.append(account.getUuid());
804 mWhere.append("\"");
805 List<Contact> contactsToDelete = databaseBackend
806 .getContacts(mWhere.toString());
807 for (Contact contact : contactsToDelete) {
808 databaseBackend.deleteContact(contact);
809 replaceContactInConversation(contact.getJid(),
810 null);
811 }
812
813 } else {
814 Log.d(LOGTAG, account.getJid()
815 + ": empty roster returend");
816 }
817 mergePhoneContactsWithRoster(new OnPhoneContactsMerged() {
818
819 @Override
820 public void phoneContactsMerged() {
821 if (listener != null) {
822 getRoster(account, listener);
823 }
824 }
825 });
826 }
827 });
828 }
829
830 public void mergePhoneContactsWithRoster(
831 final OnPhoneContactsMerged listener) {
832 PhoneHelper.loadPhoneContacts(getApplicationContext(),
833 new OnPhoneContactsLoadedListener() {
834 @Override
835 public void onPhoneContactsLoaded(
836 Hashtable<String, Bundle> phoneContacts) {
837 List<Contact> contacts = databaseBackend
838 .getContactsByAccount(null);
839 for (int i = 0; i < contacts.size(); ++i) {
840 Contact contact = contacts.get(i);
841 if (phoneContacts.containsKey(contact.getJid())) {
842 Bundle phoneContact = phoneContacts.get(contact
843 .getJid());
844 String systemAccount = phoneContact
845 .getInt("phoneid")
846 + "#"
847 + phoneContact.getString("lookup");
848 contact.setSystemAccount(systemAccount);
849 contact.setPhotoUri(phoneContact
850 .getString("photouri"));
851 contact.setDisplayName(phoneContact
852 .getString("displayname"));
853 databaseBackend.updateContact(contact);
854 replaceContactInConversation(contact.getJid(),
855 contact);
856 } else {
857 if ((contact.getSystemAccount() != null)
858 || (contact.getProfilePhoto() != null)) {
859 contact.setSystemAccount(null);
860 contact.setPhotoUri(null);
861 databaseBackend.updateContact(contact);
862 replaceContactInConversation(
863 contact.getJid(), contact);
864 }
865 }
866 }
867 if (listener != null) {
868 listener.phoneContactsMerged();
869 }
870 }
871 });
872 }
873
874 public List<Conversation> getConversations() {
875 if (this.conversations == null) {
876 Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
877 for (Account account : this.accounts) {
878 accountLookupTable.put(account.getUuid(), account);
879 }
880 this.conversations = databaseBackend
881 .getConversations(Conversation.STATUS_AVAILABLE);
882 for (Conversation conv : this.conversations) {
883 Account account = accountLookupTable.get(conv.getAccountUuid());
884 conv.setAccount(account);
885 conv.setContact(findContact(account, conv.getContactJid()));
886 conv.setMessages(databaseBackend.getMessages(conv, 50));
887 }
888 }
889 Collections.sort(this.conversations, new Comparator<Conversation>() {
890 @Override
891 public int compare(Conversation lhs, Conversation rhs) {
892 return (int) (rhs.getLatestMessage().getTimeSent() - lhs
893 .getLatestMessage().getTimeSent());
894 }
895 });
896 return this.conversations;
897 }
898
899 public List<Account> getAccounts() {
900 return this.accounts;
901 }
902
903 public Contact findContact(Account account, String jid) {
904 Contact contact = databaseBackend.findContact(account, jid);
905 if (contact != null) {
906 contact.setAccount(account);
907 }
908 return contact;
909 }
910
911 public Conversation findOrCreateConversation(Account account, String jid,
912 boolean muc) {
913 for (Conversation conv : this.getConversations()) {
914 if ((conv.getAccount().equals(account))
915 && (conv.getContactJid().split("/")[0].equals(jid))) {
916 return conv;
917 }
918 }
919 Conversation conversation = databaseBackend.findConversation(account,
920 jid);
921 if (conversation != null) {
922 conversation.setStatus(Conversation.STATUS_AVAILABLE);
923 conversation.setAccount(account);
924 if (muc) {
925 conversation.setMode(Conversation.MODE_MULTI);
926 } else {
927 conversation.setMode(Conversation.MODE_SINGLE);
928 }
929 conversation.setMessages(databaseBackend.getMessages(conversation,
930 50));
931 this.databaseBackend.updateConversation(conversation);
932 conversation.setContact(findContact(account,
933 conversation.getContactJid()));
934 } else {
935 String conversationName;
936 Contact contact = findContact(account, jid);
937 if (contact != null) {
938 conversationName = contact.getDisplayName();
939 } else {
940 conversationName = jid.split("@")[0];
941 }
942 if (muc) {
943 conversation = new Conversation(conversationName, account, jid,
944 Conversation.MODE_MULTI);
945 } else {
946 conversation = new Conversation(conversationName, account, jid,
947 Conversation.MODE_SINGLE);
948 }
949 conversation.setContact(contact);
950 this.databaseBackend.createConversation(conversation);
951 }
952 this.conversations.add(conversation);
953 if ((account.getStatus() == Account.STATUS_ONLINE)&&(conversation.getMode() == Conversation.MODE_MULTI)) {
954 joinMuc(conversation);
955 }
956 if (this.convChangedListener != null) {
957 this.convChangedListener.onConversationListChanged();
958 }
959 return conversation;
960 }
961
962 public void archiveConversation(Conversation conversation) {
963 if (conversation.getMode() == Conversation.MODE_MULTI) {
964 leaveMuc(conversation);
965 } else {
966 conversation.endOtrIfNeeded();
967 }
968 this.databaseBackend.updateConversation(conversation);
969 this.conversations.remove(conversation);
970 if (this.convChangedListener != null) {
971 this.convChangedListener.onConversationListChanged();
972 }
973 }
974
975 public int getConversationCount() {
976 return this.databaseBackend.getConversationCount();
977 }
978
979 public void createAccount(Account account) {
980 databaseBackend.createAccount(account);
981 this.accounts.add(account);
982 this.reconnectAccount(account, false);
983 if (accountChangedListener != null)
984 accountChangedListener.onAccountListChangedListener();
985 }
986
987 public void deleteContact(Contact contact) {
988 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
989 Element query = iq.query("jabber:iq:roster");
990 query.addChild("item").setAttribute("jid", contact.getJid()).setAttribute("subscription", "remove");
991 contact.getAccount().getXmppConnection().sendIqPacket(iq, null);
992 replaceContactInConversation(contact.getJid(), null);
993 databaseBackend.deleteContact(contact);
994 }
995
996 public void updateAccount(Account account) {
997 databaseBackend.updateAccount(account);
998 reconnectAccount(account, false);
999 if (accountChangedListener != null)
1000 accountChangedListener.onAccountListChangedListener();
1001 }
1002
1003 public void deleteAccount(Account account) {
1004 if (account.getXmppConnection() != null) {
1005 this.disconnect(account, true);
1006 }
1007 databaseBackend.deleteAccount(account);
1008 this.accounts.remove(account);
1009 if (accountChangedListener != null)
1010 accountChangedListener.onAccountListChangedListener();
1011 }
1012
1013 public void setOnConversationListChangedListener(
1014 OnConversationListChangedListener listener) {
1015 this.convChangedListener = listener;
1016 this.convChangedListenerCount++;
1017 Log.d(LOGTAG,"registered on conv changed in backend ("+convChangedListenerCount+")");
1018 }
1019
1020 public void removeOnConversationListChangedListener() {
1021 this.convChangedListenerCount--;
1022 Log.d(LOGTAG,"someone on conv changed listener removed listener ("+convChangedListenerCount+")");
1023 if (this.convChangedListenerCount==0) {
1024 this.convChangedListener = null;
1025 }
1026 }
1027
1028 public void setOnAccountListChangedListener(
1029 OnAccountListChangedListener listener) {
1030 this.accountChangedListener = listener;
1031 }
1032
1033 public void removeOnAccountListChangedListener() {
1034 this.accountChangedListener = null;
1035 }
1036
1037 public void connectMultiModeConversations(Account account) {
1038 List<Conversation> conversations = getConversations();
1039 for (int i = 0; i < conversations.size(); i++) {
1040 Conversation conversation = conversations.get(i);
1041 if ((conversation.getMode() == Conversation.MODE_MULTI)
1042 && (conversation.getAccount() == account)) {
1043 joinMuc(conversation);
1044 }
1045 }
1046 }
1047
1048 public void joinMuc(Conversation conversation) {
1049 String[] mucParts = conversation.getContactJid().split("/");
1050 String muc;
1051 String nick;
1052 if (mucParts.length == 2) {
1053 muc = mucParts[0];
1054 nick = mucParts[1];
1055 } else {
1056 muc = mucParts[0];
1057 nick = conversation.getAccount().getUsername();
1058 }
1059 PresencePacket packet = new PresencePacket();
1060 packet.setAttribute("to", muc + "/" + nick);
1061 Element x = new Element("x");
1062 x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
1063 if (conversation.getMessages().size() != 0) {
1064 long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1065 long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1066 x.addChild("history").setAttribute("seconds", diff + "");
1067 }
1068 packet.addChild(x);
1069 Log.d(LOGTAG,conversation.getAccount().getJid()+": joining muc "+packet.toString());
1070 conversation.getAccount().getXmppConnection()
1071 .sendPresencePacket(packet);
1072 }
1073
1074 private OnRenameListener renameListener = null;
1075
1076 public void setOnRenameListener(OnRenameListener listener) {
1077 this.renameListener = listener;
1078 }
1079
1080 public void renameInMuc(final Conversation conversation, final String nick) {
1081 final MucOptions options = conversation.getMucOptions();
1082 if (options.online()) {
1083 options.setOnRenameListener(new OnRenameListener() {
1084
1085 @Override
1086 public void onRename(boolean success) {
1087 if (renameListener != null) {
1088 renameListener.onRename(success);
1089 }
1090 if (success) {
1091 databaseBackend.updateConversation(conversation);
1092 }
1093 }
1094 });
1095 options.flagAboutToRename();
1096 PresencePacket packet = new PresencePacket();
1097 packet.setAttribute("to",
1098 conversation.getContactJid().split("/")[0] + "/" + nick);
1099 packet.setAttribute("from", conversation.getAccount().getFullJid());
1100
1101 conversation.getAccount().getXmppConnection()
1102 .sendPresencePacket(packet, null);
1103 } else {
1104 String jid = conversation.getContactJid().split("/")[0] + "/"
1105 + nick;
1106 conversation.setContactJid(jid);
1107 databaseBackend.updateConversation(conversation);
1108 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1109 joinMuc(conversation);
1110 }
1111 }
1112 }
1113
1114 public void leaveMuc(Conversation conversation) {
1115 PresencePacket packet = new PresencePacket();
1116 packet.setAttribute("to", conversation.getContactJid().split("/")[0] + "/" + conversation.getMucOptions().getNick());
1117 packet.setAttribute("from", conversation.getAccount().getFullJid());
1118 packet.setAttribute("type", "unavailable");
1119 Log.d(LOGTAG,"send leaving muc " + packet);
1120 conversation.getAccount().getXmppConnection()
1121 .sendPresencePacket(packet);
1122 conversation.getMucOptions().setOffline();
1123 }
1124
1125 public void disconnect(Account account, boolean force) {
1126 if ((account.getStatus() == Account.STATUS_ONLINE)
1127 || (account.getStatus() == Account.STATUS_DISABLED)) {
1128 if (!force) {
1129 List<Conversation> conversations = getConversations();
1130 for (int i = 0; i < conversations.size(); i++) {
1131 Conversation conversation = conversations.get(i);
1132 if (conversation.getAccount() == account) {
1133 if (conversation.getMode() == Conversation.MODE_MULTI) {
1134 leaveMuc(conversation);
1135 } else {
1136 conversation.endOtrIfNeeded();
1137 }
1138 }
1139 }
1140 }
1141 account.getXmppConnection().disconnect(force);
1142 }
1143 }
1144
1145 @Override
1146 public IBinder onBind(Intent intent) {
1147 return mBinder;
1148 }
1149
1150 public void updateContact(Contact contact) {
1151 databaseBackend.updateContact(contact);
1152 replaceContactInConversation(contact.getJid(), contact);
1153 }
1154
1155 public void updateMessage(Message message) {
1156 databaseBackend.updateMessage(message);
1157 }
1158
1159 public void createContact(Contact contact) {
1160 SharedPreferences sharedPref = PreferenceManager
1161 .getDefaultSharedPreferences(getApplicationContext());
1162 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1163 if (autoGrant) {
1164 contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1165 contact.setSubscriptionOption(Contact.Subscription.ASKING);
1166 }
1167 databaseBackend.createContact(contact);
1168 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1169 Element query = new Element("query");
1170 query.setAttribute("xmlns", "jabber:iq:roster");
1171 Element item = new Element("item");
1172 item.setAttribute("jid", contact.getJid());
1173 item.setAttribute("name", contact.getJid());
1174 query.addChild(item);
1175 iq.addChild(query);
1176 Account account = contact.getAccount();
1177 account.getXmppConnection().sendIqPacket(iq, null);
1178 if (autoGrant) {
1179 requestPresenceUpdatesFrom(contact);
1180 }
1181 replaceContactInConversation(contact.getJid(), contact);
1182 }
1183
1184 public void requestPresenceUpdatesFrom(Contact contact) {
1185 // Requesting a Subscription type=subscribe
1186 PresencePacket packet = new PresencePacket();
1187 packet.setAttribute("type", "subscribe");
1188 packet.setAttribute("to", contact.getJid());
1189 packet.setAttribute("from", contact.getAccount().getJid());
1190 Log.d(LOGTAG, packet.toString());
1191 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1192 }
1193
1194 public void stopPresenceUpdatesFrom(Contact contact) {
1195 // Unsubscribing type='unsubscribe'
1196 PresencePacket packet = new PresencePacket();
1197 packet.setAttribute("type", "unsubscribe");
1198 packet.setAttribute("to", contact.getJid());
1199 packet.setAttribute("from", contact.getAccount().getJid());
1200 Log.d(LOGTAG, packet.toString());
1201 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1202 }
1203
1204 public void stopPresenceUpdatesTo(Contact contact) {
1205 // Canceling a Subscription type=unsubscribed
1206 PresencePacket packet = new PresencePacket();
1207 packet.setAttribute("type", "unsubscribed");
1208 packet.setAttribute("to", contact.getJid());
1209 packet.setAttribute("from", contact.getAccount().getJid());
1210 Log.d(LOGTAG, packet.toString());
1211 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1212 }
1213
1214 public void sendPresenceUpdatesTo(Contact contact) {
1215 // type='subscribed'
1216 PresencePacket packet = new PresencePacket();
1217 packet.setAttribute("type", "subscribed");
1218 packet.setAttribute("to", contact.getJid());
1219 packet.setAttribute("from", contact.getAccount().getJid());
1220 Log.d(LOGTAG, packet.toString());
1221 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1222 }
1223
1224 public void sendPgpPresence(Account account, String signature) {
1225 PresencePacket packet = new PresencePacket();
1226 packet.setAttribute("from", account.getFullJid());
1227 Element status = new Element("status");
1228 status.setContent("online");
1229 packet.addChild(status);
1230 Element x = new Element("x");
1231 x.setAttribute("xmlns", "jabber:x:signed");
1232 x.setContent(signature);
1233 packet.addChild(x);
1234 account.getXmppConnection().sendPresencePacket(packet);
1235 }
1236
1237 public void generatePgpAnnouncement(Account account)
1238 throws PgpEngine.UserInputRequiredException {
1239 if (account.getStatus() == Account.STATUS_ONLINE) {
1240 String signature = getPgpEngine().generateSignature("online");
1241 account.setKey("pgp_signature", signature);
1242 databaseBackend.updateAccount(account);
1243 sendPgpPresence(account, signature);
1244 }
1245 }
1246
1247 public void updateConversation(Conversation conversation) {
1248 this.databaseBackend.updateConversation(conversation);
1249 }
1250
1251 public Contact findContact(String uuid) {
1252 Contact contact = this.databaseBackend.getContact(uuid);
1253 for (Account account : getAccounts()) {
1254 if (contact.getAccountUuid().equals(account.getUuid())) {
1255 contact.setAccount(account);
1256 }
1257 }
1258 return contact;
1259 }
1260
1261 public void removeOnTLSExceptionReceivedListener() {
1262 this.tlsException = null;
1263 }
1264
1265 // TODO dont let thread sleep but schedule wake up
1266 public void reconnectAccount(final Account account, final boolean force) {
1267 new Thread(new Runnable() {
1268
1269 @Override
1270 public void run() {
1271 if (account.getXmppConnection() != null) {
1272 disconnect(account, force);
1273 }
1274 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1275 if (account.getXmppConnection() == null) {
1276 account.setXmppConnection(createConnection(account));
1277 }
1278 Thread thread = new Thread(account.getXmppConnection());
1279 thread.start();
1280 scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1281 }
1282 }
1283 }).start();
1284 }
1285
1286 public void updateConversationInGui() {
1287 if (convChangedListener != null) {
1288 convChangedListener.onConversationListChanged();
1289 }
1290 }
1291
1292 public void sendConversationSubject(Conversation conversation,
1293 String subject) {
1294 MessagePacket packet = new MessagePacket();
1295 packet.setType(MessagePacket.TYPE_GROUPCHAT);
1296 packet.setTo(conversation.getContactJid().split("/")[0]);
1297 Element subjectChild = new Element("subject");
1298 subjectChild.setContent(subject);
1299 packet.addChild(subjectChild);
1300 packet.setFrom(conversation.getAccount().getJid());
1301 Account account = conversation.getAccount();
1302 if (account.getStatus() == Account.STATUS_ONLINE) {
1303 account.getXmppConnection().sendMessagePacket(packet);
1304 }
1305 }
1306
1307 public void inviteToConference(Conversation conversation,
1308 List<Contact> contacts) {
1309 for (Contact contact : contacts) {
1310 MessagePacket packet = new MessagePacket();
1311 packet.setTo(conversation.getContactJid().split("/")[0]);
1312 packet.setFrom(conversation.getAccount().getFullJid());
1313 Element x = new Element("x");
1314 x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1315 Element invite = new Element("invite");
1316 invite.setAttribute("to", contact.getJid());
1317 x.addChild(invite);
1318 packet.addChild(x);
1319 Log.d(LOGTAG, packet.toString());
1320 conversation.getAccount().getXmppConnection()
1321 .sendMessagePacket(packet);
1322 }
1323
1324 }
1325}