6e14a09ff071e179d76ac64b4be00618190f72b0
[android/platform/packages/apps/Phone.git] / src / com / android / phone / BluetoothAtPhonebook.java
1 /*
2  * Copyright (C) 2008 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.phone;
18
19 import android.bluetooth.AtCommandHandler;
20 import android.bluetooth.AtCommandResult;
21 import android.bluetooth.AtParser;
22 import android.content.Context;
23 import android.database.Cursor;
24 import android.net.Uri;
25 import android.provider.CallLog.Calls;
26 import android.provider.Contacts.Phones;
27 import android.provider.Contacts.PhonesColumns;
28 import android.telephony.PhoneNumberUtils;
29 import android.text.TextUtils;
30 import android.util.Log;
31
32 import java.util.HashMap;
33
34 /**
35  * Helper for managing phonebook presentation over AT commands
36  * @hide
37  */
38 public class BluetoothAtPhonebook {
39     private static final String TAG = "BtAtPhonebook";
40     private static final boolean DBG = false;
41     
42     /** The projection to use when querying the call log database in response
43      *  to AT+CPBR for the MC, RC, and DC phone books (missed, received, and
44      *   dialed calls respectively)
45      */
46     private static final String[] CALLS_PROJECTION = new String[] {
47         Calls._ID, Calls.NUMBER
48     };
49
50     /** The projection to use when querying the contacts database in response
51      *   to AT+CPBR for the ME phonebook (saved phone numbers).
52      */
53     private static final String[] PHONES_PROJECTION = new String[] {
54         Phones._ID, Phones.NAME, Phones.NUMBER, Phones.TYPE
55     };
56
57     /** The projection to use when querying the contacts database in response
58      *  to AT+CNUM for the ME phonebook (saved phone numbers).  We need only
59      *   the phone numbers here and the phone type.
60      */
61     private static final String[] PHONES_LITE_PROJECTION = new String[] {
62         Phones._ID, Phones.NUMBER, Phones.TYPE
63     };
64
65     /** Android supports as many phonebook entries as the flash can hold, but
66      *  BT periphals don't. Limit the number we'll report. */
67     private static final int MAX_PHONEBOOK_SIZE = 16384;
68
69     private static final String OUTGOING_CALL_WHERE = Calls.TYPE + "=" + Calls.OUTGOING_TYPE;
70     private static final String INCOMING_CALL_WHERE = Calls.TYPE + "=" + Calls.INCOMING_TYPE;
71     private static final String MISSED_CALL_WHERE = Calls.TYPE + "=" + Calls.MISSED_TYPE;
72
73     private class PhonebookResult {
74         public Cursor  cursor; // result set of last query
75         public int     numberColumn;
76         public int     typeColumn;
77         public int     nameColumn;
78     };
79
80     private final Context mContext;
81     private final BluetoothHandsfree mHandsfree;
82
83     private String mCurrentPhonebook;
84
85     private final HashMap<String, PhonebookResult> mPhonebooks =
86             new HashMap<String, PhonebookResult>(4);
87
88     public BluetoothAtPhonebook(Context context, BluetoothHandsfree handsfree) {
89         mContext = context;
90         mHandsfree = handsfree;
91         mPhonebooks.put("DC", new PhonebookResult());  // dialled calls
92         mPhonebooks.put("RC", new PhonebookResult());  // received calls
93         mPhonebooks.put("MC", new PhonebookResult());  // missed calls
94         mPhonebooks.put("ME", new PhonebookResult());  // mobile phonebook
95
96         mCurrentPhonebook = "ME";  // default to mobile phonebook
97     }
98
99     /** Returns the last dialled number, or null if no numbers have been called */
100     public String getLastDialledNumber() {
101         String[] projection = {Calls.NUMBER};
102         Cursor cursor = mContext.getContentResolver().query(Calls.CONTENT_URI, projection,
103                 Calls.TYPE + "=" + Calls.OUTGOING_TYPE, null, Calls.DEFAULT_SORT_ORDER +
104                 " LIMIT 1");
105         if (cursor.getCount() < 1) {
106             cursor.close();
107             return null;
108         }
109         cursor.moveToNext();
110         int column = cursor.getColumnIndexOrThrow(Calls.NUMBER);
111         String number = cursor.getString(column);
112         cursor.close();
113         return number;
114     }
115     
116     public void register(AtParser parser) {
117         // Select Character Set
118         // We support IRA and GSM (although we behave the same for both)
119         parser.register("+CSCS", new AtCommandHandler() {
120             @Override
121             public AtCommandResult handleReadCommand() {
122                 return new AtCommandResult("+CSCS: \"IRA\"");
123             }
124             @Override
125             public AtCommandResult handleSetCommand(Object[] args) {
126                 if (args.length < 1) {
127                     return new AtCommandResult(AtCommandResult.ERROR);
128                 }
129                 if (((String)args[0]).equals("\"GSM\"") || ((String)args[0]).equals("\"IRA\"")) {
130                     return new AtCommandResult(AtCommandResult.OK);
131                 } else {
132                     return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
133                 }
134             }
135             @Override
136             public AtCommandResult handleTestCommand() {
137                 return new AtCommandResult( "+CSCS: (\"IRA\",\"GSM\")");
138             }
139         });
140
141         // Select PhoneBook memory Storage
142         parser.register("+CPBS", new AtCommandHandler() {
143             @Override
144             public AtCommandResult handleReadCommand() {
145                 // Return current size and max size
146                 if ("SM".equals(mCurrentPhonebook)) {
147                     return new AtCommandResult("+CPBS: \"SM\",0," + MAX_PHONEBOOK_SIZE);
148                 }
149                     
150                 PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true);
151                 if (pbr == null) {
152                     return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
153                 }
154                 return new AtCommandResult("+CPBS: \"" + mCurrentPhonebook + "\"," +
155                         pbr.cursor.getCount() + "," + MAX_PHONEBOOK_SIZE);
156             }
157             @Override
158             public AtCommandResult handleSetCommand(Object[] args) {
159                 // Select phonebook memory
160                 if (args.length < 1 || !(args[0] instanceof String)) {
161                     return new AtCommandResult(AtCommandResult.ERROR);
162                 }
163                 String pb = ((String)args[0]).trim();
164                 while (pb.endsWith("\"")) pb = pb.substring(0, pb.length() - 1);
165                 while (pb.startsWith("\"")) pb = pb.substring(1, pb.length());
166                 if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
167                     if (DBG) log("Dont know phonebook: '" + pb + "'");
168                     return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
169                 }
170                 mCurrentPhonebook = pb;
171                 return new AtCommandResult(AtCommandResult.OK);
172             }
173             @Override
174             public AtCommandResult handleTestCommand() {
175                 return new AtCommandResult("+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")");
176             }
177         });
178
179         // Read PhoneBook Entries
180         parser.register("+CPBR", new AtCommandHandler() {
181             @Override
182             public AtCommandResult handleSetCommand(Object[] args) {
183                 // Phone Book Read Request
184                 // AT+CPBR=<index1>[,<index2>]
185
186                 // Parse indexes
187                 int index1;
188                 int index2;
189                 if (args.length < 1 || !(args[0] instanceof Integer)) {
190                     return new AtCommandResult(AtCommandResult.ERROR);
191                 } else {
192                     index1 = (Integer)args[0];
193                 }
194
195                 if (args.length == 1) {
196                     index2 = index1;
197                 } else if (!(args[1] instanceof Integer)) {
198                     return mHandsfree.reportCmeError(BluetoothCmeError.TEXT_HAS_INVALID_CHARS);
199                 } else {
200                     index2 = (Integer)args[1];
201                 }
202
203                 // Shortcut SM phonebook
204                 if ("SM".equals(mCurrentPhonebook)) {
205                     return new AtCommandResult(AtCommandResult.OK);
206                 }
207
208                 // Check phonebook
209                 PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
210                 if (pbr == null) {
211                     return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
212                 }
213
214                 // More sanity checks
215                 if (index1 <= 0 || index2 < index1 || index2 > pbr.cursor.getCount()) {
216                     return new AtCommandResult(AtCommandResult.ERROR);
217                 }
218
219                 // Process
220                 AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
221                 int errorDetected = -1; // no error
222                 pbr.cursor.moveToPosition(index1 - 1);
223                 for (int index = index1; index <= index2; index++) {
224                     String number = pbr.cursor.getString(pbr.numberColumn);
225                     String name = null;
226                     int type = -1;
227                     if (pbr.nameColumn == -1) {
228                         // try caller id lookup
229                         // TODO: This code is horribly inefficient. I saw it
230                         // take 7 seconds to process 100 missed calls.
231                         Cursor c = mContext.getContentResolver().query(
232                                 Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, number),
233                                 new String[] {Phones.NAME, Phones.TYPE}, null, null, null);
234                         if (c != null) {
235                             if (c.moveToFirst()) {
236                                 name = c.getString(0);
237                                 type = c.getInt(1);
238                             }
239                             c.close();
240                         }
241                         if (DBG && name == null) log("Caller ID lookup failed for " + number);
242
243                     } else {
244                         name = pbr.cursor.getString(pbr.nameColumn);
245                     }
246                     if (name == null) name = "";
247                     name = name.trim();
248                     if (name.length() > 28) name = name.substring(0, 28);
249
250                     if (pbr.typeColumn != -1) {
251                         type = pbr.cursor.getInt(pbr.typeColumn);
252                         name = name + "/" + getPhoneType(type);
253                     }
254
255                     int regionType = PhoneNumberUtils.toaFromString(number);
256
257                     number = number.trim();
258                     number = PhoneNumberUtils.stripSeparators(number);
259                     if (number.length() > 30) number = number.substring(0, 30);
260                     if (number.equals("-1")) {
261                         // unknown numbers are stored as -1 in our database
262                         number = "";
263                         name = "unknown";
264                     }
265
266                     result.addResponse("+CPBR: " + index + ",\"" + number + "\"," +
267                                        regionType + ",\"" + name + "\"");
268                     if (!pbr.cursor.moveToNext()) {
269                         break;
270                     }
271                 }
272                 return result;
273             }
274             @Override
275             public AtCommandResult handleTestCommand() {
276                 /* Ideally we should return the maximum range of valid index's
277                  * for the selected phone book, but this causes problems for the
278                  * Parrot CK3300. So instead send just the range of currently
279                  * valid index's.
280                  */
281                 int size;
282                 if ("SM".equals(mCurrentPhonebook)) {
283                     size = 0;
284                 } else {
285                     PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
286                     if (pbr == null) {
287                         return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
288                     }
289                     size = pbr.cursor.getCount();
290                 }
291
292                 if (size == 0) {
293                     /* Sending "+CPBR: (1-0)" can confused some carkits, send "1-1"
294                      * instead */
295                     size = 1;
296                 }
297                 return new AtCommandResult("+CPBR: (1-" + size + "),30,30");
298             }
299         });
300     }
301
302     /** Get the most recent result for the given phone book,
303      *  with the cursor ready to go.
304      *  If force then re-query that phonebook
305      *  Returns null if the cursor is not ready
306      */
307     private synchronized PhonebookResult getPhonebookResult(String pb, boolean force) {
308         if (pb == null) {
309             return null;
310         }
311         PhonebookResult pbr = mPhonebooks.get(pb);
312         if (pbr == null) {
313             pbr = new PhonebookResult();
314         }
315         if (force || pbr.cursor == null) {
316             if (!queryPhonebook(pb, pbr)) {
317                 return null;
318             }
319         }
320
321         if (pbr.cursor == null) {
322             return null;
323         }
324
325         return pbr;
326     }
327
328     private synchronized boolean queryPhonebook(String pb, PhonebookResult pbr) {
329         String where;
330         boolean ancillaryPhonebook = true;
331
332         if (pb.equals("ME")) {
333             ancillaryPhonebook = false;
334             where = null;
335         } else if (pb.equals("DC")) {
336             where = OUTGOING_CALL_WHERE;
337         } else if (pb.equals("RC")) {
338             where = INCOMING_CALL_WHERE;
339         } else if (pb.equals("MC")) {
340             where = MISSED_CALL_WHERE;
341         } else {
342             return false;
343         }
344
345         if (pbr.cursor != null) {
346             pbr.cursor.close();
347             pbr.cursor = null;
348         }
349
350         if (ancillaryPhonebook) {
351             pbr.cursor = mContext.getContentResolver().query(
352                     Calls.CONTENT_URI, CALLS_PROJECTION, where, null,
353                     Calls.DEFAULT_SORT_ORDER + " LIMIT " + MAX_PHONEBOOK_SIZE);
354             pbr.numberColumn = pbr.cursor.getColumnIndexOrThrow(Calls.NUMBER);
355             pbr.typeColumn = -1;
356             pbr.nameColumn = -1;
357         } else {
358             pbr.cursor = mContext.getContentResolver().query(
359                     Phones.CONTENT_URI, PHONES_PROJECTION, where, null,
360                     Phones.DEFAULT_SORT_ORDER + " LIMIT " + MAX_PHONEBOOK_SIZE);
361             pbr.numberColumn = pbr.cursor.getColumnIndex(Phones.NUMBER);
362             pbr.typeColumn = pbr.cursor.getColumnIndex(Phones.TYPE);
363             pbr.nameColumn = pbr.cursor.getColumnIndex(Phones.NAME);
364         }
365         Log.i(TAG, "Refreshed phonebook " + pb + " with " + pbr.cursor.getCount() + " results");
366         return true;
367     }
368
369     private static String getPhoneType(int type) {
370         switch (type) {
371             case PhonesColumns.TYPE_HOME:
372                 return "H";
373             case PhonesColumns.TYPE_MOBILE:
374                 return "M";
375             case PhonesColumns.TYPE_WORK:
376                 return "W";
377             case PhonesColumns.TYPE_FAX_HOME:
378             case PhonesColumns.TYPE_FAX_WORK:
379                 return "F";
380             case PhonesColumns.TYPE_OTHER:
381             case PhonesColumns.TYPE_CUSTOM:
382             default:
383                 return "O";
384         }
385     }
386
387     private static void log(String msg) {
388         Log.d(TAG, msg);
389     }
390 }