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