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