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 this.statusListener.onStatusChanged(account);
998 databaseBackend.updateAccount(account);
999 reconnectAccount(account, false);
1000 if (accountChangedListener != null)
1001 accountChangedListener.onAccountListChangedListener();
1002 }
1003
1004 public void deleteAccount(Account account) {
1005 if (account.getXmppConnection() != null) {
1006 this.disconnect(account, true);
1007 }
1008 databaseBackend.deleteAccount(account);
1009 this.accounts.remove(account);
1010 if (accountChangedListener != null)
1011 accountChangedListener.onAccountListChangedListener();
1012 }
1013
1014 public void setOnConversationListChangedListener(
1015 OnConversationListChangedListener listener) {
1016 this.convChangedListener = listener;
1017 this.convChangedListenerCount++;
1018 Log.d(LOGTAG,"registered on conv changed in backend ("+convChangedListenerCount+")");
1019 }
1020
1021 public void removeOnConversationListChangedListener() {
1022 this.convChangedListenerCount--;
1023 Log.d(LOGTAG,"someone on conv changed listener removed listener ("+convChangedListenerCount+")");
1024 if (this.convChangedListenerCount==0) {
1025 this.convChangedListener = null;
1026 }
1027 }
1028
1029 public void setOnAccountListChangedListener(
1030 OnAccountListChangedListener listener) {
1031 this.accountChangedListener = listener;
1032 }
1033
1034 public void removeOnAccountListChangedListener() {
1035 this.accountChangedListener = null;
1036 }
1037
1038 public void connectMultiModeConversations(Account account) {
1039 List<Conversation> conversations = getConversations();
1040 for (int i = 0; i < conversations.size(); i++) {
1041 Conversation conversation = conversations.get(i);
1042 if ((conversation.getMode() == Conversation.MODE_MULTI)
1043 && (conversation.getAccount() == account)) {
1044 joinMuc(conversation);
1045 }
1046 }
1047 }
1048
1049 public void joinMuc(Conversation conversation) {
1050 String[] mucParts = conversation.getContactJid().split("/");
1051 String muc;
1052 String nick;
1053 if (mucParts.length == 2) {
1054 muc = mucParts[0];
1055 nick = mucParts[1];
1056 } else {
1057 muc = mucParts[0];
1058 nick = conversation.getAccount().getUsername();
1059 }
1060 PresencePacket packet = new PresencePacket();
1061 packet.setAttribute("to", muc + "/" + nick);
1062 Element x = new Element("x");
1063 x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
1064 if (conversation.getMessages().size() != 0) {
1065 long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1066 long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1067 x.addChild("history").setAttribute("seconds", diff + "");
1068 }
1069 packet.addChild(x);
1070 Log.d(LOGTAG,conversation.getAccount().getJid()+": joining muc "+packet.toString());
1071 conversation.getAccount().getXmppConnection()
1072 .sendPresencePacket(packet);
1073 }
1074
1075 private OnRenameListener renameListener = null;
1076
1077 public void setOnRenameListener(OnRenameListener listener) {
1078 this.renameListener = listener;
1079 }
1080
1081 public void renameInMuc(final Conversation conversation, final String nick) {
1082 final MucOptions options = conversation.getMucOptions();
1083 if (options.online()) {
1084 options.setOnRenameListener(new OnRenameListener() {
1085
1086 @Override
1087 public void onRename(boolean success) {
1088 if (renameListener != null) {
1089 renameListener.onRename(success);
1090 }
1091 if (success) {
1092 databaseBackend.updateConversation(conversation);
1093 }
1094 }
1095 });
1096 options.flagAboutToRename();
1097 PresencePacket packet = new PresencePacket();
1098 packet.setAttribute("to",
1099 conversation.getContactJid().split("/")[0] + "/" + nick);
1100 packet.setAttribute("from", conversation.getAccount().getFullJid());
1101
1102 conversation.getAccount().getXmppConnection()
1103 .sendPresencePacket(packet, null);
1104 } else {
1105 String jid = conversation.getContactJid().split("/")[0] + "/"
1106 + nick;
1107 conversation.setContactJid(jid);
1108 databaseBackend.updateConversation(conversation);
1109 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1110 joinMuc(conversation);
1111 }
1112 }
1113 }
1114
1115 public void leaveMuc(Conversation conversation) {
1116 PresencePacket packet = new PresencePacket();
1117 packet.setAttribute("to", conversation.getContactJid().split("/")[0] + "/" + conversation.getMucOptions().getNick());
1118 packet.setAttribute("from", conversation.getAccount().getFullJid());
1119 packet.setAttribute("type", "unavailable");
1120 Log.d(LOGTAG,"send leaving muc " + packet);
1121 conversation.getAccount().getXmppConnection()
1122 .sendPresencePacket(packet);
1123 conversation.getMucOptions().setOffline();
1124 }
1125
1126 public void disconnect(Account account, boolean force) {
1127 if ((account.getStatus() == Account.STATUS_ONLINE)
1128 || (account.getStatus() == Account.STATUS_DISABLED)) {
1129 if (!force) {
1130 List<Conversation> conversations = getConversations();
1131 for (int i = 0; i < conversations.size(); i++) {
1132 Conversation conversation = conversations.get(i);
1133 if (conversation.getAccount() == account) {
1134 if (conversation.getMode() == Conversation.MODE_MULTI) {
1135 leaveMuc(conversation);
1136 } else {
1137 conversation.endOtrIfNeeded();
1138 }
1139 }
1140 }
1141 }
1142 account.getXmppConnection().disconnect(force);
1143 }
1144 }
1145
1146 @Override
1147 public IBinder onBind(Intent intent) {
1148 return mBinder;
1149 }
1150
1151 public void updateContact(Contact contact) {
1152 databaseBackend.updateContact(contact);
1153 replaceContactInConversation(contact.getJid(), contact);
1154 }
1155
1156 public void updateMessage(Message message) {
1157 databaseBackend.updateMessage(message);
1158 }
1159
1160 public void createContact(Contact contact) {
1161 SharedPreferences sharedPref = PreferenceManager
1162 .getDefaultSharedPreferences(getApplicationContext());
1163 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1164 if (autoGrant) {
1165 contact.setSubscriptionOption(Contact.Subscription.PREEMPTIVE_GRANT);
1166 contact.setSubscriptionOption(Contact.Subscription.ASKING);
1167 }
1168 databaseBackend.createContact(contact);
1169 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1170 Element query = new Element("query");
1171 query.setAttribute("xmlns", "jabber:iq:roster");
1172 Element item = new Element("item");
1173 item.setAttribute("jid", contact.getJid());
1174 item.setAttribute("name", contact.getJid());
1175 query.addChild(item);
1176 iq.addChild(query);
1177 Account account = contact.getAccount();
1178 account.getXmppConnection().sendIqPacket(iq, null);
1179 if (autoGrant) {
1180 requestPresenceUpdatesFrom(contact);
1181 }
1182 replaceContactInConversation(contact.getJid(), contact);
1183 }
1184
1185 public void requestPresenceUpdatesFrom(Contact contact) {
1186 // Requesting a Subscription type=subscribe
1187 PresencePacket packet = new PresencePacket();
1188 packet.setAttribute("type", "subscribe");
1189 packet.setAttribute("to", contact.getJid());
1190 packet.setAttribute("from", contact.getAccount().getJid());
1191 Log.d(LOGTAG, packet.toString());
1192 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1193 }
1194
1195 public void stopPresenceUpdatesFrom(Contact contact) {
1196 // Unsubscribing type='unsubscribe'
1197 PresencePacket packet = new PresencePacket();
1198 packet.setAttribute("type", "unsubscribe");
1199 packet.setAttribute("to", contact.getJid());
1200 packet.setAttribute("from", contact.getAccount().getJid());
1201 Log.d(LOGTAG, packet.toString());
1202 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1203 }
1204
1205 public void stopPresenceUpdatesTo(Contact contact) {
1206 // Canceling a Subscription type=unsubscribed
1207 PresencePacket packet = new PresencePacket();
1208 packet.setAttribute("type", "unsubscribed");
1209 packet.setAttribute("to", contact.getJid());
1210 packet.setAttribute("from", contact.getAccount().getJid());
1211 Log.d(LOGTAG, packet.toString());
1212 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1213 }
1214
1215 public void sendPresenceUpdatesTo(Contact contact) {
1216 // type='subscribed'
1217 PresencePacket packet = new PresencePacket();
1218 packet.setAttribute("type", "subscribed");
1219 packet.setAttribute("to", contact.getJid());
1220 packet.setAttribute("from", contact.getAccount().getJid());
1221 Log.d(LOGTAG, packet.toString());
1222 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1223 }
1224
1225 public void sendPgpPresence(Account account, String signature) {
1226 PresencePacket packet = new PresencePacket();
1227 packet.setAttribute("from", account.getFullJid());
1228 Element status = new Element("status");
1229 status.setContent("online");
1230 packet.addChild(status);
1231 Element x = new Element("x");
1232 x.setAttribute("xmlns", "jabber:x:signed");
1233 x.setContent(signature);
1234 packet.addChild(x);
1235 account.getXmppConnection().sendPresencePacket(packet);
1236 }
1237
1238 public void generatePgpAnnouncement(Account account)
1239 throws PgpEngine.UserInputRequiredException {
1240 if (account.getStatus() == Account.STATUS_ONLINE) {
1241 String signature = getPgpEngine().generateSignature("online");
1242 account.setKey("pgp_signature", signature);
1243 databaseBackend.updateAccount(account);
1244 sendPgpPresence(account, signature);
1245 }
1246 }
1247
1248 public void updateConversation(Conversation conversation) {
1249 this.databaseBackend.updateConversation(conversation);
1250 }
1251
1252 public Contact findContact(String uuid) {
1253 Contact contact = this.databaseBackend.getContact(uuid);
1254 for (Account account : getAccounts()) {
1255 if (contact.getAccountUuid().equals(account.getUuid())) {
1256 contact.setAccount(account);
1257 }
1258 }
1259 return contact;
1260 }
1261
1262 public void removeOnTLSExceptionReceivedListener() {
1263 this.tlsException = null;
1264 }
1265
1266 // TODO dont let thread sleep but schedule wake up
1267 public void reconnectAccount(final Account account, final boolean force) {
1268 new Thread(new Runnable() {
1269
1270 @Override
1271 public void run() {
1272 if (account.getXmppConnection() != null) {
1273 disconnect(account, force);
1274 }
1275 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1276 if (account.getXmppConnection() == null) {
1277 account.setXmppConnection(createConnection(account));
1278 }
1279 Thread thread = new Thread(account.getXmppConnection());
1280 thread.start();
1281 scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1282 }
1283 }
1284 }).start();
1285 }
1286
1287 public void updateConversationInGui() {
1288 if (convChangedListener != null) {
1289 convChangedListener.onConversationListChanged();
1290 }
1291 }
1292
1293 public void sendConversationSubject(Conversation conversation,
1294 String subject) {
1295 MessagePacket packet = new MessagePacket();
1296 packet.setType(MessagePacket.TYPE_GROUPCHAT);
1297 packet.setTo(conversation.getContactJid().split("/")[0]);
1298 Element subjectChild = new Element("subject");
1299 subjectChild.setContent(subject);
1300 packet.addChild(subjectChild);
1301 packet.setFrom(conversation.getAccount().getJid());
1302 Account account = conversation.getAccount();
1303 if (account.getStatus() == Account.STATUS_ONLINE) {
1304 account.getXmppConnection().sendMessagePacket(packet);
1305 }
1306 }
1307
1308 public void inviteToConference(Conversation conversation,
1309 List<Contact> contacts) {
1310 for (Contact contact : contacts) {
1311 MessagePacket packet = new MessagePacket();
1312 packet.setTo(conversation.getContactJid().split("/")[0]);
1313 packet.setFrom(conversation.getAccount().getFullJid());
1314 Element x = new Element("x");
1315 x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1316 Element invite = new Element("invite");
1317 invite.setAttribute("to", contact.getJid());
1318 x.addChild(invite);
1319 packet.addChild(x);
1320 Log.d(LOGTAG, packet.toString());
1321 conversation.getAccount().getXmppConnection()
1322 .sendMessagePacket(packet);
1323 }
1324
1325 }
1326}