Conversation.java revision 445fb5abf8804279e591d1c35657c9162625135e
1package com.android.mms.data;
2
3import java.util.HashSet;
4import java.util.Iterator;
5import java.util.Set;
6
7import android.content.AsyncQueryHandler;
8import android.content.ContentUris;
9import android.content.ContentValues;
10import android.content.Context;
11import android.database.Cursor;
12import android.net.Uri;
13import android.provider.Telephony.MmsSms;
14import android.provider.Telephony.Threads;
15import android.provider.Telephony.Sms.Conversations;
16import android.text.TextUtils;
17import android.util.Log;
18
19import com.android.mms.R;
20import com.android.mms.LogTag;
21import com.android.mms.transaction.MessagingNotification;
22import com.android.mms.ui.MessageUtils;
23import com.android.mms.util.DraftCache;
24
25/**
26 * An interface for finding information about conversations and/or creating new ones.
27 */
28public class Conversation {
29    private static final String TAG = "Mms/conv";
30    private static final boolean DEBUG = false;
31
32    private static final Uri sAllThreadsUri =
33        Threads.CONTENT_URI.buildUpon().appendQueryParameter("simple", "true").build();
34
35    private static final String[] ALL_THREADS_PROJECTION = {
36        Threads._ID, Threads.DATE, Threads.MESSAGE_COUNT, Threads.RECIPIENT_IDS,
37        Threads.SNIPPET, Threads.SNIPPET_CHARSET, Threads.READ, Threads.ERROR,
38        Threads.HAS_ATTACHMENT
39    };
40    private static final int ID             = 0;
41    private static final int DATE           = 1;
42    private static final int MESSAGE_COUNT  = 2;
43    private static final int RECIPIENT_IDS  = 3;
44    private static final int SNIPPET        = 4;
45    private static final int SNIPPET_CS     = 5;
46    private static final int READ           = 6;
47    private static final int ERROR          = 7;
48    private static final int HAS_ATTACHMENT = 8;
49
50
51    private final Context mContext;
52
53    // The thread ID of this conversation.  Can be zero in the case of a
54    // new conversation where the recipient set is changing as the user
55    // types and we have not hit the database yet to create a thread.
56    private long mThreadId;
57
58    private ContactList mRecipients;    // The current set of recipients.
59    private long mDate;                 // The last update time.
60    private int mMessageCount;          // Number of messages.
61    private String mSnippet;            // Text of the most recent message.
62    private boolean mHasUnreadMessages; // True if there are unread messages.
63    private boolean mHasAttachment;     // True if any message has an attachment.
64    private boolean mHasError;          // True if any message is in an error state.
65
66    private static ContentValues mReadContentValues;
67    private static boolean mLoadingThreads;
68
69
70    private Conversation(Context context) {
71        mContext = context;
72        mRecipients = new ContactList();
73        mThreadId = 0;
74    }
75
76    private Conversation(Context context, long threadId) {
77        mContext = context;
78        if (!loadFromThreadId(threadId)) {
79            mRecipients = new ContactList();
80            mThreadId = 0;
81        }
82    }
83
84    private Conversation(Context context, Cursor cursor, boolean allowQuery) {
85        mContext = context;
86        fillFromCursor(context, this, cursor, allowQuery);
87    }
88
89    /**
90     * Create a new conversation with no recipients.  {@link setRecipients} can
91     * be called as many times as you like; the conversation will not be
92     * created in the database until {@link ensureThreadId} is called.
93     */
94    public static Conversation createNew(Context context) {
95        return new Conversation(context);
96    }
97
98    /**
99     * Find the conversation matching the provided thread ID.
100     */
101    public static Conversation get(Context context, long threadId) {
102        synchronized (Cache.getInstance()) {
103            Conversation conv = Cache.get(threadId);
104            if (conv != null)
105                return conv;
106
107            conv = new Conversation(context, threadId);
108            try {
109                Cache.put(conv);
110            } catch (IllegalStateException e) {
111                LogTag.error("Tried to add duplicate Conversation to Cache");
112            }
113            return conv;
114        }
115    }
116
117    /**
118     * Find the conversation matching the provided recipient set.
119     * When called with an empty recipient list, equivalent to {@link createEmpty}.
120     */
121    public static Conversation get(Context context, ContactList recipients) {
122        // If there are no recipients in the list, make a new conversation.
123        if (recipients.size() < 1) {
124            return createNew(context);
125        }
126
127        synchronized (Cache.getInstance()) {
128            Conversation conv = Cache.get(recipients);
129            if (conv != null)
130                return conv;
131
132            long threadId = getOrCreateThreadId(context, recipients);
133            conv = new Conversation(context, threadId);
134
135            try {
136                Cache.put(conv);
137            } catch (IllegalStateException e) {
138                LogTag.error("Tried to add duplicate Conversation to Cache");
139            }
140
141            return conv;
142        }
143    }
144
145    /**
146     * Find the conversation matching in the specified Uri.  Example
147     * forms: {@value content://mms-sms/conversations/3} or
148     * {@value sms:+12124797990}.
149     * When called with a null Uri, equivalent to {@link createEmpty}.
150     */
151    public static Conversation get(Context context, Uri uri) {
152        if (uri == null) {
153            return createNew(context);
154        }
155
156        if (DEBUG) {
157            Log.v(TAG, "Conversation get URI: " + uri);
158        }
159        // Handle a conversation URI
160        if (uri.getPathSegments().size() >= 2) {
161            try {
162                long threadId = Long.parseLong(uri.getPathSegments().get(1));
163                if (DEBUG) {
164                    Log.v(TAG, "Conversation get threadId: " + threadId);
165                }
166                return get(context, threadId);
167            } catch (NumberFormatException exception) {
168                LogTag.error("Invalid URI: " + uri);
169            }
170        }
171
172        String recipient = uri.getSchemeSpecificPart();
173        return get(context, ContactList.getByNumbers(recipient,
174                false /* don't block */, true /* replace number */));
175    }
176
177    /**
178     * Returns true if the recipient in the uri matches the recipient list in this
179     * conversation.
180     */
181    public boolean sameRecipient(Uri uri) {
182        int size = mRecipients.size();
183        if (size > 1) {
184            return false;
185        }
186        if (uri == null) {
187            return size == 0;
188        }
189        if (uri.getPathSegments().size() >= 2) {
190            return false;       // it's a thread id for a conversation
191        }
192        String recipient = uri.getSchemeSpecificPart();
193        ContactList incomingRecipient = ContactList.getByNumbers(recipient,
194                false /* don't block */, false /* don't replace number */);
195        return mRecipients.equals(incomingRecipient);
196    }
197
198    /**
199     * Returns a temporary Conversation (not representing one on disk) wrapping
200     * the contents of the provided cursor.  The cursor should be the one
201     * returned to your AsyncQueryHandler passed in to {@link startQueryForAll}.
202     * The recipient list of this conversation can be empty if the results
203     * were not in cache.
204     */
205    // TODO: check why can't load a cached Conversation object here.
206    public static Conversation from(Context context, Cursor cursor) {
207        return new Conversation(context, cursor, false);
208    }
209
210    private void buildReadContentValues() {
211        if (mReadContentValues == null) {
212            mReadContentValues = new ContentValues(1);
213            mReadContentValues.put("read", 1);
214        }
215    }
216
217    /**
218     * Marks all messages in this conversation as read and updates
219     * relevant notifications.  This method returns immediately;
220     * work is dispatched to a background thread.
221     */
222    public synchronized void markAsRead() {
223        // If we have no Uri to mark (as in the case of a conversation that
224        // has not yet made its way to disk), there's nothing to do.
225        final Uri threadUri = getUri();
226
227        new Thread(new Runnable() {
228            public void run() {
229                if (threadUri != null) {
230                    buildReadContentValues();
231                    mContext.getContentResolver().update(threadUri, mReadContentValues,
232                            "read=0", null);
233                    mHasUnreadMessages = false;
234                }
235                // Always update notifications regardless of the read state.
236                MessagingNotification.updateAllNotifications(mContext);
237            }
238        }).start();
239    }
240
241    /**
242     * Returns a content:// URI referring to this conversation,
243     * or null if it does not exist on disk yet.
244     */
245    public synchronized Uri getUri() {
246        if (mThreadId <= 0)
247            return null;
248
249        return ContentUris.withAppendedId(Threads.CONTENT_URI, mThreadId);
250    }
251
252    /**
253     * Return the Uri for all messages in the given thread ID.
254     * @deprecated
255     */
256    public static Uri getUri(long threadId) {
257        // TODO: Callers using this should really just have a Conversation
258        // and call getUri() on it, but this guarantees no blocking.
259        return ContentUris.withAppendedId(Threads.CONTENT_URI, threadId);
260    }
261
262    /**
263     * Returns the thread ID of this conversation.  Can be zero if
264     * {@link ensureThreadId} has not been called yet.
265     */
266    public synchronized long getThreadId() {
267        return mThreadId;
268    }
269
270    /**
271     * Guarantees that the conversation has been created in the database.
272     * This will make a blocking database call if it hasn't.
273     *
274     * @return The thread ID of this conversation in the database
275     */
276    public synchronized long ensureThreadId() {
277        if (DEBUG) {
278            LogTag.debug("ensureThreadId before: " + mThreadId);
279        }
280        if (mThreadId <= 0) {
281            mThreadId = getOrCreateThreadId(mContext, mRecipients);
282        }
283        if (DEBUG) {
284            LogTag.debug("ensureThreadId after: " + mThreadId);
285        }
286
287        return mThreadId;
288    }
289
290    public synchronized void clearThreadId() {
291        // remove ourself from the cache
292        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
293            LogTag.debug("clearThreadId old threadId was: " + mThreadId + " now zero");
294        }
295        Cache.remove(mThreadId);
296
297        mThreadId = 0;
298    }
299
300    /**
301     * Sets the list of recipients associated with this conversation.
302     * If called, {@link ensureThreadId} must be called before the next
303     * operation that depends on this conversation existing in the
304     * database (e.g. storing a draft message to it).
305     */
306    public synchronized void setRecipients(ContactList list) {
307        mRecipients = list;
308
309        // Invalidate thread ID because the recipient set has changed.
310        mThreadId = 0;
311    }
312
313    /**
314     * Returns the recipient set of this conversation.
315     */
316    public synchronized ContactList getRecipients() {
317        return mRecipients;
318    }
319
320    /**
321     * Returns true if a draft message exists in this conversation.
322     */
323    public synchronized boolean hasDraft() {
324        if (mThreadId <= 0)
325            return false;
326
327        return DraftCache.getInstance().hasDraft(mThreadId);
328    }
329
330    /**
331     * Sets whether or not this conversation has a draft message.
332     */
333    public synchronized void setDraftState(boolean hasDraft) {
334        if (mThreadId <= 0)
335            return;
336
337        DraftCache.getInstance().setDraftState(mThreadId, hasDraft);
338    }
339
340    /**
341     * Returns the time of the last update to this conversation in milliseconds,
342     * on the {@link System.currentTimeMillis} timebase.
343     */
344    public synchronized long getDate() {
345        return mDate;
346    }
347
348    /**
349     * Returns the number of messages in this conversation, excluding the draft
350     * (if it exists).
351     */
352    public synchronized int getMessageCount() {
353        return mMessageCount;
354    }
355
356    /**
357     * Returns a snippet of text from the most recent message in the conversation.
358     */
359    public synchronized String getSnippet() {
360        return mSnippet;
361    }
362
363    /**
364     * Returns true if there are any unread messages in the conversation.
365     */
366    public synchronized boolean hasUnreadMessages() {
367        return mHasUnreadMessages;
368    }
369
370    /**
371     * Returns true if any messages in the conversation have attachments.
372     */
373    public synchronized boolean hasAttachment() {
374        return mHasAttachment;
375    }
376
377    /**
378     * Returns true if any messages in the conversation are in an error state.
379     */
380    public synchronized boolean hasError() {
381        return mHasError;
382    }
383
384    private static long getOrCreateThreadId(Context context, ContactList list) {
385        HashSet<String> recipients = new HashSet<String>();
386        Contact cacheContact = null;
387        for (Contact c : list) {
388            cacheContact = Contact.get(c.getNumber(),true);
389            if (cacheContact != null) {
390                recipients.add(cacheContact.getNumber());
391            } else {
392                recipients.add(c.getNumber());
393            }
394        }
395        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
396            LogTag.debug("getOrCreateThreadId %s", recipients);
397        }
398        return Threads.getOrCreateThreadId(context, recipients);
399    }
400
401    /*
402     * The primary key of a conversation is its recipient set; override
403     * equals() and hashCode() to just pass through to the internal
404     * recipient sets.
405     */
406    @Override
407    public synchronized boolean equals(Object obj) {
408        try {
409            Conversation other = (Conversation)obj;
410            return (mRecipients.equals(other.mRecipients));
411        } catch (ClassCastException e) {
412            return false;
413        }
414    }
415
416    @Override
417    public synchronized int hashCode() {
418        return mRecipients.hashCode();
419    }
420
421    @Override
422    public synchronized String toString() {
423        return String.format("[%s] (tid %d)", mRecipients.serialize(), mThreadId);
424    }
425
426    /**
427     * Remove any obsolete conversations sitting around on disk.
428     * @deprecated
429     */
430    public static void cleanup(Context context) {
431        // TODO: Get rid of this awful hack.
432        context.getContentResolver().delete(Threads.OBSOLETE_THREADS_URI, null, null);
433    }
434
435    /**
436     * Start a query for all conversations in the database on the specified
437     * AsyncQueryHandler.
438     *
439     * @param handler An AsyncQueryHandler that will receive onQueryComplete
440     *                upon completion of the query
441     * @param token   The token that will be passed to onQueryComplete
442     */
443    public static void startQueryForAll(AsyncQueryHandler handler, int token) {
444        handler.cancelOperation(token);
445        handler.startQuery(token, null, sAllThreadsUri,
446                ALL_THREADS_PROJECTION, null, null, Conversations.DEFAULT_SORT_ORDER);
447    }
448
449    /**
450     * Start a delete of the conversation with the specified thread ID.
451     *
452     * @param handler An AsyncQueryHandler that will receive onDeleteComplete
453     *                upon completion of the conversation being deleted
454     * @param token   The token that will be passed to onDeleteComplete
455     * @param deleteAll Delete the whole thread including locked messages
456     * @param threadId Thread ID of the conversation to be deleted
457     */
458    public static void startDelete(AsyncQueryHandler handler, int token, boolean deleteAll,
459            long threadId) {
460        Uri uri = ContentUris.withAppendedId(Threads.CONTENT_URI, threadId);
461        String selection = deleteAll ? null : "locked=0";
462        handler.startDelete(token, null, uri, selection, null);
463    }
464
465    /**
466     * Start deleting all conversations in the database.
467     * @param handler An AsyncQueryHandler that will receive onDeleteComplete
468     *                upon completion of all conversations being deleted
469     * @param token   The token that will be passed to onDeleteComplete
470     * @param deleteAll Delete the whole thread including locked messages
471     */
472    public static void startDeleteAll(AsyncQueryHandler handler, int token, boolean deleteAll) {
473        String selection = deleteAll ? null : "locked=0";
474        handler.startDelete(token, null, Threads.CONTENT_URI, selection, null);
475    }
476
477    /**
478     * Check for locked messages in all threads or a specified thread.
479     * @param handler An AsyncQueryHandler that will receive onQueryComplete
480     *                upon completion of looking for locked messages
481     * @param threadId   The threadId of the thread to search. -1 means all threads
482     * @param token   The token that will be passed to onQueryComplete
483     */
484    public static void startQueryHaveLockedMessages(AsyncQueryHandler handler, long threadId,
485            int token) {
486        handler.cancelOperation(token);
487        Uri uri = MmsSms.CONTENT_LOCKED_URI;
488        if (threadId != -1) {
489            uri = ContentUris.withAppendedId(uri, threadId);
490        }
491        handler.startQuery(token, new Long(threadId), uri,
492                ALL_THREADS_PROJECTION, null, null, Conversations.DEFAULT_SORT_ORDER);
493    }
494
495    /**
496     * Fill the specified conversation with the values from the specified
497     * cursor, possibly setting recipients to empty if {@value allowQuery}
498     * is false and the recipient IDs are not in cache.  The cursor should
499     * be one made via {@link startQueryForAll}.
500     */
501    private static void fillFromCursor(Context context, Conversation conv,
502                                       Cursor c, boolean allowQuery) {
503        synchronized (conv) {
504            conv.mThreadId = c.getLong(ID);
505            conv.mDate = c.getLong(DATE);
506            conv.mMessageCount = c.getInt(MESSAGE_COUNT);
507
508            // Replace the snippet with a default value if it's empty.
509            String snippet = MessageUtils.extractEncStrFromCursor(c, SNIPPET, SNIPPET_CS);
510            if (TextUtils.isEmpty(snippet)) {
511                snippet = context.getString(R.string.no_subject_view);
512            }
513            conv.mSnippet = snippet;
514
515            conv.mHasUnreadMessages = (c.getInt(READ) == 0);
516            conv.mHasError = (c.getInt(ERROR) != 0);
517            conv.mHasAttachment = (c.getInt(HAS_ATTACHMENT) != 0);
518
519            String recipientIds = c.getString(RECIPIENT_IDS);
520            conv.mRecipients = ContactList.getByIds(recipientIds, allowQuery);
521        }
522    }
523
524    /**
525     * Private cache for the use of the various forms of Conversation.get.
526     */
527    private static class Cache {
528        private static Cache sInstance = new Cache();
529        static Cache getInstance() { return sInstance; }
530        private final HashSet<Conversation> mCache;
531        private Cache() {
532            mCache = new HashSet<Conversation>(10);
533        }
534
535        /**
536         * Return the conversation with the specified thread ID, or
537         * null if it's not in cache.
538         */
539        static Conversation get(long threadId) {
540            synchronized (sInstance) {
541                if (DEBUG) {
542                    LogTag.debug("Conversation get with threadId: " + threadId);
543                }
544                dumpCache();
545                for (Conversation c : sInstance.mCache) {
546                    if (DEBUG) {
547                        LogTag.debug("Conversation get() threadId: " + threadId +
548                                " c.getThreadId(): " + c.getThreadId());
549                    }
550                    if (c.getThreadId() == threadId) {
551                        return c;
552                    }
553                }
554            }
555            return null;
556        }
557
558        /**
559         * Return the conversation with the specified recipient
560         * list, or null if it's not in cache.
561         */
562        static Conversation get(ContactList list) {
563            synchronized (sInstance) {
564                if (DEBUG) {
565                    LogTag.debug("Conversation get with ContactList: " + list);
566                    dumpCache();
567                }
568                for (Conversation c : sInstance.mCache) {
569                    if (c.getRecipients().equals(list)) {
570                        return c;
571                    }
572                }
573            }
574            return null;
575        }
576
577        /**
578         * Put the specified conversation in the cache.  The caller
579         * should not place an already-existing conversation in the
580         * cache, but rather update it in place.
581         */
582        static void put(Conversation c) {
583            synchronized (sInstance) {
584                // We update cache entries in place so people with long-
585                // held references get updated.
586                if (DEBUG) {
587                    LogTag.debug("Conversation c: " + c + " put with threadid: " + c.getThreadId() +
588                            " c.hash: " + c.hashCode());
589                    dumpCache();
590                }
591
592                if (sInstance.mCache.contains(c)) {
593                    throw new IllegalStateException("cache already contains " + c +
594                            " threadId: " + c.mThreadId);
595                }
596                sInstance.mCache.add(c);
597            }
598        }
599
600        static void remove(long threadId) {
601            if (DEBUG) {
602                LogTag.debug("remove threadid: " + threadId);
603                dumpCache();
604            }
605            for (Conversation c : sInstance.mCache) {
606                if (c.getThreadId() == threadId) {
607                    sInstance.mCache.remove(c);
608                    return;
609                }
610            }
611        }
612
613        static void dumpCache() {
614            if (DEBUG) {
615                synchronized (sInstance) {
616                    LogTag.debug("Conversation dumpCache: ");
617                    for (Conversation c : sInstance.mCache) {
618                        LogTag.debug("   c: " + c + " c.getThreadId(): " + c.getThreadId() +
619                                " hash: " + c.hashCode());
620                    }
621                }
622            }
623        }
624
625        /**
626         * Remove all conversations from the cache that are not in
627         * the provided set of thread IDs.
628         */
629        static void keepOnly(Set<Long> threads) {
630            synchronized (sInstance) {
631                Iterator<Conversation> iter = sInstance.mCache.iterator();
632                while (iter.hasNext()) {
633                    Conversation c = iter.next();
634                    if (!threads.contains(c.getThreadId())) {
635                        iter.remove();
636                    }
637                }
638            }
639        }
640    }
641
642    /**
643     * Set up the conversation cache.  To be called once at application
644     * startup time.
645     */
646    public static void init(final Context context) {
647        new Thread(new Runnable() {
648            public void run() {
649                cacheAllThreads(context);
650            }
651        }).start();
652    }
653
654    /**
655     * Are we in the process of loading and caching all the threads?.
656     */
657   public static boolean loadingThreads() {
658        return mLoadingThreads;
659    }
660
661    private static void cacheAllThreads(Context context) {
662        synchronized (Cache.getInstance()) {
663            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
664                LogTag.debug("[Conversation] cacheAllThreads");
665            }
666            mLoadingThreads = true;
667
668            // Keep track of what threads are now on disk so we
669            // can discard anything removed from the cache.
670            HashSet<Long> threadsOnDisk = new HashSet<Long>();
671
672            // Query for all conversations.
673            Cursor c = context.getContentResolver().query(sAllThreadsUri,
674                    ALL_THREADS_PROJECTION, null, null, null);
675            try {
676                while (c.moveToNext()) {
677                    long threadId = c.getLong(ID);
678                    threadsOnDisk.add(threadId);
679
680                    // Try to find this thread ID in the cache.
681                    Conversation conv = Cache.get(threadId);
682
683                    if (conv == null) {
684                        // Make a new Conversation and put it in
685                        // the cache if necessary.
686                        conv = new Conversation(context, c, true);
687                        try {
688                            Cache.put(conv);
689                        } catch (IllegalStateException e) {
690                            LogTag.error("Tried to add duplicate Conversation to Cache");
691                        }
692                    } else {
693                        // Or update in place so people with references
694                        // to conversations get updated too.
695                        fillFromCursor(context, conv, c, true);
696                    }
697                }
698            } finally {
699                c.close();
700                mLoadingThreads = false;
701            }
702
703            // Purge the cache of threads that no longer exist on disk.
704            Cache.keepOnly(threadsOnDisk);
705        }
706    }
707
708    private boolean loadFromThreadId(long threadId) {
709        Cursor c = mContext.getContentResolver().query(sAllThreadsUri, ALL_THREADS_PROJECTION,
710                "_id=" + Long.toString(threadId), null, null);
711        try {
712            if (c.moveToFirst()) {
713                fillFromCursor(mContext, this, c, true);
714            } else {
715                LogTag.error("loadFromThreadId: Can't find thread ID " + threadId);
716                return false;
717            }
718        } finally {
719            c.close();
720        }
721        return true;
722    }
723}
724