blob: 4d2d535444f717e705b0327cd7c832eccd2d7d94 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007-2008 Esmertec AG.
3 * Copyright (C) 2007-2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
Tom Taylora87afd02010-03-08 16:34:53 -080018package com.google.android.mms.pdu;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080019
Tom Taylora87afd02010-03-08 16:34:53 -080020import com.google.android.mms.ContentType;
21import com.google.android.mms.InvalidHeaderValueException;
22import com.google.android.mms.MmsException;
23import com.google.android.mms.util.PduCache;
24import com.google.android.mms.util.PduCacheEntry;
25import com.google.android.mms.util.SqliteWrapper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import android.content.ContentResolver;
28import android.content.ContentUris;
29import android.content.ContentValues;
30import android.content.Context;
31import android.database.Cursor;
32import android.database.DatabaseUtils;
33import android.net.Uri;
Tom Taylora87afd02010-03-08 16:34:53 -080034import android.provider.Telephony;
35import android.provider.Telephony.Mms;
36import android.provider.Telephony.MmsSms;
37import android.provider.Telephony.Threads;
38import android.provider.Telephony.Mms.Addr;
39import android.provider.Telephony.Mms.Part;
40import android.provider.Telephony.MmsSms.PendingMessages;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.util.Log;
43
44import java.io.ByteArrayOutputStream;
45import java.io.FileNotFoundException;
46import java.io.IOException;
47import java.io.InputStream;
48import java.io.OutputStream;
49import java.io.UnsupportedEncodingException;
50import java.util.ArrayList;
51import java.util.HashMap;
52import java.util.HashSet;
53import java.util.Map;
54import java.util.Set;
55import java.util.Map.Entry;
56
Tom Taylora87afd02010-03-08 16:34:53 -080057import com.google.android.mms.pdu.EncodedStringValue;
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -070058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059/**
60 * This class is the high-level manager of PDU storage.
61 */
62public class PduPersister {
63 private static final String TAG = "PduPersister";
64 private static final boolean DEBUG = false;
Joe Onorato43a17652011-04-06 19:22:23 -070065 private static final boolean LOCAL_LOGV = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67 private static final long DUMMY_THREAD_ID = Long.MAX_VALUE;
68
69 /**
70 * The uri of temporary drm objects.
71 */
72 public static final String TEMPORARY_DRM_OBJECT_URI =
73 "content://mms/" + Long.MAX_VALUE + "/part";
74 /**
75 * Indicate that we transiently failed to process a MM.
76 */
77 public static final int PROC_STATUS_TRANSIENT_FAILURE = 1;
78 /**
79 * Indicate that we permanently failed to process a MM.
80 */
81 public static final int PROC_STATUS_PERMANENTLY_FAILURE = 2;
82 /**
83 * Indicate that we have successfully processed a MM.
84 */
85 public static final int PROC_STATUS_COMPLETED = 3;
86
87 private static PduPersister sPersister;
88 private static final PduCache PDU_CACHE_INSTANCE;
89
90 private static final int[] ADDRESS_FIELDS = new int[] {
91 PduHeaders.BCC,
92 PduHeaders.CC,
93 PduHeaders.FROM,
94 PduHeaders.TO
95 };
96
97 private static final String[] PDU_PROJECTION = new String[] {
98 Mms._ID,
99 Mms.MESSAGE_BOX,
100 Mms.THREAD_ID,
101 Mms.RETRIEVE_TEXT,
102 Mms.SUBJECT,
103 Mms.CONTENT_LOCATION,
104 Mms.CONTENT_TYPE,
105 Mms.MESSAGE_CLASS,
106 Mms.MESSAGE_ID,
107 Mms.RESPONSE_TEXT,
108 Mms.TRANSACTION_ID,
109 Mms.CONTENT_CLASS,
110 Mms.DELIVERY_REPORT,
111 Mms.MESSAGE_TYPE,
112 Mms.MMS_VERSION,
113 Mms.PRIORITY,
114 Mms.READ_REPORT,
115 Mms.READ_STATUS,
116 Mms.REPORT_ALLOWED,
117 Mms.RETRIEVE_STATUS,
118 Mms.STATUS,
119 Mms.DATE,
120 Mms.DELIVERY_TIME,
121 Mms.EXPIRY,
122 Mms.MESSAGE_SIZE,
123 Mms.SUBJECT_CHARSET,
124 Mms.RETRIEVE_TEXT_CHARSET,
125 };
126
127 private static final int PDU_COLUMN_ID = 0;
128 private static final int PDU_COLUMN_MESSAGE_BOX = 1;
129 private static final int PDU_COLUMN_THREAD_ID = 2;
130 private static final int PDU_COLUMN_RETRIEVE_TEXT = 3;
131 private static final int PDU_COLUMN_SUBJECT = 4;
132 private static final int PDU_COLUMN_CONTENT_LOCATION = 5;
133 private static final int PDU_COLUMN_CONTENT_TYPE = 6;
134 private static final int PDU_COLUMN_MESSAGE_CLASS = 7;
135 private static final int PDU_COLUMN_MESSAGE_ID = 8;
136 private static final int PDU_COLUMN_RESPONSE_TEXT = 9;
137 private static final int PDU_COLUMN_TRANSACTION_ID = 10;
138 private static final int PDU_COLUMN_CONTENT_CLASS = 11;
139 private static final int PDU_COLUMN_DELIVERY_REPORT = 12;
140 private static final int PDU_COLUMN_MESSAGE_TYPE = 13;
141 private static final int PDU_COLUMN_MMS_VERSION = 14;
142 private static final int PDU_COLUMN_PRIORITY = 15;
143 private static final int PDU_COLUMN_READ_REPORT = 16;
144 private static final int PDU_COLUMN_READ_STATUS = 17;
145 private static final int PDU_COLUMN_REPORT_ALLOWED = 18;
146 private static final int PDU_COLUMN_RETRIEVE_STATUS = 19;
147 private static final int PDU_COLUMN_STATUS = 20;
148 private static final int PDU_COLUMN_DATE = 21;
149 private static final int PDU_COLUMN_DELIVERY_TIME = 22;
150 private static final int PDU_COLUMN_EXPIRY = 23;
151 private static final int PDU_COLUMN_MESSAGE_SIZE = 24;
152 private static final int PDU_COLUMN_SUBJECT_CHARSET = 25;
153 private static final int PDU_COLUMN_RETRIEVE_TEXT_CHARSET = 26;
154
155 private static final String[] PART_PROJECTION = new String[] {
156 Part._ID,
157 Part.CHARSET,
158 Part.CONTENT_DISPOSITION,
159 Part.CONTENT_ID,
160 Part.CONTENT_LOCATION,
161 Part.CONTENT_TYPE,
162 Part.FILENAME,
163 Part.NAME,
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700164 Part.TEXT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 };
166
167 private static final int PART_COLUMN_ID = 0;
168 private static final int PART_COLUMN_CHARSET = 1;
169 private static final int PART_COLUMN_CONTENT_DISPOSITION = 2;
170 private static final int PART_COLUMN_CONTENT_ID = 3;
171 private static final int PART_COLUMN_CONTENT_LOCATION = 4;
172 private static final int PART_COLUMN_CONTENT_TYPE = 5;
173 private static final int PART_COLUMN_FILENAME = 6;
174 private static final int PART_COLUMN_NAME = 7;
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700175 private static final int PART_COLUMN_TEXT = 8;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
177 private static final HashMap<Uri, Integer> MESSAGE_BOX_MAP;
178 // These map are used for convenience in persist() and load().
179 private static final HashMap<Integer, Integer> CHARSET_COLUMN_INDEX_MAP;
180 private static final HashMap<Integer, Integer> ENCODED_STRING_COLUMN_INDEX_MAP;
181 private static final HashMap<Integer, Integer> TEXT_STRING_COLUMN_INDEX_MAP;
182 private static final HashMap<Integer, Integer> OCTET_COLUMN_INDEX_MAP;
183 private static final HashMap<Integer, Integer> LONG_COLUMN_INDEX_MAP;
184 private static final HashMap<Integer, String> CHARSET_COLUMN_NAME_MAP;
185 private static final HashMap<Integer, String> ENCODED_STRING_COLUMN_NAME_MAP;
186 private static final HashMap<Integer, String> TEXT_STRING_COLUMN_NAME_MAP;
187 private static final HashMap<Integer, String> OCTET_COLUMN_NAME_MAP;
188 private static final HashMap<Integer, String> LONG_COLUMN_NAME_MAP;
189
190 static {
191 MESSAGE_BOX_MAP = new HashMap<Uri, Integer>();
192 MESSAGE_BOX_MAP.put(Mms.Inbox.CONTENT_URI, Mms.MESSAGE_BOX_INBOX);
193 MESSAGE_BOX_MAP.put(Mms.Sent.CONTENT_URI, Mms.MESSAGE_BOX_SENT);
194 MESSAGE_BOX_MAP.put(Mms.Draft.CONTENT_URI, Mms.MESSAGE_BOX_DRAFTS);
195 MESSAGE_BOX_MAP.put(Mms.Outbox.CONTENT_URI, Mms.MESSAGE_BOX_OUTBOX);
196
197 CHARSET_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
198 CHARSET_COLUMN_INDEX_MAP.put(PduHeaders.SUBJECT, PDU_COLUMN_SUBJECT_CHARSET);
199 CHARSET_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_TEXT, PDU_COLUMN_RETRIEVE_TEXT_CHARSET);
200
201 CHARSET_COLUMN_NAME_MAP = new HashMap<Integer, String>();
202 CHARSET_COLUMN_NAME_MAP.put(PduHeaders.SUBJECT, Mms.SUBJECT_CHARSET);
203 CHARSET_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_TEXT, Mms.RETRIEVE_TEXT_CHARSET);
204
205 // Encoded string field code -> column index/name map.
206 ENCODED_STRING_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
207 ENCODED_STRING_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_TEXT, PDU_COLUMN_RETRIEVE_TEXT);
208 ENCODED_STRING_COLUMN_INDEX_MAP.put(PduHeaders.SUBJECT, PDU_COLUMN_SUBJECT);
209
210 ENCODED_STRING_COLUMN_NAME_MAP = new HashMap<Integer, String>();
211 ENCODED_STRING_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_TEXT, Mms.RETRIEVE_TEXT);
212 ENCODED_STRING_COLUMN_NAME_MAP.put(PduHeaders.SUBJECT, Mms.SUBJECT);
213
214 // Text string field code -> column index/name map.
215 TEXT_STRING_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
216 TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_LOCATION, PDU_COLUMN_CONTENT_LOCATION);
217 TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_TYPE, PDU_COLUMN_CONTENT_TYPE);
218 TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_CLASS, PDU_COLUMN_MESSAGE_CLASS);
219 TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_ID, PDU_COLUMN_MESSAGE_ID);
220 TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.RESPONSE_TEXT, PDU_COLUMN_RESPONSE_TEXT);
221 TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.TRANSACTION_ID, PDU_COLUMN_TRANSACTION_ID);
222
223 TEXT_STRING_COLUMN_NAME_MAP = new HashMap<Integer, String>();
224 TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_LOCATION, Mms.CONTENT_LOCATION);
225 TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_TYPE, Mms.CONTENT_TYPE);
226 TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_CLASS, Mms.MESSAGE_CLASS);
227 TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_ID, Mms.MESSAGE_ID);
228 TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.RESPONSE_TEXT, Mms.RESPONSE_TEXT);
229 TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.TRANSACTION_ID, Mms.TRANSACTION_ID);
230
231 // Octet field code -> column index/name map.
232 OCTET_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
233 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_CLASS, PDU_COLUMN_CONTENT_CLASS);
234 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.DELIVERY_REPORT, PDU_COLUMN_DELIVERY_REPORT);
235 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_TYPE, PDU_COLUMN_MESSAGE_TYPE);
236 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.MMS_VERSION, PDU_COLUMN_MMS_VERSION);
237 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.PRIORITY, PDU_COLUMN_PRIORITY);
238 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.READ_REPORT, PDU_COLUMN_READ_REPORT);
239 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.READ_STATUS, PDU_COLUMN_READ_STATUS);
240 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.REPORT_ALLOWED, PDU_COLUMN_REPORT_ALLOWED);
241 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_STATUS, PDU_COLUMN_RETRIEVE_STATUS);
242 OCTET_COLUMN_INDEX_MAP.put(PduHeaders.STATUS, PDU_COLUMN_STATUS);
243
244 OCTET_COLUMN_NAME_MAP = new HashMap<Integer, String>();
245 OCTET_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_CLASS, Mms.CONTENT_CLASS);
246 OCTET_COLUMN_NAME_MAP.put(PduHeaders.DELIVERY_REPORT, Mms.DELIVERY_REPORT);
247 OCTET_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_TYPE, Mms.MESSAGE_TYPE);
248 OCTET_COLUMN_NAME_MAP.put(PduHeaders.MMS_VERSION, Mms.MMS_VERSION);
249 OCTET_COLUMN_NAME_MAP.put(PduHeaders.PRIORITY, Mms.PRIORITY);
250 OCTET_COLUMN_NAME_MAP.put(PduHeaders.READ_REPORT, Mms.READ_REPORT);
251 OCTET_COLUMN_NAME_MAP.put(PduHeaders.READ_STATUS, Mms.READ_STATUS);
252 OCTET_COLUMN_NAME_MAP.put(PduHeaders.REPORT_ALLOWED, Mms.REPORT_ALLOWED);
253 OCTET_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_STATUS, Mms.RETRIEVE_STATUS);
254 OCTET_COLUMN_NAME_MAP.put(PduHeaders.STATUS, Mms.STATUS);
255
256 // Long field code -> column index/name map.
257 LONG_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
258 LONG_COLUMN_INDEX_MAP.put(PduHeaders.DATE, PDU_COLUMN_DATE);
259 LONG_COLUMN_INDEX_MAP.put(PduHeaders.DELIVERY_TIME, PDU_COLUMN_DELIVERY_TIME);
260 LONG_COLUMN_INDEX_MAP.put(PduHeaders.EXPIRY, PDU_COLUMN_EXPIRY);
261 LONG_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_SIZE, PDU_COLUMN_MESSAGE_SIZE);
262
263 LONG_COLUMN_NAME_MAP = new HashMap<Integer, String>();
264 LONG_COLUMN_NAME_MAP.put(PduHeaders.DATE, Mms.DATE);
265 LONG_COLUMN_NAME_MAP.put(PduHeaders.DELIVERY_TIME, Mms.DELIVERY_TIME);
266 LONG_COLUMN_NAME_MAP.put(PduHeaders.EXPIRY, Mms.EXPIRY);
267 LONG_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_SIZE, Mms.MESSAGE_SIZE);
268
269 PDU_CACHE_INSTANCE = PduCache.getInstance();
270 }
271
272 private final Context mContext;
273 private final ContentResolver mContentResolver;
274
275 private PduPersister(Context context) {
276 mContext = context;
277 mContentResolver = context.getContentResolver();
278 }
279
280 /** Get(or create if not exist) an instance of PduPersister */
281 public static PduPersister getPduPersister(Context context) {
282 if ((sPersister == null) || !context.equals(sPersister.mContext)) {
283 sPersister = new PduPersister(context);
284 }
285
286 return sPersister;
287 }
288
289 private void setEncodedStringValueToHeaders(
290 Cursor c, int columnIndex,
291 PduHeaders headers, int mapColumn) {
292 String s = c.getString(columnIndex);
293 if ((s != null) && (s.length() > 0)) {
294 int charsetColumnIndex = CHARSET_COLUMN_INDEX_MAP.get(mapColumn);
295 int charset = c.getInt(charsetColumnIndex);
296 EncodedStringValue value = new EncodedStringValue(
297 charset, getBytes(s));
298 headers.setEncodedStringValue(value, mapColumn);
299 }
300 }
301
302 private void setTextStringToHeaders(
303 Cursor c, int columnIndex,
304 PduHeaders headers, int mapColumn) {
305 String s = c.getString(columnIndex);
306 if (s != null) {
307 headers.setTextString(getBytes(s), mapColumn);
308 }
309 }
310
311 private void setOctetToHeaders(
312 Cursor c, int columnIndex,
313 PduHeaders headers, int mapColumn) throws InvalidHeaderValueException {
314 if (!c.isNull(columnIndex)) {
315 int b = c.getInt(columnIndex);
316 headers.setOctet(b, mapColumn);
317 }
318 }
319
320 private void setLongToHeaders(
321 Cursor c, int columnIndex,
322 PduHeaders headers, int mapColumn) {
323 if (!c.isNull(columnIndex)) {
324 long l = c.getLong(columnIndex);
325 headers.setLongInteger(l, mapColumn);
326 }
327 }
328
329 private Integer getIntegerFromPartColumn(Cursor c, int columnIndex) {
330 if (!c.isNull(columnIndex)) {
331 return c.getInt(columnIndex);
332 }
333 return null;
334 }
335
336 private byte[] getByteArrayFromPartColumn(Cursor c, int columnIndex) {
337 if (!c.isNull(columnIndex)) {
338 return getBytes(c.getString(columnIndex));
339 }
340 return null;
341 }
342
343 private PduPart[] loadParts(long msgId) throws MmsException {
344 Cursor c = SqliteWrapper.query(mContext, mContentResolver,
345 Uri.parse("content://mms/" + msgId + "/part"),
346 PART_PROJECTION, null, null, null);
347
348 PduPart[] parts = null;
349
350 try {
351 if ((c == null) || (c.getCount() == 0)) {
352 if (LOCAL_LOGV) {
353 Log.v(TAG, "loadParts(" + msgId + "): no part to load.");
354 }
355 return null;
356 }
357
358 int partCount = c.getCount();
359 int partIdx = 0;
360 parts = new PduPart[partCount];
361 while (c.moveToNext()) {
362 PduPart part = new PduPart();
363 Integer charset = getIntegerFromPartColumn(
364 c, PART_COLUMN_CHARSET);
365 if (charset != null) {
366 part.setCharset(charset);
367 }
368
369 byte[] contentDisposition = getByteArrayFromPartColumn(
370 c, PART_COLUMN_CONTENT_DISPOSITION);
371 if (contentDisposition != null) {
372 part.setContentDisposition(contentDisposition);
373 }
374
375 byte[] contentId = getByteArrayFromPartColumn(
376 c, PART_COLUMN_CONTENT_ID);
377 if (contentId != null) {
378 part.setContentId(contentId);
379 }
380
381 byte[] contentLocation = getByteArrayFromPartColumn(
382 c, PART_COLUMN_CONTENT_LOCATION);
383 if (contentLocation != null) {
384 part.setContentLocation(contentLocation);
385 }
386
387 byte[] contentType = getByteArrayFromPartColumn(
388 c, PART_COLUMN_CONTENT_TYPE);
389 if (contentType != null) {
390 part.setContentType(contentType);
391 } else {
392 throw new MmsException("Content-Type must be set.");
393 }
394
395 byte[] fileName = getByteArrayFromPartColumn(
396 c, PART_COLUMN_FILENAME);
397 if (fileName != null) {
398 part.setFilename(fileName);
399 }
400
401 byte[] name = getByteArrayFromPartColumn(
402 c, PART_COLUMN_NAME);
403 if (name != null) {
404 part.setName(name);
405 }
406
407 // Construct a Uri for this part.
408 long partId = c.getLong(PART_COLUMN_ID);
409 Uri partURI = Uri.parse("content://mms/part/" + partId);
410 part.setDataUri(partURI);
411
412 // For images/audio/video, we won't keep their data in Part
413 // because their renderer accept Uri as source.
414 String type = toIsoString(contentType);
415 if (!ContentType.isImageType(type)
416 && !ContentType.isAudioType(type)
417 && !ContentType.isVideoType(type)) {
418 ByteArrayOutputStream baos = new ByteArrayOutputStream();
419 InputStream is = null;
420
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700421 // Store simple string values directly in the database instead of an
422 // external file. This makes the text searchable and retrieval slightly
423 // faster.
Tom Taylordbac1802010-07-21 10:49:48 -0700424 if (ContentType.TEXT_PLAIN.equals(type) || ContentType.APP_SMIL.equals(type)
425 || ContentType.TEXT_HTML.equals(type)) {
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700426 String text = c.getString(PART_COLUMN_TEXT);
Mark Wagnerb054f272010-03-22 11:43:24 -0700427 byte [] blob = new EncodedStringValue(text != null ? text : "")
428 .getTextString();
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700429 baos.write(blob, 0, blob.length);
430 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700432 try {
433 is = mContentResolver.openInputStream(partURI);
434
435 byte[] buffer = new byte[256];
436 int len = is.read(buffer);
437 while (len >= 0) {
438 baos.write(buffer, 0, len);
439 len = is.read(buffer);
440 }
441 } catch (IOException e) {
442 Log.e(TAG, "Failed to load part data", e);
443 c.close();
444 throw new MmsException(e);
445 } finally {
446 if (is != null) {
447 try {
448 is.close();
449 } catch (IOException e) {
450 Log.e(TAG, "Failed to close stream", e);
451 } // Ignore
452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454 }
455 part.setData(baos.toByteArray());
456 }
457 parts[partIdx++] = part;
458 }
459 } finally {
460 if (c != null) {
461 c.close();
462 }
463 }
464
465 return parts;
466 }
467
468 private void loadAddress(long msgId, PduHeaders headers) {
469 Cursor c = SqliteWrapper.query(mContext, mContentResolver,
470 Uri.parse("content://mms/" + msgId + "/addr"),
471 new String[] { Addr.ADDRESS, Addr.CHARSET, Addr.TYPE },
472 null, null, null);
473
474 if (c != null) {
475 try {
476 while (c.moveToNext()) {
477 String addr = c.getString(0);
478 if (!TextUtils.isEmpty(addr)) {
479 int addrType = c.getInt(2);
480 switch (addrType) {
481 case PduHeaders.FROM:
482 headers.setEncodedStringValue(
483 new EncodedStringValue(c.getInt(1), getBytes(addr)),
484 addrType);
485 break;
486 case PduHeaders.TO:
487 case PduHeaders.CC:
488 case PduHeaders.BCC:
489 headers.appendEncodedStringValue(
490 new EncodedStringValue(c.getInt(1), getBytes(addr)),
491 addrType);
492 break;
493 default:
494 Log.e(TAG, "Unknown address type: " + addrType);
495 break;
496 }
497 }
498 }
499 } finally {
500 c.close();
501 }
502 }
503 }
504
505 /**
506 * Load a PDU from storage by given Uri.
507 *
508 * @param uri The Uri of the PDU to be loaded.
509 * @return A generic PDU object, it may be cast to dedicated PDU.
510 * @throws MmsException Failed to load some fields of a PDU.
511 */
512 public GenericPdu load(Uri uri) throws MmsException {
513 PduCacheEntry cacheEntry = PDU_CACHE_INSTANCE.get(uri);
514 if (cacheEntry != null) {
515 return cacheEntry.getPdu();
516 }
517
518 Cursor c = SqliteWrapper.query(mContext, mContentResolver, uri,
519 PDU_PROJECTION, null, null, null);
520 PduHeaders headers = new PduHeaders();
521 Set<Entry<Integer, Integer>> set;
522 long msgId = ContentUris.parseId(uri);
523 int msgBox;
524 long threadId;
525
526 try {
527 if ((c == null) || (c.getCount() != 1) || !c.moveToFirst()) {
528 throw new MmsException("Bad uri: " + uri);
529 }
530
531 msgBox = c.getInt(PDU_COLUMN_MESSAGE_BOX);
532 threadId = c.getLong(PDU_COLUMN_THREAD_ID);
533
534 set = ENCODED_STRING_COLUMN_INDEX_MAP.entrySet();
535 for (Entry<Integer, Integer> e : set) {
536 setEncodedStringValueToHeaders(
537 c, e.getValue(), headers, e.getKey());
538 }
539
540 set = TEXT_STRING_COLUMN_INDEX_MAP.entrySet();
541 for (Entry<Integer, Integer> e : set) {
542 setTextStringToHeaders(
543 c, e.getValue(), headers, e.getKey());
544 }
545
546 set = OCTET_COLUMN_INDEX_MAP.entrySet();
547 for (Entry<Integer, Integer> e : set) {
548 setOctetToHeaders(
549 c, e.getValue(), headers, e.getKey());
550 }
551
552 set = LONG_COLUMN_INDEX_MAP.entrySet();
553 for (Entry<Integer, Integer> e : set) {
554 setLongToHeaders(
555 c, e.getValue(), headers, e.getKey());
556 }
557 } finally {
558 if (c != null) {
559 c.close();
560 }
561 }
562
563 // Check whether 'msgId' has been assigned a valid value.
564 if (msgId == -1L) {
565 throw new MmsException("Error! ID of the message: -1.");
566 }
567
568 // Load address information of the MM.
569 loadAddress(msgId, headers);
570
571 int msgType = headers.getOctet(PduHeaders.MESSAGE_TYPE);
572 PduBody body = new PduBody();
573
574 // For PDU which type is M_retrieve.conf or Send.req, we should
575 // load multiparts and put them into the body of the PDU.
576 if ((msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF)
577 || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) {
578 PduPart[] parts = loadParts(msgId);
579 if (parts != null) {
580 int partsNum = parts.length;
581 for (int i = 0; i < partsNum; i++) {
582 body.addPart(parts[i]);
583 }
584 }
585 }
586
587 GenericPdu pdu = null;
588 switch (msgType) {
589 case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
590 pdu = new NotificationInd(headers);
591 break;
592 case PduHeaders.MESSAGE_TYPE_DELIVERY_IND:
593 pdu = new DeliveryInd(headers);
594 break;
595 case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND:
596 pdu = new ReadOrigInd(headers);
597 break;
598 case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
599 pdu = new RetrieveConf(headers, body);
600 break;
601 case PduHeaders.MESSAGE_TYPE_SEND_REQ:
602 pdu = new SendReq(headers, body);
603 break;
604 case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND:
605 pdu = new AcknowledgeInd(headers);
606 break;
607 case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND:
608 pdu = new NotifyRespInd(headers);
609 break;
610 case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
611 pdu = new ReadRecInd(headers);
612 break;
613 case PduHeaders.MESSAGE_TYPE_SEND_CONF:
614 case PduHeaders.MESSAGE_TYPE_FORWARD_REQ:
615 case PduHeaders.MESSAGE_TYPE_FORWARD_CONF:
616 case PduHeaders.MESSAGE_TYPE_MBOX_STORE_REQ:
617 case PduHeaders.MESSAGE_TYPE_MBOX_STORE_CONF:
618 case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_REQ:
619 case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_CONF:
620 case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_REQ:
621 case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_CONF:
622 case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_REQ:
623 case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_CONF:
624 case PduHeaders.MESSAGE_TYPE_MBOX_DESCR:
625 case PduHeaders.MESSAGE_TYPE_DELETE_REQ:
626 case PduHeaders.MESSAGE_TYPE_DELETE_CONF:
627 case PduHeaders.MESSAGE_TYPE_CANCEL_REQ:
628 case PduHeaders.MESSAGE_TYPE_CANCEL_CONF:
629 throw new MmsException(
630 "Unsupported PDU type: " + Integer.toHexString(msgType));
631
632 default:
633 throw new MmsException(
634 "Unrecognized PDU type: " + Integer.toHexString(msgType));
635 }
636
637 cacheEntry = new PduCacheEntry(pdu, msgBox, threadId);
638 PDU_CACHE_INSTANCE.put(uri, cacheEntry);
639 return pdu;
640 }
641
642 private void persistAddress(
643 long msgId, int type, EncodedStringValue[] array) {
644 ContentValues values = new ContentValues(3);
645
646 for (EncodedStringValue addr : array) {
647 values.clear(); // Clear all values first.
648 values.put(Addr.ADDRESS, toIsoString(addr.getTextString()));
649 values.put(Addr.CHARSET, addr.getCharacterSet());
650 values.put(Addr.TYPE, type);
651
652 Uri uri = Uri.parse("content://mms/" + msgId + "/addr");
653 SqliteWrapper.insert(mContext, mContentResolver, uri, values);
654 }
655 }
656
657 public Uri persistPart(PduPart part, long msgId)
658 throws MmsException {
659 Uri uri = Uri.parse("content://mms/" + msgId + "/part");
660 ContentValues values = new ContentValues(8);
661
662 int charset = part.getCharset();
663 if (charset != 0 ) {
664 values.put(Part.CHARSET, charset);
665 }
666
667 String contentType = null;
668 if (part.getContentType() != null) {
669 contentType = toIsoString(part.getContentType());
670 values.put(Part.CONTENT_TYPE, contentType);
671 // To ensure the SMIL part is always the first part.
672 if (ContentType.APP_SMIL.equals(contentType)) {
673 values.put(Part.SEQ, -1);
674 }
675 } else {
676 throw new MmsException("MIME type of the part must be set.");
677 }
678
679 if (part.getFilename() != null) {
680 String fileName = new String(part.getFilename());
681 values.put(Part.FILENAME, fileName);
682 }
683
684 if (part.getName() != null) {
685 String name = new String(part.getName());
686 values.put(Part.NAME, name);
687 }
688
689 Object value = null;
690 if (part.getContentDisposition() != null) {
691 value = toIsoString(part.getContentDisposition());
692 values.put(Part.CONTENT_DISPOSITION, (String) value);
693 }
694
695 if (part.getContentId() != null) {
696 value = toIsoString(part.getContentId());
697 values.put(Part.CONTENT_ID, (String) value);
698 }
699
700 if (part.getContentLocation() != null) {
701 value = toIsoString(part.getContentLocation());
702 values.put(Part.CONTENT_LOCATION, (String) value);
703 }
704
705 Uri res = SqliteWrapper.insert(mContext, mContentResolver, uri, values);
706 if (res == null) {
707 throw new MmsException("Failed to persist part, return null.");
708 }
709
710 persistData(part, res, contentType);
711 // After successfully store the data, we should update
712 // the dataUri of the part.
713 part.setDataUri(res);
714
715 return res;
716 }
717
718 /**
719 * Save data of the part into storage. The source data may be given
720 * by a byte[] or a Uri. If it's a byte[], directly save it
721 * into storage, otherwise load source data from the dataUri and then
722 * save it. If the data is an image, we may scale down it according
723 * to user preference.
724 *
725 * @param part The PDU part which contains data to be saved.
726 * @param uri The URI of the part.
727 * @param contentType The MIME type of the part.
728 * @throws MmsException Cannot find source data or error occurred
729 * while saving the data.
730 */
731 private void persistData(PduPart part, Uri uri,
732 String contentType)
733 throws MmsException {
734 OutputStream os = null;
735 InputStream is = null;
736
737 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 byte[] data = part.getData();
Tom Taylordbac1802010-07-21 10:49:48 -0700739 if (ContentType.TEXT_PLAIN.equals(contentType)
740 || ContentType.APP_SMIL.equals(contentType)
741 || ContentType.TEXT_HTML.equals(contentType)) {
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700742 ContentValues cv = new ContentValues();
Tom Taylora87afd02010-03-08 16:34:53 -0800743 cv.put(Telephony.Mms.Part.TEXT, new EncodedStringValue(data).getString());
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700744 if (mContentResolver.update(uri, cv, null, null) != 1) {
745 throw new MmsException("unable to update " + uri.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 }
747 } else {
Mark Wagnerf4f8a7fe2009-06-19 09:09:02 -0700748 os = mContentResolver.openOutputStream(uri);
749 if (data == null) {
750 Uri dataUri = part.getDataUri();
751 if ((dataUri == null) || (dataUri == uri)) {
752 Log.w(TAG, "Can't find data for this part.");
753 return;
754 }
755 is = mContentResolver.openInputStream(dataUri);
756
757 if (LOCAL_LOGV) {
758 Log.v(TAG, "Saving data to: " + uri);
759 }
760
761 byte[] buffer = new byte[256];
762 for (int len = 0; (len = is.read(buffer)) != -1; ) {
763 os.write(buffer, 0, len);
764 }
765 } else {
766 if (LOCAL_LOGV) {
767 Log.v(TAG, "Saving data to: " + uri);
768 }
769 os.write(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 }
772 } catch (FileNotFoundException e) {
773 Log.e(TAG, "Failed to open Input/Output stream.", e);
774 throw new MmsException(e);
775 } catch (IOException e) {
776 Log.e(TAG, "Failed to read/write data.", e);
777 throw new MmsException(e);
778 } finally {
779 if (os != null) {
780 try {
781 os.close();
782 } catch (IOException e) {
783 Log.e(TAG, "IOException while closing: " + os, e);
784 } // Ignore
785 }
786 if (is != null) {
787 try {
788 is.close();
789 } catch (IOException e) {
790 Log.e(TAG, "IOException while closing: " + is, e);
791 } // Ignore
792 }
793 }
794 }
795
796 private void updateAddress(
797 long msgId, int type, EncodedStringValue[] array) {
798 // Delete old address information and then insert new ones.
799 SqliteWrapper.delete(mContext, mContentResolver,
800 Uri.parse("content://mms/" + msgId + "/addr"),
801 Addr.TYPE + "=" + type, null);
802
803 persistAddress(msgId, type, array);
804 }
805
806 /**
807 * Update headers of a SendReq.
808 *
809 * @param uri The PDU which need to be updated.
810 * @param pdu New headers.
811 * @throws MmsException Bad URI or updating failed.
812 */
813 public void updateHeaders(Uri uri, SendReq sendReq) {
814 PDU_CACHE_INSTANCE.purge(uri);
815
Tom Taylora67c8cd2009-09-17 16:39:27 -0700816 ContentValues values = new ContentValues(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 byte[] contentType = sendReq.getContentType();
818 if (contentType != null) {
819 values.put(Mms.CONTENT_TYPE, toIsoString(contentType));
820 }
821
822 long date = sendReq.getDate();
823 if (date != -1) {
824 values.put(Mms.DATE, date);
825 }
826
827 int deliveryReport = sendReq.getDeliveryReport();
828 if (deliveryReport != 0) {
829 values.put(Mms.DELIVERY_REPORT, deliveryReport);
830 }
831
832 long expiry = sendReq.getExpiry();
833 if (expiry != -1) {
834 values.put(Mms.EXPIRY, expiry);
835 }
836
837 byte[] msgClass = sendReq.getMessageClass();
838 if (msgClass != null) {
839 values.put(Mms.MESSAGE_CLASS, toIsoString(msgClass));
840 }
841
842 int priority = sendReq.getPriority();
843 if (priority != 0) {
844 values.put(Mms.PRIORITY, priority);
845 }
846
847 int readReport = sendReq.getReadReport();
848 if (readReport != 0) {
849 values.put(Mms.READ_REPORT, readReport);
850 }
851
852 byte[] transId = sendReq.getTransactionId();
853 if (transId != null) {
854 values.put(Mms.TRANSACTION_ID, toIsoString(transId));
855 }
856
857 EncodedStringValue subject = sendReq.getSubject();
858 if (subject != null) {
859 values.put(Mms.SUBJECT, toIsoString(subject.getTextString()));
860 values.put(Mms.SUBJECT_CHARSET, subject.getCharacterSet());
Satish Roddom6cec6e12009-09-22 23:54:05 -0500861 } else {
862 values.put(Mms.SUBJECT, "");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
Mark Wagnerb054f272010-03-22 11:43:24 -0700864
Tom Taylora67c8cd2009-09-17 16:39:27 -0700865 long messageSize = sendReq.getMessageSize();
866 if (messageSize > 0) {
867 values.put(Mms.MESSAGE_SIZE, messageSize);
868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
870 PduHeaders headers = sendReq.getPduHeaders();
871 HashSet<String> recipients = new HashSet<String>();
872 for (int addrType : ADDRESS_FIELDS) {
873 EncodedStringValue[] array = null;
874 if (addrType == PduHeaders.FROM) {
875 EncodedStringValue v = headers.getEncodedStringValue(addrType);
876 if (v != null) {
877 array = new EncodedStringValue[1];
878 array[0] = v;
879 }
880 } else {
881 array = headers.getEncodedStringValues(addrType);
882 }
883
884 if (array != null) {
885 long msgId = ContentUris.parseId(uri);
886 updateAddress(msgId, addrType, array);
887 if (addrType == PduHeaders.TO) {
888 for (EncodedStringValue v : array) {
889 if (v != null) {
890 recipients.add(v.getString());
891 }
892 }
893 }
894 }
895 }
896
897 long threadId = Threads.getOrCreateThreadId(mContext, recipients);
898 values.put(Mms.THREAD_ID, threadId);
899
900 SqliteWrapper.update(mContext, mContentResolver, uri, values, null, null);
901 }
902
903 private void updatePart(Uri uri, PduPart part) throws MmsException {
904 ContentValues values = new ContentValues(7);
905
906 int charset = part.getCharset();
907 if (charset != 0 ) {
908 values.put(Part.CHARSET, charset);
909 }
910
911 String contentType = null;
912 if (part.getContentType() != null) {
913 contentType = toIsoString(part.getContentType());
914 values.put(Part.CONTENT_TYPE, contentType);
915 } else {
916 throw new MmsException("MIME type of the part must be set.");
917 }
918
919 if (part.getFilename() != null) {
920 String fileName = new String(part.getFilename());
921 values.put(Part.FILENAME, fileName);
922 }
923
924 if (part.getName() != null) {
925 String name = new String(part.getName());
926 values.put(Part.NAME, name);
927 }
928
929 Object value = null;
930 if (part.getContentDisposition() != null) {
931 value = toIsoString(part.getContentDisposition());
932 values.put(Part.CONTENT_DISPOSITION, (String) value);
933 }
934
935 if (part.getContentId() != null) {
936 value = toIsoString(part.getContentId());
937 values.put(Part.CONTENT_ID, (String) value);
938 }
939
940 if (part.getContentLocation() != null) {
941 value = toIsoString(part.getContentLocation());
942 values.put(Part.CONTENT_LOCATION, (String) value);
943 }
944
945 SqliteWrapper.update(mContext, mContentResolver, uri, values, null, null);
946
947 // Only update the data when:
948 // 1. New binary data supplied or
949 // 2. The Uri of the part is different from the current one.
950 if ((part.getData() != null)
951 || (uri != part.getDataUri())) {
952 persistData(part, uri, contentType);
953 }
954 }
955
956 /**
957 * Update all parts of a PDU.
958 *
959 * @param uri The PDU which need to be updated.
960 * @param body New message body of the PDU.
961 * @throws MmsException Bad URI or updating failed.
962 */
963 public void updateParts(Uri uri, PduBody body)
964 throws MmsException {
965 PduCacheEntry cacheEntry = PDU_CACHE_INSTANCE.get(uri);
966 if (cacheEntry != null) {
967 ((MultimediaMessagePdu) cacheEntry.getPdu()).setBody(body);
968 }
969
970 ArrayList<PduPart> toBeCreated = new ArrayList<PduPart>();
971 HashMap<Uri, PduPart> toBeUpdated = new HashMap<Uri, PduPart>();
972
973 int partsNum = body.getPartsNum();
974 StringBuilder filter = new StringBuilder().append('(');
975 for (int i = 0; i < partsNum; i++) {
976 PduPart part = body.getPart(i);
977 Uri partUri = part.getDataUri();
978 if ((partUri == null) || !partUri.getAuthority().startsWith("mms")) {
979 toBeCreated.add(part);
980 } else {
981 toBeUpdated.put(partUri, part);
982
983 // Don't use 'i > 0' to determine whether we should append
984 // 'AND' since 'i = 0' may be skipped in another branch.
985 if (filter.length() > 1) {
986 filter.append(" AND ");
987 }
988
989 filter.append(Part._ID);
990 filter.append("!=");
991 DatabaseUtils.appendEscapedSQLString(filter, partUri.getLastPathSegment());
992 }
993 }
994 filter.append(')');
995
996 long msgId = ContentUris.parseId(uri);
997
998 // Remove the parts which doesn't exist anymore.
999 SqliteWrapper.delete(mContext, mContentResolver,
1000 Uri.parse(Mms.CONTENT_URI + "/" + msgId + "/part"),
1001 filter.length() > 2 ? filter.toString() : null, null);
1002
1003 // Create new parts which didn't exist before.
1004 for (PduPart part : toBeCreated) {
1005 persistPart(part, msgId);
1006 }
1007
1008 // Update the modified parts.
1009 for (Map.Entry<Uri, PduPart> e : toBeUpdated.entrySet()) {
1010 updatePart(e.getKey(), e.getValue());
1011 }
1012 }
1013
1014 /**
1015 * Persist a PDU object to specific location in the storage.
1016 *
1017 * @param pdu The PDU object to be stored.
1018 * @param uri Where to store the given PDU object.
1019 * @return A Uri which can be used to access the stored PDU.
1020 */
1021 public Uri persist(GenericPdu pdu, Uri uri) throws MmsException {
1022 if (uri == null) {
1023 throw new MmsException("Uri may not be null.");
1024 }
1025
1026 Integer msgBox = MESSAGE_BOX_MAP.get(uri);
1027 if (msgBox == null) {
1028 throw new MmsException(
1029 "Bad destination, must be one of "
1030 + "content://mms/inbox, content://mms/sent, "
1031 + "content://mms/drafts, content://mms/outbox, "
1032 + "content://mms/temp.");
1033 }
Tom Taylor4ddacd02009-08-21 13:09:55 -07001034 PDU_CACHE_INSTANCE.purge(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035
1036 PduHeaders header = pdu.getPduHeaders();
1037 PduBody body = null;
1038 ContentValues values = new ContentValues();
1039 Set<Entry<Integer, String>> set;
1040
1041 set = ENCODED_STRING_COLUMN_NAME_MAP.entrySet();
1042 for (Entry<Integer, String> e : set) {
1043 int field = e.getKey();
1044 EncodedStringValue encodedString = header.getEncodedStringValue(field);
1045 if (encodedString != null) {
1046 String charsetColumn = CHARSET_COLUMN_NAME_MAP.get(field);
1047 values.put(e.getValue(), toIsoString(encodedString.getTextString()));
1048 values.put(charsetColumn, encodedString.getCharacterSet());
1049 }
1050 }
1051
1052 set = TEXT_STRING_COLUMN_NAME_MAP.entrySet();
1053 for (Entry<Integer, String> e : set){
1054 byte[] text = header.getTextString(e.getKey());
1055 if (text != null) {
1056 values.put(e.getValue(), toIsoString(text));
1057 }
1058 }
1059
1060 set = OCTET_COLUMN_NAME_MAP.entrySet();
1061 for (Entry<Integer, String> e : set){
1062 int b = header.getOctet(e.getKey());
1063 if (b != 0) {
1064 values.put(e.getValue(), b);
1065 }
1066 }
1067
1068 set = LONG_COLUMN_NAME_MAP.entrySet();
1069 for (Entry<Integer, String> e : set){
1070 long l = header.getLongInteger(e.getKey());
1071 if (l != -1L) {
1072 values.put(e.getValue(), l);
1073 }
1074 }
1075
1076 HashMap<Integer, EncodedStringValue[]> addressMap =
1077 new HashMap<Integer, EncodedStringValue[]>(ADDRESS_FIELDS.length);
1078 // Save address information.
1079 for (int addrType : ADDRESS_FIELDS) {
1080 EncodedStringValue[] array = null;
1081 if (addrType == PduHeaders.FROM) {
1082 EncodedStringValue v = header.getEncodedStringValue(addrType);
1083 if (v != null) {
1084 array = new EncodedStringValue[1];
1085 array[0] = v;
1086 }
1087 } else {
1088 array = header.getEncodedStringValues(addrType);
1089 }
1090 addressMap.put(addrType, array);
1091 }
1092
1093 HashSet<String> recipients = new HashSet<String>();
1094 long threadId = DUMMY_THREAD_ID;
1095 int msgType = pdu.getMessageType();
1096 // Here we only allocate thread ID for M-Notification.ind,
1097 // M-Retrieve.conf and M-Send.req.
1098 // Some of other PDU types may be allocated a thread ID outside
1099 // this scope.
1100 if ((msgType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND)
1101 || (msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF)
1102 || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) {
1103 EncodedStringValue[] array = null;
1104 switch (msgType) {
1105 case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
1106 case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
1107 array = addressMap.get(PduHeaders.FROM);
1108 break;
1109 case PduHeaders.MESSAGE_TYPE_SEND_REQ:
1110 array = addressMap.get(PduHeaders.TO);
1111 break;
1112 }
1113
1114 if (array != null) {
1115 for (EncodedStringValue v : array) {
1116 if (v != null) {
1117 recipients.add(v.getString());
1118 }
1119 }
1120 }
1121 threadId = Threads.getOrCreateThreadId(mContext, recipients);
1122 }
1123 values.put(Mms.THREAD_ID, threadId);
1124
1125 // Save parts first to avoid inconsistent message is loaded
1126 // while saving the parts.
1127 long dummyId = System.currentTimeMillis(); // Dummy ID of the msg.
1128 // Get body if the PDU is a RetrieveConf or SendReq.
1129 if (pdu instanceof MultimediaMessagePdu) {
1130 body = ((MultimediaMessagePdu) pdu).getBody();
1131 // Start saving parts if necessary.
1132 if (body != null) {
1133 int partsNum = body.getPartsNum();
1134 for (int i = 0; i < partsNum; i++) {
1135 PduPart part = body.getPart(i);
1136 persistPart(part, dummyId);
1137 }
1138 }
1139 }
1140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 Uri res = SqliteWrapper.insert(mContext, mContentResolver, uri, values);
1142 if (res == null) {
1143 throw new MmsException("persist() failed: return null.");
1144 }
1145
1146 // Get the real ID of the PDU and update all parts which were
1147 // saved with the dummy ID.
1148 long msgId = ContentUris.parseId(res);
1149 values = new ContentValues(1);
1150 values.put(Part.MSG_ID, msgId);
1151 SqliteWrapper.update(mContext, mContentResolver,
1152 Uri.parse("content://mms/" + dummyId + "/part"),
1153 values, null, null);
1154 // We should return the longest URI of the persisted PDU, for
1155 // example, if input URI is "content://mms/inbox" and the _ID of
1156 // persisted PDU is '8', we should return "content://mms/inbox/8"
1157 // instead of "content://mms/8".
1158 // FIXME: Should the MmsProvider be responsible for this???
1159 res = Uri.parse(uri + "/" + msgId);
1160
1161 // Save address information.
1162 for (int addrType : ADDRESS_FIELDS) {
1163 EncodedStringValue[] array = addressMap.get(addrType);
1164 if (array != null) {
1165 persistAddress(msgId, addrType, array);
1166 }
1167 }
1168
1169 return res;
1170 }
1171
1172 /**
1173 * Move a PDU object from one location to another.
1174 *
1175 * @param from Specify the PDU object to be moved.
1176 * @param to The destination location, should be one of the following:
1177 * "content://mms/inbox", "content://mms/sent",
1178 * "content://mms/drafts", "content://mms/outbox",
1179 * "content://mms/trash".
1180 * @return New Uri of the moved PDU.
1181 * @throws MmsException Error occurred while moving the message.
1182 */
1183 public Uri move(Uri from, Uri to) throws MmsException {
1184 // Check whether the 'msgId' has been assigned a valid value.
1185 long msgId = ContentUris.parseId(from);
1186 if (msgId == -1L) {
1187 throw new MmsException("Error! ID of the message: -1.");
1188 }
1189
1190 // Get corresponding int value of destination box.
1191 Integer msgBox = MESSAGE_BOX_MAP.get(to);
1192 if (msgBox == null) {
1193 throw new MmsException(
1194 "Bad destination, must be one of "
1195 + "content://mms/inbox, content://mms/sent, "
1196 + "content://mms/drafts, content://mms/outbox, "
1197 + "content://mms/temp.");
1198 }
1199
1200 ContentValues values = new ContentValues(1);
1201 values.put(Mms.MESSAGE_BOX, msgBox);
1202 SqliteWrapper.update(mContext, mContentResolver, from, values, null, null);
1203 return ContentUris.withAppendedId(to, msgId);
1204 }
1205
1206 /**
1207 * Wrap a byte[] into a String.
1208 */
1209 public static String toIsoString(byte[] bytes) {
1210 try {
1211 return new String(bytes, CharacterSets.MIMENAME_ISO_8859_1);
1212 } catch (UnsupportedEncodingException e) {
1213 // Impossible to reach here!
1214 Log.e(TAG, "ISO_8859_1 must be supported!", e);
1215 return "";
1216 }
1217 }
1218
1219 /**
1220 * Unpack a given String into a byte[].
1221 */
1222 public static byte[] getBytes(String data) {
1223 try {
1224 return data.getBytes(CharacterSets.MIMENAME_ISO_8859_1);
1225 } catch (UnsupportedEncodingException e) {
1226 // Impossible to reach here!
1227 Log.e(TAG, "ISO_8859_1 must be supported!", e);
1228 return new byte[0];
1229 }
1230 }
1231
1232 /**
1233 * Remove all objects in the temporary path.
1234 */
1235 public void release() {
1236 Uri uri = Uri.parse(TEMPORARY_DRM_OBJECT_URI);
1237 SqliteWrapper.delete(mContext, mContentResolver, uri, null, null);
1238 }
1239
1240 /**
1241 * Find all messages to be sent or downloaded before certain time.
1242 */
1243 public Cursor getPendingMessages(long dueTime) {
1244 Uri.Builder uriBuilder = PendingMessages.CONTENT_URI.buildUpon();
1245 uriBuilder.appendQueryParameter("protocol", "mms");
1246
1247 String selection = PendingMessages.ERROR_TYPE + " < ?"
1248 + " AND " + PendingMessages.DUE_TIME + " <= ?";
1249
1250 String[] selectionArgs = new String[] {
1251 String.valueOf(MmsSms.ERR_TYPE_GENERIC_PERMANENT),
1252 String.valueOf(dueTime)
1253 };
1254
1255 return SqliteWrapper.query(mContext, mContentResolver,
1256 uriBuilder.build(), null, selection, selectionArgs,
1257 PendingMessages.DUE_TIME);
1258 }
1259}