summaryrefslogtreecommitdiffstats
path: root/src/com/android/messaging/datamodel/ParticipantRefresh.java
blob: 532449643cd761322e17b8dddd1637cf38b625c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.messaging.datamodel;

import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Color;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.util.ArrayMap;
import android.telephony.SubscriptionInfo;
import android.text.TextUtils;

import com.android.messaging.Factory;
import com.android.messaging.datamodel.DatabaseHelper.ConversationColumns;
import com.android.messaging.datamodel.DatabaseHelper.ConversationParticipantsColumns;
import com.android.messaging.datamodel.DatabaseHelper.ParticipantColumns;
import com.android.messaging.datamodel.data.ParticipantData;
import com.android.messaging.datamodel.data.ParticipantData.ParticipantsQuery;
import com.android.messaging.ui.UIIntents;
import com.android.messaging.util.Assert;
import com.android.messaging.util.ContactUtil;
import com.android.messaging.util.LogUtil;
import com.android.messaging.util.OsUtil;
import com.android.messaging.util.PhoneUtils;
import com.android.messaging.util.SafeAsyncTask;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Utility class for refreshing participant information based on matching contact. This updates
 *     1. name, photo_uri, matching contact_id of participants.
 *     2. generated_name of conversations.
 *
 * There are two kinds of participant refreshes,
 *     1. Full refresh, this is triggered at application start or activity resumes after contact
 *        change is detected.
 *     2. Partial refresh, this is triggered when a participant is added to a conversation. This
 *        normally happens during SMS sync.
 */
@VisibleForTesting
public class ParticipantRefresh {
    private static final String TAG = LogUtil.BUGLE_DATAMODEL_TAG;

    /**
     * Refresh all participants including ones that were resolved before.
     */
    public static final int REFRESH_MODE_FULL = 0;

    /**
     * Refresh all unresolved participants.
     */
    public static final int REFRESH_MODE_INCREMENTAL = 1;

    /**
     * Force refresh all self participants.
     */
    public static final int REFRESH_MODE_SELF_ONLY = 2;

    public static class ConversationParticipantsQuery {
        public static final String[] PROJECTION = new String[] {
            ConversationParticipantsColumns._ID,
            ConversationParticipantsColumns.CONVERSATION_ID,
            ConversationParticipantsColumns.PARTICIPANT_ID
        };

        public static final int INDEX_ID                        = 0;
        public static final int INDEX_CONVERSATION_ID           = 1;
        public static final int INDEX_PARTICIPANT_ID            = 2;
    }

    // Track whether observer is initialized or not.
    private static volatile boolean sObserverInitialized = false;
    private static final Object sLock = new Object();
    private static final AtomicBoolean sFullRefreshScheduled = new AtomicBoolean(false);
    private static final Runnable sFullRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            final boolean oldScheduled = sFullRefreshScheduled.getAndSet(false);
            Assert.isTrue(oldScheduled);
            refreshParticipants(REFRESH_MODE_FULL);
        }
    };
    private static final Runnable sSelfOnlyRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            refreshParticipants(REFRESH_MODE_SELF_ONLY);
        }
    };

    /**
     * A customized content resolver to track contact changes.
     */
    public static class ContactContentObserver extends ContentObserver {
        private volatile boolean mContactChanged = false;

        public ContactContentObserver() {
            super(null);
        }

        @Override
        public void onChange(final boolean selfChange) {
            super.onChange(selfChange);
            if (LogUtil.isLoggable(TAG, LogUtil.VERBOSE)) {
                LogUtil.v(TAG, "Contacts changed");
            }
            mContactChanged = true;
        }

        public boolean getContactChanged() {
            return mContactChanged;
        }

        public void resetContactChanged() {
            mContactChanged = false;
        }

        public void initialize() {
            // TODO: Handle enterprise contacts post M once contacts provider supports it
            Factory.get().getApplicationContext().getContentResolver().registerContentObserver(
                    Phone.CONTENT_URI, true, this);
            mContactChanged = true; // Force a full refresh on initialization.
        }
    }

    /**
     * Refresh participants only if needed, i.e., application start or contact changed.
     */
    public static void refreshParticipantsIfNeeded() {
        if (ParticipantRefresh.getNeedFullRefresh() &&
                sFullRefreshScheduled.compareAndSet(false, true)) {
            if (LogUtil.isLoggable(TAG, LogUtil.VERBOSE)) {
                LogUtil.v(TAG, "Started full participant refresh");
            }
            SafeAsyncTask.executeOnThreadPool(sFullRefreshRunnable);
        } else if (LogUtil.isLoggable(TAG, LogUtil.VERBOSE)) {
            LogUtil.v(TAG, "Skipped full participant refresh");
        }
    }

    /**
     * Refresh self participants on subscription or settings change.
     */
    public static void refreshSelfParticipants() {
        SafeAsyncTask.executeOnThreadPool(sSelfOnlyRefreshRunnable);
    }

    private static boolean getNeedFullRefresh() {
        final ContactContentObserver observer = Factory.get().getContactContentObserver();
        if (observer == null) {
            // If there is no observer (for unittest cases), we don't need to refresh participants.
            return false;
        }

        if (!sObserverInitialized) {
            synchronized (sLock) {
                if (!sObserverInitialized) {
                    observer.initialize();
                    sObserverInitialized = true;
                }
            }
        }

        return observer.getContactChanged();
    }

    private static void resetNeedFullRefresh() {
        final ContactContentObserver observer = Factory.get().getContactContentObserver();
        if (observer != null) {
            observer.resetContactChanged();
        }
    }

    /**
     * This class is totally static. Make constructor to be private so that an instance
     * of this class would not be created by by mistake.
     */
    private ParticipantRefresh() {
    }

    /**
     * Refresh participants in Bugle.
     *
     * @param refreshMode the refresh mode desired. See {@link #REFRESH_MODE_FULL},
     *        {@link #REFRESH_MODE_INCREMENTAL}, and {@link #REFRESH_MODE_SELF_ONLY}
     */
     @VisibleForTesting
     static void refreshParticipants(final int refreshMode) {
        Assert.inRange(refreshMode, REFRESH_MODE_FULL, REFRESH_MODE_SELF_ONLY);
        if (LogUtil.isLoggable(TAG, LogUtil.VERBOSE)) {
            switch (refreshMode) {
                case REFRESH_MODE_FULL:
                    LogUtil.v(TAG, "Start full participant refresh");
                    break;
                case REFRESH_MODE_INCREMENTAL:
                    LogUtil.v(TAG, "Start partial participant refresh");
                    break;
                case REFRESH_MODE_SELF_ONLY:
                    LogUtil.v(TAG, "Start self participant refresh");
                    break;
            }
        }

        if (!ContactUtil.hasReadContactsPermission() || !OsUtil.hasPhonePermission()) {
            if (LogUtil.isLoggable(TAG, LogUtil.VERBOSE)) {
                LogUtil.v(TAG, "Skipping participant referesh because of permissions");
            }
            return;
        }

        if (refreshMode == REFRESH_MODE_FULL) {
            // resetNeedFullRefresh right away so that we will skip duplicated full refresh
            // requests.
            resetNeedFullRefresh();
        }

        if (refreshMode == REFRESH_MODE_FULL || refreshMode == REFRESH_MODE_SELF_ONLY) {
            refreshSelfParticipantList();
        }

        final ArrayList<String> changedParticipants = new ArrayList<String>();

        String selection = null;
        String[] selectionArgs = null;

        if (refreshMode == REFRESH_MODE_INCREMENTAL) {
            // In case of incremental refresh, filter out participants that are already resolved.
            selection = ParticipantColumns.CONTACT_ID + "=?";
            selectionArgs = new String[] {
                    String.valueOf(ParticipantData.PARTICIPANT_CONTACT_ID_NOT_RESOLVED) };
        } else if (refreshMode == REFRESH_MODE_SELF_ONLY) {
            // In case of self-only refresh, filter out non-self participants.
            selection = SELF_PARTICIPANTS_CLAUSE;
            selectionArgs = null;
        }

        final DatabaseWrapper db = DataModel.get().getDatabase();
        Cursor cursor = null;
        boolean selfUpdated = false;
        try {
            cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE,
                    ParticipantsQuery.PROJECTION, selection, selectionArgs, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    try {
                        final ParticipantData participantData =
                                ParticipantData.getFromCursor(cursor);
                        if (refreshParticipant(db, participantData)) {
                            if (participantData.isSelf()) {
                                selfUpdated = true;
                            }
                            updateParticipant(db, participantData);
                            final String id = participantData.getId();
                            changedParticipants.add(id);
                        }
                    } catch (final Exception exception) {
                        // Failure to update one participant shouldn't cancel the entire refresh.
                        // Log the failure so we know what's going on and resume the loop.
                        LogUtil.e(LogUtil.BUGLE_DATAMODEL_TAG, "ParticipantRefresh: Failed to " +
                                "update participant", exception);
                    }
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        if (LogUtil.isLoggable(TAG, LogUtil.VERBOSE)) {
            LogUtil.v(TAG, "Number of participants refreshed:" + changedParticipants.size());
        }

        // Refresh conversations for participants that are changed.
        if (changedParticipants.size() > 0) {
            BugleDatabaseOperations.refreshConversationsForParticipants(changedParticipants);
        }
        if (selfUpdated) {
            // Boom
            MessagingContentProvider.notifyAllParticipantsChanged();
            MessagingContentProvider.notifyAllMessagesChanged();
        }
    }

    private static final String SELF_PARTICIPANTS_CLAUSE = ParticipantColumns.SUB_ID
            + " NOT IN ( "
            + ParticipantData.OTHER_THAN_SELF_SUB_ID
            + " )";

    private static final Set<Integer> getExistingSubIds() {
        final DatabaseWrapper db = DataModel.get().getDatabase();
        final HashSet<Integer> existingSubIds = new HashSet<Integer>();

        Cursor cursor = null;
        try {
            cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE,
                    ParticipantsQuery.PROJECTION,
                    SELF_PARTICIPANTS_CLAUSE, null, null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    final int subId = cursor.getInt(ParticipantsQuery.INDEX_SUB_ID);
                    existingSubIds.add(subId);
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return existingSubIds;
    }

    private static final String UPDATE_SELF_PARTICIPANT_SUBSCRIPTION_SQL =
            "UPDATE " + DatabaseHelper.PARTICIPANTS_TABLE + " SET "
            +  ParticipantColumns.SIM_SLOT_ID + " = %d, "
            +  ParticipantColumns.SUBSCRIPTION_COLOR + " = %d, "
            +  ParticipantColumns.SUBSCRIPTION_NAME + " = %s "
            + " WHERE %s";

    static String getUpdateSelfParticipantSubscriptionInfoSql(final int slotId,
            final int subscriptionColor, final String subscriptionName, final String where) {
        return String.format((Locale) null /* construct SQL string without localization */,
                UPDATE_SELF_PARTICIPANT_SUBSCRIPTION_SQL,
                slotId, subscriptionColor, subscriptionName, where);
    }

    /**
     * Ensure that there is a self participant corresponding to every active SIM. Also, ensure
     * that any other older SIM self participants are marked as inactive.
     */
    private static void refreshSelfParticipantList() {
        if (!OsUtil.isAtLeastL_MR1()) {
            return;
        }

        final DatabaseWrapper db = DataModel.get().getDatabase();

        final List<SubscriptionInfo> subInfoRecords =
                PhoneUtils.getDefault().toLMr1().getActiveSubscriptionInfoList();
        final ArrayMap<Integer, SubscriptionInfo> activeSubscriptionIdToRecordMap =
                new ArrayMap<Integer, SubscriptionInfo>();
        db.beginTransaction();
        final Set<Integer> existingSubIds = getExistingSubIds();

        try {
            if (subInfoRecords != null) {
                for (final SubscriptionInfo subInfoRecord : subInfoRecords) {
                    final int subId = subInfoRecord.getSubscriptionId();
                    // If its a new subscription, add it to the database.
                    if (!existingSubIds.contains(subId)) {
                        db.execSQL(DatabaseHelper.getCreateSelfParticipantSql(subId));
                        // Add it to the local set to guard against duplicated entries returned
                        // by subscription manager.
                        existingSubIds.add(subId);
                    }
                    activeSubscriptionIdToRecordMap.put(subId, subInfoRecord);

                    if (subId == PhoneUtils.getDefault().getDefaultSmsSubscriptionId()) {
                        // This is the system default subscription, so update the default self.
                        activeSubscriptionIdToRecordMap.put(ParticipantData.DEFAULT_SELF_SUB_ID,
                                subInfoRecord);
                    }
                }
            }

            // For subscriptions already in the database, refresh ParticipantColumns.SIM_SLOT_ID.
            for (final Integer subId : activeSubscriptionIdToRecordMap.keySet()) {
                final SubscriptionInfo record = activeSubscriptionIdToRecordMap.get(subId);
                final String displayName =
                        DatabaseUtils.sqlEscapeString(record.getDisplayName().toString());
                db.execSQL(getUpdateSelfParticipantSubscriptionInfoSql(record.getSimSlotIndex(),
                        record.getIconTint(), displayName,
                        ParticipantColumns.SUB_ID + " = " + subId));
            }
            db.execSQL(getUpdateSelfParticipantSubscriptionInfoSql(
                    ParticipantData.INVALID_SLOT_ID, Color.TRANSPARENT, "''",
                    ParticipantColumns.SUB_ID + " NOT IN (" +
                    Joiner.on(", ").join(activeSubscriptionIdToRecordMap.keySet()) + ")"));
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        // Fix up conversation self ids by reverting to default self for conversations whose self
        // ids are no longer active.
        refreshConversationSelfIds();
    }

    /**
     * Refresh one participant.
     * @return true if the ParticipantData was changed
     */
    public static boolean refreshParticipant(final DatabaseWrapper db,
            final ParticipantData participantData) {
        boolean updated = false;

        if (participantData.isSelf()) {
            final int selfChange = refreshFromSelfProfile(db, participantData);

            if (selfChange == SELF_PROFILE_EXISTS) {
                // If a self-profile exists, it takes precedence over Contacts data. So we are done.
                return true;
            }

            updated = (selfChange == SELF_PHONE_NUMBER_OR_SUBSCRIPTION_CHANGED);

            // Fall-through and try to update based on Contacts data
        }

        updated |= refreshFromContacts(db, participantData);
        return updated;
    }

    private static final int SELF_PHONE_NUMBER_OR_SUBSCRIPTION_CHANGED = 1;
    private static final int SELF_PROFILE_EXISTS = 2;

    private static int refreshFromSelfProfile(final DatabaseWrapper db,
            final ParticipantData participantData) {
        int changed = 0;
        // Refresh the phone number based on information from telephony
        if (participantData.updatePhoneNumberForSelfIfChanged()) {
            changed = SELF_PHONE_NUMBER_OR_SUBSCRIPTION_CHANGED;
        }

        if (OsUtil.isAtLeastL_MR1()) {
            // Refresh the subscription info based on information from SubscriptionManager.
            final SubscriptionInfo subscriptionInfo =
                    PhoneUtils.get(participantData.getSubId()).toLMr1().getActiveSubscriptionInfo();
            if (participantData.updateSubscriptionInfoForSelfIfChanged(subscriptionInfo)) {
                changed = SELF_PHONE_NUMBER_OR_SUBSCRIPTION_CHANGED;
            }
        }

        // For self participant, try getting name/avatar from self profile in CP2 first.
        // TODO: in case of multi-sim, profile would not be able to be used for
        // different numbers. Need to figure out that.
        Cursor selfCursor = null;
        try {
            selfCursor = ContactUtil.getSelf(db.getContext()).performSynchronousQuery();
            if (selfCursor != null && selfCursor.getCount() > 0) {
                selfCursor.moveToNext();
                final long selfContactId = selfCursor.getLong(ContactUtil.INDEX_CONTACT_ID);
                participantData.setContactId(selfContactId);
                participantData.setFullName(selfCursor.getString(
                        ContactUtil.INDEX_DISPLAY_NAME));
                participantData.setFirstName(
                        ContactUtil.lookupFirstName(db.getContext(), selfContactId));
                participantData.setProfilePhotoUri(selfCursor.getString(
                        ContactUtil.INDEX_PHOTO_URI));
                participantData.setLookupKey(selfCursor.getString(
                        ContactUtil.INDEX_SELF_QUERY_LOOKUP_KEY));
                return SELF_PROFILE_EXISTS;
            }
        } catch (final Exception exception) {
            // It's possible for contact query to fail and we don't want that to crash our app.
            // However, we need to at least log the exception so we know something was wrong.
            LogUtil.e(LogUtil.BUGLE_DATAMODEL_TAG, "Participant refresh: failed to refresh " +
                    "participant. exception=" + exception);
        } finally {
            if (selfCursor != null) {
                selfCursor.close();
            }
        }
        return changed;
    }

    private static boolean refreshFromContacts(final DatabaseWrapper db,
            final ParticipantData participantData) {
        final String normalizedDestination = participantData.getNormalizedDestination();
        final long currentContactId = participantData.getContactId();
        final String currentDisplayName = participantData.getFullName();
        final String currentFirstName = participantData.getFirstName();
        final String currentPhotoUri = participantData.getProfilePhotoUri();
        final String currentContactDestination = participantData.getContactDestination();

        Cursor matchingContactCursor = null;
        long matchingContactId = -1;
        String matchingDisplayName = null;
        String matchingFirstName = null;
        String matchingPhotoUri = null;
        String matchingLookupKey = null;
        String matchingDestination = null;
        boolean updated = false;

        if (TextUtils.isEmpty(normalizedDestination)) {
            // The normalized destination can be "" for the self id if we can't get it from the
            // SIM.  Some contact providers throw an IllegalArgumentException if you lookup "",
            // so we early out.
            return false;
        }

        try {
            matchingContactCursor = ContactUtil.lookupDestination(db.getContext(),
                    normalizedDestination).performSynchronousQuery();
            if (matchingContactCursor == null || matchingContactCursor.getCount() == 0) {
                // If there is no match, mark the participant as contact not found.
                if (currentContactId != ParticipantData.PARTICIPANT_CONTACT_ID_NOT_FOUND) {
                    participantData.setContactId(ParticipantData.PARTICIPANT_CONTACT_ID_NOT_FOUND);
                    participantData.setFullName(null);
                    participantData.setFirstName(null);
                    participantData.setProfilePhotoUri(null);
                    participantData.setLookupKey(null);
                    updated = true;
                }
                return updated;
            }

            while (matchingContactCursor.moveToNext()) {
                final long contactId = matchingContactCursor.getLong(ContactUtil.INDEX_CONTACT_ID);
                // Pick either the first contact or the contact with same id as previous matched
                // contact id.
                if (matchingContactId == -1 || currentContactId == contactId) {
                    matchingContactId = contactId;
                    matchingDisplayName = matchingContactCursor.getString(
                            ContactUtil.INDEX_DISPLAY_NAME);
                    matchingFirstName = ContactUtil.lookupFirstName(db.getContext(), contactId);
                    matchingPhotoUri = matchingContactCursor.getString(
                            ContactUtil.INDEX_PHOTO_URI);
                    matchingLookupKey = matchingContactCursor.getString(
                            ContactUtil.INDEX_LOOKUP_KEY);
                    matchingDestination = matchingContactCursor.getString(
                            ContactUtil.INDEX_PHONE_EMAIL);
                }

                // There is no need to try other contacts if the current contactId was not filled...
                if (currentContactId < 0
                        // or we found the matching contact id
                        || currentContactId == contactId) {
                    break;
                }
            }
        } catch (final Exception exception) {
            // It's possible for contact query to fail and we don't want that to crash our app.
            // However, we need to at least log the exception so we know something was wrong.
            LogUtil.e(LogUtil.BUGLE_DATAMODEL_TAG, "Participant refresh: failed to refresh " +
                    "participant. exception=" + exception);
            return false;
        } finally {
            if (matchingContactCursor != null) {
                matchingContactCursor.close();
            }
        }

        // Update participant only if something changed.
        final boolean isContactIdChanged = (matchingContactId != currentContactId);
        final boolean isDisplayNameChanged =
                !TextUtils.equals(matchingDisplayName, currentDisplayName);
        final boolean isFirstNameChanged = !TextUtils.equals(matchingFirstName, currentFirstName);
        final boolean isPhotoUrlChanged = !TextUtils.equals(matchingPhotoUri, currentPhotoUri);
        final boolean isDestinationChanged = !TextUtils.equals(matchingDestination,
                currentContactDestination);

        if (isContactIdChanged || isDisplayNameChanged || isFirstNameChanged || isPhotoUrlChanged
                || isDestinationChanged) {
            participantData.setContactId(matchingContactId);
            participantData.setFullName(matchingDisplayName);
            participantData.setFirstName(matchingFirstName);
            participantData.setProfilePhotoUri(matchingPhotoUri);
            participantData.setLookupKey(matchingLookupKey);
            participantData.setContactDestination(matchingDestination);
            if (isDestinationChanged) {
                // Update the send destination to the new one entered by user in Contacts.
                participantData.setSendDestination(matchingDestination);
            }
            updated = true;
        }

        return updated;
    }

    /**
     * Update participant with matching contact's contactId, displayName and photoUri.
     */
    private static void updateParticipant(final DatabaseWrapper db,
            final ParticipantData participantData) {
        final ContentValues values = new ContentValues();
        if (participantData.isSelf()) {
            // Self participants can refresh their normalized phone numbers
            values.put(ParticipantColumns.NORMALIZED_DESTINATION,
                    participantData.getNormalizedDestination());
            values.put(ParticipantColumns.DISPLAY_DESTINATION,
                    participantData.getDisplayDestination());
        }
        values.put(ParticipantColumns.CONTACT_ID, participantData.getContactId());
        values.put(ParticipantColumns.LOOKUP_KEY, participantData.getLookupKey());
        values.put(ParticipantColumns.FULL_NAME, participantData.getFullName());
        values.put(ParticipantColumns.FIRST_NAME, participantData.getFirstName());
        values.put(ParticipantColumns.PROFILE_PHOTO_URI, participantData.getProfilePhotoUri());
        values.put(ParticipantColumns.CONTACT_DESTINATION, participantData.getContactDestination());
        values.put(ParticipantColumns.SEND_DESTINATION, participantData.getSendDestination());

        db.beginTransaction();
        try {
            db.update(DatabaseHelper.PARTICIPANTS_TABLE, values, ParticipantColumns._ID + "=?",
                    new String[] { participantData.getId() });
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    /**
     * Get a list of inactive self ids in the participants table.
     */
    private static List<String> getInactiveSelfParticipantIds() {
        final DatabaseWrapper db = DataModel.get().getDatabase();
        final List<String> inactiveSelf = new ArrayList<String>();

        final String selection = ParticipantColumns.SIM_SLOT_ID + "=? AND " +
                SELF_PARTICIPANTS_CLAUSE;
        Cursor cursor = null;
        try {
            cursor = db.query(DatabaseHelper.PARTICIPANTS_TABLE,
                    new String[] { ParticipantColumns._ID },
                    selection, new String[] { String.valueOf(ParticipantData.INVALID_SLOT_ID) },
                    null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    final String participantId = cursor.getString(0);
                    inactiveSelf.add(participantId);
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return inactiveSelf;
    }

    /**
     * Gets a list of conversations with the given self ids.
     */
    private static List<String> getConversationsWithSelfParticipantIds(final List<String> selfIds) {
        final DatabaseWrapper db = DataModel.get().getDatabase();
        final List<String> conversationIds = new ArrayList<String>();

        Cursor cursor = null;
        try {
            final StringBuilder selectionList = new StringBuilder();
            for (int i = 0; i < selfIds.size(); i++) {
                selectionList.append('?');
                if (i < selfIds.size() - 1) {
                    selectionList.append(',');
                }
            }
            final String selection =
                    ConversationColumns.CURRENT_SELF_ID + " IN (" + selectionList + ")";
            cursor = db.query(DatabaseHelper.CONVERSATIONS_TABLE,
                    new String[] { ConversationColumns._ID },
                    selection, selfIds.toArray(new String[0]),
                    null, null, null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    final String conversationId = cursor.getString(0);
                    conversationIds.add(conversationId);
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return conversationIds;
    }

    /**
     * Refresh one conversation's self id.
     */
    private static void updateConversationSelfId(final String conversationId,
            final String selfId) {
        final DatabaseWrapper db = DataModel.get().getDatabase();

        db.beginTransaction();
        try {
            BugleDatabaseOperations.updateConversationSelfIdInTransaction(db, conversationId,
                    selfId);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        MessagingContentProvider.notifyMessagesChanged(conversationId);
        MessagingContentProvider.notifyConversationMetadataChanged(conversationId);
        UIIntents.get().broadcastConversationSelfIdChange(db.getContext(), conversationId, selfId);
    }

    /**
     * After refreshing the self participant list, find all conversations with inactive self ids,
     * and switch them back to system default.
     */
    private static void refreshConversationSelfIds() {
        final List<String> inactiveSelfs = getInactiveSelfParticipantIds();
        if (inactiveSelfs.size() == 0) {
            return;
        }
        final List<String> conversationsToRefresh =
                getConversationsWithSelfParticipantIds(inactiveSelfs);
        if (conversationsToRefresh.size() == 0) {
            return;
        }
        final DatabaseWrapper db = DataModel.get().getDatabase();
        final ParticipantData defaultSelf =
                BugleDatabaseOperations.getOrCreateSelf(db, ParticipantData.DEFAULT_SELF_SUB_ID);

        if (defaultSelf != null) {
            for (final String conversationId : conversationsToRefresh) {
                updateConversationSelfId(conversationId, defaultSelf.getId());
            }
        }
    }
}