CallerInfo.java revision 1a7f2bcab2d2023f2ee4cfb0bc57bc265b5aab87
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
17package com.android.incallui;
18
19import android.content.Context;
20import android.database.Cursor;
21import android.graphics.Bitmap;
22import android.graphics.drawable.Drawable;
23import android.location.CountryDetector;
24import android.net.Uri;
25import android.provider.ContactsContract.CommonDataKinds.Phone;
26import android.provider.ContactsContract.Data;
27import android.provider.ContactsContract.PhoneLookup;
28import android.provider.ContactsContract.RawContacts;
29import android.telephony.PhoneNumberUtils;
30import android.telephony.TelephonyManager;
31import android.text.TextUtils;
32
33import com.android.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;
34import com.android.i18n.phonenumbers.NumberParseException;
35import com.android.i18n.phonenumbers.PhoneNumberUtil;
36import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber;
37
38import java.util.Locale;
39
40
41/**
42 * Looks up caller information for the given phone number.
43 *
44 * {@hide}
45 */
46public 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 geoDescription;
80
81    public String cnapName;
82    public int numberPresentation;
83    public int namePresentation;
84    public boolean contactExists;
85
86    public String phoneLabel;
87    /* Split up the phoneLabel into number type and label name */
88    public int    numberType;
89    public String numberLabel;
90
91    public int photoResource;
92    public long person_id;
93    public boolean needUpdate;
94    public Uri contactRefUri;
95
96    // fields to hold individual contact preference data,
97    // including the send to voicemail flag and the ringtone
98    // uri reference.
99    public Uri contactRingtoneUri;
100    public boolean shouldSendToVoicemail;
101
102    /**
103     * Drawable representing the caller image.  This is essentially
104     * a cache for the image data tied into the connection /
105     * callerinfo object.
106     *
107     * This might be a high resolution picture which is more suitable
108     * for full-screen image view than for smaller icons used in some
109     * kinds of notifications.
110     *
111     * The {@link #isCachedPhotoCurrent} flag indicates if the image
112     * data needs to be reloaded.
113     */
114    public Drawable cachedPhoto;
115    /**
116     * Bitmap representing the caller image which has possibly lower
117     * resolution than {@link #cachedPhoto} and thus more suitable for
118     * icons (like notification icons).
119     *
120     * In usual cases this is just down-scaled image of {@link #cachedPhoto}.
121     * If the down-scaling fails, this will just become null.
122     *
123     * The {@link #isCachedPhotoCurrent} flag indicates if the image
124     * data needs to be reloaded.
125     */
126    public Bitmap cachedPhotoIcon;
127    /**
128     * Boolean which indicates if {@link #cachedPhoto} and
129     * {@link #cachedPhotoIcon} is fresh enough. If it is false,
130     * those images aren't pointing to valid objects.
131     */
132    public boolean isCachedPhotoCurrent;
133
134    private boolean mIsEmergency;
135    private boolean mIsVoiceMail;
136
137    public CallerInfo() {
138        // TODO: Move all the basic initialization here?
139        mIsEmergency = false;
140        mIsVoiceMail = false;
141    }
142
143    /**
144     * getCallerInfo given a Cursor.
145     * @param context the context used to retrieve string constants
146     * @param contactRef the URI to attach to this CallerInfo object
147     * @param cursor the first object in the cursor is used to build the CallerInfo object.
148     * @return the CallerInfo which contains the caller id for the given
149     * number. The returned CallerInfo is null if no number is supplied.
150     */
151    public static CallerInfo getCallerInfo(Context context, Uri contactRef, Cursor cursor) {
152        CallerInfo info = new CallerInfo();
153        info.photoResource = 0;
154        info.phoneLabel = null;
155        info.numberType = 0;
156        info.numberLabel = null;
157        info.cachedPhoto = null;
158        info.isCachedPhotoCurrent = false;
159        info.contactExists = false;
160
161        Log.v(TAG, "getCallerInfo() based on cursor...");
162
163        if (cursor != null) {
164            if (cursor.moveToFirst()) {
165                // TODO: photo_id is always available but not taken
166                // care of here. Maybe we should store it in the
167                // CallerInfo object as well.
168
169                int columnIndex;
170
171                // Look for the name
172                columnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
173                if (columnIndex != -1) {
174                    info.name = cursor.getString(columnIndex);
175                }
176
177                // Look for the number
178                columnIndex = cursor.getColumnIndex(PhoneLookup.NUMBER);
179                if (columnIndex != -1) {
180                    info.phoneNumber = cursor.getString(columnIndex);
181                }
182
183                // Look for the normalized number
184                columnIndex = cursor.getColumnIndex(PhoneLookup.NORMALIZED_NUMBER);
185                if (columnIndex != -1) {
186                    info.normalizedNumber = cursor.getString(columnIndex);
187                }
188
189                // Look for the label/type combo
190                columnIndex = cursor.getColumnIndex(PhoneLookup.LABEL);
191                if (columnIndex != -1) {
192                    int typeColumnIndex = cursor.getColumnIndex(PhoneLookup.TYPE);
193                    if (typeColumnIndex != -1) {
194                        info.numberType = cursor.getInt(typeColumnIndex);
195                        info.numberLabel = cursor.getString(columnIndex);
196                        info.phoneLabel = Phone.getDisplayLabel(context,
197                                info.numberType, info.numberLabel)
198                                .toString();
199                    }
200                }
201
202                // Look for the person_id.
203                columnIndex = getColumnIndexForPersonId(contactRef, cursor);
204                if (columnIndex != -1) {
205                    info.person_id = cursor.getLong(columnIndex);
206                    Log.v(TAG, "==> got info.person_id: " + info.person_id);
207                } else {
208                    // No valid columnIndex, so we can't look up person_id.
209                    Log.v(TAG, "Couldn't find person_id column for " + contactRef);
210                    // Watch out: this means that anything that depends on
211                    // person_id will be broken (like contact photo lookups in
212                    // the in-call UI, for example.)
213                }
214
215                // look for the custom ringtone, create from the string stored
216                // in the database.
217                columnIndex = cursor.getColumnIndex(PhoneLookup.CUSTOM_RINGTONE);
218                if ((columnIndex != -1) && (cursor.getString(columnIndex) != null)) {
219                    info.contactRingtoneUri = Uri.parse(cursor.getString(columnIndex));
220                } else {
221                    info.contactRingtoneUri = null;
222                }
223
224                // look for the send to voicemail flag, set it to true only
225                // under certain circumstances.
226                columnIndex = cursor.getColumnIndex(PhoneLookup.SEND_TO_VOICEMAIL);
227                info.shouldSendToVoicemail = (columnIndex != -1) &&
228                        ((cursor.getInt(columnIndex)) == 1);
229                info.contactExists = true;
230            }
231            cursor.close();
232        }
233
234        info.needUpdate = false;
235        info.name = normalize(info.name);
236        info.contactRefUri = contactRef;
237
238        return info;
239    }
240
241    /**
242     * getCallerInfo given a URI, look up in the call-log database
243     * for the uri unique key.
244     * @param context the context used to get the ContentResolver
245     * @param contactRef the URI used to lookup caller id
246     * @return the CallerInfo which contains the caller id for the given
247     * number. The returned CallerInfo is null if no number is supplied.
248     */
249    public static CallerInfo getCallerInfo(Context context, Uri contactRef) {
250
251        return getCallerInfo(context, contactRef,
252                context.getContentResolver().query(contactRef, null, null, null, null));
253    }
254
255    /**
256     * getCallerInfo given a phone number, look up in the call-log database
257     * for the matching caller id info.
258     * @param context the context used to get the ContentResolver
259     * @param number the phone number used to lookup caller id
260     * @return the CallerInfo which contains the caller id for the given
261     * number. The returned CallerInfo is null if no number is supplied. If
262     * a matching number is not found, then a generic caller info is returned,
263     * with all relevant fields empty or null.
264     */
265    public static CallerInfo getCallerInfo(Context context, String number) {
266        Log.v(TAG, "getCallerInfo() based on number...");
267
268        if (TextUtils.isEmpty(number)) {
269            return null;
270        }
271
272        // Change the callerInfo number ONLY if it is an emergency number
273        // or if it is the voicemail number.  If it is either, take a
274        // shortcut and skip the query.
275        if (PhoneNumberUtils.isLocalEmergencyNumber(number, context)) {
276            return new CallerInfo().markAsEmergency(context);
277        } else if (PhoneNumberUtils.isVoiceMailNumber(number)) {
278            return new CallerInfo().markAsVoiceMail();
279        }
280
281        Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
282
283        CallerInfo info = getCallerInfo(context, contactUri);
284        info = doSecondaryLookupIfNecessary(context, number, info);
285
286        // if no query results were returned with a viable number,
287        // fill in the original number value we used to query with.
288        if (TextUtils.isEmpty(info.phoneNumber)) {
289            info.phoneNumber = number;
290        }
291
292        return info;
293    }
294
295    /**
296     * Performs another lookup if previous lookup fails and it's a SIP call
297     * and the peer's username is all numeric. Look up the username as it
298     * could be a PSTN number in the contact database.
299     *
300     * @param context the query context
301     * @param number the original phone number, could be a SIP URI
302     * @param previousResult the result of previous lookup
303     * @return previousResult if it's not the case
304     */
305    static CallerInfo doSecondaryLookupIfNecessary(Context context,
306            String number, CallerInfo previousResult) {
307        if (!previousResult.contactExists
308                && PhoneNumberUtils.isUriNumber(number)) {
309            String username = PhoneNumberUtils.getUsernameFromUriNumber(number);
310            if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
311                previousResult = getCallerInfo(context,
312                        Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
313                                Uri.encode(username)));
314            }
315        }
316        return previousResult;
317    }
318
319    /**
320     * getCallerId: a convenience method to get the caller id for a given
321     * number.
322     *
323     * @param context the context used to get the ContentResolver.
324     * @param number a phone number.
325     * @return if the number belongs to a contact, the contact's name is
326     * returned; otherwise, the number itself is returned.
327     *
328     * TODO NOTE: This MAY need to refer to the Asynchronous Query API
329     * [startQuery()], instead of getCallerInfo, but since it looks like
330     * it is only being used by the provider calls in the messaging app:
331     *   1. android.provider.Telephony.Mms.getDisplayAddress()
332     *   2. android.provider.Telephony.Sms.getDisplayAddress()
333     * We may not need to make the change.
334     */
335    public static String getCallerId(Context context, String number) {
336        CallerInfo info = getCallerInfo(context, number);
337        String callerID = null;
338
339        if (info != null) {
340            String name = info.name;
341
342            if (!TextUtils.isEmpty(name)) {
343                callerID = name;
344            } else {
345                callerID = number;
346            }
347        }
348
349        return callerID;
350    }
351
352    // Accessors
353
354    /**
355     * @return true if the caller info is an emergency number.
356     */
357    public boolean isEmergencyNumber() {
358        return mIsEmergency;
359    }
360
361    /**
362     * @return true if the caller info is a voicemail number.
363     */
364    public boolean isVoiceMailNumber() {
365        return mIsVoiceMail;
366    }
367
368    /**
369     * Mark this CallerInfo as an emergency call.
370     * @param context To lookup the localized 'Emergency Number' string.
371     * @return this instance.
372     */
373    // TODO: Note we're setting the phone number here (refer to
374    // javadoc comments at the top of CallerInfo class) to a localized
375    // string 'Emergency Number'. This is pretty bad because we are
376    // making UI work here instead of just packaging the data. We
377    // should set the phone number to the dialed number and name to
378    // 'Emergency Number' and let the UI make the decision about what
379    // should be displayed.
380    /* package */ CallerInfo markAsEmergency(Context context) {
381        phoneNumber = context.getString(
382            com.android.internal.R.string.emergency_call_dialog_number_for_display);
383        photoResource = com.android.internal.R.drawable.picture_emergency;
384        mIsEmergency = true;
385        return this;
386    }
387
388
389    /**
390     * Mark this CallerInfo as a voicemail call. The voicemail label
391     * is obtained from the telephony manager. Caller must hold the
392     * READ_PHONE_STATE permission otherwise the phoneNumber will be
393     * set to null.
394     * @return this instance.
395     */
396    // TODO: As in the emergency number handling, we end up writing a
397    // string in the phone number field.
398    /* package */ CallerInfo markAsVoiceMail() {
399        mIsVoiceMail = true;
400
401        try {
402            String voiceMailLabel = TelephonyManager.getDefault().getVoiceMailAlphaTag();
403
404            phoneNumber = voiceMailLabel;
405        } catch (SecurityException se) {
406            // Should never happen: if this process does not have
407            // permission to retrieve VM tag, it should not have
408            // permission to retrieve VM number and would not call
409            // this method.
410            // Leave phoneNumber untouched.
411            Log.e(TAG, "Cannot access VoiceMail.", se);
412        }
413        // TODO: There is no voicemail picture?
414        // FIXME: FIND ANOTHER ICON
415        // photoResource = android.R.drawable.badge_voicemail;
416        return this;
417    }
418
419    private static String normalize(String s) {
420        if (s == null || s.length() > 0) {
421            return s;
422        } else {
423            return null;
424        }
425    }
426
427    /**
428     * Returns the column index to use to find the "person_id" field in
429     * the specified cursor, based on the contact URI that was originally
430     * queried.
431     *
432     * This is a helper function for the getCallerInfo() method that takes
433     * a Cursor.  Looking up the person_id is nontrivial (compared to all
434     * the other CallerInfo fields) since the column we need to use
435     * depends on what query we originally ran.
436     *
437     * Watch out: be sure to not do any database access in this method, since
438     * it's run from the UI thread (see comments below for more info.)
439     *
440     * @return the columnIndex to use (with cursor.getLong()) to get the
441     * person_id, or -1 if we couldn't figure out what colum to use.
442     *
443     * TODO: Add a unittest for this method.  (This is a little tricky to
444     * test, since we'll need a live contacts database to test against,
445     * preloaded with at least some phone numbers and SIP addresses.  And
446     * we'll probably have to hardcode the column indexes we expect, so
447     * the test might break whenever the contacts schema changes.  But we
448     * can at least make sure we handle all the URI patterns we claim to,
449     * and that the mime types match what we expect...)
450     */
451    private static int getColumnIndexForPersonId(Uri contactRef, Cursor cursor) {
452        // TODO: This is pretty ugly now, see bug 2269240 for
453        // more details. The column to use depends upon the type of URL:
454        // - content://com.android.contacts/data/phones ==> use the "contact_id" column
455        // - content://com.android.contacts/phone_lookup ==> use the "_ID" column
456        // - content://com.android.contacts/data ==> use the "contact_id" column
457        // If it's none of the above, we leave columnIndex=-1 which means
458        // that the person_id field will be left unset.
459        //
460        // The logic here *used* to be based on the mime type of contactRef
461        // (for example Phone.CONTENT_ITEM_TYPE would tell us to use the
462        // RawContacts.CONTACT_ID column).  But looking up the mime type requires
463        // a call to context.getContentResolver().getType(contactRef), which
464        // isn't safe to do from the UI thread since it can cause an ANR if
465        // the contacts provider is slow or blocked (like during a sync.)
466        //
467        // So instead, figure out the column to use for person_id by just
468        // looking at the URI itself.
469
470        Log.v(TAG, "- getColumnIndexForPersonId: contactRef URI = '"
471                + contactRef + "'...");
472        // Warning: Do not enable the following logging (due to ANR risk.)
473        // if (VDBG) Rlog.v(TAG, "- MIME type: "
474        //                 + context.getContentResolver().getType(contactRef));
475
476        String url = contactRef.toString();
477        String columnName = null;
478        if (url.startsWith("content://com.android.contacts/data/phones")) {
479            // Direct lookup in the Phone table.
480            // MIME type: Phone.CONTENT_ITEM_TYPE (= "vnd.android.cursor.item/phone_v2")
481            Log.v(TAG, "'data/phones' URI; using RawContacts.CONTACT_ID");
482            columnName = RawContacts.CONTACT_ID;
483        } else if (url.startsWith("content://com.android.contacts/data")) {
484            // Direct lookup in the Data table.
485            // MIME type: Data.CONTENT_TYPE (= "vnd.android.cursor.dir/data")
486            Log.v(TAG, "'data' URI; using Data.CONTACT_ID");
487            // (Note Data.CONTACT_ID and RawContacts.CONTACT_ID are equivalent.)
488            columnName = Data.CONTACT_ID;
489        } else if (url.startsWith("content://com.android.contacts/phone_lookup")) {
490            // Lookup in the PhoneLookup table, which provides "fuzzy matching"
491            // for phone numbers.
492            // MIME type: PhoneLookup.CONTENT_TYPE (= "vnd.android.cursor.dir/phone_lookup")
493            Log.v(TAG, "'phone_lookup' URI; using PhoneLookup._ID");
494            columnName = PhoneLookup._ID;
495        } else {
496            Log.v(TAG, "Unexpected prefix for contactRef '" + url + "'");
497        }
498        int columnIndex = (columnName != null) ? cursor.getColumnIndex(columnName) : -1;
499        Log.v(TAG, "==> Using column '" + columnName
500                + "' (columnIndex = " + columnIndex + ") for person_id lookup...");
501        return columnIndex;
502    }
503
504    /**
505     * Updates this CallerInfo's geoDescription field, based on the raw
506     * phone number in the phoneNumber field.
507     *
508     * (Note that the various getCallerInfo() methods do *not* set the
509     * geoDescription automatically; you need to call this method
510     * explicitly to get it.)
511     *
512     * @param context the context used to look up the current locale / country
513     * @param fallbackNumber if this CallerInfo's phoneNumber field is empty,
514     *        this specifies a fallback number to use instead.
515     */
516    public void updateGeoDescription(Context context, String fallbackNumber) {
517        String number = TextUtils.isEmpty(phoneNumber) ? fallbackNumber : phoneNumber;
518        geoDescription = getGeoDescription(context, number);
519    }
520
521    /**
522     * @return a geographical description string for the specified number.
523     * @see com.android.i18n.phonenumbers.PhoneNumberOfflineGeocoder
524     */
525    private static String getGeoDescription(Context context, String number) {
526        Log.v(TAG, "getGeoDescription('" + number + "')...");
527
528        if (TextUtils.isEmpty(number)) {
529            return null;
530        }
531
532        PhoneNumberUtil util = PhoneNumberUtil.getInstance();
533        PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
534
535        Locale locale = context.getResources().getConfiguration().locale;
536        String countryIso = getCurrentCountryIso(context, locale);
537        PhoneNumber pn = null;
538        try {
539            Log.v(TAG, "parsing '" + number
540                    + "' for countryIso '" + countryIso + "'...");
541            pn = util.parse(number, countryIso);
542            Log.v(TAG, "- parsed number: " + pn);
543        } catch (NumberParseException e) {
544            Log.v(TAG, "getGeoDescription: NumberParseException for incoming number '" +
545                    number + "'");
546        }
547
548        if (pn != null) {
549            String description = geocoder.getDescriptionForNumber(pn, locale);
550            Log.v(TAG, "- got description: '" + description + "'");
551            return description;
552        } else {
553            return null;
554        }
555    }
556
557    /**
558     * @return The ISO 3166-1 two letters country code of the country the user
559     *         is in.
560     */
561    private static String getCurrentCountryIso(Context context, Locale locale) {
562      String countryIso;
563      CountryDetector detector = (CountryDetector) context.getSystemService(
564          Context.COUNTRY_DETECTOR);
565      if (detector != null) {
566        countryIso = detector.detectCountry().getCountryIso();
567      } else {
568        countryIso = locale.getCountry();
569            Log.v(TAG, "No CountryDetector; falling back to countryIso based on locale: "
570                    + countryIso);
571      }
572      return countryIso;
573    }
574
575    /**
576     * @return a string debug representation of this instance.
577     */
578    @Override
579    public String toString() {
580        // Warning: never check in this file with VERBOSE_DEBUG = true
581        // because that will result in PII in the system log.
582        final boolean VERBOSE_DEBUG = false;
583
584        if (VERBOSE_DEBUG) {
585            return new StringBuilder(384)
586                    .append(super.toString() + " { ")
587                    .append("\nname: " + name)
588                    .append("\nphoneNumber: " + phoneNumber)
589                    .append("\nnormalizedNumber: " + normalizedNumber)
590                    .append("\ngeoDescription: " + geoDescription)
591                    .append("\ncnapName: " + cnapName)
592                    .append("\nnumberPresentation: " + numberPresentation)
593                    .append("\nnamePresentation: " + namePresentation)
594                    .append("\ncontactExists: " + contactExists)
595                    .append("\nphoneLabel: " + phoneLabel)
596                    .append("\nnumberType: " + numberType)
597                    .append("\nnumberLabel: " + numberLabel)
598                    .append("\nphotoResource: " + photoResource)
599                    .append("\nperson_id: " + person_id)
600                    .append("\nneedUpdate: " + needUpdate)
601                    .append("\ncontactRefUri: " + contactRefUri)
602                    .append("\ncontactRingtoneUri: " + contactRefUri)
603                    .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail)
604                    .append("\ncachedPhoto: " + cachedPhoto)
605                    .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent)
606                    .append("\nemergency: " + mIsEmergency)
607                    .append("\nvoicemail " + mIsVoiceMail)
608                    .append(" }")
609                    .toString();
610        } else {
611            return new StringBuilder(128)
612                    .append(super.toString() + " { ")
613                    .append("name " + ((name == null) ? "null" : "non-null"))
614                    .append(", phoneNumber " + ((phoneNumber == null) ? "null" : "non-null"))
615                    .append(" }")
616                    .toString();
617        }
618    }
619}
620