blob: 473bb8f4e7084e793d92e81cc8f99016d9ac41be [file] [log] [blame]
Eric Erfanianccca3152017-02-22 16:32:36 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
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.incallui;
18
19import android.content.Context;
20import android.database.Cursor;
21import android.graphics.Bitmap;
22import android.graphics.drawable.Drawable;
23import android.net.Uri;
24import android.os.Build.VERSION;
25import android.os.Build.VERSION_CODES;
26import android.provider.ContactsContract;
27import android.provider.ContactsContract.CommonDataKinds.Phone;
28import android.provider.ContactsContract.Contacts;
29import android.provider.ContactsContract.Data;
30import android.provider.ContactsContract.PhoneLookup;
31import android.provider.ContactsContract.RawContacts;
32import android.support.annotation.RequiresApi;
33import android.telephony.PhoneNumberUtils;
34import android.text.TextUtils;
35import com.android.contacts.common.ContactsUtils;
36import com.android.contacts.common.ContactsUtils.UserType;
37import com.android.contacts.common.util.TelephonyManagerUtils;
38import com.android.dialer.phonenumbercache.ContactInfoHelper;
39import com.android.dialer.phonenumbercache.PhoneLookupUtil;
40import com.android.dialer.phonenumberutil.PhoneNumberHelper;
41
42/**
43 * Looks up caller information for the given phone number. This is intermediate data and should NOT
44 * be used by any UI.
45 */
46public class CallerInfo {
47
48 private static final String TAG = "CallerInfo";
49
50 // We should always use this projection starting from N onward.
51 @RequiresApi(VERSION_CODES.N)
52 private static final String[] DEFAULT_PHONELOOKUP_PROJECTION =
53 new String[] {
54 PhoneLookup.CONTACT_ID,
55 PhoneLookup.DISPLAY_NAME,
56 PhoneLookup.LOOKUP_KEY,
57 PhoneLookup.NUMBER,
58 PhoneLookup.NORMALIZED_NUMBER,
59 PhoneLookup.LABEL,
60 PhoneLookup.TYPE,
61 PhoneLookup.PHOTO_URI,
62 PhoneLookup.CUSTOM_RINGTONE,
63 PhoneLookup.SEND_TO_VOICEMAIL
64 };
65
66 // In pre-N, contact id is stored in {@link PhoneLookup._ID} in non-sip query.
67 private static final String[] BACKWARD_COMPATIBLE_NON_SIP_DEFAULT_PHONELOOKUP_PROJECTION =
68 new String[] {
69 PhoneLookup._ID,
70 PhoneLookup.DISPLAY_NAME,
71 PhoneLookup.LOOKUP_KEY,
72 PhoneLookup.NUMBER,
73 PhoneLookup.NORMALIZED_NUMBER,
74 PhoneLookup.LABEL,
75 PhoneLookup.TYPE,
76 PhoneLookup.PHOTO_URI,
77 PhoneLookup.CUSTOM_RINGTONE,
78 PhoneLookup.SEND_TO_VOICEMAIL
79 };
80 /**
81 * Please note that, any one of these member variables can be null, and any accesses to them
82 * should be prepared to handle such a case.
83 *
84 * <p>Also, it is implied that phoneNumber is more often populated than name is, (think of calls
85 * being dialed/received using numbers where names are not known to the device), so phoneNumber
86 * should serve as a dependable fallback when name is unavailable.
87 *
88 * <p>One other detail here is that this CallerInfo object reflects information found on a
89 * connection, it is an OUTPUT that serves mainly to display information to the user. In no way is
90 * this object used as input to make a connection, so we can choose to display whatever
91 * human-readable text makes sense to the user for a connection. This is especially relevant for
92 * the phone number field, since it is the one field that is most likely exposed to the user.
93 *
94 * <p>As an example: 1. User dials "911" 2. Device recognizes that this is an emergency number 3.
95 * We use the "Emergency Number" string instead of "911" in the phoneNumber field.
96 *
97 * <p>What we're really doing here is treating phoneNumber as an essential field here, NOT name.
98 * We're NOT always guaranteed to have a name for a connection, but the number should be
99 * displayable.
100 */
101 public String name;
102
103 public String nameAlternative;
104 public String phoneNumber;
105 public String normalizedNumber;
106 public String forwardingNumber;
107 public String geoDescription;
108 public String cnapName;
109 public int numberPresentation;
110 public int namePresentation;
111 public boolean contactExists;
112 public String phoneLabel;
113 /* Split up the phoneLabel into number type and label name */
114 public int numberType;
115 public String numberLabel;
116 public int photoResource;
117 // Contact ID, which will be 0 if a contact comes from the corp CP2.
118 public long contactIdOrZero;
119 public String lookupKeyOrNull;
120 public boolean needUpdate;
121 public Uri contactRefUri;
122 public @UserType long userType;
123 /**
124 * Contact display photo URI. If a contact has no display photo but a thumbnail, it'll be the
125 * thumbnail URI instead.
126 */
127 public Uri contactDisplayPhotoUri;
128 // fields to hold individual contact preference data,
129 // including the send to voicemail flag and the ringtone
130 // uri reference.
131 public Uri contactRingtoneUri;
132 public boolean shouldSendToVoicemail;
133 /**
134 * Drawable representing the caller image. This is essentially a cache for the image data tied
135 * into the connection / callerinfo object.
136 *
137 * <p>This might be a high resolution picture which is more suitable for full-screen image view
138 * than for smaller icons used in some kinds of notifications.
139 *
140 * <p>The {@link #isCachedPhotoCurrent} flag indicates if the image data needs to be reloaded.
141 */
142 public Drawable cachedPhoto;
143 /**
144 * Bitmap representing the caller image which has possibly lower resolution than {@link
145 * #cachedPhoto} and thus more suitable for icons (like notification icons).
146 *
147 * <p>In usual cases this is just down-scaled image of {@link #cachedPhoto}. If the down-scaling
148 * fails, this will just become null.
149 *
150 * <p>The {@link #isCachedPhotoCurrent} flag indicates if the image data needs to be reloaded.
151 */
152 public Bitmap cachedPhotoIcon;
153 /**
154 * Boolean which indicates if {@link #cachedPhoto} and {@link #cachedPhotoIcon} is fresh enough.
155 * If it is false, those images aren't pointing to valid objects.
156 */
157 public boolean isCachedPhotoCurrent;
158 /**
159 * String which holds the call subject sent as extra from the lower layers for this call. This is
160 * used to display the no-caller ID reason for restricted/unknown number presentation.
161 */
162 public String callSubject;
163
164 private boolean mIsEmergency;
165 private boolean mIsVoiceMail;
166
167 public CallerInfo() {
168 // TODO: Move all the basic initialization here?
169 mIsEmergency = false;
170 mIsVoiceMail = false;
171 userType = ContactsUtils.USER_TYPE_CURRENT;
172 }
173
174 public static String[] getDefaultPhoneLookupProjection(Uri phoneLookupUri) {
175 if (VERSION.SDK_INT >= VERSION_CODES.N) {
176 return DEFAULT_PHONELOOKUP_PROJECTION;
177 }
178 // Pre-N
179 boolean isSip =
180 phoneLookupUri.getBooleanQueryParameter(
181 ContactsContract.PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, false);
182 return (isSip)
183 ? DEFAULT_PHONELOOKUP_PROJECTION
184 : BACKWARD_COMPATIBLE_NON_SIP_DEFAULT_PHONELOOKUP_PROJECTION;
185 }
186
187 /**
188 * getCallerInfo given a Cursor.
189 *
190 * @param context the context used to retrieve string constants
191 * @param contactRef the URI to attach to this CallerInfo object
192 * @param cursor the first object in the cursor is used to build the CallerInfo object.
193 * @return the CallerInfo which contains the caller id for the given number. The returned
194 * CallerInfo is null if no number is supplied.
195 */
196 public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) {
197 CallerInfo info = new CallerInfo();
198 info.photoResource = 0;
199 info.phoneLabel = null;
200 info.numberType = 0;
201 info.numberLabel = null;
202 info.cachedPhoto = null;
203 info.isCachedPhotoCurrent = false;
204 info.contactExists = false;
205 info.userType = ContactsUtils.USER_TYPE_CURRENT;
206
207 Log.v(TAG, "getCallerInfo() based on cursor...");
208
209 if (cursor != null) {
210 if (cursor.moveToFirst()) {
211 // TODO: photo_id is always available but not taken
212 // care of here. Maybe we should store it in the
213 // CallerInfo object as well.
214
215 long contactId = 0L;
216 int columnIndex;
217
218 // Look for the name
219 columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
220 if (columnIndex != -1) {
221 info.name = cursor.getString(columnIndex);
222 }
223
224 // Look for the number
225 columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER);
226 if (columnIndex != -1) {
227 info.phoneNumber = cursor.getString(columnIndex);
228 }
229
230 // Look for the normalized number
231 columnIndex = cursor.getColumnIndex(PhoneLookup.NORMALIZED_NUMBER);
232 if (columnIndex != -1) {
233 info.normalizedNumber = cursor.getString(columnIndex);
234 }
235
236 // Look for the label/type combo
237 columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL);
238 if (columnIndex != -1) {
239 int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE);
240 if (typeColumnIndex != -1) {
241 info.numberType = cursor.getInt(typeColumnIndex);
242 info.numberLabel = cursor.getString(columnIndex);
243 info.phoneLabel =
244 Phone.getTypeLabel(context.getResources(), info.numberType, info.numberLabel)
245 .toString();
246 }
247 }
248
249 // cache the lookup key for later use to create lookup URIs
250 columnIndex = cursor.getColumnIndex(PhoneLookup.LOOKUP_KEY);
251 if (columnIndex != -1) {
252 info.lookupKeyOrNull = cursor.getString(columnIndex);
253 }
254
255 // Look for the person_id.
256 columnIndex = getColumnIndexForPersonId(contactRef, cursor);
257 if (columnIndex != -1) {
258 contactId = cursor.getLong(columnIndex);
259 // QuickContacts in M doesn't support enterprise contact id
260 if (contactId != 0
261 && (VERSION.SDK_INT >= VERSION_CODES.N
262 || !Contacts.isEnterpriseContactId(contactId))) {
263 info.contactIdOrZero = contactId;
264 Log.v(TAG, "==> got info.contactIdOrZero: " + info.contactIdOrZero);
265 }
266 } else {
267 // No valid columnIndex, so we can't look up person_id.
268 Log.v(TAG, "Couldn't find contactId column for " + contactRef);
269 // Watch out: this means that anything that depends on
270 // person_id will be broken (like contact photo lookups in
271 // the in-call UI, for example.)
272 }
273
274 // Display photo URI.
275 columnIndex = cursor.getColumnIndex(PhoneLookup.PHOTO_URI);
276 if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) {
277 info.contactDisplayPhotoUri = Uri.parse(cursor.getString(columnIndex));
278 } else {
279 info.contactDisplayPhotoUri = null;
280 }
281
282 // look for the custom ringtone, create from the string stored
283 // in the database.
284 columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE);
285 if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) {
286 if (TextUtils.isEmpty(cursor.getString(columnIndex))) {
287 // make it consistent with frameworks/base/.../CallerInfo.java
288 info.contactRingtoneUri = Uri.EMPTY;
289 } else {
290 info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex));
291 }
292 } else {
293 info.contactRingtoneUri = null;
294 }
295
296 // look for the send to voicemail flag, set it to true only
297 // under certain circumstances.
298 columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL);
299 info.shouldSendToVoicemail = (columnIndex != -1) && ((cursor.getInt(columnIndex)) == 1);
300 info.contactExists = true;
301
302 // Determine userType by directoryId and contactId
303 final String directory =
304 contactRef == null
305 ? null
306 : contactRef.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY);
307 Long directoryId = null;
308 if (directory != null) {
309 try {
310 directoryId = Long.parseLong(directory);
311 } catch (NumberFormatException e) {
312 // do nothing
313 }
314 }
315 info.userType = ContactsUtils.determineUserType(directoryId, contactId);
316
317 info.nameAlternative =
318 ContactInfoHelper.lookUpDisplayNameAlternative(
319 context, info.lookupKeyOrNull, info.userType, directoryId);
320 }
321 cursor.close();
322 }
323
324 info.needUpdate = false;
325 info.name = normalize(info.name);
326 info.contactRefUri = contactRef;
327
328 return info;
329 }
330
331 /**
332 * getCallerInfo given a URI, look up in the call-log database for the uri unique key.
333 *
334 * @param context the context used to get the ContentResolver
335 * @param contactRef the URI used to lookup caller id
336 * @return the CallerInfo which contains the caller id for the given number. The returned
337 * CallerInfo is null if no number is supplied.
338 */
339 private static CallerInfo getCallerInfo(Context context, Uri contactRef) {
340
341 return getCallerInfo(
342 context,
343 contactRef,
344 context.getContentResolver().query(contactRef, null, null, null, null));
345 }
346
347 /**
348 * Performs another lookup if previous lookup fails and it's a SIP call and the peer's username is
349 * all numeric. Look up the username as it could be a PSTN number in the contact database.
350 *
351 * @param context the query context
352 * @param number the original phone number, could be a SIP URI
353 * @param previousResult the result of previous lookup
354 * @return previousResult if it's not the case
355 */
356 static CallerInfo doSecondaryLookupIfNecessary(
357 Context context, String number, CallerInfo previousResult) {
358 if (!previousResult.contactExists && PhoneNumberHelper.isUriNumber(number)) {
359 String username = PhoneNumberHelper.getUsernameFromUriNumber(number);
360 if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
361 previousResult =
362 getCallerInfo(
363 context,
364 Uri.withAppendedPath(
365 PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, Uri.encode(username)));
366 }
367 }
368 return previousResult;
369 }
370
371 // Accessors
372
373 private static String normalize(String s) {
374 if (s == null || s.length() > 0) {
375 return s;
376 } else {
377 return null;
378 }
379 }
380
381 /**
382 * Returns the column index to use to find the "person_id" field in the specified cursor, based on
383 * the contact URI that was originally queried.
384 *
385 * <p>This is a helper function for the getCallerInfo() method that takes a Cursor. Looking up the
386 * person_id is nontrivial (compared to all the other CallerInfo fields) since the column we need
387 * to use depends on what query we originally ran.
388 *
389 * <p>Watch out: be sure to not do any database access in this method, since it's run from the UI
390 * thread (see comments below for more info.)
391 *
392 * @return the columnIndex to use (with cursor.getLong()) to get the person_id, or -1 if we
393 * couldn't figure out what colum to use.
394 * <p>TODO: Add a unittest for this method. (This is a little tricky to test, since we'll need
395 * a live contacts database to test against, preloaded with at least some phone numbers and
396 * SIP addresses. And we'll probably have to hardcode the column indexes we expect, so the
397 * test might break whenever the contacts schema changes. But we can at least make sure we
398 * handle all the URI patterns we claim to, and that the mime types match what we expect...)
399 */
400 private static int getColumnIndexForPersonId(Uri contactRef, Cursor cursor) {
401 // TODO: This is pretty ugly now, see bug 2269240 for
402 // more details. The column to use depends upon the type of URL:
403 // - content://com.android.contacts/data/phones ==> use the "contact_id" column
404 // - content://com.android.contacts/phone_lookup ==> use the "_ID" column
405 // - content://com.android.contacts/data ==> use the "contact_id" column
406 // If it's none of the above, we leave columnIndex=-1 which means
407 // that the person_id field will be left unset.
408 //
409 // The logic here *used* to be based on the mime type of contactRef
410 // (for example Phone.CONTENT_ITEM_TYPE would tell us to use the
411 // RawContacts.CONTACT_ID column). But looking up the mime type requires
412 // a call to context.getContentResolver().getType(contactRef), which
413 // isn't safe to do from the UI thread since it can cause an ANR if
414 // the contacts provider is slow or blocked (like during a sync.)
415 //
416 // So instead, figure out the column to use for person_id by just
417 // looking at the URI itself.
418
419 Log.v(TAG, "- getColumnIndexForPersonId: contactRef URI = '" + contactRef + "'...");
420 // Warning: Do not enable the following logging (due to ANR risk.)
421 // if (VDBG) Rlog.v(TAG, "- MIME type: "
422 // + context.getContentResolver().getType(contactRef));
423
424 String url = contactRef.toString();
425 String columnName = null;
426 if (url.startsWith("content://com.android.contacts/data/phones")) {
427 // Direct lookup in the Phone table.
428 // MIME type: Phone.CONTENT_ITEM_TYPE (= "vnd.android.cursor.item/phone_v2")
429 Log.v(TAG, "'data/phones' URI; using RawContacts.CONTACT_ID");
430 columnName = RawContacts.CONTACT_ID;
431 } else if (url.startsWith("content://com.android.contacts/data")) {
432 // Direct lookup in the Data table.
433 // MIME type: Data.CONTENT_TYPE (= "vnd.android.cursor.dir/data")
434 Log.v(TAG, "'data' URI; using Data.CONTACT_ID");
435 // (Note Data.CONTACT_ID and RawContacts.CONTACT_ID are equivalent.)
436 columnName = Data.CONTACT_ID;
437 } else if (url.startsWith("content://com.android.contacts/phone_lookup")) {
438 // Lookup in the PhoneLookup table, which provides "fuzzy matching"
439 // for phone numbers.
440 // MIME type: PhoneLookup.CONTENT_TYPE (= "vnd.android.cursor.dir/phone_lookup")
441 Log.v(TAG, "'phone_lookup' URI; using PhoneLookup._ID");
442 columnName = PhoneLookupUtil.getContactIdColumnNameForUri(contactRef);
443 } else {
444 Log.v(TAG, "Unexpected prefix for contactRef '" + url + "'");
445 }
446 int columnIndex = (columnName != null) ? cursor.getColumnIndex(columnName) : -1;
447 Log.v(
448 TAG,
449 "==> Using column '"
450 + columnName
451 + "' (columnIndex = "
452 + columnIndex
453 + ") for person_id lookup...");
454 return columnIndex;
455 }
456
457 /** @return true if the caller info is an emergency number. */
458 public boolean isEmergencyNumber() {
459 return mIsEmergency;
460 }
461
462 /** @return true if the caller info is a voicemail number. */
463 public boolean isVoiceMailNumber() {
464 return mIsVoiceMail;
465 }
466
467 /**
468 * Mark this CallerInfo as an emergency call.
469 *
470 * @param context To lookup the localized 'Emergency Number' string.
471 * @return this instance.
472 */
473 /* package */ CallerInfo markAsEmergency(Context context) {
474 name = context.getString(R.string.emergency_call_dialog_number_for_display);
475 phoneNumber = null;
476
477 photoResource = R.drawable.img_phone;
478 mIsEmergency = true;
479 return this;
480 }
481
482 /**
483 * Mark this CallerInfo as a voicemail call. The voicemail label is obtained from the telephony
484 * manager. Caller must hold the READ_PHONE_STATE permission otherwise the phoneNumber will be set
485 * to null.
486 *
487 * @return this instance.
488 */
489 /* package */ CallerInfo markAsVoiceMail(Context context) {
490 mIsVoiceMail = true;
491
492 try {
493 // For voicemail calls, we display the voice mail tag
494 // instead of the real phone number in the "number"
495 // field.
496 name = TelephonyManagerUtils.getVoiceMailAlphaTag(context);
497 phoneNumber = null;
498 } catch (SecurityException se) {
499 // Should never happen: if this process does not have
500 // permission to retrieve VM tag, it should not have
501 // permission to retrieve VM number and would not call
502 // this method.
503 // Leave phoneNumber untouched.
504 Log.e(TAG, "Cannot access VoiceMail.", se);
505 }
506 // TODO: There is no voicemail picture?
507 // FIXME: FIND ANOTHER ICON
508 // photoResource = android.R.drawable.badge_voicemail;
509 return this;
510 }
511
512 /**
513 * Updates this CallerInfo's geoDescription field, based on the raw phone number in the
514 * phoneNumber field.
515 *
516 * <p>(Note that the various getCallerInfo() methods do *not* set the geoDescription
517 * automatically; you need to call this method explicitly to get it.)
518 *
519 * @param context the context used to look up the current locale / country
520 * @param fallbackNumber if this CallerInfo's phoneNumber field is empty, this specifies a
521 * fallback number to use instead.
522 */
523 public void updateGeoDescription(Context context, String fallbackNumber) {
524 String number = TextUtils.isEmpty(phoneNumber) ? fallbackNumber : phoneNumber;
525 geoDescription = PhoneNumberHelper.getGeoDescription(context, number);
526 }
527
528 /** @return a string debug representation of this instance. */
529 @Override
530 public String toString() {
531 // Warning: never check in this file with VERBOSE_DEBUG = true
532 // because that will result in PII in the system log.
533 final boolean VERBOSE_DEBUG = false;
534
535 if (VERBOSE_DEBUG) {
536 return new StringBuilder(384)
537 .append(super.toString() + " { ")
538 .append("\nname: " + name)
539 .append("\nphoneNumber: " + phoneNumber)
540 .append("\nnormalizedNumber: " + normalizedNumber)
541 .append("\forwardingNumber: " + forwardingNumber)
542 .append("\ngeoDescription: " + geoDescription)
543 .append("\ncnapName: " + cnapName)
544 .append("\nnumberPresentation: " + numberPresentation)
545 .append("\nnamePresentation: " + namePresentation)
546 .append("\ncontactExists: " + contactExists)
547 .append("\nphoneLabel: " + phoneLabel)
548 .append("\nnumberType: " + numberType)
549 .append("\nnumberLabel: " + numberLabel)
550 .append("\nphotoResource: " + photoResource)
551 .append("\ncontactIdOrZero: " + contactIdOrZero)
552 .append("\nneedUpdate: " + needUpdate)
553 .append("\ncontactRefUri: " + contactRefUri)
554 .append("\ncontactRingtoneUri: " + contactRingtoneUri)
555 .append("\ncontactDisplayPhotoUri: " + contactDisplayPhotoUri)
556 .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail)
557 .append("\ncachedPhoto: " + cachedPhoto)
558 .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent)
559 .append("\nemergency: " + mIsEmergency)
560 .append("\nvoicemail: " + mIsVoiceMail)
561 .append("\nuserType: " + userType)
562 .append(" }")
563 .toString();
564 } else {
565 return new StringBuilder(128)
566 .append(super.toString() + " { ")
567 .append("name " + ((name == null) ? "null" : "non-null"))
568 .append(", phoneNumber " + ((phoneNumber == null) ? "null" : "non-null"))
569 .append(" }")
570 .toString();
571 }
572 }
573}