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 private boolean mIsEmergency; 145 private boolean mIsVoiceMail; 146 CallerInfo()147 public CallerInfo() { 148 // TODO: Move all the basic initialization here? 149 mIsEmergency = false; 150 mIsVoiceMail = false; 151 } 152 153 /** 154 * getCallerInfo given a Cursor. 155 * @param context the context used to retrieve string constants 156 * @param contactRef the URI to attach to this CallerInfo object 157 * @param cursor the first object in the cursor is used to build the CallerInfo object. 158 * @return the CallerInfo which contains the caller id for the given 159 * number. The returned CallerInfo is null if no number is supplied. 160 */ getCallerInfo(Context context, Uri contactRef, Cursor cursor)161 public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) { 162 CallerInfo info = new CallerInfo(); 163 info.photoResource = 0; 164 info.phoneLabel = null; 165 info.numberType = 0; 166 info.numberLabel = null; 167 info.cachedPhoto = null; 168 info.isCachedPhotoCurrent = false; 169 info.contactExists = false; 170 171 Log.v(TAG, "getCallerInfo() based on cursor..."); 172 173 if (cursor != null) { 174 if (cursor.moveToFirst()) { 175 // TODO: photo_id is always available but not taken 176 // care of here. Maybe we should store it in the 177 // CallerInfo object as well. 178 179 int columnIndex; 180 181 // Look for the name 182 columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); 183 if (columnIndex != -1) { 184 info.name = cursor.getString(columnIndex); 185 } 186 187 // Look for the number 188 columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER); 189 if (columnIndex != -1) { 190 info.phoneNumber = cursor.getString(columnIndex); 191 } 192 193 // Look for the normalized number 194 columnIndex = cursor.getColumnIndex(PhoneLookup.NORMALIZED_NUMBER); 195 if (columnIndex != -1) { 196 info.normalizedNumber = cursor.getString(columnIndex); 197 } 198 199 // Look for the label/type combo 200 columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL); 201 if (columnIndex != -1) { 202 int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE); 203 if (typeColumnIndex != -1) { 204 info.numberType = cursor.getInt(typeColumnIndex); 205 info.numberLabel = cursor.getString(columnIndex); 206 info.phoneLabel = Phone.getTypeLabel(context.getResources(), 207 info.numberType, info.numberLabel) 208 .toString(); 209 } 210 } 211 212 // Look for the person_id. 213 columnIndex = getColumnIndexForPersonId(contactRef, cursor); 214 if (columnIndex != -1) { 215 final long contactId = cursor.getLong(columnIndex); 216 if (contactId != 0 && !Contacts.isEnterpriseContactId(contactId)) { 217 info.contactIdOrZero = contactId; 218 Log.v(TAG, "==> got info.contactIdOrZero: " + info.contactIdOrZero); 219 220 // cache the lookup key for later use with person_id to create lookup URIs 221 columnIndex = cursor.getColumnIndex(PhoneLookup.LOOKUP_KEY); 222 if (columnIndex != -1) { 223 info.lookupKeyOrNull = cursor.getString(columnIndex); 224 } 225 } 226 } else { 227 // No valid columnIndex, so we can't look up person_id. 228 Log.v(TAG, "Couldn't find contactId column for " + contactRef); 229 // Watch out: this means that anything that depends on 230 // person_id will be broken (like contact photo lookups in 231 // the in-call UI, for example.) 232 } 233 234 // Display photo URI. 235 columnIndex = cursor.getColumnIndex(PhoneLookup.PHOTO_URI); 236 if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) { 237 info.contactDisplayPhotoUri = Uri.parse(cursor.getString(columnIndex)); 238 } else { 239 info.contactDisplayPhotoUri = null; 240 } 241 242 // look for the custom ringtone, create from the string stored 243 // in the database. 244 columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE); 245 if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) { 246 info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex)); 247 } else { 248 info.contactRingtoneUri = null; 249 } 250 251 // look for the send to voicemail flag, set it to true only 252 // under certain circumstances. 253 columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL); 254 info.shouldSendToVoicemail = (columnIndex != -1) && 255 ((cursor.getInt(columnIndex)) == 1); 256 info.contactExists = true; 257 } 258 cursor.close(); 259 } 260 261 info.needUpdate = false; 262 info.name = normalize(info.name); 263 info.contactRefUri = contactRef; 264 265 return info; 266 } 267 268 /** 269 * getCallerInfo given a URI, look up in the call-log database 270 * for the uri unique key. 271 * @param context the context used to get the ContentResolver 272 * @param contactRef the URI used to lookup caller id 273 * @return the CallerInfo which contains the caller id for the given 274 * number. The returned CallerInfo is null if no number is supplied. 275 */ getCallerInfo(Context context, Uri contactRef)276 private static CallerInfo getCallerInfo(Context context, Uri contactRef) { 277 278 return getCallerInfo(context, contactRef, 279 context.getContentResolver().query(contactRef, null, null, null, null)); 280 } 281 282 /** 283 * Performs another lookup if previous lookup fails and it's a SIP call 284 * and the peer's username is all numeric. Look up the username as it 285 * could be a PSTN number in the contact database. 286 * 287 * @param context the query context 288 * @param number the original phone number, could be a SIP URI 289 * @param previousResult the result of previous lookup 290 * @return previousResult if it's not the case 291 */ doSecondaryLookupIfNecessary(Context context, String number, CallerInfo previousResult)292 static CallerInfo doSecondaryLookupIfNecessary(Context context, 293 String number, CallerInfo previousResult) { 294 if (!previousResult.contactExists 295 && PhoneNumberHelper.isUriNumber(number)) { 296 String username = PhoneNumberHelper.getUsernameFromUriNumber(number); 297 if (PhoneNumberUtils.isGlobalPhoneNumber(username)) { 298 previousResult = getCallerInfo(context, 299 Uri.withAppendedPath(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI, 300 Uri.encode(username))); 301 } 302 } 303 return previousResult; 304 } 305 306 // Accessors 307 308 /** 309 * @return true if the caller info is an emergency number. 310 */ isEmergencyNumber()311 public boolean isEmergencyNumber() { 312 return mIsEmergency; 313 } 314 315 /** 316 * @return true if the caller info is a voicemail number. 317 */ isVoiceMailNumber()318 public boolean isVoiceMailNumber() { 319 return mIsVoiceMail; 320 } 321 322 /** 323 * Mark this CallerInfo as an emergency call. 324 * @param context To lookup the localized 'Emergency Number' string. 325 * @return this instance. 326 */ markAsEmergency(Context context)327 /* package */ CallerInfo markAsEmergency(Context context) { 328 name = context.getString(R.string.emergency_call_dialog_number_for_display); 329 phoneNumber = null; 330 331 photoResource = R.drawable.img_phone; 332 mIsEmergency = true; 333 return this; 334 } 335 336 337 /** 338 * Mark this CallerInfo as a voicemail call. The voicemail label 339 * is obtained from the telephony manager. Caller must hold the 340 * READ_PHONE_STATE permission otherwise the phoneNumber will be 341 * set to null. 342 * @return this instance. 343 */ markAsVoiceMail(Context context)344 /* package */ CallerInfo markAsVoiceMail(Context context) { 345 mIsVoiceMail = true; 346 347 try { 348 // For voicemail calls, we display the voice mail tag 349 // instead of the real phone number in the "number" 350 // field. 351 name = TelephonyManagerUtils.getVoiceMailAlphaTag(context); 352 phoneNumber = null; 353 } catch (SecurityException se) { 354 // Should never happen: if this process does not have 355 // permission to retrieve VM tag, it should not have 356 // permission to retrieve VM number and would not call 357 // this method. 358 // Leave phoneNumber untouched. 359 Log.e(TAG, "Cannot access VoiceMail.", se); 360 } 361 // TODO: There is no voicemail picture? 362 // FIXME: FIND ANOTHER ICON 363 // photoResource = android.R.drawable.badge_voicemail; 364 return this; 365 } 366 normalize(String s)367 private static String normalize(String s) { 368 if (s == null || s.length() > 0) { 369 return s; 370 } else { 371 return null; 372 } 373 } 374 375 /** 376 * Returns the column index to use to find the "person_id" field in 377 * the specified cursor, based on the contact URI that was originally 378 * queried. 379 * 380 * This is a helper function for the getCallerInfo() method that takes 381 * a Cursor. Looking up the person_id is nontrivial (compared to all 382 * the other CallerInfo fields) since the column we need to use 383 * depends on what query we originally ran. 384 * 385 * Watch out: be sure to not do any database access in this method, since 386 * it's run from the UI thread (see comments below for more info.) 387 * 388 * @return the columnIndex to use (with cursor.getLong()) to get the 389 * person_id, or -1 if we couldn't figure out what colum to use. 390 * 391 * TODO: Add a unittest for this method. (This is a little tricky to 392 * test, since we'll need a live contacts database to test against, 393 * preloaded with at least some phone numbers and SIP addresses. And 394 * we'll probably have to hardcode the column indexes we expect, so 395 * the test might break whenever the contacts schema changes. But we 396 * can at least make sure we handle all the URI patterns we claim to, 397 * and that the mime types match what we expect...) 398 */ getColumnIndexForPersonId(Uri contactRef, Cursor cursor)399 private static int getColumnIndexForPersonId(Uri contactRef, Cursor cursor) { 400 // TODO: This is pretty ugly now, see bug 2269240 for 401 // more details. The column to use depends upon the type of URL: 402 // - content://com.android.contacts/data/phones ==> use the "contact_id" column 403 // - content://com.android.contacts/phone_lookup ==> use the "_ID" column 404 // - content://com.android.contacts/data ==> use the "contact_id" column 405 // If it's none of the above, we leave columnIndex=-1 which means 406 // that the person_id field will be left unset. 407 // 408 // The logic here *used* to be based on the mime type of contactRef 409 // (for example Phone.CONTENT_ITEM_TYPE would tell us to use the 410 // RawContacts.CONTACT_ID column). But looking up the mime type requires 411 // a call to context.getContentResolver().getType(contactRef), which 412 // isn't safe to do from the UI thread since it can cause an ANR if 413 // the contacts provider is slow or blocked (like during a sync.) 414 // 415 // So instead, figure out the column to use for person_id by just 416 // looking at the URI itself. 417 418 Log.v(TAG, "- getColumnIndexForPersonId: contactRef URI = '" 419 + 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 = PhoneLookup._ID; 443 } else { 444 Log.v(TAG, "Unexpected prefix for contactRef '" + url + "'"); 445 } 446 int columnIndex = (columnName != null) ? cursor.getColumnIndex(columnName) : -1; 447 Log.v(TAG, "==> Using column '" + columnName 448 + "' (columnIndex = " + columnIndex + ") for person_id lookup..."); 449 return columnIndex; 450 } 451 452 /** 453 * Updates this CallerInfo's geoDescription field, based on the raw 454 * phone number in the phoneNumber field. 455 * 456 * (Note that the various getCallerInfo() methods do *not* set the 457 * geoDescription automatically; you need to call this method 458 * explicitly to get it.) 459 * 460 * @param context the context used to look up the current locale / country 461 * @param fallbackNumber if this CallerInfo's phoneNumber field is empty, 462 * this specifies a fallback number to use instead. 463 */ updateGeoDescription(Context context, String fallbackNumber)464 public void updateGeoDescription(Context context, String fallbackNumber) { 465 String number = TextUtils.isEmpty(phoneNumber) ? fallbackNumber : phoneNumber; 466 geoDescription = getGeoDescription(context, number); 467 } 468 469 /** 470 * @return a geographical description string for the specified number. 471 * @see com.android.i18n.phonenumbers.PhoneNumberOfflineGeocoder 472 */ getGeoDescription(Context context, String number)473 private static String getGeoDescription(Context context, String number) { 474 Log.v(TAG, "getGeoDescription('" + number + "')..."); 475 476 if (TextUtils.isEmpty(number)) { 477 return null; 478 } 479 480 PhoneNumberUtil util = PhoneNumberUtil.getInstance(); 481 PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance(); 482 483 Locale locale = context.getResources().getConfiguration().locale; 484 String countryIso = TelephonyManagerUtils.getCurrentCountryIso(context, locale); 485 PhoneNumber pn = null; 486 try { 487 Log.v(TAG, "parsing '" + number 488 + "' for countryIso '" + countryIso + "'..."); 489 pn = util.parse(number, countryIso); 490 Log.v(TAG, "- parsed number: " + pn); 491 } catch (NumberParseException e) { 492 Log.v(TAG, "getGeoDescription: NumberParseException for incoming number '" + 493 number + "'"); 494 } 495 496 if (pn != null) { 497 String description = geocoder.getDescriptionForNumber(pn, locale); 498 Log.v(TAG, "- got description: '" + description + "'"); 499 return description; 500 } 501 502 return null; 503 } 504 505 /** 506 * @return a string debug representation of this instance. 507 */ 508 @Override toString()509 public String toString() { 510 // Warning: never check in this file with VERBOSE_DEBUG = true 511 // because that will result in PII in the system log. 512 final boolean VERBOSE_DEBUG = false; 513 514 if (VERBOSE_DEBUG) { 515 return new StringBuilder(384) 516 .append(super.toString() + " { ") 517 .append("\nname: " + name) 518 .append("\nphoneNumber: " + phoneNumber) 519 .append("\nnormalizedNumber: " + normalizedNumber) 520 .append("\forwardingNumber: " + forwardingNumber) 521 .append("\ngeoDescription: " + geoDescription) 522 .append("\ncnapName: " + cnapName) 523 .append("\nnumberPresentation: " + numberPresentation) 524 .append("\nnamePresentation: " + namePresentation) 525 .append("\ncontactExists: " + contactExists) 526 .append("\nphoneLabel: " + phoneLabel) 527 .append("\nnumberType: " + numberType) 528 .append("\nnumberLabel: " + numberLabel) 529 .append("\nphotoResource: " + photoResource) 530 .append("\ncontactIdOrZero: " + contactIdOrZero) 531 .append("\nneedUpdate: " + needUpdate) 532 .append("\ncontactRefUri: " + contactRefUri) 533 .append("\ncontactRingtoneUri: " + contactRingtoneUri) 534 .append("\ncontactDisplayPhotoUri: " + contactDisplayPhotoUri) 535 .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail) 536 .append("\ncachedPhoto: " + cachedPhoto) 537 .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent) 538 .append("\nemergency: " + mIsEmergency) 539 .append("\nvoicemail " + mIsVoiceMail) 540 .append(" }") 541 .toString(); 542 } else { 543 return new StringBuilder(128) 544 .append(super.toString() + " { ") 545 .append("name " + ((name == null) ? "null" : "non-null")) 546 .append(", phoneNumber " + ((phoneNumber == null) ? "null" : "non-null")) 547 .append(" }") 548 .toString(); 549 } 550 } 551 } 552