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