From be8060acf5ecbb916c161d3249813098c0611ed5 Mon Sep 17 00:00:00 2001 From: Yorke Lee Date: Wed, 7 Aug 2013 13:49:32 -0700 Subject: Display primary call info in call card * CallerInfo, CallerInfoAsyncQuery are copied verbatim from existing Phone code. * Added logging methods to Logger to support logging via TAG in static methods * Only primary caller information (name, phone number and label) are displayed for now. Secondary caller information and photos are not displayed. Change-Id: Id4cfdef78f10f7b32255f4892cd51161f37c8be5 --- InCallUI/AndroidManifest.xml | 1 + InCallUI/res/values/strings.xml | 7 + .../src/com/android/incallui/CallCardFragment.java | 44 +- .../com/android/incallui/CallCardPresenter.java | 194 ++++++- InCallUI/src/com/android/incallui/CallerInfo.java | 620 +++++++++++++++++++++ .../com/android/incallui/CallerInfoAsyncQuery.java | 473 ++++++++++++++++ .../src/com/android/incallui/CallerInfoUtils.java | 177 ++++++ InCallUI/src/com/android/incallui/Logger.java | 24 + 8 files changed, 1532 insertions(+), 8 deletions(-) create mode 100644 InCallUI/src/com/android/incallui/CallerInfo.java create mode 100644 InCallUI/src/com/android/incallui/CallerInfoAsyncQuery.java create mode 100644 InCallUI/src/com/android/incallui/CallerInfoUtils.java (limited to 'InCallUI') diff --git a/InCallUI/AndroidManifest.xml b/InCallUI/AndroidManifest.xml index 78bc0fb35..cc0ffec15 100644 --- a/InCallUI/AndroidManifest.xml +++ b/InCallUI/AndroidManifest.xml @@ -20,6 +20,7 @@ + On hold + + Unknown + + Private number + + Pay phone + Speaker diff --git a/InCallUI/src/com/android/incallui/CallCardFragment.java b/InCallUI/src/com/android/incallui/CallCardFragment.java index 76bdd1157..9819f15f7 100644 --- a/InCallUI/src/com/android/incallui/CallCardFragment.java +++ b/InCallUI/src/com/android/incallui/CallCardFragment.java @@ -16,7 +16,9 @@ package com.android.incallui; +import android.app.Activity; import android.os.Bundle; +import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -30,6 +32,9 @@ public class CallCardFragment extends BaseFragment implements CallCardPresenter.CallCardUi { private TextView mPhoneNumber; + private TextView mNumberLabel; + private TextView mName; + private ViewStub mSecondaryCallInfo; private TextView mSecondaryCallName; @@ -48,6 +53,8 @@ public class CallCardFragment extends BaseFragment @Override public void onViewCreated(View view, Bundle savedInstanceState) { mPhoneNumber = (TextView) view.findViewById(R.id.phoneNumber); + mName = (TextView) view.findViewById(R.id.name); + mNumberLabel = (TextView) view.findViewById(R.id.label); mSecondaryCallInfo = (ViewStub) view.findViewById(R.id.secondary_call_info); // This method call will begin the callbacks on CallCardUi. We need to ensure @@ -64,6 +71,12 @@ public class CallCardFragment extends BaseFragment } } + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + getPresenter().setContext(activity); + } + @Override public void setSecondaryCallInfo(boolean show, String number) { if (show) { @@ -78,11 +91,40 @@ public class CallCardFragment extends BaseFragment @Override public void setNumber(String number) { - mPhoneNumber.setText(number); + if (!TextUtils.isEmpty(number)) { + mPhoneNumber.setText(number); + mPhoneNumber.setVisibility(View.VISIBLE); + // We have a real phone number as "mPhoneNumber" so make it always LTR + mPhoneNumber.setTextDirection(View.TEXT_DIRECTION_LTR); + } else { + mPhoneNumber.setVisibility(View.GONE); + } + } + + @Override + public void setName(String name, boolean isNumber) { + mName.setText(name); + mName.setVisibility(View.VISIBLE); + if (isNumber) { + mName.setTextDirection(View.TEXT_DIRECTION_LTR); + } else { + mName.setTextDirection(View.TEXT_DIRECTION_INHERIT); + } } @Override public void setName(String name) { + setName(name, false); + } + + @Override + public void setNumberLabel(String label) { + if (!TextUtils.isEmpty(label)) { + mNumberLabel.setText(label); + mNumberLabel.setVisibility(View.VISIBLE); + } else { + mNumberLabel.setVisibility(View.GONE); + } } private void showAndInitializeSecondaryCallInfo() { diff --git a/InCallUI/src/com/android/incallui/CallCardPresenter.java b/InCallUI/src/com/android/incallui/CallCardPresenter.java index bea89ef8e..f37956569 100644 --- a/InCallUI/src/com/android/incallui/CallCardPresenter.java +++ b/InCallUI/src/com/android/incallui/CallCardPresenter.java @@ -16,8 +16,15 @@ package com.android.incallui; +import android.content.ContentUris; +import android.content.Context; +import android.net.Uri; +import android.provider.ContactsContract.Contacts; +import android.text.TextUtils; + import com.android.incallui.InCallPresenter.InCallState; import com.android.incallui.InCallPresenter.InCallStateListener; + import com.android.services.telephony.common.Call; /** @@ -25,13 +32,19 @@ import com.android.services.telephony.common.Call; * This class listens for changes to InCallState and passes it along to the fragment. */ public class CallCardPresenter extends Presenter - implements InCallStateListener { + implements InCallStateListener, CallerInfoAsyncQuery.OnQueryCompleteListener { + + private Context mContext; @Override public void onUiReady(CallCardUi ui) { super.onUiReady(ui); } + public void setContext(Context context) { + mContext = context; + } + @Override public void onStateChange(InCallState state, CallList callList) { final CallCardUi ui = getUi(); @@ -55,11 +68,9 @@ public class CallCardPresenter extends Presenter Logger.d(this, "Secondary call: " + secondary); // Set primary call data - if (primary != null) { - ui.setNumber(primary.getNumber()); - } else { - ui.setNumber(""); - } + final CallerInfo primaryCallInfo = CallerInfoUtils.getCallerInfoForCall(mContext, primary, + null, this); + updateDisplayByCallerInfo(primary, primaryCallInfo, primary.getNumberPresentation(), true); // Set secondary call data if (secondary != null) { @@ -71,10 +82,179 @@ public class CallCardPresenter extends Presenter public interface CallCardUi extends Ui { // TODO(klp): Consider passing in the Call object directly in these methods. - void setVisible(boolean on); void setNumber(String number); + void setNumberLabel(String label); void setName(String name); + void setName(String name, boolean isNumber); void setSecondaryCallInfo(boolean show, String number); } + + @Override + public void onQueryComplete(int token, Object cookie, CallerInfo ci) { + if (cookie instanceof Call) { + final Call call = (Call) cookie; + if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) { + updateDisplayByCallerInfo(call, ci, Call.PRESENTATION_ALLOWED, true); + } else { + // If the contact doesn't exist, we can still use information from the + // returned caller info (geodescription, etc). + updateDisplayByCallerInfo(call, ci, call.getNumberPresentation(), true); + } + + // Todo (klp): updatePhotoForCallState(call); + } + } + + /** + * Based on the given caller info, determine a suitable name, phone number and label + * to be passed to the CallCardUI. + * + * If the current call is a conference call, use + * updateDisplayForConference() instead. + */ + private void updateDisplayByCallerInfo(Call call, CallerInfo info, int presentation, + boolean isPrimary) { + + //Todo (klp): Either enable or get rid of this + // inform the state machine that we are displaying a photo. + //mPhotoTracker.setPhotoRequest(info); + //mPhotoTracker.setPhotoState(ContactsAsyncHelper.ImageTracker.DISPLAY_IMAGE); + + + // The actual strings we're going to display onscreen: + String displayName; + String displayNumber = null; + String label = null; + Uri personUri = null; + + // Gather missing info unless the call is generic, in which case we wouldn't use + // the gathered information anyway. + if (info != null) { + + // It appears that there is a small change in behaviour with the + // PhoneUtils' startGetCallerInfo whereby if we query with an + // empty number, we will get a valid CallerInfo object, but with + // fields that are all null, and the isTemporary boolean input + // parameter as true. + + // In the past, we would see a NULL callerinfo object, but this + // ends up causing null pointer exceptions elsewhere down the + // line in other cases, so we need to make this fix instead. It + // appears that this was the ONLY call to PhoneUtils + // .getCallerInfo() that relied on a NULL CallerInfo to indicate + // an unknown contact. + + // Currently, infi.phoneNumber may actually be a SIP address, and + // if so, it might sometimes include the "sip:" prefix. That + // prefix isn't really useful to the user, though, so strip it off + // if present. (For any other URI scheme, though, leave the + // prefix alone.) + // TODO: It would be cleaner for CallerInfo to explicitly support + // SIP addresses instead of overloading the "phoneNumber" field. + // Then we could remove this hack, and instead ask the CallerInfo + // for a "user visible" form of the SIP address. + String number = info.phoneNumber; + if ((number != null) && number.startsWith("sip:")) { + number = number.substring(4); + } + + if (TextUtils.isEmpty(info.name)) { + // No valid "name" in the CallerInfo, so fall back to + // something else. + // (Typically, we promote the phone number up to the "name" slot + // onscreen, and possibly display a descriptive string in the + // "number" slot.) + if (TextUtils.isEmpty(number)) { + // No name *or* number! Display a generic "unknown" string + // (or potentially some other default based on the presentation.) + displayName = getPresentationString(presentation); + Logger.d(this, " ==> no name *or* number! displayName = " + displayName); + } else if (presentation != Call.PRESENTATION_ALLOWED) { + // This case should never happen since the network should never send a phone # + // AND a restricted presentation. However we leave it here in case of weird + // network behavior + displayName = getPresentationString(presentation); + Logger.d(this, " ==> presentation not allowed! displayName = " + displayName); + } else if (!TextUtils.isEmpty(info.cnapName)) { + // No name, but we do have a valid CNAP name, so use that. + displayName = info.cnapName; + info.name = info.cnapName; + displayNumber = number; + Logger.d(this, " ==> cnapName available: displayName '" + + displayName + "', displayNumber '" + displayNumber + "'"); + } else { + // No name; all we have is a number. This is the typical + // case when an incoming call doesn't match any contact, + // or if you manually dial an outgoing number using the + // dialpad. + + // Promote the phone number up to the "name" slot: + displayName = number; + + // ...and use the "number" slot for a geographical description + // string if available (but only for incoming calls.) + if ((call != null) && (call.getState() == Call.State.INCOMING)) { + // TODO (CallerInfoAsyncQuery cleanup): Fix the CallerInfo + // query to only do the geoDescription lookup in the first + // place for incoming calls. + displayNumber = info.geoDescription; // may be null + Logger.d(this, "Geodescrption: " + info.geoDescription); + } + + Logger.d(this, " ==> no name; falling back to number: displayName '" + + displayName + "', displayNumber '" + displayNumber + "'"); + } + } else { + // We do have a valid "name" in the CallerInfo. Display that + // in the "name" slot, and the phone number in the "number" slot. + if (presentation != Call.PRESENTATION_ALLOWED) { + // This case should never happen since the network should never send a name + // AND a restricted presentation. However we leave it here in case of weird + // network behavior + displayName = getPresentationString(presentation); + Logger.d(this, " ==> valid name, but presentation not allowed!" + + " displayName = " + displayName); + } else { + displayName = info.name; + displayNumber = number; + label = info.phoneLabel; + Logger.d(this, " ==> name is present in CallerInfo: displayName '" + + displayName + "', displayNumber '" + displayNumber + "'"); + } + } + personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, info.person_id); + Logger.d(this, "- got personUri: '" + personUri + + "', based on info.person_id: " + info.person_id); + } else { + displayName = getPresentationString(presentation); + } + + // TODO (klp): Update secondary user call info as well. + if (isPrimary) { + updateInfoUiForPrimary(displayName, displayNumber, label); + } + + // TODO (klp): Update other fields - photo, sip label, etc. + } + + /** + * Updates the info portion of the call card with passed in values for the primary user. + */ + private void updateInfoUiForPrimary(String displayName, String displayNumber, String label) { + final CallCardUi ui = getUi(); + ui.setName(displayName); + ui.setNumber(displayNumber); + ui.setNumberLabel(label); + } + + public String getPresentationString(int presentation) { + String name = mContext.getString(R.string.unknown); + if (presentation == Call.PRESENTATION_RESTRICTED) { + name = mContext.getString(R.string.private_num); + } else if (presentation == Call.PRESENTATION_PAYPHONE) { + name = mContext.getString(R.string.payphone); + } + return name; + } } diff --git a/InCallUI/src/com/android/incallui/CallerInfo.java b/InCallUI/src/com/android/incallui/CallerInfo.java new file mode 100644 index 000000000..323e276b2 --- /dev/null +++ b/InCallUI/src/com/android/incallui/CallerInfo.java @@ -0,0 +1,620 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.incallui; + +import android.content.Context; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.drawable.Drawable; +import android.location.CountryDetector; +import android.net.Uri; +import android.provider.ContactsContract.CommonDataKinds.Phone; +import android.provider.ContactsContract.Data; +import android.provider.ContactsContract.PhoneLookup; +import android.provider.ContactsContract.RawContacts; +import android.telephony.PhoneNumberUtils; +import android.telephony.TelephonyManager; +import android.text.TextUtils; +import android.util.Log; + +import com.android.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder; +import com.android.i18n.phonenumbers.NumberParseException; +import com.android.i18n.phonenumbers.PhoneNumberUtil; +import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber; + +import java.util.Locale; + + +/** + * Looks up caller information for the given phone number. + * + * {@hide} + */ +public class CallerInfo { + private static final String TAG = "CallerInfo"; + + /** + * Please note that, any one of these member variables can be null, + * and any accesses to them should be prepared to handle such a case. + * + * Also, it is implied that phoneNumber is more often populated than + * name is, (think of calls being dialed/received using numbers where + * names are not known to the device), so phoneNumber should serve as + * a dependable fallback when name is unavailable. + * + * One other detail here is that this CallerInfo object reflects + * information found on a connection, it is an OUTPUT that serves + * mainly to display information to the user. In no way is this object + * used as input to make a connection, so we can choose to display + * whatever human-readable text makes sense to the user for a + * connection. This is especially relevant for the phone number field, + * since it is the one field that is most likely exposed to the user. + * + * As an example: + * 1. User dials "911" + * 2. Device recognizes that this is an emergency number + * 3. We use the "Emergency Number" string instead of "911" in the + * phoneNumber field. + * + * What we're really doing here is treating phoneNumber as an essential + * field here, NOT name. We're NOT always guaranteed to have a name + * for a connection, but the number should be displayable. + */ + public String name; + public String phoneNumber; + public String normalizedNumber; + public String geoDescription; + + public String cnapName; + public int numberPresentation; + public int namePresentation; + public boolean contactExists; + + public String phoneLabel; + /* Split up the phoneLabel into number type and label name */ + public int numberType; + public String numberLabel; + + public int photoResource; + public long person_id; + public boolean needUpdate; + public Uri contactRefUri; + + // fields to hold individual contact preference data, + // including the send to voicemail flag and the ringtone + // uri reference. + public Uri contactRingtoneUri; + public boolean shouldSendToVoicemail; + + /** + * Drawable representing the caller image. This is essentially + * a cache for the image data tied into the connection / + * callerinfo object. + * + * This might be a high resolution picture which is more suitable + * for full-screen image view than for smaller icons used in some + * kinds of notifications. + * + * The {@link #isCachedPhotoCurrent} flag indicates if the image + * data needs to be reloaded. + */ + public Drawable cachedPhoto; + /** + * Bitmap representing the caller image which has possibly lower + * resolution than {@link #cachedPhoto} and thus more suitable for + * icons (like notification icons). + * + * In usual cases this is just down-scaled image of {@link #cachedPhoto}. + * If the down-scaling fails, this will just become null. + * + * The {@link #isCachedPhotoCurrent} flag indicates if the image + * data needs to be reloaded. + */ + public Bitmap cachedPhotoIcon; + /** + * Boolean which indicates if {@link #cachedPhoto} and + * {@link #cachedPhotoIcon} is fresh enough. If it is false, + * those images aren't pointing to valid objects. + */ + public boolean isCachedPhotoCurrent; + + private boolean mIsEmergency; + private boolean mIsVoiceMail; + + public CallerInfo() { + // TODO: Move all the basic initialization here? + mIsEmergency = false; + mIsVoiceMail = false; + } + + /** + * getCallerInfo given a Cursor. + * @param context the context used to retrieve string constants + * @param contactRef the URI to attach to this CallerInfo object + * @param cursor the first object in the cursor is used to build the CallerInfo object. + * @return the CallerInfo which contains the caller id for the given + * number. The returned CallerInfo is null if no number is supplied. + */ + public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) { + CallerInfo info = new CallerInfo(); + info.photoResource = 0; + info.phoneLabel = null; + info.numberType = 0; + info.numberLabel = null; + info.cachedPhoto = null; + info.isCachedPhotoCurrent = false; + info.contactExists = false; + + Logger.v(TAG, "getCallerInfo() based on cursor..."); + + if (cursor != null) { + if (cursor.moveToFirst()) { + // TODO: photo_id is always available but not taken + // care of here. Maybe we should store it in the + // CallerInfo object as well. + + int columnIndex; + + // Look for the name + columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); + if (columnIndex != -1) { + info.name = cursor.getString(columnIndex); + } + + // Look for the number + columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER); + if (columnIndex != -1) { + info.phoneNumber = cursor.getString(columnIndex); + } + + // Look for the normalized number + columnIndex = cursor.getColumnIndex(PhoneLookup.NORMALIZED_NUMBER); + if (columnIndex != -1) { + info.normalizedNumber = cursor.getString(columnIndex); + } + + // Look for the label/type combo + columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL); + if (columnIndex != -1) { + int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE); + if (typeColumnIndex != -1) { + info.numberType = cursor.getInt(typeColumnIndex); + info.numberLabel = cursor.getString(columnIndex); + info.phoneLabel = Phone.getDisplayLabel(context, + info.numberType, info.numberLabel) + .toString(); + } + } + + // Look for the person_id. + columnIndex = getColumnIndexForPersonId(contactRef, cursor); + if (columnIndex != -1) { + info.person_id = cursor.getLong(columnIndex); + Logger.v(TAG, "==> got info.person_id: " + info.person_id); + } else { + // No valid columnIndex, so we can't look up person_id. + Logger.v(TAG, "Couldn't find person_id column for " + contactRef); + // Watch out: this means that anything that depends on + // person_id will be broken (like contact photo lookups in + // the in-call UI, for example.) + } + + // look for the custom ringtone, create from the string stored + // in the database. + columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE); + if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) { + info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex)); + } else { + info.contactRingtoneUri = null; + } + + // look for the send to voicemail flag, set it to true only + // under certain circumstances. + columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL); + info.shouldSendToVoicemail = (columnIndex != -1) && + ((cursor.getInt(columnIndex)) == 1); + info.contactExists = true; + } + cursor.close(); + } + + info.needUpdate = false; + info.name = normalize(info.name); + info.contactRefUri = contactRef; + + return info; + } + + /** + * getCallerInfo given a URI, look up in the call-log database + * for the uri unique key. + * @param context the context used to get the ContentResolver + * @param contactRef the URI used to lookup caller id + * @return the CallerInfo which contains the caller id for the given + * number. The returned CallerInfo is null if no number is supplied. + */ + public static CallerInfo getCallerInfo(Context context, Uri contactRef) { + + return getCallerInfo(context, contactRef, + context.getContentResolver().query(contactRef, null, null, null, null)); + } + + /** + * getCallerInfo given a phone number, look up in the call-log database + * for the matching caller id info. + * @param context the context used to get the ContentResolver + * @param number the phone number used to lookup caller id + * @return the CallerInfo which contains the caller id for the given + * number. The returned CallerInfo is null if no number is supplied. If + * a matching number is not found, then a generic caller info is returned, + * with all relevant fields empty or null. + */ + public static CallerInfo getCallerInfo(Context context, String number) { + Logger.v(TAG, "getCallerInfo() based on number..."); + + if (TextUtils.isEmpty(number)) { + return null; + } + + // Change the callerInfo number ONLY if it is an emergency number + // or if it is the voicemail number. If it is either, take a + // shortcut and skip the query. + if (PhoneNumberUtils.isLocalEmergencyNumber(number, context)) { + return new CallerInfo().markAsEmergency(context); + } else if (PhoneNumberUtils.isVoiceMailNumber(number)) { + return new CallerInfo().markAsVoiceMail(); + } + + Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); + + CallerInfo info = getCallerInfo(context, contactUri); + info = doSecondaryLookupIfNecessary(context, number, info); + + // if no query results were returned with a viable number, + // fill in the original number value we used to query with. + if (TextUtils.isEmpty(info.phoneNumber)) { + info.phoneNumber = number; + } + + return info; + } + + /** + * Performs another lookup if previous lookup fails and it's a SIP call + * and the peer's username is all numeric. Look up the username as it + * could be a PSTN number in the contact database. + * + * @param context the query context + * @param number the original phone number, could be a SIP URI + * @param previousResult the result of previous lookup + * @return previousResult if it's not the case + */ + static CallerInfo doSecondaryLookupIfNecessary(Context context, + String number, CallerInfo previousResult) { + if (!previousResult.contactExists + && PhoneNumberUtils.isUriNumber(number)) { + String username = PhoneNumberUtils.getUsernameFromUriNumber(number); + if (PhoneNumberUtils.isGlobalPhoneNumber(username)) { + previousResult = getCallerInfo(context, + Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, + Uri.encode(username))); + } + } + return previousResult; + } + + /** + * getCallerId: a convenience method to get the caller id for a given + * number. + * + * @param context the context used to get the ContentResolver. + * @param number a phone number. + * @return if the number belongs to a contact, the contact's name is + * returned; otherwise, the number itself is returned. + * + * TODO NOTE: This MAY need to refer to the Asynchronous Query API + * [startQuery()], instead of getCallerInfo, but since it looks like + * it is only being used by the provider calls in the messaging app: + * 1. android.provider.Telephony.Mms.getDisplayAddress() + * 2. android.provider.Telephony.Sms.getDisplayAddress() + * We may not need to make the change. + */ + public static String getCallerId(Context context, String number) { + CallerInfo info = getCallerInfo(context, number); + String callerID = null; + + if (info != null) { + String name = info.name; + + if (!TextUtils.isEmpty(name)) { + callerID = name; + } else { + callerID = number; + } + } + + return callerID; + } + + // Accessors + + /** + * @return true if the caller info is an emergency number. + */ + public boolean isEmergencyNumber() { + return mIsEmergency; + } + + /** + * @return true if the caller info is a voicemail number. + */ + public boolean isVoiceMailNumber() { + return mIsVoiceMail; + } + + /** + * Mark this CallerInfo as an emergency call. + * @param context To lookup the localized 'Emergency Number' string. + * @return this instance. + */ + // TODO: Note we're setting the phone number here (refer to + // javadoc comments at the top of CallerInfo class) to a localized + // string 'Emergency Number'. This is pretty bad because we are + // making UI work here instead of just packaging the data. We + // should set the phone number to the dialed number and name to + // 'Emergency Number' and let the UI make the decision about what + // should be displayed. + /* package */ CallerInfo markAsEmergency(Context context) { + phoneNumber = context.getString( + com.android.internal.R.string.emergency_call_dialog_number_for_display); + photoResource = com.android.internal.R.drawable.picture_emergency; + mIsEmergency = true; + return this; + } + + + /** + * Mark this CallerInfo as a voicemail call. The voicemail label + * is obtained from the telephony manager. Caller must hold the + * READ_PHONE_STATE permission otherwise the phoneNumber will be + * set to null. + * @return this instance. + */ + // TODO: As in the emergency number handling, we end up writing a + // string in the phone number field. + /* package */ CallerInfo markAsVoiceMail() { + mIsVoiceMail = true; + + try { + String voiceMailLabel = TelephonyManager.getDefault().getVoiceMailAlphaTag(); + + phoneNumber = voiceMailLabel; + } catch (SecurityException se) { + // Should never happen: if this process does not have + // permission to retrieve VM tag, it should not have + // permission to retrieve VM number and would not call + // this method. + // Leave phoneNumber untouched. + Logger.e(TAG, "Cannot access VoiceMail.", se); + } + // TODO: There is no voicemail picture? + // FIXME: FIND ANOTHER ICON + // photoResource = android.R.drawable.badge_voicemail; + return this; + } + + private static String normalize(String s) { + if (s == null || s.length() > 0) { + return s; + } else { + return null; + } + } + + /** + * Returns the column index to use to find the "person_id" field in + * the specified cursor, based on the contact URI that was originally + * queried. + * + * This is a helper function for the getCallerInfo() method that takes + * a Cursor. Looking up the person_id is nontrivial (compared to all + * the other CallerInfo fields) since the column we need to use + * depends on what query we originally ran. + * + * Watch out: be sure to not do any database access in this method, since + * it's run from the UI thread (see comments below for more info.) + * + * @return the columnIndex to use (with cursor.getLong()) to get the + * person_id, or -1 if we couldn't figure out what colum to use. + * + * TODO: Add a unittest for this method. (This is a little tricky to + * test, since we'll need a live contacts database to test against, + * preloaded with at least some phone numbers and SIP addresses. And + * we'll probably have to hardcode the column indexes we expect, so + * the test might break whenever the contacts schema changes. But we + * can at least make sure we handle all the URI patterns we claim to, + * and that the mime types match what we expect...) + */ + private static int getColumnIndexForPersonId(Uri contactRef, Cursor cursor) { + // TODO: This is pretty ugly now, see bug 2269240 for + // more details. The column to use depends upon the type of URL: + // - content://com.android.contacts/data/phones ==> use the "contact_id" column + // - content://com.android.contacts/phone_lookup ==> use the "_ID" column + // - content://com.android.contacts/data ==> use the "contact_id" column + // If it's none of the above, we leave columnIndex=-1 which means + // that the person_id field will be left unset. + // + // The logic here *used* to be based on the mime type of contactRef + // (for example Phone.CONTENT_ITEM_TYPE would tell us to use the + // RawContacts.CONTACT_ID column). But looking up the mime type requires + // a call to context.getContentResolver().getType(contactRef), which + // isn't safe to do from the UI thread since it can cause an ANR if + // the contacts provider is slow or blocked (like during a sync.) + // + // So instead, figure out the column to use for person_id by just + // looking at the URI itself. + + Logger.v(TAG, "- getColumnIndexForPersonId: contactRef URI = '" + + contactRef + "'..."); + // Warning: Do not enable the following logging (due to ANR risk.) + // if (VDBG) Rlog.v(TAG, "- MIME type: " + // + context.getContentResolver().getType(contactRef)); + + String url = contactRef.toString(); + String columnName = null; + if (url.startsWith("content://com.android.contacts/data/phones")) { + // Direct lookup in the Phone table. + // MIME type: Phone.CONTENT_ITEM_TYPE (= "vnd.android.cursor.item/phone_v2") + Logger.v(TAG, "'data/phones' URI; using RawContacts.CONTACT_ID"); + columnName = RawContacts.CONTACT_ID; + } else if (url.startsWith("content://com.android.contacts/data")) { + // Direct lookup in the Data table. + // MIME type: Data.CONTENT_TYPE (= "vnd.android.cursor.dir/data") + Logger.v(TAG, "'data' URI; using Data.CONTACT_ID"); + // (Note Data.CONTACT_ID and RawContacts.CONTACT_ID are equivalent.) + columnName = Data.CONTACT_ID; + } else if (url.startsWith("content://com.android.contacts/phone_lookup")) { + // Lookup in the PhoneLookup table, which provides "fuzzy matching" + // for phone numbers. + // MIME type: PhoneLookup.CONTENT_TYPE (= "vnd.android.cursor.dir/phone_lookup") + Logger.v(TAG, "'phone_lookup' URI; using PhoneLookup._ID"); + columnName = PhoneLookup._ID; + } else { + Logger.v(TAG, "Unexpected prefix for contactRef '" + url + "'"); + } + int columnIndex = (columnName != null) ? cursor.getColumnIndex(columnName) : -1; + Logger.v(TAG, "==> Using column '" + columnName + + "' (columnIndex = " + columnIndex + ") for person_id lookup..."); + return columnIndex; + } + + /** + * Updates this CallerInfo's geoDescription field, based on the raw + * phone number in the phoneNumber field. + * + * (Note that the various getCallerInfo() methods do *not* set the + * geoDescription automatically; you need to call this method + * explicitly to get it.) + * + * @param context the context used to look up the current locale / country + * @param fallbackNumber if this CallerInfo's phoneNumber field is empty, + * this specifies a fallback number to use instead. + */ + public void updateGeoDescription(Context context, String fallbackNumber) { + String number = TextUtils.isEmpty(phoneNumber) ? fallbackNumber : phoneNumber; + geoDescription = getGeoDescription(context, number); + } + + /** + * @return a geographical description string for the specified number. + * @see com.android.i18n.phonenumbers.PhoneNumberOfflineGeocoder + */ + private static String getGeoDescription(Context context, String number) { + Logger.v(TAG, "getGeoDescription('" + number + "')..."); + + if (TextUtils.isEmpty(number)) { + return null; + } + + PhoneNumberUtil util = PhoneNumberUtil.getInstance(); + PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance(); + + Locale locale = context.getResources().getConfiguration().locale; + String countryIso = getCurrentCountryIso(context, locale); + PhoneNumber pn = null; + try { + Logger.v(TAG, "parsing '" + number + + "' for countryIso '" + countryIso + "'..."); + pn = util.parse(number, countryIso); + Logger.v(TAG, "- parsed number: " + pn); + } catch (NumberParseException e) { + Logger.v(TAG, "getGeoDescription: NumberParseException for incoming number '" + + number + "'"); + } + + if (pn != null) { + String description = geocoder.getDescriptionForNumber(pn, locale); + Logger.v(TAG, "- got description: '" + description + "'"); + return description; + } else { + return null; + } + } + + /** + * @return The ISO 3166-1 two letters country code of the country the user + * is in. + */ + private static String getCurrentCountryIso(Context context, Locale locale) { + String countryIso; + CountryDetector detector = (CountryDetector) context.getSystemService( + Context.COUNTRY_DETECTOR); + if (detector != null) { + countryIso = detector.detectCountry().getCountryIso(); + } else { + countryIso = locale.getCountry(); + Logger.v(TAG, "No CountryDetector; falling back to countryIso based on locale: " + + countryIso); + } + return countryIso; + } + + /** + * @return a string debug representation of this instance. + */ + @Override + public String toString() { + // Warning: never check in this file with VERBOSE_DEBUG = true + // because that will result in PII in the system log. + final boolean VERBOSE_DEBUG = false; + + if (VERBOSE_DEBUG) { + return new StringBuilder(384) + .append(super.toString() + " { ") + .append("\nname: " + name) + .append("\nphoneNumber: " + phoneNumber) + .append("\nnormalizedNumber: " + normalizedNumber) + .append("\ngeoDescription: " + geoDescription) + .append("\ncnapName: " + cnapName) + .append("\nnumberPresentation: " + numberPresentation) + .append("\nnamePresentation: " + namePresentation) + .append("\ncontactExists: " + contactExists) + .append("\nphoneLabel: " + phoneLabel) + .append("\nnumberType: " + numberType) + .append("\nnumberLabel: " + numberLabel) + .append("\nphotoResource: " + photoResource) + .append("\nperson_id: " + person_id) + .append("\nneedUpdate: " + needUpdate) + .append("\ncontactRefUri: " + contactRefUri) + .append("\ncontactRingtoneUri: " + contactRefUri) + .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail) + .append("\ncachedPhoto: " + cachedPhoto) + .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent) + .append("\nemergency: " + mIsEmergency) + .append("\nvoicemail " + mIsVoiceMail) + .append(" }") + .toString(); + } else { + return new StringBuilder(128) + .append(super.toString() + " { ") + .append("name " + ((name == null) ? "null" : "non-null")) + .append(", phoneNumber " + ((phoneNumber == null) ? "null" : "non-null")) + .append(" }") + .toString(); + } + } +} diff --git a/InCallUI/src/com/android/incallui/CallerInfoAsyncQuery.java b/InCallUI/src/com/android/incallui/CallerInfoAsyncQuery.java new file mode 100644 index 000000000..3ebad5edb --- /dev/null +++ b/InCallUI/src/com/android/incallui/CallerInfoAsyncQuery.java @@ -0,0 +1,473 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.incallui; + +import android.content.AsyncQueryHandler; +import android.content.Context; +import android.database.Cursor; +import android.database.SQLException; +import android.location.CountryDetector; +import android.net.Uri; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.os.SystemProperties; +import android.provider.ContactsContract.CommonDataKinds.SipAddress; +import android.provider.ContactsContract.Data; +import android.provider.ContactsContract.PhoneLookup; +import android.telephony.PhoneNumberUtils; +import android.text.TextUtils; + +/** + * Helper class to make it easier to run asynchronous caller-id lookup queries. + * @see CallerInfo + * + */ +public class CallerInfoAsyncQuery { + private static final boolean DBG = false; + private static final String LOG_TAG = "CallerInfoAsyncQuery"; + + private static final int EVENT_NEW_QUERY = 1; + private static final int EVENT_ADD_LISTENER = 2; + private static final int EVENT_END_OF_QUEUE = 3; + private static final int EVENT_EMERGENCY_NUMBER = 4; + private static final int EVENT_VOICEMAIL_NUMBER = 5; + + private CallerInfoAsyncQueryHandler mHandler; + + // If the CallerInfo query finds no contacts, should we use the + // PhoneNumberOfflineGeocoder to look up a "geo description"? + // (TODO: This could become a flag in config.xml if it ever needs to be + // configured on a per-product basis.) + private static final boolean ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION = true; + + /** + * Interface for a CallerInfoAsyncQueryHandler result return. + */ + public interface OnQueryCompleteListener { + /** + * Called when the query is complete. + */ + public void onQueryComplete(int token, Object cookie, CallerInfo ci); + } + + + /** + * Wrap the cookie from the WorkerArgs with additional information needed by our + * classes. + */ + private static final class CookieWrapper { + public OnQueryCompleteListener listener; + public Object cookie; + public int event; + public String number; + } + + + /** + * Simple exception used to communicate problems with the query pool. + */ + public static class QueryPoolException extends SQLException { + public QueryPoolException(String error) { + super(error); + } + } + + /** + * Our own implementation of the AsyncQueryHandler. + */ + private class CallerInfoAsyncQueryHandler extends AsyncQueryHandler { + + /** + * The information relevant to each CallerInfo query. Each query may have multiple + * listeners, so each AsyncCursorInfo is associated with 2 or more CookieWrapper + * objects in the queue (one with a new query event, and one with a end event, with + * 0 or more additional listeners in between). + */ + private Context mQueryContext; + private Uri mQueryUri; + private CallerInfo mCallerInfo; + + /** + * Our own query worker thread. + * + * This thread handles the messages enqueued in the looper. The normal sequence + * of events is that a new query shows up in the looper queue, followed by 0 or + * more add listener requests, and then an end request. Of course, these requests + * can be interlaced with requests from other tokens, but is irrelevant to this + * handler since the handler has no state. + * + * Note that we depend on the queue to keep things in order; in other words, the + * looper queue must be FIFO with respect to input from the synchronous startQuery + * calls and output to this handleMessage call. + * + * This use of the queue is required because CallerInfo objects may be accessed + * multiple times before the query is complete. All accesses (listeners) must be + * queued up and informed in order when the query is complete. + */ + protected class CallerInfoWorkerHandler extends WorkerHandler { + public CallerInfoWorkerHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + WorkerArgs args = (WorkerArgs) msg.obj; + CookieWrapper cw = (CookieWrapper) args.cookie; + + if (cw == null) { + // Normally, this should never be the case for calls originating + // from within this code. + // However, if there is any code that this Handler calls (such as in + // super.handleMessage) that DOES place unexpected messages on the + // queue, then we need pass these messages on. + Logger.d(this, "Unexpected command (CookieWrapper is null): " + msg.what + + " ignored by CallerInfoWorkerHandler, passing onto parent."); + + super.handleMessage(msg); + } else { + + Logger.d(this, "Processing event: " + cw.event + " token (arg1): " + msg.arg1 + + " command: " + msg.what + " query URI: " + sanitizeUriToString(args.uri)); + + switch (cw.event) { + case EVENT_NEW_QUERY: + //start the sql command. + super.handleMessage(msg); + break; + + // shortcuts to avoid query for recognized numbers. + case EVENT_EMERGENCY_NUMBER: + case EVENT_VOICEMAIL_NUMBER: + + case EVENT_ADD_LISTENER: + case EVENT_END_OF_QUEUE: + // query was already completed, so just send the reply. + // passing the original token value back to the caller + // on top of the event values in arg1. + Message reply = args.handler.obtainMessage(msg.what); + reply.obj = args; + reply.arg1 = msg.arg1; + + reply.sendToTarget(); + + break; + default: + } + } + } + } + + + /** + * Asynchronous query handler class for the contact / callerinfo object. + */ + private CallerInfoAsyncQueryHandler(Context context) { + super(context.getContentResolver()); + } + + @Override + protected Handler createHandler(Looper looper) { + return new CallerInfoWorkerHandler(looper); + } + + /** + * Overrides onQueryComplete from AsyncQueryHandler. + * + * This method takes into account the state of this class; we construct the CallerInfo + * object only once for each set of listeners. When the query thread has done its work + * and calls this method, we inform the remaining listeners in the queue, until we're + * out of listeners. Once we get the message indicating that we should expect no new + * listeners for this CallerInfo object, we release the AsyncCursorInfo back into the + * pool. + */ + @Override + protected void onQueryComplete(int token, Object cookie, Cursor cursor) { + Logger.d(this, "##### onQueryComplete() ##### query complete for token: " + token); + + //get the cookie and notify the listener. + CookieWrapper cw = (CookieWrapper) cookie; + if (cw == null) { + // Normally, this should never be the case for calls originating + // from within this code. + // However, if there is any code that calls this method, we should + // check the parameters to make sure they're viable. + Logger.d(this, "Cookie is null, ignoring onQueryComplete() request."); + return; + } + + if (cw.event == EVENT_END_OF_QUEUE) { + release(); + return; + } + + // check the token and if needed, create the callerinfo object. + if (mCallerInfo == null) { + if ((mQueryContext == null) || (mQueryUri == null)) { + throw new QueryPoolException + ("Bad context or query uri, or CallerInfoAsyncQuery already released."); + } + + // adjust the callerInfo data as needed, and only if it was set from the + // initial query request. + // Change the callerInfo number ONLY if it is an emergency number or the + // voicemail number, and adjust other data (including photoResource) + // accordingly. + if (cw.event == EVENT_EMERGENCY_NUMBER) { + // Note we're setting the phone number here (refer to javadoc + // comments at the top of CallerInfo class). + mCallerInfo = new CallerInfo().markAsEmergency(mQueryContext); + } else if (cw.event == EVENT_VOICEMAIL_NUMBER) { + mCallerInfo = new CallerInfo().markAsVoiceMail(); + } else { + mCallerInfo = CallerInfo.getCallerInfo(mQueryContext, mQueryUri, cursor); + Logger.d(this, "==> Got mCallerInfo: " + mCallerInfo); + + CallerInfo newCallerInfo = CallerInfo.doSecondaryLookupIfNecessary( + mQueryContext, cw.number, mCallerInfo); + if (newCallerInfo != mCallerInfo) { + mCallerInfo = newCallerInfo; + Logger.d(this, "#####async contact look up with numeric username" + + mCallerInfo); + } + + // Final step: look up the geocoded description. + if (ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION) { + // Note we do this only if we *don't* have a valid name (i.e. if + // no contacts matched the phone number of the incoming call), + // since that's the only case where the incoming-call UI cares + // about this field. + // + // (TODO: But if we ever want the UI to show the geoDescription + // even when we *do* match a contact, we'll need to either call + // updateGeoDescription() unconditionally here, or possibly add a + // new parameter to CallerInfoAsyncQuery.startQuery() to force + // the geoDescription field to be populated.) + + if (TextUtils.isEmpty(mCallerInfo.name)) { + // Actually when no contacts match the incoming phone number, + // the CallerInfo object is totally blank here (i.e. no name + // *or* phoneNumber). So we need to pass in cw.number as + // a fallback number. + mCallerInfo.updateGeoDescription(mQueryContext, cw.number); + } + } + + // Use the number entered by the user for display. + if (!TextUtils.isEmpty(cw.number)) { + CountryDetector detector = (CountryDetector) mQueryContext.getSystemService( + Context.COUNTRY_DETECTOR); + mCallerInfo.phoneNumber = PhoneNumberUtils.formatNumber(cw.number, + mCallerInfo.normalizedNumber, + detector.detectCountry().getCountryIso()); + } + } + + Logger.d(this, "constructing CallerInfo object for token: " + token); + + //notify that we can clean up the queue after this. + CookieWrapper endMarker = new CookieWrapper(); + endMarker.event = EVENT_END_OF_QUEUE; + startQuery(token, endMarker, null, null, null, null, null); + } + + //notify the listener that the query is complete. + if (cw.listener != null) { + Logger.d(this, "notifying listener: " + cw.listener.getClass().toString() + + " for token: " + token + mCallerInfo); + cw.listener.onQueryComplete(token, cw.cookie, mCallerInfo); + } + } + } + + /** + * Private constructor for factory methods. + */ + private CallerInfoAsyncQuery() { + } + + + /** + * Factory method to start query with a Uri query spec + */ + public static CallerInfoAsyncQuery startQuery(int token, Context context, Uri contactRef, + OnQueryCompleteListener listener, Object cookie) { + + CallerInfoAsyncQuery c = new CallerInfoAsyncQuery(); + c.allocate(context, contactRef); + + Logger.d(LOG_TAG, "starting query for URI: " + contactRef + " handler: " + c.toString()); + + //create cookieWrapper, start query + CookieWrapper cw = new CookieWrapper(); + cw.listener = listener; + cw.cookie = cookie; + cw.event = EVENT_NEW_QUERY; + + c.mHandler.startQuery(token, cw, contactRef, null, null, null, null); + + return c; + } + + /** + * Factory method to start the query based on a number. + * + * Note: if the number contains an "@" character we treat it + * as a SIP address, and look it up directly in the Data table + * rather than using the PhoneLookup table. + * TODO: But eventually we should expose two separate methods, one for + * numbers and one for SIP addresses, and then have + * PhoneUtils.startGetCallerInfo() decide which one to call based on + * the phone type of the incoming connection. + */ + public static CallerInfoAsyncQuery startQuery(int token, Context context, String number, + OnQueryCompleteListener listener, Object cookie) { + Logger.d(LOG_TAG, "##### CallerInfoAsyncQuery startQuery()... #####"); + Logger.d(LOG_TAG, "- number: " + /* number */"xxxxxxx"); + Logger.d(LOG_TAG, "- cookie: " + cookie); + + // Construct the URI object and query params, and start the query. + + Uri contactRef; + String selection; + String[] selectionArgs; + + if (PhoneNumberUtils.isUriNumber(number)) { + // "number" is really a SIP address. + Logger.d(LOG_TAG, " - Treating number as a SIP address: " + /* number */"xxxxxxx"); + + // We look up SIP addresses directly in the Data table: + contactRef = Data.CONTENT_URI; + + // Note Data.DATA1 and SipAddress.SIP_ADDRESS are equivalent. + // + // Also note we use "upper(data1)" in the WHERE clause, and + // uppercase the incoming SIP address, in order to do a + // case-insensitive match. + // + // TODO: need to confirm that the use of upper() doesn't + // prevent us from using the index! (Linear scan of the whole + // contacts DB can be very slow.) + // + // TODO: May also need to normalize by adding "sip:" as a + // prefix, if we start storing SIP addresses that way in the + // database. + + selection = "upper(" + Data.DATA1 + ")=?" + + " AND " + + Data.MIMETYPE + "='" + SipAddress.CONTENT_ITEM_TYPE + "'"; + selectionArgs = new String[] { number.toUpperCase() }; + + } else { + // "number" is a regular phone number. Use the PhoneLookup table: + contactRef = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); + selection = null; + selectionArgs = null; + } + + if (DBG) { + Logger.d(LOG_TAG, "==> contactRef: " + sanitizeUriToString(contactRef)); + Logger.d(LOG_TAG, "==> selection: " + selection); + if (selectionArgs != null) { + for (int i = 0; i < selectionArgs.length; i++) { + Logger.d(LOG_TAG, "==> selectionArgs[" + i + "]: " + selectionArgs[i]); + } + } + } + + CallerInfoAsyncQuery c = new CallerInfoAsyncQuery(); + c.allocate(context, contactRef); + + //create cookieWrapper, start query + CookieWrapper cw = new CookieWrapper(); + cw.listener = listener; + cw.cookie = cookie; + cw.number = number; + + // check to see if these are recognized numbers, and use shortcuts if we can. + if (PhoneNumberUtils.isLocalEmergencyNumber(number, context)) { + cw.event = EVENT_EMERGENCY_NUMBER; + } else if (PhoneNumberUtils.isVoiceMailNumber(number)) { + cw.event = EVENT_VOICEMAIL_NUMBER; + } else { + cw.event = EVENT_NEW_QUERY; + } + + c.mHandler.startQuery(token, + cw, // cookie + contactRef, // uri + null, // projection + selection, // selection + selectionArgs, // selectionArgs + null); // orderBy + return c; + } + + /** + * Method to add listeners to a currently running query + */ + public void addQueryListener(int token, OnQueryCompleteListener listener, Object cookie) { + + Logger.d(this, "adding listener to query: " + sanitizeUriToString(mHandler.mQueryUri) + + " handler: " + mHandler.toString()); + + //create cookieWrapper, add query request to end of queue. + CookieWrapper cw = new CookieWrapper(); + cw.listener = listener; + cw.cookie = cookie; + cw.event = EVENT_ADD_LISTENER; + + mHandler.startQuery(token, cw, null, null, null, null, null); + } + + /** + * Method to create a new CallerInfoAsyncQueryHandler object, ensuring correct + * state of context and uri. + */ + private void allocate(Context context, Uri contactRef) { + if ((context == null) || (contactRef == null)){ + throw new QueryPoolException("Bad context or query uri."); + } + mHandler = new CallerInfoAsyncQueryHandler(context); + mHandler.mQueryContext = context; + mHandler.mQueryUri = contactRef; + } + + /** + * Releases the relevant data. + */ + private void release() { + mHandler.mQueryContext = null; + mHandler.mQueryUri = null; + mHandler.mCallerInfo = null; + mHandler = null; + } + + private static String sanitizeUriToString(Uri uri) { + if (uri != null) { + String uriString = uri.toString(); + int indexOfLastSlash = uriString.lastIndexOf('/'); + if (indexOfLastSlash > 0) { + return uriString.substring(0, indexOfLastSlash) + "/xxxxxxx"; + } else { + return uriString; + } + } else { + return ""; + } + } +} diff --git a/InCallUI/src/com/android/incallui/CallerInfoUtils.java b/InCallUI/src/com/android/incallui/CallerInfoUtils.java new file mode 100644 index 000000000..077502bcd --- /dev/null +++ b/InCallUI/src/com/android/incallui/CallerInfoUtils.java @@ -0,0 +1,177 @@ +package com.android.incallui; + +import android.content.Context; +import android.net.Uri; +import android.text.TextUtils; + +import com.android.services.telephony.common.Call; + +import java.util.Arrays; + +/** + * TODO: Insert description here. (generated by yorkelee) + */ +public class CallerInfoUtils { + + private static final String TAG = CallerInfoUtils.class.getSimpleName(); + + /** Define for not a special CNAP string */ + private static final int CNAP_SPECIAL_CASE_NO = -1; + + public CallerInfoUtils() { + } + + private static final int QUERY_TOKEN = -1; + + /** + * This is called to get caller info for a call. For outgoing calls, uri should not be null + * because we know which contact uri the user selected to make the outgoing call. This + * will return a CallerInfo object immediately based off information in the call, but + * more information is returned to the OnQueryCompleteListener (which contains + * information about the phone number label, user's name, etc). + */ + public static CallerInfo getCallerInfoForCall(Context context, Call call, Uri uri, + CallerInfoAsyncQuery.OnQueryCompleteListener listener) { + CallerInfo info = new CallerInfo(); + String number = call.getNumber(); + + // Store CNAP information retrieved from the Connection (we want to do this + // here regardless of whether the number is empty or not). + info.cnapName = call.getCnapName(); + info.name = info.cnapName; + info.numberPresentation = call.getNumberPresentation(); + info.namePresentation = call.getCnapNamePresentation(); + + if (uri != null) { + // Have an URI, so pass it to startQuery + CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, uri, listener, call); + } else { + if (!TextUtils.isEmpty(number)) { + number = modifyForSpecialCnapCases(context, info, number, info.numberPresentation); + info.phoneNumber = number; + + // For scenarios where we may receive a valid number from the network but a + // restricted/unavailable presentation, we do not want to perform a contact query, + // so just return the existing caller info. + if (info.numberPresentation != Call.PRESENTATION_ALLOWED) { + return info; + } else { + // Start the query with the number provided from the call. + Logger.d(TAG, "==> Actually starting CallerInfoAsyncQuery.startQuery()..."); + CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, number, listener, call); + } + } else { + // The number is null or empty (Blocked caller id or empty). Just return the + // caller info object as is, without starting a query. + return info; + } + } + + return info; + } + + /** + * Handles certain "corner cases" for CNAP. When we receive weird phone numbers + * from the network to indicate different number presentations, convert them to + * expected number and presentation values within the CallerInfo object. + * @param number number we use to verify if we are in a corner case + * @param presentation presentation value used to verify if we are in a corner case + * @return the new String that should be used for the phone number + */ + /* package */static String modifyForSpecialCnapCases(Context context, CallerInfo ci, + String number, int presentation) { + // Obviously we return number if ci == null, but still return number if + // number == null, because in these cases the correct string will still be + // displayed/logged after this function returns based on the presentation value. + if (ci == null || number == null) return number; + + Logger.d(TAG, "modifyForSpecialCnapCases: initially, number=" + + toLogSafePhoneNumber(number) + + ", presentation=" + presentation + " ci " + ci); + + // "ABSENT NUMBER" is a possible value we could get from the network as the + // phone number, so if this happens, change it to "Unknown" in the CallerInfo + // and fix the presentation to be the same. + final String[] absentNumberValues = + context.getResources().getStringArray(R.array.absent_num); + if (Arrays.asList(absentNumberValues).contains(number) + && presentation == Call.PRESENTATION_ALLOWED) { + number = context.getString(R.string.unknown); + ci.numberPresentation = Call.PRESENTATION_UNKNOWN; + } + + // Check for other special "corner cases" for CNAP and fix them similarly. Corner + // cases only apply if we received an allowed presentation from the network, so check + // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't + // match the presentation passed in for verification (meaning we changed it previously + // because it's a corner case and we're being called from a different entry point). + if (ci.numberPresentation == Call.PRESENTATION_ALLOWED + || (ci.numberPresentation != presentation + && presentation == Call.PRESENTATION_ALLOWED)) { + int cnapSpecialCase = checkCnapSpecialCases(number); + if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) { + // For all special strings, change number & numberPresentation. + if (cnapSpecialCase == Call.PRESENTATION_RESTRICTED) { + number = context.getString(R.string.private_num); + } else if (cnapSpecialCase == Call.PRESENTATION_UNKNOWN) { + number = context.getString(R.string.unknown); + } + Logger.d(TAG, "SpecialCnap: number=" + toLogSafePhoneNumber(number) + + "; presentation now=" + cnapSpecialCase); + ci.numberPresentation = cnapSpecialCase; + } + } + Logger.d(TAG, "modifyForSpecialCnapCases: returning number string=" + + toLogSafePhoneNumber(number)); + return number; + } + + /** + * Based on the input CNAP number string, + * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings. + * Otherwise, return CNAP_SPECIAL_CASE_NO. + */ + private static int checkCnapSpecialCases(String n) { + if (n.equals("PRIVATE") || + n.equals("P") || + n.equals("RES")) { + Logger.d(TAG, "checkCnapSpecialCases, PRIVATE string: " + n); + return Call.PRESENTATION_RESTRICTED; + } else if (n.equals("UNAVAILABLE") || + n.equals("UNKNOWN") || + n.equals("UNA") || + n.equals("U")) { + Logger.d(TAG, "checkCnapSpecialCases, UNKNOWN string: " + n); + return Call.PRESENTATION_UNKNOWN; + } else { + Logger.d(TAG, "checkCnapSpecialCases, normal str. number: " + n); + return CNAP_SPECIAL_CASE_NO; + } + } + + /* package */static String toLogSafePhoneNumber(String number) { + // For unknown number, log empty string. + if (number == null) { + return ""; + } + + // Todo (klp): Figure out an equivalent for VDBG + if (false) { + // When VDBG is true we emit PII. + return number; + } + + // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare + // sanitized phone numbers. + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < number.length(); i++) { + char c = number.charAt(i); + if (c == '-' || c == '@' || c == '.') { + builder.append(c); + } else { + builder.append('x'); + } + } + return builder.toString(); + } +} diff --git a/InCallUI/src/com/android/incallui/Logger.java b/InCallUI/src/com/android/incallui/Logger.java index dd4985598..5f628d296 100644 --- a/InCallUI/src/com/android/incallui/Logger.java +++ b/InCallUI/src/com/android/incallui/Logger.java @@ -29,18 +29,38 @@ import android.util.Log; public static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); public static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + public static void d(String tag, String msg) { + if (DEBUG) { + Log.d(TAG, tag + msg); + } + } + public static void d(Object obj, String msg) { if (DEBUG) { Log.d(TAG, getPrefix(obj) + msg); } } + public static void v(String tag, String msg) { + if (VERBOSE) { + Log.v(TAG, tag + msg); + } + } + public static void v(Object obj, String msg) { if (VERBOSE) { Log.v(TAG, getPrefix(obj) + msg); } } + public static void e(String tag, String msg, Exception e) { + Log.e(TAG, tag + msg, e); + } + + public static void e(String tag, String msg) { + Log.e(TAG, tag + msg); + } + public static void e(Object obj, String msg, Exception e) { Log.e(TAG, getPrefix(obj) + msg, e); } @@ -49,6 +69,10 @@ import android.util.Log; Log.e(TAG, getPrefix(obj) + msg); } + public static void i(String tag, String msg) { + Log.i(TAG, tag + msg); + } + public static void i(Object obj, String msg) { Log.i(TAG, getPrefix(obj) + msg); } -- cgit v1.2.3