1 /* 2 * Copyright (C) 2011 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.dialer.calllog; 18 19 import android.content.Context; 20 import android.database.Cursor; 21 import android.net.Uri; 22 import android.provider.ContactsContract; 23 import android.provider.ContactsContract.CommonDataKinds.Phone; 24 import android.provider.ContactsContract.Contacts; 25 import android.provider.ContactsContract.DisplayNameSources; 26 import android.provider.ContactsContract.PhoneLookup; 27 import android.telephony.PhoneNumberUtils; 28 import android.text.TextUtils; 29 30 import com.android.contacts.common.util.Constants; 31 import com.android.contacts.common.util.UriUtils; 32 import com.android.dialer.service.CachedNumberLookupService; 33 import com.android.dialer.service.CachedNumberLookupService.CachedContactInfo; 34 import com.android.dialerbind.ObjectFactory; 35 36 import org.json.JSONException; 37 import org.json.JSONObject; 38 39 /** 40 * Utility class to look up the contact information for a given number. 41 */ 42 public class ContactInfoHelper { 43 private final Context mContext; 44 private final String mCurrentCountryIso; 45 46 private static final CachedNumberLookupService mCachedNumberLookupService = 47 ObjectFactory.newCachedNumberLookupService(); 48 49 public ContactInfoHelper(Context context, String currentCountryIso) { 50 mContext = context; 51 mCurrentCountryIso = currentCountryIso; 52 } 53 54 /** 55 * Returns the contact information for the given number. 56 * <p> 57 * If the number does not match any contact, returns a contact info containing only the number 58 * and the formatted number. 59 * <p> 60 * If an error occurs during the lookup, it returns null. 61 * 62 * @param number the number to look up 63 * @param countryIso the country associated with this number 64 */ 65 public ContactInfo lookupNumber(String number, String countryIso) { 66 final ContactInfo info; 67 68 // Determine the contact info. 69 if (PhoneNumberUtils.isUriNumber(number)) { 70 // This "number" is really a SIP address. 71 ContactInfo sipInfo = queryContactInfoForSipAddress(number); 72 if (sipInfo == null || sipInfo == ContactInfo.EMPTY) { 73 // Check whether the "username" part of the SIP address is 74 // actually the phone number of a contact. 75 String username = PhoneNumberUtils.getUsernameFromUriNumber(number); 76 if (PhoneNumberUtils.isGlobalPhoneNumber(username)) { 77 sipInfo = queryContactInfoForPhoneNumber(username, countryIso); 78 } 79 } 80 info = sipInfo; 81 } else { 82 // Look for a contact that has the given phone number. 83 ContactInfo phoneInfo = queryContactInfoForPhoneNumber(number, countryIso); 84 85 if (phoneInfo == null || phoneInfo == ContactInfo.EMPTY) { 86 // Check whether the phone number has been saved as an "Internet call" number. 87 phoneInfo = queryContactInfoForSipAddress(number); 88 } 89 info = phoneInfo; 90 } 91 92 final ContactInfo updatedInfo; 93 if (info == null) { 94 // The lookup failed. 95 updatedInfo = null; 96 } else { 97 // If we did not find a matching contact, generate an empty contact info for the number. 98 if (info == ContactInfo.EMPTY) { 99 // Did not find a matching contact. 100 updatedInfo = new ContactInfo(); 101 updatedInfo.number = number; 102 updatedInfo.formattedNumber = formatPhoneNumber(number, null, countryIso); 103 updatedInfo.lookupUri = createTemporaryContactUri(number); 104 } else { 105 updatedInfo = info; 106 } 107 } 108 return updatedInfo; 109 } 110 111 /** 112 * Creates a JSON-encoded lookup uri for a unknown number without an associated contact 113 * 114 * @param number - Unknown phone number 115 * @return JSON-encoded URI that can be used to perform a lookup when clicking 116 * on the quick contact card. 117 */ 118 private static Uri createTemporaryContactUri(String number) { 119 try { 120 final JSONObject contactRows = new JSONObject() 121 .put(Phone.CONTENT_ITEM_TYPE, new JSONObject() 122 .put(Phone.NUMBER, number) 123 .put(Phone.TYPE, Phone.TYPE_CUSTOM)); 124 125 final String jsonString = new JSONObject() 126 .put(Contacts.DISPLAY_NAME, number) 127 .put(Contacts.DISPLAY_NAME_SOURCE, DisplayNameSources.PHONE) 128 .put(Contacts.CONTENT_ITEM_TYPE, contactRows) 129 .toString(); 130 131 return Contacts.CONTENT_LOOKUP_URI.buildUpon() 132 .appendPath(Constants.LOOKUP_URI_ENCODED) 133 .appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY, 134 String.valueOf(Long.MAX_VALUE)) 135 .encodedFragment(jsonString) 136 .build(); 137 } catch (JSONException e) { 138 return null; 139 } 140 } 141 142 /** 143 * Looks up a contact using the given URI. 144 * <p> 145 * It returns null if an error occurs, {@link ContactInfo#EMPTY} if no matching contact is 146 * found, or the {@link ContactInfo} for the given contact. 147 * <p> 148 * The {@link ContactInfo#formattedNumber} field is always set to {@code null} in the returned 149 * value. 150 */ 151 private ContactInfo lookupContactFromUri(Uri uri) { 152 final ContactInfo info; 153 Cursor phonesCursor = 154 mContext.getContentResolver().query( 155 uri, PhoneQuery._PROJECTION, null, null, null); 156 157 if (phonesCursor != null) { 158 try { 159 if (phonesCursor.moveToFirst()) { 160 info = new ContactInfo(); 161 long contactId = phonesCursor.getLong(PhoneQuery.PERSON_ID); 162 String lookupKey = phonesCursor.getString(PhoneQuery.LOOKUP_KEY); 163 info.lookupUri = Contacts.getLookupUri(contactId, lookupKey); 164 info.name = phonesCursor.getString(PhoneQuery.NAME); 165 info.type = phonesCursor.getInt(PhoneQuery.PHONE_TYPE); 166 info.label = phonesCursor.getString(PhoneQuery.LABEL); 167 info.number = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER); 168 info.normalizedNumber = phonesCursor.getString(PhoneQuery.NORMALIZED_NUMBER); 169 info.photoId = phonesCursor.getLong(PhoneQuery.PHOTO_ID); 170 info.photoUri = 171 UriUtils.parseUriOrNull(phonesCursor.getString(PhoneQuery.PHOTO_URI)); 172 info.formattedNumber = null; 173 } else { 174 info = ContactInfo.EMPTY; 175 } 176 } finally { 177 phonesCursor.close(); 178 } 179 } else { 180 // Failed to fetch the data, ignore this request. 181 info = null; 182 } 183 return info; 184 } 185 186 /** 187 * Determines the contact information for the given SIP address. 188 * <p> 189 * It returns the contact info if found. 190 * <p> 191 * If no contact corresponds to the given SIP address, returns {@link ContactInfo#EMPTY}. 192 * <p> 193 * If the lookup fails for some other reason, it returns null. 194 */ 195 private ContactInfo queryContactInfoForSipAddress(String sipAddress) { 196 final ContactInfo info; 197 198 // "contactNumber" is a SIP address, so use the PhoneLookup table with the SIP parameter. 199 Uri.Builder uriBuilder = PhoneLookup.CONTENT_FILTER_URI.buildUpon(); 200 uriBuilder.appendPath(Uri.encode(sipAddress)); 201 uriBuilder.appendQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, "1"); 202 return lookupContactFromUri(uriBuilder.build()); 203 } 204 205 /** 206 * Determines the contact information for the given phone number. 207 * <p> 208 * It returns the contact info if found. 209 * <p> 210 * If no contact corresponds to the given phone number, returns {@link ContactInfo#EMPTY}. 211 * <p> 212 * If the lookup fails for some other reason, it returns null. 213 */ 214 private ContactInfo queryContactInfoForPhoneNumber(String number, String countryIso) { 215 String contactNumber = number; 216 if (!TextUtils.isEmpty(countryIso)) { 217 // Normalize the number: this is needed because the PhoneLookup query below does not 218 // accept a country code as an input. 219 String numberE164 = PhoneNumberUtils.formatNumberToE164(number, countryIso); 220 if (!TextUtils.isEmpty(numberE164)) { 221 // Only use it if the number could be formatted to E164. 222 contactNumber = numberE164; 223 } 224 } 225 226 // The "contactNumber" is a regular phone number, so use the PhoneLookup table. 227 Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(contactNumber)); 228 ContactInfo info = lookupContactFromUri(uri); 229 if (info != null && info != ContactInfo.EMPTY) { 230 info.formattedNumber = formatPhoneNumber(number, null, countryIso); 231 } else if (mCachedNumberLookupService != null) { 232 CachedContactInfo cacheInfo = mCachedNumberLookupService 233 .lookupCachedContactFromNumber(mContext, number); 234 info = cacheInfo != null ? cacheInfo.getContactInfo() : null; 235 } 236 return info; 237 } 238 239 /** 240 * Format the given phone number 241 * 242 * @param number the number to be formatted. 243 * @param normalizedNumber the normalized number of the given number. 244 * @param countryIso the ISO 3166-1 two letters country code, the country's 245 * convention will be used to format the number if the normalized 246 * phone is null. 247 * 248 * @return the formatted number, or the given number if it was formatted. 249 */ 250 private String formatPhoneNumber(String number, String normalizedNumber, 251 String countryIso) { 252 if (TextUtils.isEmpty(number)) { 253 return ""; 254 } 255 // If "number" is really a SIP address, don't try to do any formatting at all. 256 if (PhoneNumberUtils.isUriNumber(number)) { 257 return number; 258 } 259 if (TextUtils.isEmpty(countryIso)) { 260 countryIso = mCurrentCountryIso; 261 } 262 return PhoneNumberUtils.formatNumber(number, normalizedNumber, countryIso); 263 } 264 } 265