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