QuickConversationsService.java

  1package eu.siacs.conversations.services;
  2
  3
  4import android.content.SharedPreferences;
  5import android.net.Uri;
  6import android.os.SystemClock;
  7import android.preference.PreferenceManager;
  8import android.util.Log;
  9
 10import java.io.BufferedWriter;
 11import java.io.OutputStream;
 12import java.io.OutputStreamWriter;
 13import java.net.ConnectException;
 14import java.net.HttpURLConnection;
 15import java.net.URL;
 16import java.net.UnknownHostException;
 17import java.security.SecureRandom;
 18import java.util.ArrayList;
 19import java.util.Collection;
 20import java.util.Collections;
 21import java.util.List;
 22import java.util.Locale;
 23import java.util.Map;
 24import java.util.Set;
 25import java.util.UUID;
 26import java.util.WeakHashMap;
 27import java.util.concurrent.CountDownLatch;
 28import java.util.concurrent.TimeUnit;
 29import java.util.concurrent.atomic.AtomicBoolean;
 30import java.util.concurrent.atomic.AtomicInteger;
 31
 32import javax.net.ssl.SSLHandshakeException;
 33
 34import eu.siacs.conversations.Config;
 35import eu.siacs.conversations.android.JabberIdContact;
 36import eu.siacs.conversations.android.PhoneNumberContact;
 37import eu.siacs.conversations.crypto.sasl.Plain;
 38import eu.siacs.conversations.entities.Account;
 39import eu.siacs.conversations.entities.Contact;
 40import eu.siacs.conversations.entities.Entry;
 41import eu.siacs.conversations.utils.AccountUtils;
 42import eu.siacs.conversations.utils.CryptoHelper;
 43import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
 44import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 45import eu.siacs.conversations.xml.Element;
 46import eu.siacs.conversations.xml.Namespace;
 47import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 48import eu.siacs.conversations.xmpp.XmppConnection;
 49import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 50import io.michaelrocks.libphonenumber.android.Phonenumber;
 51import rocks.xmpp.addr.Jid;
 52
 53public class QuickConversationsService extends AbstractQuickConversationsService {
 54
 55
 56    public static final int API_ERROR_OTHER = -1;
 57    public static final int API_ERROR_UNKNOWN_HOST = -2;
 58    public static final int API_ERROR_CONNECT = -3;
 59    public static final int API_ERROR_SSL_HANDSHAKE = -4;
 60    public static final int API_ERROR_AIRPLANE_MODE = -5;
 61
 62    private static final String API_DOMAIN = "api." + Config.QUICKSY_DOMAIN;
 63
 64    private static final String BASE_URL = "https://" + API_DOMAIN;
 65
 66    private static final String INSTALLATION_ID = "eu.siacs.conversations.installation-id";
 67
 68    private final Set<OnVerificationRequested> mOnVerificationRequested = Collections.newSetFromMap(new WeakHashMap<>());
 69    private final Set<OnVerification> mOnVerification = Collections.newSetFromMap(new WeakHashMap<>());
 70
 71    private final AtomicBoolean mVerificationInProgress = new AtomicBoolean(false);
 72    private final AtomicBoolean mVerificationRequestInProgress = new AtomicBoolean(false);
 73    private final AtomicInteger mRunningSyncJobs = new AtomicInteger(0);
 74    private CountDownLatch awaitingAccountStateChange;
 75
 76    private Attempt mLastSyncAttempt = Attempt.NULL;
 77
 78    private final SerialSingleThreadExecutor mSerialSingleThreadExecutor = new SerialSingleThreadExecutor(QuickConversationsService.class.getSimpleName());
 79
 80    QuickConversationsService(XmppConnectionService xmppConnectionService) {
 81        super(xmppConnectionService);
 82    }
 83
 84    private static long retryAfter(HttpURLConnection connection) {
 85        try {
 86            return SystemClock.elapsedRealtime() + (Long.parseLong(connection.getHeaderField("Retry-After")) * 1000L);
 87        } catch (Exception e) {
 88            return 0;
 89        }
 90    }
 91
 92    public void addOnVerificationRequestedListener(OnVerificationRequested onVerificationRequested) {
 93        synchronized (mOnVerificationRequested) {
 94            mOnVerificationRequested.add(onVerificationRequested);
 95        }
 96    }
 97
 98    public void removeOnVerificationRequestedListener(OnVerificationRequested onVerificationRequested) {
 99        synchronized (mOnVerificationRequested) {
100            mOnVerificationRequested.remove(onVerificationRequested);
101        }
102    }
103
104    public void addOnVerificationListener(OnVerification onVerification) {
105        synchronized (mOnVerification) {
106            mOnVerification.add(onVerification);
107        }
108    }
109
110    public void removeOnVerificationListener(OnVerification onVerification) {
111        synchronized (mOnVerification) {
112            mOnVerification.remove(onVerification);
113        }
114    }
115
116    public void requestVerification(Phonenumber.PhoneNumber phoneNumber) {
117        final String e164 = PhoneNumberUtilWrapper.normalize(service, phoneNumber);
118        if (mVerificationRequestInProgress.compareAndSet(false, true)) {
119            new Thread(() -> {
120                try {
121                    final URL url = new URL(BASE_URL + "/authentication/" + e164);
122                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
123                    connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
124                    connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
125                    setHeader(connection);
126                    final int code = connection.getResponseCode();
127                    if (code == 200) {
128                        createAccountAndWait(phoneNumber, 0L);
129                    } else if (code == 429) {
130                        createAccountAndWait(phoneNumber, retryAfter(connection));
131                    } else {
132                        synchronized (mOnVerificationRequested) {
133                            for (OnVerificationRequested onVerificationRequested : mOnVerificationRequested) {
134                                onVerificationRequested.onVerificationRequestFailed(code);
135                            }
136                        }
137                    }
138                } catch (Exception e) {
139                    final int code = getApiErrorCode(e);
140                    synchronized (mOnVerificationRequested) {
141                        for (OnVerificationRequested onVerificationRequested : mOnVerificationRequested) {
142                            onVerificationRequested.onVerificationRequestFailed(code);
143                        }
144                    }
145                } finally {
146                    mVerificationRequestInProgress.set(false);
147                }
148            }).start();
149        }
150
151
152    }
153
154    public void signalAccountStateChange() {
155        if (awaitingAccountStateChange != null && awaitingAccountStateChange.getCount() > 0) {
156            Log.d(Config.LOGTAG, "signaled state change");
157            awaitingAccountStateChange.countDown();
158        }
159    }
160
161    private void createAccountAndWait(Phonenumber.PhoneNumber phoneNumber, final long timestamp) {
162        String local = PhoneNumberUtilWrapper.normalize(service, phoneNumber);
163        Log.d(Config.LOGTAG, "requesting verification for " + PhoneNumberUtilWrapper.normalize(service, phoneNumber));
164        Jid jid = Jid.of(local, Config.QUICKSY_DOMAIN, null);
165        Account account = AccountUtils.getFirst(service);
166        if (account == null || !account.getJid().asBareJid().equals(jid.asBareJid())) {
167            if (account != null) {
168                service.deleteAccount(account);
169            }
170            account = new Account(jid, CryptoHelper.createPassword(new SecureRandom()));
171            account.setOption(Account.OPTION_DISABLED, true);
172            account.setOption(Account.OPTION_UNVERIFIED, true);
173            service.createAccount(account);
174        }
175        synchronized (mOnVerificationRequested) {
176            for (OnVerificationRequested onVerificationRequested : mOnVerificationRequested) {
177                if (timestamp <= 0) {
178                    onVerificationRequested.onVerificationRequested();
179                } else {
180                    onVerificationRequested.onVerificationRequestedRetryAt(timestamp);
181                }
182            }
183        }
184    }
185
186    public void verify(final Account account, String pin) {
187        if (mVerificationInProgress.compareAndSet(false, true)) {
188            new Thread(() -> {
189                try {
190                    final URL url = new URL(BASE_URL + "/password");
191                    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
192                    connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
193                    connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
194                    connection.setRequestMethod("POST");
195                    connection.setRequestProperty("Authorization", Plain.getMessage(account.getUsername(), pin));
196                    setHeader(connection);
197                    final OutputStream os = connection.getOutputStream();
198                    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
199                    writer.write(account.getPassword());
200                    writer.flush();
201                    writer.close();
202                    os.close();
203                    connection.connect();
204                    final int code = connection.getResponseCode();
205                    if (code == 200) {
206                        account.setOption(Account.OPTION_UNVERIFIED, false);
207                        account.setOption(Account.OPTION_DISABLED, false);
208                        awaitingAccountStateChange = new CountDownLatch(1);
209                        service.updateAccount(account);
210                        try {
211                            awaitingAccountStateChange.await(5, TimeUnit.SECONDS);
212                        } catch (InterruptedException e) {
213                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": timer expired while waiting for account to connect");
214                        }
215                        synchronized (mOnVerification) {
216                            for (OnVerification onVerification : mOnVerification) {
217                                onVerification.onVerificationSucceeded();
218                            }
219                        }
220                    } else if (code == 429) {
221                        final long retryAfter = retryAfter(connection);
222                        synchronized (mOnVerification) {
223                            for (OnVerification onVerification : mOnVerification) {
224                                onVerification.onVerificationRetryAt(retryAfter);
225                            }
226                        }
227                    } else {
228                        synchronized (mOnVerification) {
229                            for (OnVerification onVerification : mOnVerification) {
230                                onVerification.onVerificationFailed(code);
231                            }
232                        }
233                    }
234                } catch (Exception e) {
235                    final int code = getApiErrorCode(e);
236                    synchronized (mOnVerification) {
237                        for (OnVerification onVerification : mOnVerification) {
238                            onVerification.onVerificationFailed(code);
239                        }
240                    }
241                } finally {
242                    mVerificationInProgress.set(false);
243                }
244            }).start();
245        }
246    }
247
248    private void setHeader(HttpURLConnection connection) {
249        connection.setRequestProperty("User-Agent", service.getIqGenerator().getUserAgent());
250        connection.setRequestProperty("Installation-Id", getInstallationId());
251        connection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
252    }
253
254    private String getInstallationId() {
255        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(service);
256        String id = preferences.getString(INSTALLATION_ID, null);
257        if (id != null) {
258            return id;
259        } else {
260            id = UUID.randomUUID().toString();
261            preferences.edit().putString(INSTALLATION_ID, id).apply();
262            return id;
263        }
264
265    }
266
267    private int getApiErrorCode(Exception e) {
268        if (!service.hasInternetConnection()) {
269            return API_ERROR_AIRPLANE_MODE;
270        } else if (e instanceof UnknownHostException) {
271            return API_ERROR_UNKNOWN_HOST;
272        } else if (e instanceof ConnectException) {
273            return API_ERROR_CONNECT;
274        } else if (e instanceof SSLHandshakeException) {
275            return API_ERROR_SSL_HANDSHAKE;
276        } else {
277            Log.d(Config.LOGTAG, e.getClass().getName());
278            return API_ERROR_OTHER;
279        }
280    }
281
282    public boolean isVerifying() {
283        return mVerificationInProgress.get();
284    }
285
286    public boolean isRequestingVerification() {
287        return mVerificationRequestInProgress.get();
288    }
289
290
291    @Override
292    public boolean isSynchronizing() {
293        return mRunningSyncJobs.get() > 0;
294    }
295
296    @Override
297    public void considerSync() {
298        considerSync(false);
299    }
300
301    @Override
302    public void considerSyncBackground(final boolean forced) {
303        mRunningSyncJobs.incrementAndGet();
304        mSerialSingleThreadExecutor.execute(() -> {
305            considerSync(forced);
306            if (mRunningSyncJobs.decrementAndGet() == 0) {
307                service.updateRosterUi();
308            }
309        });
310    }
311
312
313    private void considerSync(boolean forced) {
314        Map<String, PhoneNumberContact> contacts = PhoneNumberContact.load(service);
315        for (Account account : service.getAccounts()) {
316            refresh(account, contacts.values());
317            if (!considerSync(account, contacts, forced)) {
318                service.syncRoster(account);
319            }
320        }
321    }
322
323    private void refresh(Account account, Collection<PhoneNumberContact> contacts) {
324        for (Contact contact : account.getRoster().getWithSystemAccounts(PhoneNumberContact.class)) {
325            final Uri uri = contact.getSystemAccount();
326            if (uri == null) {
327                continue;
328            }
329            PhoneNumberContact phoneNumberContact = PhoneNumberContact.findByUri(contacts, uri);
330            final boolean needsCacheClean;
331            if (phoneNumberContact != null) {
332                needsCacheClean = contact.setPhoneContact(phoneNumberContact);
333            } else {
334                needsCacheClean = contact.unsetPhoneContact(PhoneNumberContact.class);
335                Log.d(Config.LOGTAG, uri.toString() + " vanished from address book");
336            }
337            if (needsCacheClean) {
338                service.getAvatarService().clear(contact);
339            }
340        }
341    }
342
343    private boolean considerSync(Account account, final Map<String, PhoneNumberContact> contacts, final boolean forced) {
344        final int hash = contacts.keySet().hashCode();
345        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": consider sync of " + hash);
346        if (!mLastSyncAttempt.retry(hash) && !forced) {
347            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not attempt sync");
348            return false;
349        }
350        mRunningSyncJobs.incrementAndGet();
351        final Jid syncServer = Jid.of(API_DOMAIN);
352        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending phone list to " + syncServer);
353        List<Element> entries = new ArrayList<>();
354        for (PhoneNumberContact c : contacts.values()) {
355            entries.add(new Element("entry").setAttribute("number", c.getPhoneNumber()));
356        }
357        IqPacket query = new IqPacket(IqPacket.TYPE.GET);
358        query.setTo(syncServer);
359        Element book = new Element("phone-book", Namespace.SYNCHRONIZATION).setChildren(entries);
360        String statusQuo = Entry.statusQuo(contacts.values(), account.getRoster().getWithSystemAccounts(PhoneNumberContact.class));
361        book.setAttribute("ver", statusQuo);
362        query.addChild(book);
363        mLastSyncAttempt = Attempt.create(hash);
364        service.sendIqPacket(account, query, (a, response) -> {
365            if (response.getType() == IqPacket.TYPE.RESULT) {
366                final Element phoneBook = response.findChild("phone-book", Namespace.SYNCHRONIZATION);
367                if (phoneBook != null) {
368                    List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(PhoneNumberContact.class);
369                    for (Entry entry : Entry.ofPhoneBook(phoneBook)) {
370                        PhoneNumberContact phoneContact = contacts.get(entry.getNumber());
371                        if (phoneContact == null) {
372                            continue;
373                        }
374                        for (Jid jid : entry.getJids()) {
375                            Contact contact = account.getRoster().getContact(jid);
376                            final boolean needsCacheClean = contact.setPhoneContact(phoneContact);
377                            if (needsCacheClean) {
378                                service.getAvatarService().clear(contact);
379                            }
380                            withSystemAccounts.remove(contact);
381                        }
382                    }
383                    for (Contact contact : withSystemAccounts) {
384                        final boolean needsCacheClean = contact.unsetPhoneContact(PhoneNumberContact.class);
385                        if (needsCacheClean) {
386                            service.getAvatarService().clear(contact);
387                        }
388                    }
389                } else {
390                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": phone number contact list remains unchanged");
391                }
392            } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
393                mLastSyncAttempt = Attempt.NULL;
394            } else {
395                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": failed to sync contact list with api server");
396            }
397            mRunningSyncJobs.decrementAndGet();
398            service.syncRoster(account);
399            service.updateRosterUi();
400        });
401        return true;
402    }
403
404
405    public interface OnVerificationRequested {
406        void onVerificationRequestFailed(int code);
407
408        void onVerificationRequested();
409
410        void onVerificationRequestedRetryAt(long timestamp);
411    }
412
413    public interface OnVerification {
414        void onVerificationFailed(int code);
415
416        void onVerificationSucceeded();
417
418        void onVerificationRetryAt(long timestamp);
419    }
420
421    private static class Attempt {
422        private final long timestamp;
423        private int hash;
424
425        private static final Attempt NULL = new Attempt(0, 0);
426
427        private Attempt(long timestamp, int hash) {
428            this.timestamp = timestamp;
429            this.hash = hash;
430        }
431
432        public static Attempt create(int hash) {
433            return new Attempt(SystemClock.elapsedRealtime(), hash);
434        }
435
436        public boolean retry(int hash) {
437            return hash != this.hash || SystemClock.elapsedRealtime() - timestamp >= Config.CONTACT_SYNC_RETRY_INTERVAL;
438        }
439    }
440}