Message.java revision 72e2ea860f66f496537e37ebc0ddd2c670d4c651
1/**
2 * Copyright (c) 2012, Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.mail.providers;
18
19import android.content.AsyncQueryHandler;
20import android.content.ContentValues;
21import android.database.Cursor;
22import android.net.Uri;
23import android.os.Parcel;
24import android.os.Parcelable;
25import android.provider.BaseColumns;
26import android.text.Html;
27import android.text.SpannedString;
28import android.text.TextUtils;
29import android.text.util.Rfc822Token;
30import android.text.util.Rfc822Tokenizer;
31
32import com.android.mail.providers.UIProvider.MessageColumns;
33import com.android.mail.utils.Utils;
34import com.google.common.base.Objects;
35
36import java.util.Collections;
37import java.util.List;
38import java.util.regex.Pattern;
39
40
41public class Message implements Parcelable {
42    /**
43     * Regex pattern used to look for any inline images in message bodies, including Gmail-hosted
44     * relative-URL images, Gmail emoticons, and any external inline images (although we usually
45     * count on the server to detect external images).
46     */
47    private static Pattern INLINE_IMAGE_PATTERN = Pattern.compile("<img\\s+[^>]*src=",
48            Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
49
50    /**
51     * @see BaseColumns#_ID
52     */
53    public long id;
54    /**
55     * @see UIProvider.MessageColumns#SERVER_ID
56     */
57    public String serverId;
58    /**
59     * @see UIProvider.MessageColumns#URI
60     */
61    public Uri uri;
62    /**
63     * @see UIProvider.MessageColumns#CONVERSATION_ID
64     */
65    public Uri conversationUri;
66    /**
67     * @see UIProvider.MessageColumns#SUBJECT
68     */
69    public String subject;
70    /**
71     * @see UIProvider.MessageColumns#SNIPPET
72     */
73    public String snippet;
74    /**
75     * @see UIProvider.MessageColumns#FROM
76     */
77    public String from;
78    /**
79     * @see UIProvider.MessageColumns#TO
80     */
81    public String to;
82    /**
83     * @see UIProvider.MessageColumns#CC
84     */
85    public String cc;
86    /**
87     * @see UIProvider.MessageColumns#BCC
88     */
89    public String bcc;
90    /**
91     * @see UIProvider.MessageColumns#REPLY_TO
92     */
93    public String replyTo;
94    /**
95     * @see UIProvider.MessageColumns#DATE_RECEIVED_MS
96     */
97    public long dateReceivedMs;
98    /**
99     * @see UIProvider.MessageColumns#BODY_HTML
100     */
101    public String bodyHtml;
102    /**
103     * @see UIProvider.MessageColumns#BODY_TEXT
104     */
105    public String bodyText;
106    /**
107     * @see UIProvider.MessageColumns#EMBEDS_EXTERNAL_RESOURCES
108     */
109    public boolean embedsExternalResources;
110    /**
111     * @see UIProvider.MessageColumns#REF_MESSAGE_ID
112     */
113    public String refMessageId;
114    /**
115     * @see UIProvider.MessageColumns#DRAFT_TYPE
116     */
117    public int draftType;
118    /**
119     * @see UIProvider.MessageColumns#APPEND_REF_MESSAGE_CONTENT
120     */
121    public boolean appendRefMessageContent;
122    /**
123     * @see UIProvider.MessageColumns#HAS_ATTACHMENTS
124     */
125    public boolean hasAttachments;
126    /**
127     * @see UIProvider.MessageColumns#ATTACHMENT_LIST_URI
128     */
129    public Uri attachmentListUri;
130    /**
131     * @see UIProvider.MessageColumns#MESSAGE_FLAGS
132     */
133    public long messageFlags;
134    /**
135     * @see UIProvider.MessageColumns#SAVE_MESSAGE_URI
136     */
137    @Deprecated
138    public String saveUri;
139    /**
140     * @see UIProvider.MessageColumns#SEND_MESSAGE_URI
141     */
142    @Deprecated
143    public String sendUri;
144    /**
145     * @see UIProvider.MessageColumns#ALWAYS_SHOW_IMAGES
146     */
147    public boolean alwaysShowImages;
148    /**
149     * @see UIProvider.MessageColumns#READ
150     */
151    public boolean read;
152    /**
153     * @see UIProvider.MessageColumns#STARRED
154     */
155    public boolean starred;
156    /**
157     * @see UIProvider.MessageColumns#QUOTE_START_POS
158     */
159    public int quotedTextOffset;
160    /**
161     * @see UIProvider.MessageColumns#ATTACHMENTS
162     *<p>
163     * N.B. this value is NOT immutable and may change during conversation view render.
164     */
165    public String attachmentsJson;
166    /**
167     * @see UIProvider.MessageColumns#MESSAGE_ACCOUNT_URI
168     */
169    public Uri accountUri;
170    /**
171     * @see UIProvider.MessageColumns#EVENT_INTENT_URI
172     */
173    public Uri eventIntentUri;
174    /**
175     * @see UIProvider.MessageColumns#SPAM_WARNING_STRING
176     */
177    public String spamWarningString;
178    /**
179     * @see UIProvider.MessageColumns#SPAM_WARNING_LEVEL
180     */
181    public int spamWarningLevel;
182    /**
183     * @see UIProvider.MessageColumns#SPAM_WARNING_LINK_TYPE
184     */
185    public int spamLinkType;
186    /**
187     * @see UIProvider.MessageColumns#VIA_DOMAIN
188     */
189    public String viaDomain;
190    /**
191     * @see UIProvider.MessageColumns#IS_SENDING
192     */
193    public boolean isSending;
194
195    private transient String[] mFromAddresses = null;
196    private transient String[] mToAddresses = null;
197    private transient String[] mCcAddresses = null;
198    private transient String[] mBccAddresses = null;
199    private transient String[] mReplyToAddresses = null;
200
201    private transient List<Attachment> mAttachments = null;
202
203    @Override
204    public int describeContents() {
205        return 0;
206    }
207
208    @Override
209    public boolean equals(Object o) {
210        return this == o || (o != null && o instanceof Message
211                && Objects.equal(uri, ((Message) o).uri));
212    }
213
214    @Override
215    public int hashCode() {
216        return uri == null ? 0 : uri.hashCode();
217    }
218
219    @Override
220    public void writeToParcel(Parcel dest, int flags) {
221        dest.writeLong(id);
222        dest.writeString(serverId);
223        dest.writeParcelable(uri, 0);
224        dest.writeParcelable(conversationUri, 0);
225        dest.writeString(subject);
226        dest.writeString(snippet);
227        dest.writeString(from);
228        dest.writeString(to);
229        dest.writeString(cc);
230        dest.writeString(bcc);
231        dest.writeString(replyTo);
232        dest.writeLong(dateReceivedMs);
233        dest.writeString(bodyHtml);
234        dest.writeString(bodyText);
235        dest.writeInt(embedsExternalResources ? 1 : 0);
236        dest.writeString(refMessageId);
237        dest.writeInt(draftType);
238        dest.writeInt(appendRefMessageContent ? 1 : 0);
239        dest.writeInt(hasAttachments ? 1 : 0);
240        dest.writeParcelable(attachmentListUri, 0);
241        dest.writeLong(messageFlags);
242        dest.writeString(saveUri);
243        dest.writeString(sendUri);
244        dest.writeInt(alwaysShowImages ? 1 : 0);
245        dest.writeInt(quotedTextOffset);
246        dest.writeString(attachmentsJson);
247        dest.writeParcelable(accountUri, 0);
248        dest.writeParcelable(eventIntentUri, 0);
249        dest.writeString(spamWarningString);
250        dest.writeInt(spamWarningLevel);
251        dest.writeInt(spamLinkType);
252        dest.writeString(viaDomain);
253        dest.writeInt(isSending ? 1 : 0);
254    }
255
256    private Message(Parcel in) {
257        id = in.readLong();
258        serverId = in.readString();
259        uri = in.readParcelable(null);
260        conversationUri = in.readParcelable(null);
261        subject = in.readString();
262        snippet = in.readString();
263        from = in.readString();
264        to = in.readString();
265        cc = in.readString();
266        bcc = in.readString();
267        replyTo = in.readString();
268        dateReceivedMs = in.readLong();
269        bodyHtml = in.readString();
270        bodyText = in.readString();
271        embedsExternalResources = in.readInt() != 0;
272        refMessageId = in.readString();
273        draftType = in.readInt();
274        appendRefMessageContent = in.readInt() != 0;
275        hasAttachments = in.readInt() != 0;
276        attachmentListUri = in.readParcelable(null);
277        messageFlags = in.readLong();
278        saveUri = in.readString();
279        sendUri = in.readString();
280        alwaysShowImages = in.readInt() != 0;
281        quotedTextOffset = in.readInt();
282        attachmentsJson = in.readString();
283        accountUri = in.readParcelable(null);
284        eventIntentUri = in.readParcelable(null);
285        spamWarningString = in.readString();
286        spamWarningLevel = in.readInt();
287        spamLinkType = in.readInt();
288        viaDomain = in.readString();
289        isSending = in.readInt() != 0;
290    }
291
292    public Message() {
293
294    }
295
296    @Override
297    public String toString() {
298        return "[message id=" + id + "]";
299    }
300
301    public static final Creator<Message> CREATOR = new Creator<Message>() {
302
303        @Override
304        public Message createFromParcel(Parcel source) {
305            return new Message(source);
306        }
307
308        @Override
309        public Message[] newArray(int size) {
310            return new Message[size];
311        }
312
313    };
314
315    public Message(Cursor cursor) {
316        if (cursor != null) {
317            id = cursor.getLong(UIProvider.MESSAGE_ID_COLUMN);
318            serverId = cursor.getString(UIProvider.MESSAGE_SERVER_ID_COLUMN);
319            final String messageUriStr = cursor.getString(UIProvider.MESSAGE_URI_COLUMN);
320            uri = !TextUtils.isEmpty(messageUriStr) ? Uri.parse(messageUriStr) : null;
321            final String convUriStr = cursor.getString(UIProvider.MESSAGE_CONVERSATION_URI_COLUMN);
322            conversationUri = !TextUtils.isEmpty(convUriStr) ? Uri.parse(convUriStr) : null;
323            subject = cursor.getString(UIProvider.MESSAGE_SUBJECT_COLUMN);
324            snippet = cursor.getString(UIProvider.MESSAGE_SNIPPET_COLUMN);
325            from = cursor.getString(UIProvider.MESSAGE_FROM_COLUMN);
326            to = cursor.getString(UIProvider.MESSAGE_TO_COLUMN);
327            cc = cursor.getString(UIProvider.MESSAGE_CC_COLUMN);
328            bcc = cursor.getString(UIProvider.MESSAGE_BCC_COLUMN);
329            replyTo = cursor.getString(UIProvider.MESSAGE_REPLY_TO_COLUMN);
330            dateReceivedMs = cursor.getLong(UIProvider.MESSAGE_DATE_RECEIVED_MS_COLUMN);
331            bodyHtml = cursor.getString(UIProvider.MESSAGE_BODY_HTML_COLUMN);
332            bodyText = cursor.getString(UIProvider.MESSAGE_BODY_TEXT_COLUMN);
333            embedsExternalResources = cursor
334                    .getInt(UIProvider.MESSAGE_EMBEDS_EXTERNAL_RESOURCES_COLUMN) != 0;
335            refMessageId = cursor.getString(UIProvider.MESSAGE_REF_MESSAGE_ID_COLUMN);
336            draftType = cursor.getInt(UIProvider.MESSAGE_DRAFT_TYPE_COLUMN);
337            appendRefMessageContent = cursor
338                    .getInt(UIProvider.MESSAGE_APPEND_REF_MESSAGE_CONTENT_COLUMN) != 0;
339            hasAttachments = cursor.getInt(UIProvider.MESSAGE_HAS_ATTACHMENTS_COLUMN) != 0;
340            final String attachmentsUri = cursor
341                    .getString(UIProvider.MESSAGE_ATTACHMENT_LIST_URI_COLUMN);
342            attachmentListUri = hasAttachments && !TextUtils.isEmpty(attachmentsUri) ? Uri
343                    .parse(attachmentsUri) : null;
344            messageFlags = cursor.getLong(UIProvider.MESSAGE_FLAGS_COLUMN);
345            saveUri = cursor
346                    .getString(UIProvider.MESSAGE_SAVE_URI_COLUMN);
347            sendUri = cursor
348                    .getString(UIProvider.MESSAGE_SEND_URI_COLUMN);
349            alwaysShowImages = cursor.getInt(UIProvider.MESSAGE_ALWAYS_SHOW_IMAGES_COLUMN) != 0;
350            read = cursor.getInt(UIProvider.MESSAGE_READ_COLUMN) != 0;
351            starred = cursor.getInt(UIProvider.MESSAGE_STARRED_COLUMN) != 0;
352            quotedTextOffset = cursor.getInt(UIProvider.QUOTED_TEXT_OFFSET_COLUMN);
353            attachmentsJson = cursor.getString(UIProvider.MESSAGE_ATTACHMENTS_COLUMN);
354            String accountUriString = cursor.getString(UIProvider.MESSAGE_ACCOUNT_URI_COLUMN);
355            accountUri = !TextUtils.isEmpty(accountUriString) ? Uri.parse(accountUriString) : null;
356            eventIntentUri =
357                    Utils.getValidUri(cursor.getString(UIProvider.MESSAGE_EVENT_INTENT_COLUMN));
358            spamWarningString =
359                    cursor.getString(UIProvider.MESSAGE_SPAM_WARNING_STRING_ID_COLUMN);
360            spamWarningLevel = cursor.getInt(UIProvider.MESSAGE_SPAM_WARNING_LEVEL_COLUMN);
361            spamLinkType = cursor.getInt(UIProvider.MESSAGE_SPAM_WARNING_LINK_TYPE_COLUMN);
362            viaDomain = cursor.getString(UIProvider.MESSAGE_VIA_DOMAIN_COLUMN);
363            isSending = cursor.getInt(UIProvider.MESSAGE_IS_SENDING_COLUMN) != 0;
364        }
365    }
366
367    public boolean isFlaggedReplied() {
368        return (messageFlags & UIProvider.MessageFlags.REPLIED) ==
369                UIProvider.MessageFlags.REPLIED;
370    }
371
372    public boolean isFlaggedForwarded() {
373        return (messageFlags & UIProvider.MessageFlags.FORWARDED) ==
374                UIProvider.MessageFlags.FORWARDED;
375    }
376
377    public boolean isFlaggedCalendarInvite() {
378        return (messageFlags & UIProvider.MessageFlags.CALENDAR_INVITE) ==
379                UIProvider.MessageFlags.CALENDAR_INVITE;
380    }
381
382    public synchronized String[] getFromAddresses() {
383        if (mFromAddresses == null) {
384            mFromAddresses = tokenizeAddresses(from);
385        }
386        return mFromAddresses;
387    }
388
389    public synchronized String[] getToAddresses() {
390        if (mToAddresses == null) {
391            mToAddresses = tokenizeAddresses(to);
392        }
393        return mToAddresses;
394    }
395
396    public synchronized String[] getCcAddresses() {
397        if (mCcAddresses == null) {
398            mCcAddresses = tokenizeAddresses(cc);
399        }
400        return mCcAddresses;
401    }
402
403    public synchronized String[] getBccAddresses() {
404        if (mBccAddresses == null) {
405            mBccAddresses = tokenizeAddresses(bcc);
406        }
407        return mBccAddresses;
408    }
409
410    public synchronized String[] getReplyToAddresses() {
411        if (mReplyToAddresses == null) {
412            mReplyToAddresses = tokenizeAddresses(replyTo);
413        }
414        return mReplyToAddresses;
415    }
416
417    public static String[] tokenizeAddresses(String addresses) {
418        if (TextUtils.isEmpty(addresses)) {
419            return new String[0];
420        }
421        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addresses);
422        String[] strings = new String[tokens.length];
423        for (int i = 0; i < tokens.length;i++) {
424            strings[i] = tokens[i].toString();
425        }
426        return strings;
427    }
428
429    public List<Attachment> getAttachments() {
430        if (mAttachments == null) {
431            if (attachmentsJson != null) {
432                mAttachments = Attachment.fromJSONArray(attachmentsJson);
433            } else {
434                mAttachments = Collections.emptyList();
435            }
436        }
437        return mAttachments;
438    }
439
440    /**
441     * Returns whether a "Show Pictures" button should initially appear for this message. If the
442     * button is shown, the message must also block all non-local images in the body. Inversely, if
443     * the button is not shown, the message must show all images within (or else the user would be
444     * stuck with no images and no way to reveal them).
445     *
446     * @return true if a "Show Pictures" button should appear.
447     */
448    public boolean shouldShowImagePrompt() {
449        return !alwaysShowImages && embedsExternalResources();
450    }
451
452    private boolean embedsExternalResources() {
453        return embedsExternalResources ||
454                (!TextUtils.isEmpty(bodyHtml) && INLINE_IMAGE_PATTERN.matcher(bodyHtml).find());
455    }
456
457    /**
458     * Helper method to command a provider to mark all messages from this sender with the
459     * {@link MessageColumns#ALWAYS_SHOW_IMAGES} flag set.
460     *
461     * @param handler a caller-provided handler to run the query on
462     * @param token (optional) token to identify the command to the handler
463     * @param cookie (optional) cookie to pass to the handler
464     */
465    public void markAlwaysShowImages(AsyncQueryHandler handler, int token, Object cookie) {
466        alwaysShowImages = true;
467
468        final ContentValues values = new ContentValues(1);
469        values.put(UIProvider.MessageColumns.ALWAYS_SHOW_IMAGES, 1);
470
471        handler.startUpdate(token, cookie, uri, values, null, null);
472    }
473
474    public String getBodyAsHtml() {
475        String body = "";
476        if (!TextUtils.isEmpty(bodyHtml)) {
477            body = bodyHtml;
478        } else if (!TextUtils.isEmpty(bodyText)) {
479            body = Html.toHtml(new SpannedString(bodyText));
480        }
481        return body;
482    }
483
484}
485