1package eu.siacs.conversations.services;
2
3import java.util.Collections;
4import java.util.Comparator;
5import java.util.Hashtable;
6import java.util.List;
7import java.util.Locale;
8import java.util.Random;
9
10import org.openintents.openpgp.util.OpenPgpApi;
11import org.openintents.openpgp.util.OpenPgpServiceConnection;
12
13import net.java.otr4j.OtrException;
14import net.java.otr4j.session.Session;
15import net.java.otr4j.session.SessionStatus;
16import eu.siacs.conversations.crypto.PgpEngine;
17import eu.siacs.conversations.entities.Account;
18import eu.siacs.conversations.entities.Contact;
19import eu.siacs.conversations.entities.Conversation;
20import eu.siacs.conversations.entities.Message;
21import eu.siacs.conversations.entities.MucOptions;
22import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
23import eu.siacs.conversations.entities.Presences;
24import eu.siacs.conversations.parser.MessageParser;
25import eu.siacs.conversations.parser.PresenceParser;
26import eu.siacs.conversations.persistance.DatabaseBackend;
27import eu.siacs.conversations.persistance.FileBackend;
28import eu.siacs.conversations.ui.OnAccountListChangedListener;
29import eu.siacs.conversations.ui.OnConversationListChangedListener;
30import eu.siacs.conversations.ui.UiCallback;
31import eu.siacs.conversations.utils.ExceptionHelper;
32import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
33import eu.siacs.conversations.utils.PhoneHelper;
34import eu.siacs.conversations.utils.UIHelper;
35import eu.siacs.conversations.xml.Element;
36import eu.siacs.conversations.xmpp.OnBindListener;
37import eu.siacs.conversations.xmpp.OnContactStatusChanged;
38import eu.siacs.conversations.xmpp.OnIqPacketReceived;
39import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
40import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
41import eu.siacs.conversations.xmpp.OnStatusChanged;
42import eu.siacs.conversations.xmpp.OnTLSExceptionReceived;
43import eu.siacs.conversations.xmpp.XmppConnection;
44import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
45import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
46import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
47import eu.siacs.conversations.xmpp.stanzas.IqPacket;
48import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
49import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
50import android.app.AlarmManager;
51import android.app.PendingIntent;
52import android.app.Service;
53import android.content.Context;
54import android.content.Intent;
55import android.content.SharedPreferences;
56import android.database.ContentObserver;
57import android.net.ConnectivityManager;
58import android.net.NetworkInfo;
59import android.net.Uri;
60import android.os.Binder;
61import android.os.Bundle;
62import android.os.IBinder;
63import android.os.PowerManager;
64import android.os.PowerManager.WakeLock;
65import android.os.SystemClock;
66import android.preference.PreferenceManager;
67import android.provider.ContactsContract;
68import android.util.Log;
69
70public class XmppConnectionService extends Service {
71
72 protected static final String LOGTAG = "xmppService";
73 public DatabaseBackend databaseBackend;
74 private FileBackend fileBackend;
75
76 public long startDate;
77
78 private static final int PING_MAX_INTERVAL = 300;
79 private static final int PING_MIN_INTERVAL = 10;
80 private static final int PING_TIMEOUT = 5;
81 private static final int CONNECT_TIMEOUT = 60;
82 private static final long CARBON_GRACE_PERIOD = 60000L;
83
84 private static String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
85
86 private MessageParser mMessageParser = new MessageParser(this);
87 private PresenceParser mPresenceParser = new PresenceParser(this);
88
89 private List<Account> accounts;
90 private List<Conversation> conversations = null;
91 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
92 this);
93
94 private OnConversationListChangedListener convChangedListener = null;
95 private int convChangedListenerCount = 0;
96 private OnAccountListChangedListener accountChangedListener = null;
97 private OnTLSExceptionReceived tlsException = null;
98 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
99
100 @Override
101 public void onContactStatusChanged(Contact contact, boolean online) {
102 Conversation conversation = findActiveConversation(contact);
103 if (conversation != null) {
104 conversation.endOtrIfNeeded();
105 if (online&&(contact.getPresences().size() == 1)) {
106 sendUnsendMessages(conversation);
107 }
108 }
109 }
110 };
111
112 public void setOnTLSExceptionReceivedListener(
113 OnTLSExceptionReceived listener) {
114 tlsException = listener;
115 }
116
117 private Random mRandom = new Random(System.currentTimeMillis());
118
119 private long lastCarbonMessageReceived = -CARBON_GRACE_PERIOD;
120
121 private ContentObserver contactObserver = new ContentObserver(null) {
122 @Override
123 public void onChange(boolean selfChange) {
124 super.onChange(selfChange);
125 Intent intent = new Intent(getApplicationContext(),
126 XmppConnectionService.class);
127 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
128 startService(intent);
129 }
130 };
131
132 private final IBinder mBinder = new XmppConnectionBinder();
133 private OnMessagePacketReceived messageListener = new OnMessagePacketReceived() {
134
135 @Override
136 public void onMessagePacketReceived(Account account,
137 MessagePacket packet) {
138 Message message = null;
139 boolean notify = true;
140 if (getPreferences().getBoolean(
141 "notification_grace_period_after_carbon_received", true)) {
142 notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > CARBON_GRACE_PERIOD;
143 }
144
145 if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
146 if ((packet.getBody() != null)
147 && (packet.getBody().startsWith("?OTR"))) {
148 message = mMessageParser.parseOtrChat(packet, account);
149 if (message != null) {
150 message.markUnread();
151 }
152 } else if (packet.hasChild("body")) {
153 message = mMessageParser.parseChat(packet, account);
154 message.markUnread();
155 } else if (packet.hasChild("received")
156 || (packet.hasChild("sent"))) {
157 message = mMessageParser
158 .parseCarbonMessage(packet, account);
159 if (message != null) {
160 if (message.getStatus() == Message.STATUS_SEND) {
161 lastCarbonMessageReceived = SystemClock
162 .elapsedRealtime();
163 notify = false;
164 message.getConversation().markRead();
165 } else {
166 message.markUnread();
167 }
168 }
169 }
170
171 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
172 message = mMessageParser.parseGroupchat(packet, account);
173 if (message != null) {
174 if (message.getStatus() == Message.STATUS_RECIEVED) {
175 message.markUnread();
176 } else {
177 message.getConversation().markRead();
178 notify = false;
179 }
180 }
181 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
182 mMessageParser.parseError(packet, account);
183 return;
184 } else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
185 mMessageParser.parseNormal(packet, account);
186 }
187 if ((message == null) || (message.getBody() == null)) {
188 return;
189 }
190 if ((confirmMessages()) && ((packet.getId() != null))) {
191 MessagePacket receivedPacket = new MessagePacket();
192 receivedPacket.setType(MessagePacket.TYPE_NORMAL);
193 receivedPacket.setTo(message.getCounterpart());
194 receivedPacket.setFrom(account.getFullJid());
195 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
196 Element received = receivedPacket.addChild("received",
197 "urn:xmpp:chat-markers:0");
198 received.setAttribute("id", packet.getId());
199 account.getXmppConnection().sendMessagePacket(
200 receivedPacket);
201 } else if (packet.hasChild("request", "urn:xmpp:receipts")) {
202 Element received = receivedPacket.addChild("received",
203 "urn:xmpp:receipts");
204 received.setAttribute("id", packet.getId());
205 account.getXmppConnection().sendMessagePacket(
206 receivedPacket);
207 }
208 }
209 Conversation conversation = message.getConversation();
210 conversation.getMessages().add(message);
211 if (packet.getType() != MessagePacket.TYPE_ERROR) {
212 databaseBackend.createMessage(message);
213 }
214 if (convChangedListener != null) {
215 convChangedListener.onConversationListChanged();
216 } else {
217 UIHelper.updateNotification(getApplicationContext(),
218 getConversations(), message.getConversation(), notify);
219 }
220 }
221 };
222 private OnStatusChanged statusListener = new OnStatusChanged() {
223
224 @Override
225 public void onStatusChanged(Account account) {
226 if (accountChangedListener != null) {
227 accountChangedListener.onAccountListChangedListener();
228 }
229 if (account.getStatus() == Account.STATUS_ONLINE) {
230 List<Conversation> conversations = getConversations();
231 for (int i = 0; i < conversations.size(); ++i) {
232 if (conversations.get(i).getAccount() == account) {
233 conversations.get(i).endOtrIfNeeded();
234 sendUnsendMessages(conversations.get(i));
235 }
236 }
237 syncDirtyContacts(account);
238 scheduleWakeupCall(PING_MAX_INTERVAL, true);
239 } else if (account.getStatus() == Account.STATUS_OFFLINE) {
240 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
241 int timeToReconnect = mRandom.nextInt(50) + 10;
242 scheduleWakeupCall(timeToReconnect, false);
243 }
244
245 } else if (account.getStatus() == Account.STATUS_REGISTRATION_SUCCESSFULL) {
246 databaseBackend.updateAccount(account);
247 reconnectAccount(account, true);
248 } else if ((account.getStatus() != Account.STATUS_CONNECTING)
249 && (account.getStatus() != Account.STATUS_NO_INTERNET)) {
250 int next = account.getXmppConnection().getTimeToNextAttempt();
251 Log.d(LOGTAG, account.getJid()
252 + ": error connecting account. try again in " + next
253 + "s for the "
254 + (account.getXmppConnection().getAttempt() + 1)
255 + " time");
256 scheduleWakeupCall(next, false);
257 }
258 UIHelper.showErrorNotification(getApplicationContext(),
259 getAccounts());
260 }
261 };
262
263 private OnPresencePacketReceived presenceListener = new OnPresencePacketReceived() {
264
265 @Override
266 public void onPresencePacketReceived(final Account account,
267 PresencePacket packet) {
268 if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
269 mPresenceParser.parseConferencePresence(packet, account);
270 } else if (packet.hasChild("x", "http://jabber.org/protocol/muc")) {
271 mPresenceParser.parseConferencePresence(packet, account);
272 } else {
273 mPresenceParser.parseContactPresence(packet, account);
274 }
275 }
276 };
277
278 private OnIqPacketReceived unknownIqListener = new OnIqPacketReceived() {
279
280 @Override
281 public void onIqPacketReceived(Account account, IqPacket packet) {
282 if (packet.hasChild("query", "jabber:iq:roster")) {
283 String from = packet.getFrom();
284 if ((from == null) || (from.equals(account.getJid()))) {
285 Element query = packet.findChild("query");
286 processRosterItems(account, query);
287 } else {
288 Log.d(LOGTAG, "unauthorized roster push from: " + from);
289 }
290 } else if (packet
291 .hasChild("open", "http://jabber.org/protocol/ibb")
292 || packet
293 .hasChild("data", "http://jabber.org/protocol/ibb")) {
294 XmppConnectionService.this.mJingleConnectionManager
295 .deliverIbbPacket(account, packet);
296 } else if (packet.hasChild("query",
297 "http://jabber.org/protocol/disco#info")) {
298 IqPacket iqResponse = packet
299 .generateRespone(IqPacket.TYPE_RESULT);
300 Element query = iqResponse.addChild("query",
301 "http://jabber.org/protocol/disco#info");
302 query.addChild("feature").setAttribute("var",
303 "urn:xmpp:jingle:1");
304 query.addChild("feature").setAttribute("var",
305 "urn:xmpp:jingle:apps:file-transfer:3");
306 query.addChild("feature").setAttribute("var",
307 "urn:xmpp:jingle:transports:s5b:1");
308 query.addChild("feature").setAttribute("var",
309 "urn:xmpp:jingle:transports:ibb:1");
310 if (confirmMessages()) {
311 query.addChild("feature").setAttribute("var",
312 "urn:xmpp:receipts");
313 }
314 account.getXmppConnection().sendIqPacket(iqResponse, null);
315 } else {
316 if ((packet.getType() == IqPacket.TYPE_GET)
317 || (packet.getType() == IqPacket.TYPE_SET)) {
318 IqPacket response = packet
319 .generateRespone(IqPacket.TYPE_ERROR);
320 Element error = response.addChild("error");
321 error.setAttribute("type", "cancel");
322 error.addChild("feature-not-implemented",
323 "urn:ietf:params:xml:ns:xmpp-stanzas");
324 account.getXmppConnection().sendIqPacket(response, null);
325 }
326 }
327 }
328 };
329
330 private OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
331
332 @Override
333 public void onJinglePacketReceived(Account account, JinglePacket packet) {
334 mJingleConnectionManager.deliverPacket(account, packet);
335 }
336 };
337
338 private OpenPgpServiceConnection pgpServiceConnection;
339 private PgpEngine mPgpEngine = null;
340 private Intent pingIntent;
341 private PendingIntent pendingPingIntent = null;
342 private WakeLock wakeLock;
343 private PowerManager pm;
344
345 public PgpEngine getPgpEngine() {
346 if (pgpServiceConnection.isBound()) {
347 if (this.mPgpEngine == null) {
348 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
349 getApplicationContext(),
350 pgpServiceConnection.getService()), this);
351 }
352 return mPgpEngine;
353 } else {
354 return null;
355 }
356
357 }
358
359 public FileBackend getFileBackend() {
360 return this.fileBackend;
361 }
362
363 public Message attachImageToConversation(final Conversation conversation,
364 final Uri uri, final UiCallback<Message> callback) {
365 final Message message;
366 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
367 message = new Message(conversation, "",
368 Message.ENCRYPTION_DECRYPTED);
369 } else {
370 message = new Message(conversation, "", Message.ENCRYPTION_NONE);
371 }
372 message.setPresence(conversation.getNextPresence());
373 message.setType(Message.TYPE_IMAGE);
374 message.setStatus(Message.STATUS_OFFERED);
375 new Thread(new Runnable() {
376
377 @Override
378 public void run() {
379 try {
380 getFileBackend().copyImageToPrivateStorage(message, uri);
381 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
382 getPgpEngine().encrypt(message, callback);
383 } else {
384 callback.success(message);
385 }
386 } catch (FileBackend.ImageCopyException e) {
387 callback.error(e.getResId(), message);
388 }
389 }
390 }).start();
391 return message;
392 }
393
394 public Conversation findMuc(String name, Account account) {
395 for (Conversation conversation : this.conversations) {
396 if (conversation.getContactJid().split("/")[0].equals(name)
397 && (conversation.getAccount() == account)) {
398 return conversation;
399 }
400 }
401 return null;
402 }
403
404 private void processRosterItems(Account account, Element elements) {
405 String version = elements.getAttribute("ver");
406 if (version != null) {
407 account.getRoster().setVersion(version);
408 }
409 for (Element item : elements.getChildren()) {
410 if (item.getName().equals("item")) {
411 String jid = item.getAttribute("jid");
412 String name = item.getAttribute("name");
413 String subscription = item.getAttribute("subscription");
414 Contact contact = account.getRoster().getContact(jid);
415 if (!contact.getOption(Contact.Options.DIRTY_PUSH)) {
416 contact.setServerName(name);
417 }
418 if (subscription.equals("remove")) {
419 contact.resetOption(Contact.Options.IN_ROSTER);
420 contact.resetOption(Contact.Options.DIRTY_DELETE);
421 } else {
422 contact.setOption(Contact.Options.IN_ROSTER);
423 contact.parseSubscriptionFromElement(item);
424 }
425 }
426 }
427 }
428
429 public class XmppConnectionBinder extends Binder {
430 public XmppConnectionService getService() {
431 return XmppConnectionService.this;
432 }
433 }
434
435 @Override
436 public int onStartCommand(Intent intent, int flags, int startId) {
437 if ((intent != null)
438 && (ACTION_MERGE_PHONE_CONTACTS.equals(intent.getAction()))) {
439 mergePhoneContactsWithRoster();
440 return START_STICKY;
441 } else if ((intent != null)
442 && (Intent.ACTION_SHUTDOWN.equals(intent.getAction()))) {
443 logoutAndSave();
444 return START_NOT_STICKY;
445 }
446 this.wakeLock.acquire();
447 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
448 .getSystemService(Context.CONNECTIVITY_SERVICE);
449 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
450 boolean isConnected = activeNetwork != null
451 && activeNetwork.isConnected();
452
453 for (Account account : accounts) {
454 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
455 if (!isConnected) {
456 account.setStatus(Account.STATUS_NO_INTERNET);
457 if (statusListener != null) {
458 statusListener.onStatusChanged(account);
459 }
460 } else {
461 if (account.getStatus() == Account.STATUS_NO_INTERNET) {
462 account.setStatus(Account.STATUS_OFFLINE);
463 if (statusListener != null) {
464 statusListener.onStatusChanged(account);
465 }
466 }
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 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
495 reconnectAccount(account, true);
496 }
497 }
498 // in any case. reschedule wakup call
499 this.scheduleWakeupCall(PING_MAX_INTERVAL, true);
500 }
501 if (accountChangedListener != null) {
502 accountChangedListener.onAccountListChangedListener();
503 }
504 }
505 }
506 if (wakeLock.isHeld()) {
507 wakeLock.release();
508 }
509 return START_STICKY;
510 }
511
512 @Override
513 public void onCreate() {
514 ExceptionHelper.init(getApplicationContext());
515 this.databaseBackend = DatabaseBackend
516 .getInstance(getApplicationContext());
517 this.fileBackend = new FileBackend(getApplicationContext());
518 this.accounts = databaseBackend.getAccounts();
519
520 for (Account account : this.accounts) {
521 this.databaseBackend.readRoster(account.getRoster());
522 }
523 this.mergePhoneContactsWithRoster();
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 this.logoutAndSave();
541 }
542
543 @Override
544 public void onTaskRemoved(Intent rootIntent) {
545 super.onTaskRemoved(rootIntent);
546 this.logoutAndSave();
547 }
548
549 private void logoutAndSave() {
550 for (Account account : accounts) {
551 databaseBackend.writeRoster(account.getRoster());
552 if (account.getXmppConnection() != null) {
553 disconnect(account, false);
554 }
555 }
556 Context context = getApplicationContext();
557 AlarmManager alarmManager = (AlarmManager) context
558 .getSystemService(Context.ALARM_SERVICE);
559 Intent intent = new Intent(context, EventReceiver.class);
560 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
561 Log.d(LOGTAG, "good bye");
562 stopSelf();
563 }
564
565 protected void scheduleWakeupCall(int seconds, boolean ping) {
566 long timeToWake = SystemClock.elapsedRealtime() + seconds * 1000;
567 Context context = getApplicationContext();
568 AlarmManager alarmManager = (AlarmManager) context
569 .getSystemService(Context.ALARM_SERVICE);
570
571 if (ping) {
572 if (this.pingIntent == null) {
573 this.pingIntent = new Intent(context, EventReceiver.class);
574 this.pingIntent.setAction("ping");
575 this.pingIntent.putExtra("time", timeToWake);
576 this.pendingPingIntent = PendingIntent.getBroadcast(context, 0,
577 this.pingIntent, 0);
578 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
579 timeToWake, pendingPingIntent);
580 } else {
581 long scheduledTime = this.pingIntent.getLongExtra("time", 0);
582 if (scheduledTime < SystemClock.elapsedRealtime()
583 || (scheduledTime > timeToWake)) {
584 this.pingIntent.putExtra("time", timeToWake);
585 alarmManager.cancel(this.pendingPingIntent);
586 this.pendingPingIntent = PendingIntent.getBroadcast(
587 context, 0, this.pingIntent, 0);
588 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
589 timeToWake, pendingPingIntent);
590 }
591 }
592 } else {
593 Intent intent = new Intent(context, EventReceiver.class);
594 intent.setAction("ping_check");
595 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0,
596 intent, 0);
597 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake,
598 alarmIntent);
599 }
600
601 }
602
603 public XmppConnection createConnection(Account account) {
604 SharedPreferences sharedPref = getPreferences();
605 account.setResource(sharedPref.getString("resource", "mobile")
606 .toLowerCase(Locale.getDefault()));
607 XmppConnection connection = new XmppConnection(account, this.pm);
608 connection.setOnMessagePacketReceivedListener(this.messageListener);
609 connection.setOnStatusChangedListener(this.statusListener);
610 connection.setOnPresencePacketReceivedListener(this.presenceListener);
611 connection
612 .setOnUnregisteredIqPacketReceivedListener(this.unknownIqListener);
613 connection.setOnJinglePacketReceivedListener(this.jingleListener);
614 connection
615 .setOnTLSExceptionReceivedListener(new OnTLSExceptionReceived() {
616
617 @Override
618 public void onTLSExceptionReceived(String fingerprint,
619 Account account) {
620 Log.d(LOGTAG, "tls exception arrived in service");
621 if (tlsException != null) {
622 tlsException.onTLSExceptionReceived(fingerprint,
623 account);
624 }
625 }
626 });
627 connection.setOnBindListener(new OnBindListener() {
628
629 @Override
630 public void onBind(final Account account) {
631 account.getRoster().clearPresences();
632 account.clearPresences(); // self presences
633 fetchRosterFromServer(account);
634 sendPresence(account);
635 connectMultiModeConversations(account);
636 if (convChangedListener != null) {
637 convChangedListener.onConversationListChanged();
638 }
639 }
640 });
641 return connection;
642 }
643
644 synchronized public void sendMessage(Message message) {
645 Account account = message.getConversation().getAccount();
646 Conversation conv = message.getConversation();
647 MessagePacket packet = null;
648 boolean saveInDb = false;
649 boolean addToConversation = false;
650 boolean send = false;
651 if (account.getStatus() == Account.STATUS_ONLINE) {
652 if (message.getType() == Message.TYPE_IMAGE) {
653 mJingleConnectionManager.createNewConnection(message);
654 } else {
655 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
656 if (!conv.hasValidOtrSession()) {
657 // starting otr session. messages will be send later
658 conv.startOtrSession(getApplicationContext(), message.getPresence(),
659 true);
660 } else if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
661 // otr session aleary exists, creating message packet
662 // accordingly
663 packet = prepareMessagePacket(account, message,
664 conv.getOtrSession());
665 send = true;
666 message.setStatus(Message.STATUS_SEND);
667 }
668 saveInDb = true;
669 addToConversation = true;
670 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
671 message.getConversation().endOtrIfNeeded();
672 packet = prepareMessagePacket(account, message, null);
673 packet.setBody("This is an XEP-0027 encryted message");
674 packet.addChild("x", "jabber:x:encrypted").setContent(
675 message.getEncryptedBody());
676 message.setStatus(Message.STATUS_SEND);
677 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
678 saveInDb = true;
679 addToConversation = true;
680 send = true;
681 } else {
682 message.getConversation().endOtrIfNeeded();
683 // don't encrypt
684 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
685 message.setStatus(Message.STATUS_SEND);
686 }
687 packet = prepareMessagePacket(account, message, null);
688 send = true;
689 saveInDb = true;
690 addToConversation = true;
691 }
692 }
693 } else {
694 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
695 String pgpBody = message.getEncryptedBody();
696 String decryptedBody = message.getBody();
697 message.setBody(pgpBody);
698 databaseBackend.createMessage(message);
699 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
700 message.setBody(decryptedBody);
701 addToConversation = true;
702 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
703 if (!conv.hasValidOtrSession()) {
704 conv.startOtrSession(getApplicationContext(), message.getPresence(),false);
705 }
706 message.setPresence(conv.getOtrSession().getSessionID().getUserID());
707 saveInDb = true;
708 addToConversation = true;
709 } else {
710 saveInDb = true;
711 addToConversation = true;
712 }
713
714 }
715 if (saveInDb) {
716 databaseBackend.createMessage(message);
717 }
718 if (addToConversation) {
719 conv.getMessages().add(message);
720 if (convChangedListener != null) {
721 convChangedListener.onConversationListChanged();
722 }
723 }
724 if ((send) && (packet != null)) {
725 account.getXmppConnection().sendMessagePacket(packet);
726 }
727
728 }
729
730 private void sendUnsendMessages(Conversation conversation) {
731 for (int i = 0; i < conversation.getMessages().size(); ++i) {
732 if (conversation.getMessages().get(i).getStatus() == Message.STATUS_UNSEND) {
733 resendMessage(conversation.getMessages().get(i));
734 }
735 }
736 }
737
738 private void resendMessage(Message message) {
739 Account account = message.getConversation().getAccount();
740 if (message.getType() == Message.TYPE_TEXT) {
741 MessagePacket packet = null;
742 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
743 packet = prepareMessagePacket(account, message, null);
744 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
745 packet = prepareMessagePacket(account, message, null);
746 packet.setBody("This is an XEP-0027 encryted message");
747 if (message.getEncryptedBody() == null) {
748 markMessage(message, Message.STATUS_SEND_FAILED);
749 return;
750 }
751 packet.addChild("x", "jabber:x:encrypted").setContent(
752 message.getEncryptedBody());
753 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
754 packet = prepareMessagePacket(account, message, null);
755 packet.setBody("This is an XEP-0027 encryted message");
756 packet.addChild("x", "jabber:x:encrypted").setContent(
757 message.getBody());
758 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
759 Presences presences = message.getConversation().getContact().getPresences();
760 if (!message.getConversation().hasValidOtrSession()) {
761 if ((message.getPresence() != null)&&(presences.has(message.getPresence()))) {
762 message.getConversation().startOtrSession(getApplicationContext(), message.getPresence(), true);
763 } else {
764 if (presences.size() == 1) {
765 String presence = presences.asStringArray()[0];
766 message.getConversation().startOtrSession(getApplicationContext(), presence, true);
767 }
768 }
769 }
770 }
771 if (packet != null) {
772 account.getXmppConnection().sendMessagePacket(packet);
773 markMessage(message, Message.STATUS_SEND);
774 }
775 } else if (message.getType() == Message.TYPE_IMAGE) {
776 // TODO: send images
777 }
778 }
779
780 public MessagePacket prepareMessagePacket(Account account, Message message,
781 Session otrSession) {
782 MessagePacket packet = new MessagePacket();
783 if (message.getConversation().getMode() == Conversation.MODE_SINGLE) {
784 packet.setType(MessagePacket.TYPE_CHAT);
785 if (otrSession != null) {
786 try {
787 packet.setBody(otrSession.transformSending(message
788 .getBody()));
789 } catch (OtrException e) {
790 Log.d(LOGTAG,
791 account.getJid()
792 + ": could not encrypt message to "
793 + message.getCounterpart());
794 }
795 packet.addChild("private", "urn:xmpp:carbons:2");
796 packet.addChild("no-copy", "urn:xmpp:hints");
797 packet.setTo(otrSession.getSessionID().getAccountID() + "/"
798 + otrSession.getSessionID().getUserID());
799 packet.setFrom(account.getFullJid());
800 } else {
801 packet.setBody(message.getBody());
802 packet.setTo(message.getCounterpart());
803 packet.setFrom(account.getJid());
804 }
805 packet.addChild("markable", "urn:xmpp:chat-markers:0");
806 } else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
807 packet.setType(MessagePacket.TYPE_GROUPCHAT);
808 packet.setBody(message.getBody());
809 packet.setTo(message.getCounterpart().split("/")[0]);
810 packet.setFrom(account.getJid());
811 }
812 packet.setId(message.getUuid());
813 return packet;
814 }
815
816 public void fetchRosterFromServer(Account account) {
817 IqPacket iqPacket = new IqPacket(IqPacket.TYPE_GET);
818 if (!"".equals(account.getRosterVersion())) {
819 Log.d(LOGTAG, account.getJid() + ": fetching roster version "
820 + account.getRosterVersion());
821 } else {
822 Log.d(LOGTAG, account.getJid() + ": fetching roster");
823 }
824 iqPacket.query("jabber:iq:roster").setAttribute("ver",
825 account.getRosterVersion());
826 account.getXmppConnection().sendIqPacket(iqPacket,
827 new OnIqPacketReceived() {
828
829 @Override
830 public void onIqPacketReceived(final Account account,
831 IqPacket packet) {
832 Element roster = packet.findChild("query");
833 if (roster != null) {
834 account.getRoster().markAllAsNotInRoster();
835 processRosterItems(account, roster);
836 }
837 }
838 });
839 }
840
841 private void mergePhoneContactsWithRoster() {
842 PhoneHelper.loadPhoneContacts(getApplicationContext(),
843 new OnPhoneContactsLoadedListener() {
844 @Override
845 public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
846 for (Account account : accounts) {
847 account.getRoster().clearSystemAccounts();
848 }
849 for (Bundle phoneContact : phoneContacts) {
850 for (Account account : accounts) {
851 String jid = phoneContact.getString("jid");
852 Contact contact = account.getRoster()
853 .getContact(jid);
854 String systemAccount = phoneContact
855 .getInt("phoneid")
856 + "#"
857 + phoneContact.getString("lookup");
858 contact.setSystemAccount(systemAccount);
859 contact.setPhotoUri(phoneContact
860 .getString("photouri"));
861 contact.setSystemName(phoneContact
862 .getString("displayname"));
863 }
864 }
865 }
866 });
867 }
868
869 public List<Conversation> getConversations() {
870 if (this.conversations == null) {
871 Hashtable<String, Account> accountLookupTable = new Hashtable<String, Account>();
872 for (Account account : this.accounts) {
873 accountLookupTable.put(account.getUuid(), account);
874 }
875 this.conversations = databaseBackend
876 .getConversations(Conversation.STATUS_AVAILABLE);
877 for (Conversation conv : this.conversations) {
878 Account account = accountLookupTable.get(conv.getAccountUuid());
879 conv.setAccount(account);
880 conv.setMessages(databaseBackend.getMessages(conv, 50));
881 }
882 }
883 Collections.sort(this.conversations, new Comparator<Conversation>() {
884 @Override
885 public int compare(Conversation lhs, Conversation rhs) {
886 Message left = lhs.getLatestMessage();
887 Message right = rhs.getLatestMessage();
888 if (left.getTimeSent() > right.getTimeSent()) {
889 return -1;
890 } else if (left.getTimeSent() < right.getTimeSent()) {
891 return 1;
892 } else {
893 return 0;
894 }
895 }
896 });
897 return this.conversations;
898 }
899
900 public List<Account> getAccounts() {
901 return this.accounts;
902 }
903
904 public Conversation findActiveConversation(Contact contact) {
905 for (Conversation conversation : this.getConversations()) {
906 if (conversation.getContact() == contact) {
907 return conversation;
908 }
909 }
910 return null;
911 }
912
913 public Conversation findOrCreateConversation(Account account, String jid,
914 boolean muc) {
915 for (Conversation conv : this.getConversations()) {
916 if ((conv.getAccount().equals(account))
917 && (conv.getContactJid().split("/")[0].equals(jid))) {
918 return conv;
919 }
920 }
921 Conversation conversation = databaseBackend.findConversation(account,
922 jid);
923 if (conversation != null) {
924 conversation.setStatus(Conversation.STATUS_AVAILABLE);
925 conversation.setAccount(account);
926 if (muc) {
927 conversation.setMode(Conversation.MODE_MULTI);
928 } else {
929 conversation.setMode(Conversation.MODE_SINGLE);
930 }
931 conversation.setMessages(databaseBackend.getMessages(conversation,
932 50));
933 this.databaseBackend.updateConversation(conversation);
934 } else {
935 String conversationName;
936 Contact contact = account.getRoster().getContact(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 this.databaseBackend.createConversation(conversation);
950 }
951 this.conversations.add(conversation);
952 if ((account.getStatus() == Account.STATUS_ONLINE)
953 && (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 void clearConversationHistory(Conversation conversation) {
976 this.databaseBackend.deleteMessagesInConversation(conversation);
977 this.fileBackend.removeFiles(conversation);
978 conversation.getMessages().clear();
979 if (this.convChangedListener != null) {
980 this.convChangedListener.onConversationListChanged();
981 }
982 }
983
984 public int getConversationCount() {
985 return this.databaseBackend.getConversationCount();
986 }
987
988 public void createAccount(Account account) {
989 databaseBackend.createAccount(account);
990 this.accounts.add(account);
991 this.reconnectAccount(account, false);
992 if (accountChangedListener != null)
993 accountChangedListener.onAccountListChangedListener();
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 UIHelper.showErrorNotification(getApplicationContext(), getAccounts());
1004 }
1005
1006 public void deleteAccount(Account account) {
1007 if (account.getXmppConnection() != null) {
1008 this.disconnect(account, true);
1009 }
1010 databaseBackend.deleteAccount(account);
1011 this.accounts.remove(account);
1012 if (accountChangedListener != null) {
1013 accountChangedListener.onAccountListChangedListener();
1014 }
1015 UIHelper.showErrorNotification(getApplicationContext(), getAccounts());
1016 }
1017
1018 public void setOnConversationListChangedListener(
1019 OnConversationListChangedListener listener) {
1020 this.convChangedListener = listener;
1021 this.convChangedListenerCount++;
1022 }
1023
1024 public void removeOnConversationListChangedListener() {
1025 this.convChangedListenerCount--;
1026 if (this.convChangedListenerCount == 0) {
1027 this.convChangedListener = null;
1028 }
1029 }
1030
1031 public void setOnAccountListChangedListener(
1032 OnAccountListChangedListener listener) {
1033 this.accountChangedListener = listener;
1034 }
1035
1036 public void removeOnAccountListChangedListener() {
1037 this.accountChangedListener = null;
1038 }
1039
1040 public void connectMultiModeConversations(Account account) {
1041 List<Conversation> conversations = getConversations();
1042 for (int i = 0; i < conversations.size(); i++) {
1043 Conversation conversation = conversations.get(i);
1044 if ((conversation.getMode() == Conversation.MODE_MULTI)
1045 && (conversation.getAccount() == account)) {
1046 joinMuc(conversation);
1047 }
1048 }
1049 }
1050
1051 public void joinMuc(Conversation conversation) {
1052 Account account = conversation.getAccount();
1053 String[] mucParts = conversation.getContactJid().split("/");
1054 String muc;
1055 String nick;
1056 if (mucParts.length == 2) {
1057 muc = mucParts[0];
1058 nick = mucParts[1];
1059 } else {
1060 muc = mucParts[0];
1061 nick = account.getUsername();
1062 }
1063 PresencePacket packet = new PresencePacket();
1064 packet.setAttribute("to", muc + "/" + nick);
1065 Element x = new Element("x");
1066 x.setAttribute("xmlns", "http://jabber.org/protocol/muc");
1067 String sig = account.getPgpSignature();
1068 if (sig != null) {
1069 packet.addChild("status").setContent("online");
1070 packet.addChild("x", "jabber:x:signed").setContent(sig);
1071 }
1072 if (conversation.getMessages().size() != 0) {
1073 long lastMsgTime = conversation.getLatestMessage().getTimeSent();
1074 long diff = (System.currentTimeMillis() - lastMsgTime) / 1000 - 1;
1075 x.addChild("history").setAttribute("seconds", diff + "");
1076 }
1077 packet.addChild(x);
1078 account.getXmppConnection().sendPresencePacket(packet);
1079 }
1080
1081 private OnRenameListener renameListener = null;
1082
1083 public void setOnRenameListener(OnRenameListener listener) {
1084 this.renameListener = listener;
1085 }
1086
1087 public void renameInMuc(final Conversation conversation, final String nick) {
1088 final MucOptions options = conversation.getMucOptions();
1089 if (options.online()) {
1090 Account account = conversation.getAccount();
1091 options.setOnRenameListener(new OnRenameListener() {
1092
1093 @Override
1094 public void onRename(boolean success) {
1095 if (renameListener != null) {
1096 renameListener.onRename(success);
1097 }
1098 if (success) {
1099 String jid = conversation.getContactJid().split("/")[0]
1100 + "/" + nick;
1101 conversation.setContactJid(jid);
1102 databaseBackend.updateConversation(conversation);
1103 }
1104 }
1105 });
1106 options.flagAboutToRename();
1107 PresencePacket packet = new PresencePacket();
1108 packet.setAttribute("to",
1109 conversation.getContactJid().split("/")[0] + "/" + nick);
1110 packet.setAttribute("from", conversation.getAccount().getFullJid());
1111
1112 String sig = account.getPgpSignature();
1113 if (sig != null) {
1114 packet.addChild("status").setContent("online");
1115 packet.addChild("x", "jabber:x:signed").setContent(sig);
1116 }
1117
1118 account.getXmppConnection().sendPresencePacket(packet, null);
1119 } else {
1120 String jid = conversation.getContactJid().split("/")[0] + "/"
1121 + nick;
1122 conversation.setContactJid(jid);
1123 databaseBackend.updateConversation(conversation);
1124 if (conversation.getAccount().getStatus() == Account.STATUS_ONLINE) {
1125 joinMuc(conversation);
1126 }
1127 }
1128 }
1129
1130 public void leaveMuc(Conversation conversation) {
1131 PresencePacket packet = new PresencePacket();
1132 packet.setAttribute("to", conversation.getContactJid().split("/")[0]
1133 + "/" + conversation.getMucOptions().getNick());
1134 packet.setAttribute("from", conversation.getAccount().getFullJid());
1135 packet.setAttribute("type", "unavailable");
1136 Log.d(LOGTAG, "send leaving muc " + packet);
1137 conversation.getAccount().getXmppConnection()
1138 .sendPresencePacket(packet);
1139 conversation.getMucOptions().setOffline();
1140 }
1141
1142 public void disconnect(Account account, boolean force) {
1143 if ((account.getStatus() == Account.STATUS_ONLINE)
1144 || (account.getStatus() == Account.STATUS_DISABLED)) {
1145 if (!force) {
1146 List<Conversation> conversations = getConversations();
1147 for (int i = 0; i < conversations.size(); i++) {
1148 Conversation conversation = conversations.get(i);
1149 if (conversation.getAccount() == account) {
1150 if (conversation.getMode() == Conversation.MODE_MULTI) {
1151 leaveMuc(conversation);
1152 } else {
1153 conversation.endOtrIfNeeded();
1154 }
1155 }
1156 }
1157 }
1158 account.getXmppConnection().disconnect(force);
1159 }
1160 }
1161
1162 @Override
1163 public IBinder onBind(Intent intent) {
1164 return mBinder;
1165 }
1166
1167 public void updateMessage(Message message) {
1168 databaseBackend.updateMessage(message);
1169 }
1170
1171 protected void syncDirtyContacts(Account account) {
1172 for (Contact contact : account.getRoster().getContacts()) {
1173 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1174 pushContactToServer(contact);
1175 }
1176 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1177 Log.d(LOGTAG, "dirty delete");
1178 deleteContactOnServer(contact);
1179 }
1180 }
1181 }
1182
1183 public void createContact(Contact contact) {
1184 SharedPreferences sharedPref = getPreferences();
1185 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1186 if (autoGrant) {
1187 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1188 contact.setOption(Contact.Options.ASKING);
1189 }
1190 pushContactToServer(contact);
1191 }
1192
1193 public void onOtrSessionEstablished(Conversation conversation) {
1194 Account account = conversation.getAccount();
1195 List<Message> messages = conversation.getMessages();
1196 Session otrSession = conversation.getOtrSession();
1197 Log.d(LOGTAG,account.getJid()+" otr session established with "+conversation.getContactJid()+"/"+otrSession.getSessionID().getUserID());
1198 for (int i = 0; i < messages.size(); ++i) {
1199 Message msg = messages.get(i);
1200 if ((msg.getStatus() == Message.STATUS_UNSEND)
1201 && (msg.getEncryption() == Message.ENCRYPTION_OTR)) {
1202 MessagePacket outPacket = prepareMessagePacket(account, msg,
1203 otrSession);
1204 msg.setStatus(Message.STATUS_SEND);
1205 databaseBackend.updateMessage(msg);
1206 account.getXmppConnection().sendMessagePacket(outPacket);
1207 }
1208 }
1209 updateUi(conversation, false);
1210 }
1211
1212 public void pushContactToServer(Contact contact) {
1213 contact.resetOption(Contact.Options.DIRTY_DELETE);
1214 Account account = contact.getAccount();
1215 if (account.getStatus() == Account.STATUS_ONLINE) {
1216 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1217 iq.query("jabber:iq:roster").addChild(contact.asElement());
1218 account.getXmppConnection().sendIqPacket(iq, null);
1219 if (contact.getOption(Contact.Options.ASKING)) {
1220 requestPresenceUpdatesFrom(contact);
1221 }
1222 if (contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1223 Log.d("xmppService", "contact had pending subscription");
1224 sendPresenceUpdatesTo(contact);
1225 }
1226 contact.resetOption(Contact.Options.DIRTY_PUSH);
1227 } else {
1228 contact.setOption(Contact.Options.DIRTY_PUSH);
1229 }
1230 }
1231
1232 public void deleteContactOnServer(Contact contact) {
1233 contact.resetOption(Contact.Options.DIRTY_PUSH);
1234 Account account = contact.getAccount();
1235 if (account.getStatus() == Account.STATUS_ONLINE) {
1236 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
1237 Element item = iq.query("jabber:iq:roster").addChild("item");
1238 item.setAttribute("jid", contact.getJid());
1239 item.setAttribute("subscription", "remove");
1240 account.getXmppConnection().sendIqPacket(iq, null);
1241 contact.resetOption(Contact.Options.DIRTY_DELETE);
1242 } else {
1243 contact.setOption(Contact.Options.DIRTY_DELETE);
1244 }
1245 }
1246
1247 public void requestPresenceUpdatesFrom(Contact contact) {
1248 PresencePacket packet = new PresencePacket();
1249 packet.setAttribute("type", "subscribe");
1250 packet.setAttribute("to", contact.getJid());
1251 packet.setAttribute("from", contact.getAccount().getJid());
1252 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1253 }
1254
1255 public void stopPresenceUpdatesFrom(Contact contact) {
1256 PresencePacket packet = new PresencePacket();
1257 packet.setAttribute("type", "unsubscribe");
1258 packet.setAttribute("to", contact.getJid());
1259 packet.setAttribute("from", contact.getAccount().getJid());
1260 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1261 }
1262
1263 public void stopPresenceUpdatesTo(Contact contact) {
1264 PresencePacket packet = new PresencePacket();
1265 packet.setAttribute("type", "unsubscribed");
1266 packet.setAttribute("to", contact.getJid());
1267 packet.setAttribute("from", contact.getAccount().getJid());
1268 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1269 }
1270
1271 public void sendPresenceUpdatesTo(Contact contact) {
1272 PresencePacket packet = new PresencePacket();
1273 packet.setAttribute("type", "subscribed");
1274 packet.setAttribute("to", contact.getJid());
1275 packet.setAttribute("from", contact.getAccount().getJid());
1276 contact.getAccount().getXmppConnection().sendPresencePacket(packet);
1277 }
1278
1279 public void sendPresence(Account account) {
1280 PresencePacket packet = new PresencePacket();
1281 packet.setAttribute("from", account.getFullJid());
1282 String sig = account.getPgpSignature();
1283 if (sig != null) {
1284 packet.addChild("status").setContent("online");
1285 packet.addChild("x", "jabber:x:signed").setContent(sig);
1286 }
1287 account.getXmppConnection().sendPresencePacket(packet);
1288 }
1289
1290 public void updateConversation(Conversation conversation) {
1291 this.databaseBackend.updateConversation(conversation);
1292 }
1293
1294 public void removeOnTLSExceptionReceivedListener() {
1295 this.tlsException = null;
1296 }
1297
1298 public void reconnectAccount(final Account account, final boolean force) {
1299 new Thread(new Runnable() {
1300
1301 @Override
1302 public void run() {
1303 if (account.getXmppConnection() != null) {
1304 disconnect(account, force);
1305 }
1306 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
1307 if (account.getXmppConnection() == null) {
1308 account.setXmppConnection(createConnection(account));
1309 }
1310 Thread thread = new Thread(account.getXmppConnection());
1311 thread.start();
1312 scheduleWakeupCall((int) (CONNECT_TIMEOUT * 1.2), false);
1313 }
1314 }
1315 }).start();
1316 }
1317
1318 public void sendConversationSubject(Conversation conversation,
1319 String subject) {
1320 MessagePacket packet = new MessagePacket();
1321 packet.setType(MessagePacket.TYPE_GROUPCHAT);
1322 packet.setTo(conversation.getContactJid().split("/")[0]);
1323 Element subjectChild = new Element("subject");
1324 subjectChild.setContent(subject);
1325 packet.addChild(subjectChild);
1326 packet.setFrom(conversation.getAccount().getJid());
1327 Account account = conversation.getAccount();
1328 if (account.getStatus() == Account.STATUS_ONLINE) {
1329 account.getXmppConnection().sendMessagePacket(packet);
1330 }
1331 }
1332
1333 public void inviteToConference(Conversation conversation,
1334 List<Contact> contacts) {
1335 for (Contact contact : contacts) {
1336 MessagePacket packet = new MessagePacket();
1337 packet.setTo(conversation.getContactJid().split("/")[0]);
1338 packet.setFrom(conversation.getAccount().getFullJid());
1339 Element x = new Element("x");
1340 x.setAttribute("xmlns", "http://jabber.org/protocol/muc#user");
1341 Element invite = new Element("invite");
1342 invite.setAttribute("to", contact.getJid());
1343 x.addChild(invite);
1344 packet.addChild(x);
1345 Log.d(LOGTAG, packet.toString());
1346 conversation.getAccount().getXmppConnection()
1347 .sendMessagePacket(packet);
1348 }
1349
1350 }
1351
1352 public boolean markMessage(Account account, String recipient, String uuid,
1353 int status) {
1354 for (Conversation conversation : getConversations()) {
1355 if (conversation.getContactJid().equals(recipient)
1356 && conversation.getAccount().equals(account)) {
1357 return markMessage(conversation, uuid, status);
1358 }
1359 }
1360 return false;
1361 }
1362
1363 public boolean markMessage(Conversation conversation, String uuid,
1364 int status) {
1365 for (Message message : conversation.getMessages()) {
1366 if (message.getUuid().equals(uuid)) {
1367 markMessage(message, status);
1368 return true;
1369 }
1370 }
1371 return false;
1372 }
1373
1374 public void markMessage(Message message, int status) {
1375 message.setStatus(status);
1376 databaseBackend.updateMessage(message);
1377 if (convChangedListener != null) {
1378 convChangedListener.onConversationListChanged();
1379 }
1380 }
1381
1382 public SharedPreferences getPreferences() {
1383 return PreferenceManager
1384 .getDefaultSharedPreferences(getApplicationContext());
1385 }
1386
1387 public boolean confirmMessages() {
1388 return getPreferences().getBoolean("confirm_messages", true);
1389 }
1390
1391 public void updateUi(Conversation conversation, boolean notify) {
1392 if (convChangedListener != null) {
1393 convChangedListener.onConversationListChanged();
1394 } else {
1395 UIHelper.updateNotification(getApplicationContext(),
1396 getConversations(), conversation, notify);
1397 }
1398 }
1399
1400 public Account findAccountByJid(String accountJid) {
1401 for (Account account : this.accounts) {
1402 if (account.getJid().equals(accountJid)) {
1403 return account;
1404 }
1405 }
1406 return null;
1407 }
1408
1409 public void markRead(Conversation conversation) {
1410 conversation.markRead(this);
1411 }
1412
1413 public void sendConfirmMessage(Account account, String to, String id) {
1414 MessagePacket receivedPacket = new MessagePacket();
1415 receivedPacket.setType(MessagePacket.TYPE_NORMAL);
1416 receivedPacket.setTo(to);
1417 receivedPacket.setFrom(account.getFullJid());
1418 Element received = receivedPacket.addChild("displayed",
1419 "urn:xmpp:chat-markers:0");
1420 received.setAttribute("id", id);
1421 account.getXmppConnection().sendMessagePacket(receivedPacket);
1422 }
1423}