-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMMSSMSProvider.java
More file actions
1261 lines (1079 loc) · 51.2 KB
/
MMSSMSProvider.java
File metadata and controls
1261 lines (1079 loc) · 51.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.telephony;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.Telephony.CanonicalAddressesColumns;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.Sms;
import android.provider.Telephony.Threads;
import android.provider.Telephony.ThreadsColumns;
import android.provider.Telephony.MmsSms.PendingMessages;
import android.provider.Telephony.Sms.Conversations;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.mms.pdu.PduHeaders;
/**
* This class provides the ability to query the MMS and SMS databases
* at the same time, mixing messages from both in a single thread
* (A.K.A. conversation).
*
* A virtual column, MmsSms.TYPE_DISCRIMINATOR_COLUMN, may be
* requested in the projection for a query. Its value is either "mms"
* or "sms", depending on whether the message represented by the row
* is an MMS message or an SMS message, respectively.
*
* This class also provides the ability to find out what addresses
* participated in a particular thread. It doesn't support updates
* for either of these.
*
* This class provides a way to allocate and retrieve thread IDs.
* This is done atomically through a query. There is no insert URI
* for this.
*
* Finally, this class provides a way to delete or update all messages
* in a thread.
*/
public class MmsSmsProvider extends ContentProvider {
private static final UriMatcher URI_MATCHER =
new UriMatcher(UriMatcher.NO_MATCH);
private static final String LOG_TAG = "MmsSmsProvider";
private static final boolean DEBUG = false;
private static final String NO_DELETES_INSERTS_OR_UPDATES =
"MmsSmsProvider does not support deletes, inserts, or updates for this URI.";
private static final int URI_CONVERSATIONS = 0;
private static final int URI_CONVERSATIONS_MESSAGES = 1;
private static final int URI_CONVERSATIONS_RECIPIENTS = 2;
private static final int URI_MESSAGES_BY_PHONE = 3;
private static final int URI_THREAD_ID = 4;
private static final int URI_CANONICAL_ADDRESS = 5;
private static final int URI_PENDING_MSG = 6;
private static final int URI_COMPLETE_CONVERSATIONS = 7;
private static final int URI_UNDELIVERED_MSG = 8;
private static final int URI_CONVERSATIONS_SUBJECT = 9;
private static final int URI_NOTIFICATIONS = 10;
private static final int URI_OBSOLETE_THREADS = 11;
private static final int URI_DRAFT = 12;
private static final int URI_CANONICAL_ADDRESSES = 13;
private static final int URI_SEARCH = 14;
private static final int URI_SEARCH_SUGGEST = 15;
private static final int URI_FIRST_LOCKED_MESSAGE_ALL = 16;
private static final int URI_FIRST_LOCKED_MESSAGE_BY_THREAD_ID = 17;
/**
* the name of the table that is used to store the queue of
* messages(both MMS and SMS) to be sent/downloaded.
*/
public static final String TABLE_PENDING_MSG = "pending_msgs";
/**
* the name of the table that is used to store the canonical addresses for both SMS and MMS.
*/
private static final String TABLE_CANONICAL_ADDRESSES = "canonical_addresses";
// These constants are used to construct union queries across the
// MMS and SMS base tables.
// These are the columns that appear in both the MMS ("pdu") and
// SMS ("sms") message tables.
private static final String[] MMS_SMS_COLUMNS =
{ BaseColumns._ID, Mms.DATE, Mms.READ, Mms.THREAD_ID, Mms.LOCKED };
// These are the columns that appear only in the MMS message
// table.
private static final String[] MMS_ONLY_COLUMNS = {
Mms.CONTENT_CLASS, Mms.CONTENT_LOCATION, Mms.CONTENT_TYPE,
Mms.DELIVERY_REPORT, Mms.EXPIRY, Mms.MESSAGE_CLASS, Mms.MESSAGE_ID,
Mms.MESSAGE_SIZE, Mms.MESSAGE_TYPE, Mms.MESSAGE_BOX, Mms.PRIORITY,
Mms.READ_STATUS, Mms.RESPONSE_STATUS, Mms.RESPONSE_TEXT,
Mms.RETRIEVE_STATUS, Mms.RETRIEVE_TEXT_CHARSET, Mms.REPORT_ALLOWED,
Mms.READ_REPORT, Mms.STATUS, Mms.SUBJECT, Mms.SUBJECT_CHARSET,
Mms.TRANSACTION_ID, Mms.MMS_VERSION };
// These are the columns that appear only in the SMS message
// table.
private static final String[] SMS_ONLY_COLUMNS =
{ "address", "body", "person", "reply_path_present",
"service_center", "status", "subject", "type", "error_code" };
// These are all the columns that appear in the "threads" table.
private static final String[] THREADS_COLUMNS = {
BaseColumns._ID,
ThreadsColumns.DATE,
ThreadsColumns.RECIPIENT_IDS,
ThreadsColumns.MESSAGE_COUNT
};
private static final String[] CANONICAL_ADDRESSES_COLUMNS_1 =
new String[] { CanonicalAddressesColumns.ADDRESS };
private static final String[] CANONICAL_ADDRESSES_COLUMNS_2 =
new String[] { CanonicalAddressesColumns._ID,
CanonicalAddressesColumns.ADDRESS };
// These are all the columns that appear in the MMS and SMS
// message tables.
private static final String[] UNION_COLUMNS =
new String[MMS_SMS_COLUMNS.length
+ MMS_ONLY_COLUMNS.length
+ SMS_ONLY_COLUMNS.length];
// These are all the columns that appear in the MMS table.
private static final Set<String> MMS_COLUMNS = new HashSet<String>();
// These are all the columns that appear in the SMS table.
private static final Set<String> SMS_COLUMNS = new HashSet<String>();
private static final String VND_ANDROID_DIR_MMS_SMS =
"vnd.android-dir/mms-sms";
private static final String[] ID_PROJECTION = { BaseColumns._ID };
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final String SMS_CONVERSATION_CONSTRAINT = "(" +
Sms.TYPE + " != " + Sms.MESSAGE_TYPE_DRAFT + ")";
private static final String MMS_CONVERSATION_CONSTRAINT = "(" +
Mms.MESSAGE_BOX + " != " + Mms.MESSAGE_BOX_DRAFTS + " AND (" +
Mms.MESSAGE_TYPE + " = " + PduHeaders.MESSAGE_TYPE_SEND_REQ + " OR " +
Mms.MESSAGE_TYPE + " = " + PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF + " OR " +
Mms.MESSAGE_TYPE + " = " + PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND + "))";
private static final String AUTHORITY = "mms-sms";
static {
URI_MATCHER.addURI(AUTHORITY, "conversations", URI_CONVERSATIONS);
URI_MATCHER.addURI(AUTHORITY, "complete-conversations", URI_COMPLETE_CONVERSATIONS);
// In these patterns, "#" is the thread ID.
URI_MATCHER.addURI(
AUTHORITY, "conversations/#", URI_CONVERSATIONS_MESSAGES);
URI_MATCHER.addURI(
AUTHORITY, "conversations/#/recipients",
URI_CONVERSATIONS_RECIPIENTS);
URI_MATCHER.addURI(
AUTHORITY, "conversations/#/subject",
URI_CONVERSATIONS_SUBJECT);
// URI for deleting obsolete threads.
URI_MATCHER.addURI(AUTHORITY, "conversations/obsolete", URI_OBSOLETE_THREADS);
URI_MATCHER.addURI(
AUTHORITY, "messages/byphone/*",
URI_MESSAGES_BY_PHONE);
// In this pattern, two query parameter names are expected:
// "subject" and "recipient." Multiple "recipient" parameters
// may be present.
URI_MATCHER.addURI(AUTHORITY, "threadID", URI_THREAD_ID);
// Use this pattern to query the canonical address by given ID.
URI_MATCHER.addURI(AUTHORITY, "canonical-address/#", URI_CANONICAL_ADDRESS);
// Use this pattern to query all canonical addresses.
URI_MATCHER.addURI(AUTHORITY, "canonical-addresses", URI_CANONICAL_ADDRESSES);
URI_MATCHER.addURI(AUTHORITY, "search", URI_SEARCH);
URI_MATCHER.addURI(AUTHORITY, "searchSuggest", URI_SEARCH_SUGGEST);
// In this pattern, two query parameters may be supplied:
// "protocol" and "message." For example:
// content://mms-sms/pending?
// -> Return all pending messages;
// content://mms-sms/pending?protocol=sms
// -> Only return pending SMs;
// content://mms-sms/pending?protocol=mms&message=1
// -> Return the the pending MM which ID equals '1'.
//
URI_MATCHER.addURI(AUTHORITY, "pending", URI_PENDING_MSG);
// Use this pattern to get a list of undelivered messages.
URI_MATCHER.addURI(AUTHORITY, "undelivered", URI_UNDELIVERED_MSG);
// Use this pattern to see what delivery status reports (for
// both MMS and SMS) have not been delivered to the user.
URI_MATCHER.addURI(AUTHORITY, "notifications", URI_NOTIFICATIONS);
URI_MATCHER.addURI(AUTHORITY, "draft", URI_DRAFT);
URI_MATCHER.addURI(AUTHORITY, "locked", URI_FIRST_LOCKED_MESSAGE_ALL);
URI_MATCHER.addURI(AUTHORITY, "locked/#", URI_FIRST_LOCKED_MESSAGE_BY_THREAD_ID);
initializeColumnSets();
}
private SQLiteOpenHelper mOpenHelper;
private boolean mUseStrictPhoneNumberComparation;
@Override
public boolean onCreate() {
mOpenHelper = MmsSmsDatabaseHelper.getInstance(getContext());
mUseStrictPhoneNumberComparation =
getContext().getResources().getBoolean(
com.android.internal.R.bool.config_use_strict_phone_number_comparation);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor cursor = null;
switch(URI_MATCHER.match(uri)) {
case URI_COMPLETE_CONVERSATIONS:
cursor = getCompleteConversations(
projection, selection, selectionArgs, sortOrder);
break;
case URI_CONVERSATIONS:
String simple = uri.getQueryParameter("simple");
if ((simple != null) && simple.equals("true")) {
String threadType = uri.getQueryParameter("thread_type");
if (!TextUtils.isEmpty(threadType)) {
selection = concatSelections(
selection, Threads.TYPE + "=" + threadType);
}
cursor = getSimpleConversations(
projection, selection, selectionArgs, sortOrder);
} else {
cursor = getConversations(
projection, selection, selectionArgs, sortOrder);
}
break;
case URI_CONVERSATIONS_MESSAGES:
cursor = getConversationMessages(
uri.getPathSegments().get(1), projection, selection,
selectionArgs, sortOrder);
break;
case URI_CONVERSATIONS_RECIPIENTS:
cursor = getConversationById(
uri.getPathSegments().get(1), projection, selection,
selectionArgs, sortOrder);
break;
case URI_CONVERSATIONS_SUBJECT:
cursor = getConversationById(
uri.getPathSegments().get(1), projection, selection,
selectionArgs, sortOrder);
break;
case URI_MESSAGES_BY_PHONE:
cursor = getMessagesByPhoneNumber(
uri.getPathSegments().get(2), projection, selection,
selectionArgs, sortOrder);
break;
case URI_THREAD_ID:
List<String> recipients = uri.getQueryParameters("recipient");
cursor = getThreadId(recipients);
break;
case URI_CANONICAL_ADDRESS: {
String extraSelection = "_id=" + uri.getPathSegments().get(1);
String finalSelection = TextUtils.isEmpty(selection)
? extraSelection : extraSelection + " AND " + selection;
cursor = db.query(TABLE_CANONICAL_ADDRESSES,
CANONICAL_ADDRESSES_COLUMNS_1,
finalSelection,
selectionArgs,
null, null,
sortOrder);
break;
}
case URI_CANONICAL_ADDRESSES:
cursor = db.query(TABLE_CANONICAL_ADDRESSES,
CANONICAL_ADDRESSES_COLUMNS_2,
selection,
selectionArgs,
null, null,
sortOrder);
break;
case URI_SEARCH_SUGGEST: {
String searchString = uri.getQueryParameter("pattern");
String query = String.format("SELECT _id, index_text, source_id, table_to_use, offsets(words) FROM words WHERE words MATCH '%s*' LIMIT 50;", searchString);
if ( sortOrder != null
|| selection != null
|| selectionArgs != null
|| projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" +
"with this query");
}
cursor = db.rawQuery(query, null);
break;
}
case URI_SEARCH: {
if ( sortOrder != null
|| selection != null
|| selectionArgs != null
|| projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" +
"with this query");
}
// This code queries the sms and mms tables and returns a unified result set
// of text matches. We query the sms table which is pretty simple. We also
// query the pdu, part and addr table to get the mms result. Note that we're
// using a UNION so we have to have the same number of result columns from
// both queries.
String searchString = uri.getQueryParameter("pattern") + "*";
String smsProjection = "sms._id as _id,thread_id,address,body,date," +
"index_text,words._id";
String mmsProjection = "pdu._id,thread_id,addr.address,part.text as " + "" +
"body,pdu.date,index_text,words._id";
// search on the words table but return the rows from the corresponding sms table
String smsQuery = String.format(
"SELECT %s FROM sms,words WHERE (words MATCH ? " +
" AND sms._id=words.source_id AND words.table_to_use=1) ",
smsProjection);
// search on the words table but return the rows from the corresponding parts table
String mmsQuery = String.format(
"SELECT %s FROM pdu,part,addr,words WHERE ((part.mid=pdu._id) AND " +
"(addr.msg_id=pdu._id) AND " +
"(addr.type=%d) AND " +
"(part.ct='text/plain') AND " +
"(words MATCH ?) AND " +
"(part._id = words.source_id) AND " +
"(words.table_to_use=2))",
mmsProjection,
PduHeaders.TO);
// join the results from sms and part (mms)
String rawQuery = String.format(
"%s UNION %s GROUP BY %s ORDER BY %s",
smsQuery,
mmsQuery,
"thread_id",
"thread_id ASC, date DESC");
try {
cursor = db.rawQuery(rawQuery, new String[] { searchString, searchString });
} catch (Exception ex) {
Log.e(LOG_TAG, "got exception: " + ex.toString());
}
break;
}
case URI_PENDING_MSG: {
String protoName = uri.getQueryParameter("protocol");
String msgId = uri.getQueryParameter("message");
int proto = TextUtils.isEmpty(protoName) ? -1
: (protoName.equals("sms") ? MmsSms.SMS_PROTO : MmsSms.MMS_PROTO);
String extraSelection = (proto != -1) ?
(PendingMessages.PROTO_TYPE + "=" + proto) : " 0=0 ";
if (!TextUtils.isEmpty(msgId)) {
extraSelection += " AND " + PendingMessages.MSG_ID + "=" + msgId;
}
String finalSelection = TextUtils.isEmpty(selection)
? extraSelection : ("(" + extraSelection + ") AND " + selection);
String finalOrder = TextUtils.isEmpty(sortOrder)
? PendingMessages.DUE_TIME : sortOrder;
cursor = db.query(TABLE_PENDING_MSG, null,
finalSelection, selectionArgs, null, null, finalOrder);
break;
}
case URI_UNDELIVERED_MSG: {
cursor = getUndeliveredMessages(projection, selection,
selectionArgs, sortOrder);
break;
}
case URI_DRAFT: {
cursor = getDraftThread(projection, selection, selectionArgs, sortOrder);
break;
}
case URI_FIRST_LOCKED_MESSAGE_BY_THREAD_ID: {
long threadId;
try {
threadId = Long.parseLong(uri.getLastPathSegment());
} catch (NumberFormatException e) {
Log.e(LOG_TAG, "Thread ID must be a long.");
break;
}
cursor = getFirstLockedMessage(projection, "thread_id=" + Long.toString(threadId),
null, sortOrder);
break;
}
case URI_FIRST_LOCKED_MESSAGE_ALL: {
cursor = getFirstLockedMessage(projection, selection,
selectionArgs, sortOrder);
break;
}
default:
throw new IllegalStateException("Unrecognized URI:" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), MmsSms.CONTENT_URI);
return cursor;
}
/**
* Return the canonical address ID for this address.
*/
private long getSingleAddressId(String address) {
boolean isEmail = Mms.isEmailAddress(address);
String refinedAddress = isEmail ? address.toLowerCase() : address;
String selection = "address=?";
String[] selectionArgs;
long retVal = -1L;
if (isEmail) {
selectionArgs = new String[] { refinedAddress };
} else {
selection += " OR " + String.format("PHONE_NUMBERS_EQUAL(address, ?, %d)",
(mUseStrictPhoneNumberComparation ? 1 : 0));
selectionArgs = new String[] { refinedAddress, refinedAddress };
}
Cursor cursor = null;
try {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
cursor = db.query(
"canonical_addresses", ID_PROJECTION,
selection, selectionArgs, null, null, null);
if (cursor.getCount() == 0) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(CanonicalAddressesColumns.ADDRESS, refinedAddress);
db = mOpenHelper.getWritableDatabase();
retVal = db.insert("canonical_addresses",
CanonicalAddressesColumns.ADDRESS, contentValues);
Log.d(LOG_TAG, "getSingleAddressId: insert new canonical_address for " + address +
", _id=" + retVal);
return retVal;
}
if (cursor.moveToFirst()) {
retVal = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID));
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return retVal;
}
/**
* Return the canonical address IDs for these addresses.
*/
private Set<Long> getAddressIds(List<String> addresses) {
Set<Long> result = new HashSet<Long>(addresses.size());
for (String address : addresses) {
if (!address.equals(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR)) {
long id = getSingleAddressId(address);
if (id != -1L) {
result.add(id);
} else {
Log.e(LOG_TAG, "getAddressIds: address ID not found for " + address);
}
}
}
return result;
}
/**
* Return a sorted array of the given Set of Longs.
*/
private long[] getSortedSet(Set<Long> numbers) {
int size = numbers.size();
long[] result = new long[size];
int i = 0;
for (Long number : numbers) {
result[i++] = number;
}
if (size > 1) {
Arrays.sort(result);
}
return result;
}
/**
* Return a String of the numbers in the given array, in order,
* separated by spaces.
*/
private String getSpaceSeparatedNumbers(long[] numbers) {
int size = numbers.length;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < size; i++) {
if (i != 0) {
buffer.append(' ');
}
buffer.append(numbers[i]);
}
return buffer.toString();
}
/**
* Insert a record for a new thread.
*/
private void insertThread(String recipientIds, int numberOfRecipients) {
ContentValues values = new ContentValues(4);
long date = System.currentTimeMillis();
values.put(ThreadsColumns.DATE, date - date % 1000);
values.put(ThreadsColumns.RECIPIENT_IDS, recipientIds);
if (numberOfRecipients > 1) {
values.put(Threads.TYPE, Threads.BROADCAST_THREAD);
}
values.put(ThreadsColumns.MESSAGE_COUNT, 0);
long result = mOpenHelper.getWritableDatabase().insert("threads", null, values);
Log.d(LOG_TAG, "insertThread: created new thread_id " + result +
" for recipientIds " + recipientIds);
getContext().getContentResolver().notifyChange(MmsSms.CONTENT_URI, null);
}
private static final String THREAD_QUERY =
"SELECT _id FROM threads " + "WHERE recipient_ids=?";
/**
* Return the thread ID for this list of
* recipients IDs. If no thread exists with this ID, create
* one and return it. Callers should always use
* Threads.getThreadId to access this information.
*/
private synchronized Cursor getThreadId(List<String> recipients) {
Set<Long> addressIds = getAddressIds(recipients);
String recipientIds = "";
// optimize for size==1, which should be most of the cases
if (addressIds.size() == 1) {
for (Long addressId : addressIds) {
recipientIds = Long.toString(addressId);
}
} else {
recipientIds = getSpaceSeparatedNumbers(getSortedSet(addressIds));
}
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
Log.d(LOG_TAG, "getThreadId: recipientIds (selectionArgs) =" + recipientIds);
}
String[] selectionArgs = new String[] { recipientIds };
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(THREAD_QUERY, selectionArgs);
if (cursor.getCount() == 0) {
cursor.close();
Log.d(LOG_TAG, "getThreadId: create new thread_id for recipients " + recipients);
insertThread(recipientIds, recipients.size());
db = mOpenHelper.getReadableDatabase(); // In case insertThread closed it
cursor = db.rawQuery(THREAD_QUERY, selectionArgs);
}
if (cursor.getCount() > 1) {
Log.w(LOG_TAG, "getThreadId: why is cursorCount=" + cursor.getCount());
}
return cursor;
}
private static String concatSelections(String selection1, String selection2) {
if (TextUtils.isEmpty(selection1)) {
return selection2;
} else if (TextUtils.isEmpty(selection2)) {
return selection1;
} else {
return selection1 + " AND " + selection2;
}
}
/**
* If a null projection is given, return the union of all columns
* in both the MMS and SMS messages tables. Otherwise, return the
* given projection.
*/
private static String[] handleNullMessageProjection(
String[] projection) {
return projection == null ? UNION_COLUMNS : projection;
}
/**
* If a null projection is given, return the set of all columns in
* the threads table. Otherwise, return the given projection.
*/
private static String[] handleNullThreadsProjection(
String[] projection) {
return projection == null ? THREADS_COLUMNS : projection;
}
/**
* If a null sort order is given, return "normalized_date ASC".
* Otherwise, return the given sort order.
*/
private static String handleNullSortOrder (String sortOrder) {
return sortOrder == null ? "normalized_date ASC" : sortOrder;
}
/**
* Return existing threads in the database.
*/
private Cursor getSimpleConversations(String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return mOpenHelper.getReadableDatabase().query("threads", projection,
selection, selectionArgs, null, null, " date DESC");
}
/**
* Return the thread which has draft in both MMS and SMS.
*
* Use this query:
*
* SELECT ...
* FROM (SELECT _id, thread_id, ...
* FROM pdu
* WHERE msg_box = 3 AND ...
* UNION
* SELECT _id, thread_id, ...
* FROM sms
* WHERE type = 3 AND ...
* )
* ;
*/
private Cursor getDraftThread(String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String[] innerProjection = new String[] {BaseColumns._ID, Conversations.THREAD_ID};
SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
mmsQueryBuilder.setTables(MmsProvider.TABLE_PDU);
smsQueryBuilder.setTables(SmsProvider.TABLE_SMS);
String mmsSubQuery = mmsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, innerProjection,
MMS_COLUMNS, 1, "mms",
concatSelections(selection, Mms.MESSAGE_BOX + "=" + Mms.MESSAGE_BOX_DRAFTS),
selectionArgs, null, null);
String smsSubQuery = smsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, innerProjection,
SMS_COLUMNS, 1, "sms",
concatSelections(selection, Sms.TYPE + "=" + Sms.MESSAGE_TYPE_DRAFT),
selectionArgs, null, null);
SQLiteQueryBuilder unionQueryBuilder = new SQLiteQueryBuilder();
unionQueryBuilder.setDistinct(true);
String unionQuery = unionQueryBuilder.buildUnionQuery(
new String[] { mmsSubQuery, smsSubQuery }, null, null);
SQLiteQueryBuilder outerQueryBuilder = new SQLiteQueryBuilder();
outerQueryBuilder.setTables("(" + unionQuery + ")");
String outerQuery = outerQueryBuilder.buildQuery(
projection, null, null, null, null, sortOrder, null);
return mOpenHelper.getReadableDatabase().rawQuery(outerQuery, EMPTY_STRING_ARRAY);
}
/**
* Return the most recent message in each conversation in both MMS
* and SMS.
*
* Use this query:
*
* SELECT ...
* FROM (SELECT thread_id AS tid, date * 1000 AS normalized_date, ...
* FROM pdu
* WHERE msg_box != 3 AND ...
* GROUP BY thread_id
* HAVING date = MAX(date)
* UNION
* SELECT thread_id AS tid, date AS normalized_date, ...
* FROM sms
* WHERE ...
* GROUP BY thread_id
* HAVING date = MAX(date))
* GROUP BY tid
* HAVING normalized_date = MAX(normalized_date);
*
* The msg_box != 3 comparisons ensure that we don't include draft
* messages.
*/
private Cursor getConversations(String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
mmsQueryBuilder.setTables(MmsProvider.TABLE_PDU);
smsQueryBuilder.setTables(SmsProvider.TABLE_SMS);
String[] columns = handleNullMessageProjection(projection);
String[] innerMmsProjection = makeProjectionWithDateAndThreadId(
UNION_COLUMNS, 1000);
String[] innerSmsProjection = makeProjectionWithDateAndThreadId(
UNION_COLUMNS, 1);
String mmsSubQuery = mmsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, innerMmsProjection,
MMS_COLUMNS, 1, "mms",
concatSelections(selection, MMS_CONVERSATION_CONSTRAINT), selectionArgs,
"thread_id", "date = MAX(date)");
String smsSubQuery = smsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, innerSmsProjection,
SMS_COLUMNS, 1, "sms",
concatSelections(selection, SMS_CONVERSATION_CONSTRAINT), selectionArgs,
"thread_id", "date = MAX(date)");
SQLiteQueryBuilder unionQueryBuilder = new SQLiteQueryBuilder();
unionQueryBuilder.setDistinct(true);
String unionQuery = unionQueryBuilder.buildUnionQuery(
new String[] { mmsSubQuery, smsSubQuery }, null, null);
SQLiteQueryBuilder outerQueryBuilder = new SQLiteQueryBuilder();
outerQueryBuilder.setTables("(" + unionQuery + ")");
String outerQuery = outerQueryBuilder.buildQuery(
columns, null, null, "tid",
"normalized_date = MAX(normalized_date)", sortOrder, null);
return mOpenHelper.getReadableDatabase().rawQuery(outerQuery, EMPTY_STRING_ARRAY);
}
/**
* Return the first locked message found in the union of MMS
* and SMS messages.
*
* Use this query:
*
* SELECT _id FROM pdu GROUP BY _id HAVING locked=1 UNION SELECT _id FROM sms GROUP
* BY _id HAVING locked=1 LIMIT 1
*
* We limit by 1 because we're only interested in knowing if
* there is *any* locked message, not the actual messages themselves.
*/
private Cursor getFirstLockedMessage(String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
mmsQueryBuilder.setTables(MmsProvider.TABLE_PDU);
smsQueryBuilder.setTables(SmsProvider.TABLE_SMS);
String[] idColumn = new String[] { BaseColumns._ID };
String mmsSubQuery = mmsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, idColumn,
null, 1, "mms",
selection, selectionArgs,
BaseColumns._ID, "locked=1");
String smsSubQuery = smsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, idColumn,
null, 1, "sms",
selection, selectionArgs,
BaseColumns._ID, "locked=1");
SQLiteQueryBuilder unionQueryBuilder = new SQLiteQueryBuilder();
unionQueryBuilder.setDistinct(true);
String unionQuery = unionQueryBuilder.buildUnionQuery(
new String[] { mmsSubQuery, smsSubQuery }, null, "1");
Cursor cursor = mOpenHelper.getReadableDatabase().rawQuery(unionQuery, EMPTY_STRING_ARRAY);
if (DEBUG) {
Log.v("MmsSmsProvider", "getFirstLockedMessage query: " + unionQuery);
Log.v("MmsSmsProvider", "cursor count: " + cursor.getCount());
}
return cursor;
}
/**
* Return every message in each conversation in both MMS
* and SMS.
*/
private Cursor getCompleteConversations(String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
String unionQuery = buildConversationQuery(
projection, selection, selectionArgs, sortOrder);
return mOpenHelper.getReadableDatabase().rawQuery(unionQuery, EMPTY_STRING_ARRAY);
}
/**
* Add normalized date and thread_id to the list of columns for an
* inner projection. This is necessary so that the outer query
* can have access to these columns even if the caller hasn't
* requested them in the result.
*/
private String[] makeProjectionWithDateAndThreadId(
String[] projection, int dateMultiple) {
int projectionSize = projection.length;
String[] result = new String[projectionSize + 2];
result[0] = "thread_id AS tid";
result[1] = "date * " + dateMultiple + " AS normalized_date";
for (int i = 0; i < projectionSize; i++) {
result[i + 2] = projection[i];
}
return result;
}
/**
* Return the union of MMS and SMS messages for this thread ID.
*/
private Cursor getConversationMessages(
String threadIdString, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
try {
Long.parseLong(threadIdString);
} catch (NumberFormatException exception) {
Log.e(LOG_TAG, "Thread ID must be a Long.");
return null;
}
String finalSelection = concatSelections(
selection, "thread_id = " + threadIdString);
String unionQuery = buildConversationQuery(
projection, finalSelection, selectionArgs, sortOrder);
return mOpenHelper.getReadableDatabase().rawQuery(unionQuery, EMPTY_STRING_ARRAY);
}
/**
* Return the union of MMS and SMS messages whose recipients
* included this phone number.
*
* Use this query:
*
* SELECT ...
* FROM pdu, (SELECT _id AS address_id
* FROM addr
* WHERE (address='<phoneNumber>' OR
* PHONE_NUMBERS_EQUAL(addr.address, '<phoneNumber>', 1/0)))
* AS matching_addresses
* WHERE pdu._id = matching_addresses.address_id
* UNION
* SELECT ...
* FROM sms
* WHERE (address='<phoneNumber>' OR PHONE_NUMBERS_EQUAL(sms.address, '<phoneNumber>', 1/0));
*/
private Cursor getMessagesByPhoneNumber(
String phoneNumber, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String escapedPhoneNumber = DatabaseUtils.sqlEscapeString(phoneNumber);
String finalMmsSelection =
concatSelections(
selection,
"pdu._id = matching_addresses.address_id");
String finalSmsSelection =
concatSelections(
selection,
"(address=" + escapedPhoneNumber + " OR PHONE_NUMBERS_EQUAL(address, " +
escapedPhoneNumber +
(mUseStrictPhoneNumberComparation ? ", 1))" : ", 0))"));
SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
mmsQueryBuilder.setDistinct(true);
smsQueryBuilder.setDistinct(true);
mmsQueryBuilder.setTables(
MmsProvider.TABLE_PDU +
", (SELECT _id AS address_id " +
"FROM addr WHERE (address=" + escapedPhoneNumber +
" OR PHONE_NUMBERS_EQUAL(addr.address, " +
escapedPhoneNumber +
(mUseStrictPhoneNumberComparation ? ", 1))) " : ", 0))) ") +
"AS matching_addresses");
smsQueryBuilder.setTables(SmsProvider.TABLE_SMS);
String[] columns = handleNullMessageProjection(projection);
String mmsSubQuery = mmsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, columns, MMS_COLUMNS,
0, "mms", finalMmsSelection, selectionArgs, null, null);
String smsSubQuery = smsQueryBuilder.buildUnionSubQuery(
MmsSms.TYPE_DISCRIMINATOR_COLUMN, columns, SMS_COLUMNS,
0, "sms", finalSmsSelection, selectionArgs, null, null);
SQLiteQueryBuilder unionQueryBuilder = new SQLiteQueryBuilder();
unionQueryBuilder.setDistinct(true);
String unionQuery = unionQueryBuilder.buildUnionQuery(
new String[] { mmsSubQuery, smsSubQuery }, sortOrder, null);
return mOpenHelper.getReadableDatabase().rawQuery(unionQuery, EMPTY_STRING_ARRAY);
}
/**
* Return the conversation of certain thread ID.
*/
private Cursor getConversationById(
String threadIdString, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
try {
Long.parseLong(threadIdString);
} catch (NumberFormatException exception) {
Log.e(LOG_TAG, "Thread ID must be a Long.");
return null;
}
String extraSelection = "_id=" + threadIdString;
String finalSelection = concatSelections(selection, extraSelection);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
String[] columns = handleNullThreadsProjection(projection);
queryBuilder.setDistinct(true);
queryBuilder.setTables("threads");
return queryBuilder.query(
mOpenHelper.getReadableDatabase(), columns, finalSelection,
selectionArgs, sortOrder, null, null);
}
private static String joinPduAndPendingMsgTables() {
return MmsProvider.TABLE_PDU + " LEFT JOIN " + TABLE_PENDING_MSG
+ " ON pdu._id = pending_msgs.msg_id";
}
private static String[] createMmsProjection(String[] old) {
String[] newProjection = new String[old.length];
for (int i = 0; i < old.length; i++) {
if (old[i].equals(BaseColumns._ID)) {
newProjection[i] = "pdu._id";
} else {
newProjection[i] = old[i];
}
}
return newProjection;
}
private Cursor getUndeliveredMessages(
String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
String[] mmsProjection = createMmsProjection(projection);