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