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