Message.java revision 6766b6e5468d2f1935587b3bc1f8e65be94cd6fb
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    public String saveUri;
138    /**
139     * @see UIProvider.MessageColumns#SEND_MESSAGE_URI
140     */
141    public String sendUri;
142    /**
143     * @see UIProvider.MessageColumns#ALWAYS_SHOW_IMAGES
144     */
145    public boolean alwaysShowImages;
146    /**
147     * @see UIProvider.MessageColumns#READ
148     */
149    public boolean read;
150    /**
151     * @see UIProvider.MessageColumns#STARRED
152     */
153    public boolean starred;
154    /**
155     * @see UIProvider.MessageColumns#QUOTE_START_POS
156     */
157    public int quotedTextOffset;
158    /**
159     * @see UIProvider.MessageColumns#ATTACHMENTS
160     *<p>
161     * N.B. this value is NOT immutable and may change during conversation view render.
162     */
163    public String attachmentsJson;
164    /**
165     * @see UIProvider.MessageColumns#MESSAGE_ACCOUNT_URI
166     */
167    public Uri accountUri;
168    /**
169     * @see UIProvider.MessageColumns#EVENT_INTENT_URI
170     */
171    public Uri eventIntentUri;
172    /**
173     * @see UIProvider.MessageColumns#SPAM_WARNING_STRING
174     */
175    public String spamWarningString;
176    /**
177     * @see UIProvider.MessageColumns#SPAM_WARNING_LEVEL
178     */
179    public int spamWarningLevel;
180    /**
181     * @see UIProvider.MessageColumns#SPAM_WARNING_LINK_TYPE
182     */
183    public int spamLinkType;
184    /**
185     * @see UIProvider.MessageColumns#VIA_DOMAIN
186     */
187    public String viaDomain;
188    /**
189     * @see UIProvider.MessageColumns#IS_SENDING
190     */
191    public boolean isSending;
192
193    private transient String[] mFromAddresses = null;
194    private transient String[] mToAddresses = null;
195    private transient String[] mCcAddresses = null;
196    private transient String[] mBccAddresses = null;
197    private transient String[] mReplyToAddresses = null;
198
199    private transient List<Attachment> mAttachments = null;
200
201    @Override
202    public int describeContents() {
203        return 0;
204    }
205
206    @Override
207    public boolean equals(Object o) {
208        return this == o || (o != null && o instanceof Message
209                && Objects.equal(uri, ((Message) o).uri));
210    }
211
212    @Override
213    public int hashCode() {
214        return uri == null ? 0 : uri.hashCode();
215    }
216
217    @Override
218    public void writeToParcel(Parcel dest, int flags) {
219        dest.writeLong(id);
220        dest.writeString(serverId);
221        dest.writeParcelable(uri, 0);
222        dest.writeParcelable(conversationUri, 0);
223        dest.writeString(subject);
224        dest.writeString(snippet);
225        dest.writeString(from);
226        dest.writeString(to);
227        dest.writeString(cc);
228        dest.writeString(bcc);
229        dest.writeString(replyTo);
230        dest.writeLong(dateReceivedMs);
231        dest.writeString(bodyHtml);
232        dest.writeString(bodyText);
233        dest.writeInt(embedsExternalResources ? 1 : 0);
234        dest.writeString(refMessageId);
235        dest.writeInt(draftType);
236        dest.writeInt(appendRefMessageContent ? 1 : 0);
237        dest.writeInt(hasAttachments ? 1 : 0);
238        dest.writeParcelable(attachmentListUri, 0);
239        dest.writeLong(messageFlags);
240        dest.writeString(saveUri);
241        dest.writeString(sendUri);
242        dest.writeInt(alwaysShowImages ? 1 : 0);
243        dest.writeInt(quotedTextOffset);
244        dest.writeString(attachmentsJson);
245        dest.writeParcelable(accountUri, 0);
246        dest.writeParcelable(eventIntentUri, 0);
247        dest.writeString(spamWarningString);
248        dest.writeInt(spamWarningLevel);
249        dest.writeInt(spamLinkType);
250        dest.writeString(viaDomain);
251        dest.writeInt(isSending ? 1 : 0);
252    }
253
254    private Message(Parcel in) {
255        id = in.readLong();
256        serverId = in.readString();
257        uri = in.readParcelable(null);
258        conversationUri = in.readParcelable(null);
259        subject = in.readString();
260        snippet = in.readString();
261        from = in.readString();
262        to = in.readString();
263        cc = in.readString();
264        bcc = in.readString();
265        replyTo = in.readString();
266        dateReceivedMs = in.readLong();
267        bodyHtml = in.readString();
268        bodyText = in.readString();
269        embedsExternalResources = in.readInt() != 0;
270        refMessageId = in.readString();
271        draftType = in.readInt();
272        appendRefMessageContent = in.readInt() != 0;
273        hasAttachments = in.readInt() != 0;
274        attachmentListUri = in.readParcelable(null);
275        messageFlags = in.readLong();
276        saveUri = in.readString();
277        sendUri = in.readString();
278        alwaysShowImages = in.readInt() != 0;
279        quotedTextOffset = in.readInt();
280        attachmentsJson = in.readString();
281        accountUri = in.readParcelable(null);
282        eventIntentUri = in.readParcelable(null);
283        spamWarningString = in.readString();
284        spamWarningLevel = in.readInt();
285        spamLinkType = in.readInt();
286        viaDomain = in.readString();
287        isSending = in.readInt() != 0;
288    }
289
290    public Message() {
291
292    }
293
294    @Override
295    public String toString() {
296        return "[message id=" + id + "]";
297    }
298
299    public static final Creator<Message> CREATOR = new Creator<Message>() {
300
301        @Override
302        public Message createFromParcel(Parcel source) {
303            return new Message(source);
304        }
305
306        @Override
307        public Message[] newArray(int size) {
308            return new Message[size];
309        }
310
311    };
312
313    public Message(Cursor cursor) {
314        if (cursor != null) {
315            id = cursor.getLong(UIProvider.MESSAGE_ID_COLUMN);
316            serverId = cursor.getString(UIProvider.MESSAGE_SERVER_ID_COLUMN);
317            final String messageUriStr = cursor.getString(UIProvider.MESSAGE_URI_COLUMN);
318            uri = !TextUtils.isEmpty(messageUriStr) ? Uri.parse(messageUriStr) : null;
319            final String convUriStr = cursor.getString(UIProvider.MESSAGE_CONVERSATION_URI_COLUMN);
320            conversationUri = !TextUtils.isEmpty(convUriStr) ? Uri.parse(convUriStr) : null;
321            subject = cursor.getString(UIProvider.MESSAGE_SUBJECT_COLUMN);
322            snippet = cursor.getString(UIProvider.MESSAGE_SNIPPET_COLUMN);
323            from = cursor.getString(UIProvider.MESSAGE_FROM_COLUMN);
324            to = cursor.getString(UIProvider.MESSAGE_TO_COLUMN);
325            cc = cursor.getString(UIProvider.MESSAGE_CC_COLUMN);
326            bcc = cursor.getString(UIProvider.MESSAGE_BCC_COLUMN);
327            replyTo = cursor.getString(UIProvider.MESSAGE_REPLY_TO_COLUMN);
328            dateReceivedMs = cursor.getLong(UIProvider.MESSAGE_DATE_RECEIVED_MS_COLUMN);
329            bodyHtml = cursor.getString(UIProvider.MESSAGE_BODY_HTML_COLUMN);
330            bodyText = cursor.getString(UIProvider.MESSAGE_BODY_TEXT_COLUMN);
331            embedsExternalResources = cursor
332                    .getInt(UIProvider.MESSAGE_EMBEDS_EXTERNAL_RESOURCES_COLUMN) != 0;
333            refMessageId = cursor.getString(UIProvider.MESSAGE_REF_MESSAGE_ID_COLUMN);
334            draftType = cursor.getInt(UIProvider.MESSAGE_DRAFT_TYPE_COLUMN);
335            appendRefMessageContent = cursor
336                    .getInt(UIProvider.MESSAGE_APPEND_REF_MESSAGE_CONTENT_COLUMN) != 0;
337            hasAttachments = cursor.getInt(UIProvider.MESSAGE_HAS_ATTACHMENTS_COLUMN) != 0;
338            final String attachmentsUri = cursor
339                    .getString(UIProvider.MESSAGE_ATTACHMENT_LIST_URI_COLUMN);
340            attachmentListUri = hasAttachments && !TextUtils.isEmpty(attachmentsUri) ? Uri
341                    .parse(attachmentsUri) : null;
342            messageFlags = cursor.getLong(UIProvider.MESSAGE_FLAGS_COLUMN);
343            saveUri = cursor
344                    .getString(UIProvider.MESSAGE_SAVE_URI_COLUMN);
345            sendUri = cursor
346                    .getString(UIProvider.MESSAGE_SEND_URI_COLUMN);
347            alwaysShowImages = cursor.getInt(UIProvider.MESSAGE_ALWAYS_SHOW_IMAGES_COLUMN) != 0;
348            read = cursor.getInt(UIProvider.MESSAGE_READ_COLUMN) != 0;
349            starred = cursor.getInt(UIProvider.MESSAGE_STARRED_COLUMN) != 0;
350            quotedTextOffset = cursor.getInt(UIProvider.QUOTED_TEXT_OFFSET_COLUMN);
351            attachmentsJson = cursor.getString(UIProvider.MESSAGE_ATTACHMENTS_COLUMN);
352            String accountUriString = cursor.getString(UIProvider.MESSAGE_ACCOUNT_URI_COLUMN);
353            accountUri = !TextUtils.isEmpty(accountUriString) ? Uri.parse(accountUriString) : null;
354            eventIntentUri =
355                    Utils.getValidUri(cursor.getString(UIProvider.MESSAGE_EVENT_INTENT_COLUMN));
356            spamWarningString =
357                    cursor.getString(UIProvider.MESSAGE_SPAM_WARNING_STRING_ID_COLUMN);
358            spamWarningLevel = cursor.getInt(UIProvider.MESSAGE_SPAM_WARNING_LEVEL_COLUMN);
359            spamLinkType = cursor.getInt(UIProvider.MESSAGE_SPAM_WARNING_LINK_TYPE_COLUMN);
360            viaDomain = cursor.getString(UIProvider.MESSAGE_VIA_DOMAIN_COLUMN);
361            isSending = cursor.getInt(UIProvider.MESSAGE_IS_SENDING_COLUMN) != 0;
362        }
363    }
364
365    public boolean isFlaggedReplied() {
366        return (messageFlags & UIProvider.MessageFlags.REPLIED) ==
367                UIProvider.MessageFlags.REPLIED;
368    }
369
370    public boolean isFlaggedForwarded() {
371        return (messageFlags & UIProvider.MessageFlags.FORWARDED) ==
372                UIProvider.MessageFlags.FORWARDED;
373    }
374
375    public boolean isFlaggedCalendarInvite() {
376        return (messageFlags & UIProvider.MessageFlags.CALENDAR_INVITE) ==
377                UIProvider.MessageFlags.CALENDAR_INVITE;
378    }
379
380    public synchronized String[] getFromAddresses() {
381        if (mFromAddresses == null) {
382            mFromAddresses = tokenizeAddresses(from);
383        }
384        return mFromAddresses;
385    }
386
387    public synchronized String[] getToAddresses() {
388        if (mToAddresses == null) {
389            mToAddresses = tokenizeAddresses(to);
390        }
391        return mToAddresses;
392    }
393
394    public synchronized String[] getCcAddresses() {
395        if (mCcAddresses == null) {
396            mCcAddresses = tokenizeAddresses(cc);
397        }
398        return mCcAddresses;
399    }
400
401    public synchronized String[] getBccAddresses() {
402        if (mBccAddresses == null) {
403            mBccAddresses = tokenizeAddresses(bcc);
404        }
405        return mBccAddresses;
406    }
407
408    public synchronized String[] getReplyToAddresses() {
409        if (mReplyToAddresses == null) {
410            mReplyToAddresses = tokenizeAddresses(replyTo);
411        }
412        return mReplyToAddresses;
413    }
414
415    public static String[] tokenizeAddresses(String addresses) {
416        if (TextUtils.isEmpty(addresses)) {
417            return new String[0];
418        }
419        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addresses);
420        String[] strings = new String[tokens.length];
421        for (int i = 0; i < tokens.length;i++) {
422            strings[i] = tokens[i].toString();
423        }
424        return strings;
425    }
426
427    public List<Attachment> getAttachments() {
428        if (mAttachments == null) {
429            if (attachmentsJson != null) {
430                mAttachments = Attachment.fromJSONArray(attachmentsJson);
431            } else {
432                mAttachments = Collections.emptyList();
433            }
434        }
435        return mAttachments;
436    }
437
438    /**
439     * Returns whether a "Show Pictures" button should initially appear for this message. If the
440     * button is shown, the message must also block all non-local images in the body. Inversely, if
441     * the button is not shown, the message must show all images within (or else the user would be
442     * stuck with no images and no way to reveal them).
443     *
444     * @return true if a "Show Pictures" button should appear.
445     */
446    public boolean shouldShowImagePrompt() {
447        return !alwaysShowImages && embedsExternalResources();
448    }
449
450    private boolean embedsExternalResources() {
451        return embedsExternalResources ||
452                (!TextUtils.isEmpty(bodyHtml) && INLINE_IMAGE_PATTERN.matcher(bodyHtml).find());
453    }
454
455    /**
456     * Helper method to command a provider to mark all messages from this sender with the
457     * {@link MessageColumns#ALWAYS_SHOW_IMAGES} flag set.
458     *
459     * @param handler a caller-provided handler to run the query on
460     * @param token (optional) token to identify the command to the handler
461     * @param cookie (optional) cookie to pass to the handler
462     */
463    public void markAlwaysShowImages(AsyncQueryHandler handler, int token, Object cookie) {
464        alwaysShowImages = true;
465
466        final ContentValues values = new ContentValues(1);
467        values.put(UIProvider.MessageColumns.ALWAYS_SHOW_IMAGES, 1);
468
469        handler.startUpdate(token, cookie, uri, values, null, null);
470    }
471
472    public String getBodyAsHtml() {
473        String body = "";
474        if (!TextUtils.isEmpty(bodyHtml)) {
475            body = bodyHtml;
476        } else if (!TextUtils.isEmpty(bodyText)) {
477            body = Html.toHtml(new SpannedString(bodyText));
478        }
479        return body;
480    }
481
482}
483