Home | History | Annotate | Download | only in telephony
      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.internal.telephony;
     18 
     19 import android.content.Context;
     20 import android.database.Cursor;
     21 import android.graphics.drawable.Drawable;
     22 import android.net.Uri;
     23 import android.provider.ContactsContract.CommonDataKinds.Phone;
     24 import android.provider.ContactsContract.Data;
     25 import android.provider.ContactsContract.PhoneLookup;
     26 import android.provider.ContactsContract.RawContacts;
     27 import android.telephony.PhoneNumberUtils;
     28 import android.telephony.TelephonyManager;
     29 import android.text.TextUtils;
     30 import android.util.Log;
     31 
     32 
     33 /**
     34  * Looks up caller information for the given phone number.
     35  *
     36  * {@hide}
     37  */
     38 public class CallerInfo {
     39     private static final String TAG = "CallerInfo";
     40     private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
     41 
     42     public static final String UNKNOWN_NUMBER = "-1";
     43     public static final String PRIVATE_NUMBER = "-2";
     44     public static final String PAYPHONE_NUMBER = "-3";
     45 
     46     /**
     47      * Please note that, any one of these member variables can be null,
     48      * and any accesses to them should be prepared to handle such a case.
     49      *
     50      * Also, it is implied that phoneNumber is more often populated than
     51      * name is, (think of calls being dialed/received using numbers where
     52      * names are not known to the device), so phoneNumber should serve as
     53      * a dependable fallback when name is unavailable.
     54      *
     55      * One other detail here is that this CallerInfo object reflects
     56      * information found on a connection, it is an OUTPUT that serves
     57      * mainly to display information to the user.  In no way is this object
     58      * used as input to make a connection, so we can choose to display
     59      * whatever human-readable text makes sense to the user for a
     60      * connection.  This is especially relevant for the phone number field,
     61      * since it is the one field that is most likely exposed to the user.
     62      *
     63      * As an example:
     64      *   1. User dials "911"
     65      *   2. Device recognizes that this is an emergency number
     66      *   3. We use the "Emergency Number" string instead of "911" in the
     67      *     phoneNumber field.
     68      *
     69      * What we're really doing here is treating phoneNumber as an essential
     70      * field here, NOT name.  We're NOT always guaranteed to have a name
     71      * for a connection, but the number should be displayable.
     72      */
     73     public String name;
     74     public String phoneNumber;
     75 
     76     public String cnapName;
     77     public int numberPresentation;
     78     public int namePresentation;
     79     public boolean contactExists;
     80 
     81     public String phoneLabel;
     82     /* Split up the phoneLabel into number type and label name */
     83     public int    numberType;
     84     public String numberLabel;
     85 
     86     public int photoResource;
     87     public long person_id;
     88     public boolean needUpdate;
     89     public Uri contactRefUri;
     90 
     91     // fields to hold individual contact preference data,
     92     // including the send to voicemail flag and the ringtone
     93     // uri reference.
     94     public Uri contactRingtoneUri;
     95     public boolean shouldSendToVoicemail;
     96 
     97     /**
     98      * Drawable representing the caller image.  This is essentially
     99      * a cache for the image data tied into the connection /
    100      * callerinfo object.  The isCachedPhotoCurrent flag indicates
    101      * if the image data needs to be reloaded.
    102      */
    103     public Drawable cachedPhoto;
    104     public boolean isCachedPhotoCurrent;
    105 
    106     private boolean mIsEmergency;
    107     private boolean mIsVoiceMail;
    108 
    109     public CallerInfo() {
    110         // TODO: Move all the basic initialization here?
    111         mIsEmergency = false;
    112         mIsVoiceMail = false;
    113     }
    114 
    115     /**
    116      * getCallerInfo given a Cursor.
    117      * @param context the context used to retrieve string constants
    118      * @param contactRef the URI to attach to this CallerInfo object
    119      * @param cursor the first object in the cursor is used to build the CallerInfo object.
    120      * @return the CallerInfo which contains the caller id for the given
    121      * number. The returned CallerInfo is null if no number is supplied.
    122      */
    123     public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) {
    124         CallerInfo info = new CallerInfo();
    125         info.photoResource = 0;
    126         info.phoneLabel = null;
    127         info.numberType = 0;
    128         info.numberLabel = null;
    129         info.cachedPhoto = null;
    130         info.isCachedPhotoCurrent = false;
    131         info.contactExists = false;
    132 
    133         if (VDBG) Log.v(TAG, "construct callerInfo from cursor");
    134 
    135         if (cursor != null) {
    136             if (cursor.moveToFirst()) {
    137                 // TODO: photo_id is always available but not taken
    138                 // care of here. Maybe we should store it in the
    139                 // CallerInfo object as well.
    140 
    141                 int columnIndex;
    142 
    143                 // Look for the name
    144                 columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
    145                 if (columnIndex != -1) {
    146                     info.name = cursor.getString(columnIndex);
    147                 }
    148 
    149                 // Look for the number
    150                 columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER);
    151                 if (columnIndex != -1) {
    152                     info.phoneNumber = cursor.getString(columnIndex);
    153                 }
    154 
    155                 // Look for the label/type combo
    156                 columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL);
    157                 if (columnIndex != -1) {
    158                     int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE);
    159                     if (typeColumnIndex != -1) {
    160                         info.numberType = cursor.getInt(typeColumnIndex);
    161                         info.numberLabel = cursor.getString(columnIndex);
    162                         info.phoneLabel = Phone.getDisplayLabel(context,
    163                                 info.numberType, info.numberLabel)
    164                                 .toString();
    165                     }
    166                 }
    167 
    168                 // Look for the person_id.
    169                 columnIndex = getColumnIndexForPersonId(contactRef, cursor);
    170                 if (columnIndex != -1) {
    171                     info.person_id = cursor.getLong(columnIndex);
    172                     if (VDBG) Log.v(TAG, "==> got info.person_id: " + info.person_id);
    173                 } else {
    174                     // No valid columnIndex, so we can't look up person_id.
    175                     Log.w(TAG, "Couldn't find person_id column for " + contactRef);
    176                     // Watch out: this means that anything that depends on
    177                     // person_id will be broken (like contact photo lookups in
    178                     // the in-call UI, for example.)
    179                 }
    180 
    181                 // look for the custom ringtone, create from the string stored
    182                 // in the database.
    183                 columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE);
    184                 if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) {
    185                     info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex));
    186                 } else {
    187                     info.contactRingtoneUri = null;
    188                 }
    189 
    190                 // look for the send to voicemail flag, set it to true only
    191                 // under certain circumstances.
    192                 columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL);
    193                 info.shouldSendToVoicemail = (columnIndex != -1) &&
    194                         ((cursor.getInt(columnIndex)) == 1);
    195                 info.contactExists = true;
    196             }
    197             cursor.close();
    198         }
    199 
    200         info.needUpdate = false;
    201         info.name = normalize(info.name);
    202         info.contactRefUri = contactRef;
    203 
    204         return info;
    205     }
    206 
    207     /**
    208      * getCallerInfo given a URI, look up in the call-log database
    209      * for the uri unique key.
    210      * @param context the context used to get the ContentResolver
    211      * @param contactRef the URI used to lookup caller id
    212      * @return the CallerInfo which contains the caller id for the given
    213      * number. The returned CallerInfo is null if no number is supplied.
    214      */
    215     public static CallerInfo getCallerInfo(Context context, Uri contactRef) {
    216 
    217         return getCallerInfo(context, contactRef,
    218                 context.getContentResolver().query(contactRef, null, null, null, null));
    219     }
    220 
    221     /**
    222      * getCallerInfo given a phone number, look up in the call-log database
    223      * for the matching caller id info.
    224      * @param context the context used to get the ContentResolver
    225      * @param number the phone number used to lookup caller id
    226      * @return the CallerInfo which contains the caller id for the given
    227      * number. The returned CallerInfo is null if no number is supplied. If
    228      * a matching number is not found, then a generic caller info is returned,
    229      * with all relevant fields empty or null.
    230      */
    231     public static CallerInfo getCallerInfo(Context context, String number) {
    232         if (TextUtils.isEmpty(number)) {
    233             return null;
    234         }
    235 
    236         // Change the callerInfo number ONLY if it is an emergency number
    237         // or if it is the voicemail number.  If it is either, take a
    238         // shortcut and skip the query.
    239         if (PhoneNumberUtils.isEmergencyNumber(number)) {
    240             return new CallerInfo().markAsEmergency(context);
    241         } else if (PhoneNumberUtils.isVoiceMailNumber(number)) {
    242             return new CallerInfo().markAsVoiceMail();
    243         }
    244 
    245         Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    246 
    247         CallerInfo info = getCallerInfo(context, contactUri);
    248         info = doSecondaryLookupIfNecessary(context, number, info);
    249 
    250         // if no query results were returned with a viable number,
    251         // fill in the original number value we used to query with.
    252         if (TextUtils.isEmpty(info.phoneNumber)) {
    253             info.phoneNumber = number;
    254         }
    255 
    256         return info;
    257     }
    258 
    259     /**
    260      * Performs another lookup if previous lookup fails and it's a SIP call
    261      * and the peer's username is all numeric. Look up the username as it
    262      * could be a PSTN number in the contact database.
    263      *
    264      * @param context the query context
    265      * @param number the original phone number, could be a SIP URI
    266      * @param previousResult the result of previous lookup
    267      * @return previousResult if it's not the case
    268      */
    269     static CallerInfo doSecondaryLookupIfNecessary(Context context,
    270             String number, CallerInfo previousResult) {
    271         if (!previousResult.contactExists
    272                 && PhoneNumberUtils.isUriNumber(number)) {
    273             String username = number.substring(0, number.indexOf('@'));
    274             if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
    275                 previousResult = getCallerInfo(context,
    276                         Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
    277                                 Uri.encode(username)));
    278             }
    279         }
    280         return previousResult;
    281     }
    282 
    283     /**
    284      * getCallerId: a convenience method to get the caller id for a given
    285      * number.
    286      *
    287      * @param context the context used to get the ContentResolver.
    288      * @param number a phone number.
    289      * @return if the number belongs to a contact, the contact's name is
    290      * returned; otherwise, the number itself is returned.
    291      *
    292      * TODO NOTE: This MAY need to refer to the Asynchronous Query API
    293      * [startQuery()], instead of getCallerInfo, but since it looks like
    294      * it is only being used by the provider calls in the messaging app:
    295      *   1. android.provider.Telephony.Mms.getDisplayAddress()
    296      *   2. android.provider.Telephony.Sms.getDisplayAddress()
    297      * We may not need to make the change.
    298      */
    299     public static String getCallerId(Context context, String number) {
    300         CallerInfo info = getCallerInfo(context, number);
    301         String callerID = null;
    302 
    303         if (info != null) {
    304             String name = info.name;
    305 
    306             if (!TextUtils.isEmpty(name)) {
    307                 callerID = name;
    308             } else {
    309                 callerID = number;
    310             }
    311         }
    312 
    313         return callerID;
    314     }
    315 
    316     // Accessors
    317 
    318     /**
    319      * @return true if the caller info is an emergency number.
    320      */
    321     public boolean isEmergencyNumber() {
    322         return mIsEmergency;
    323     }
    324 
    325     /**
    326      * @return true if the caller info is a voicemail number.
    327      */
    328     public boolean isVoiceMailNumber() {
    329         return mIsVoiceMail;
    330     }
    331 
    332     /**
    333      * Mark this CallerInfo as an emergency call.
    334      * @param context To lookup the localized 'Emergency Number' string.
    335      * @return this instance.
    336      */
    337     // TODO: Note we're setting the phone number here (refer to
    338     // javadoc comments at the top of CallerInfo class) to a localized
    339     // string 'Emergency Number'. This is pretty bad because we are
    340     // making UI work here instead of just packaging the data. We
    341     // should set the phone number to the dialed number and name to
    342     // 'Emergency Number' and let the UI make the decision about what
    343     // should be displayed.
    344     /* package */ CallerInfo markAsEmergency(Context context) {
    345         phoneNumber = context.getString(
    346             com.android.internal.R.string.emergency_call_dialog_number_for_display);
    347         photoResource = com.android.internal.R.drawable.picture_emergency;
    348         mIsEmergency = true;
    349         return this;
    350     }
    351 
    352 
    353     /**
    354      * Mark this CallerInfo as a voicemail call. The voicemail label
    355      * is obtained from the telephony manager. Caller must hold the
    356      * READ_PHONE_STATE permission otherwise the phoneNumber will be
    357      * set to null.
    358      * @return this instance.
    359      */
    360     // TODO: As in the emergency number handling, we end up writing a
    361     // string in the phone number field.
    362     /* package */ CallerInfo markAsVoiceMail() {
    363         mIsVoiceMail = true;
    364 
    365         try {
    366             String voiceMailLabel = TelephonyManager.getDefault().getVoiceMailAlphaTag();
    367 
    368             phoneNumber = voiceMailLabel;
    369         } catch (SecurityException se) {
    370             // Should never happen: if this process does not have
    371             // permission to retrieve VM tag, it should not have
    372             // permission to retrieve VM number and would not call
    373             // this method.
    374             // Leave phoneNumber untouched.
    375             Log.e(TAG, "Cannot access VoiceMail.", se);
    376         }
    377         // TODO: There is no voicemail picture?
    378         // FIXME: FIND ANOTHER ICON
    379         // photoResource = android.R.drawable.badge_voicemail;
    380         return this;
    381     }
    382 
    383     private static String normalize(String s) {
    384         if (s == null || s.length() > 0) {
    385             return s;
    386         } else {
    387             return null;
    388         }
    389     }
    390 
    391     /**
    392      * Returns the column index to use to find the "person_id" field in
    393      * the specified cursor, based on the contact URI that was originally
    394      * queried.
    395      *
    396      * This is a helper function for the getCallerInfo() method that takes
    397      * a Cursor.  Looking up the person_id is nontrivial (compared to all
    398      * the other CallerInfo fields) since the column we need to use
    399      * depends on what query we originally ran.
    400      *
    401      * Watch out: be sure to not do any database access in this method, since
    402      * it's run from the UI thread (see comments below for more info.)
    403      *
    404      * @return the columnIndex to use (with cursor.getLong()) to get the
    405      * person_id, or -1 if we couldn't figure out what colum to use.
    406      *
    407      * TODO: Add a unittest for this method.  (This is a little tricky to
    408      * test, since we'll need a live contacts database to test against,
    409      * preloaded with at least some phone numbers and SIP addresses.  And
    410      * we'll probably have to hardcode the column indexes we expect, so
    411      * the test might break whenever the contacts schema changes.  But we
    412      * can at least make sure we handle all the URI patterns we claim to,
    413      * and that the mime types match what we expect...)
    414      */
    415     private static int getColumnIndexForPersonId(Uri contactRef, Cursor cursor) {
    416         // TODO: This is pretty ugly now, see bug 2269240 for
    417         // more details. The column to use depends upon the type of URL:
    418         // - content://com.android.contacts/data/phones ==> use the "contact_id" column
    419         // - content://com.android.contacts/phone_lookup ==> use the "_ID" column
    420         // - content://com.android.contacts/data ==> use the "contact_id" column
    421         // If it's none of the above, we leave columnIndex=-1 which means
    422         // that the person_id field will be left unset.
    423         //
    424         // The logic here *used* to be based on the mime type of contactRef
    425         // (for example Phone.CONTENT_ITEM_TYPE would tell us to use the
    426         // RawContacts.CONTACT_ID column).  But looking up the mime type requires
    427         // a call to context.getContentResolver().getType(contactRef), which
    428         // isn't safe to do from the UI thread since it can cause an ANR if
    429         // the contacts provider is slow or blocked (like during a sync.)
    430         //
    431         // So instead, figure out the column to use for person_id by just
    432         // looking at the URI itself.
    433 
    434         if (VDBG) Log.v(TAG, "- getColumnIndexForPersonId: contactRef URI = '"
    435                         + contactRef + "'...");
    436         // Warning: Do not enable the following logging (due to ANR risk.)
    437         // if (VDBG) Log.v(TAG, "- MIME type: "
    438         //                 + context.getContentResolver().getType(contactRef));
    439 
    440         String url = contactRef.toString();
    441         String columnName = null;
    442         if (url.startsWith("content://com.android.contacts/data/phones")) {
    443             // Direct lookup in the Phone table.
    444             // MIME type: Phone.CONTENT_ITEM_TYPE (= "vnd.android.cursor.item/phone_v2")
    445             if (VDBG) Log.v(TAG, "'data/phones' URI; using RawContacts.CONTACT_ID");
    446             columnName = RawContacts.CONTACT_ID;
    447         } else if (url.startsWith("content://com.android.contacts/data")) {
    448             // Direct lookup in the Data table.
    449             // MIME type: Data.CONTENT_TYPE (= "vnd.android.cursor.dir/data")
    450             if (VDBG) Log.v(TAG, "'data' URI; using Data.CONTACT_ID");
    451             // (Note Data.CONTACT_ID and RawContacts.CONTACT_ID are equivalent.)
    452             columnName = Data.CONTACT_ID;
    453         } else if (url.startsWith("content://com.android.contacts/phone_lookup")) {
    454             // Lookup in the PhoneLookup table, which provides "fuzzy matching"
    455             // for phone numbers.
    456             // MIME type: PhoneLookup.CONTENT_TYPE (= "vnd.android.cursor.dir/phone_lookup")
    457             if (VDBG) Log.v(TAG, "'phone_lookup' URI; using PhoneLookup._ID");
    458             columnName = PhoneLookup._ID;
    459         } else {
    460             Log.w(TAG, "Unexpected prefix for contactRef '" + url + "'");
    461         }
    462         int columnIndex = (columnName != null) ? cursor.getColumnIndex(columnName) : -1;
    463         if (VDBG) Log.v(TAG, "==> Using column '" + columnName
    464                         + "' (columnIndex = " + columnIndex + ") for person_id lookup...");
    465         return columnIndex;
    466     }
    467 
    468     /**
    469      * @return a string debug representation of this instance.
    470      */
    471     public String toString() {
    472         // Warning: never check in this file with VERBOSE_DEBUG = true
    473         // because that will result in PII in the system log.
    474         final boolean VERBOSE_DEBUG = false;
    475 
    476         if (VERBOSE_DEBUG) {
    477             return new StringBuilder(384)
    478                     .append("\nname: " + name)
    479                     .append("\nphoneNumber: " + phoneNumber)
    480                     .append("\ncnapName: " + cnapName)
    481                     .append("\nnumberPresentation: " + numberPresentation)
    482                     .append("\nnamePresentation: " + namePresentation)
    483                     .append("\ncontactExits: " + contactExists)
    484                     .append("\nphoneLabel: " + phoneLabel)
    485                     .append("\nnumberType: " + numberType)
    486                     .append("\nnumberLabel: " + numberLabel)
    487                     .append("\nphotoResource: " + photoResource)
    488                     .append("\nperson_id: " + person_id)
    489                     .append("\nneedUpdate: " + needUpdate)
    490                     .append("\ncontactRefUri: " + contactRefUri)
    491                     .append("\ncontactRingtoneUri: " + contactRefUri)
    492                     .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail)
    493                     .append("\ncachedPhoto: " + cachedPhoto)
    494                     .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent)
    495                     .append("\nemergency: " + mIsEmergency)
    496                     .append("\nvoicemail " + mIsVoiceMail)
    497                     .append("\ncontactExists " + contactExists)
    498                     .toString();
    499         } else {
    500             return new StringBuilder(128)
    501                     .append("CallerInfo { ")
    502                     .append("name " + ((name == null) ? "null" : "non-null"))
    503                     .append(", phoneNumber " + ((phoneNumber == null) ? "null" : "non-null"))
    504                     .append(" }")
    505                     .toString();
    506         }
    507     }
    508 }
    509