/android/import-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/import-contacts

« back to all changes in this revision

Viewing changes to src/org/waxworlds/edam/importcontacts/Importer.java

  • Committer: edam
  • Date: 2011-04-22 15:36:06 UTC
  • Revision ID: edam@waxworlds.org-20110422153606-9x9l0nbmvx6oxfxu
- pulled contacts cache out in to seperate class

Show diffs side-by-side

added added

removed removed

1
 
package org.waxworlds.importcontacts;
 
1
/*
 
2
 * Importer.java
 
3
 *
 
4
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
 
5
 *
 
6
 * This file is part of the Import Contacts program (hereafter referred
 
7
 * to as "this program"). For more information, see
 
8
 * http://www.waxworlds.org/edam/software/android/import-contacts
 
9
 *
 
10
 * This program is free software: you can redistribute it and/or modify
 
11
 * it under the terms of the GNU General Public License as published by
 
12
 * the Free Software Foundation, either version 3 of the License, or
 
13
 * (at your option) any later version.
 
14
 *
 
15
 * This program is distributed in the hope that it will be useful,
 
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
18
 * GNU General Public License for more details.
 
19
 *
 
20
 * You should have received a copy of the GNU General Public License
 
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
22
 */
 
23
 
 
24
package org.waxworlds.edam.importcontacts;
2
25
 
3
26
import java.util.HashMap;
4
 
import java.util.HashSet;
5
27
import java.util.Iterator;
6
28
import java.util.Set;
7
29
import java.util.regex.Matcher;
10
32
import android.content.ContentUris;
11
33
import android.content.ContentValues;
12
34
import android.content.SharedPreferences;
13
 
import android.database.Cursor;
14
35
import android.net.Uri;
15
36
import android.os.Message;
16
37
import android.provider.Contacts;
17
38
 
 
39
 
18
40
public class Importer extends Thread
19
41
{
20
 
        public final static int MESSAGE_FINISHED = 0;
21
 
        public final static int MESSAGE_FINISHED_BACK = 1;
22
 
        public final static int MESSAGE_ERROR = 2;
23
 
        public final static int MESSAGE_CONTINUEORABORT = 3;
24
 
        public final static int MESSAGE_SETPROGRESSMESSAGE = 4;
25
 
        public final static int MESSAGE_SETMAXPROGRESS = 5;
26
 
        public final static int MESSAGE_SETTMPPROGRESS = 6;
27
 
        public final static int MESSAGE_SETPROGRESS = 7;
28
 
        public final static int MESSAGE_MERGEPROMPT = 8;
29
 
        public final static int MESSAGE_CONTACTOVERWRITTEN = 9;
30
 
        public final static int MESSAGE_CONTACTCREATED = 10;
31
 
        public final static int MESSAGE_CONTACTMERGED = 11;
32
 
        public final static int MESSAGE_CONTACTSKIPPED = 12;
 
42
        public final static int ACTION_ABORT = 1;
 
43
        public final static int ACTION_ALLDONE = 2;
33
44
 
34
45
        public final static int RESPONSE_NEGATIVE = 0;
35
46
        public final static int RESPONSE_POSITIVE = 1;
40
51
        private Doit _doit;
41
52
        private int _response;
42
53
        private int _responseExtra;
43
 
        private HashMap< String, Long > _contacts;
44
 
        private HashMap< Long, HashSet< String > > _contactNumbers;
45
 
        private HashMap< Long, HashSet< String > > _contactEmails;
46
54
        private int _mergeSetting;
47
55
        private int _lastMergeDecision;
48
56
        private boolean _abort = false;
 
57
        private boolean _isFinished = false;
 
58
        private ContactsCache _contactsCache = null;
49
59
 
50
60
        public class ContactData
51
61
        {
99
109
                        }
100
110
                }
101
111
 
 
112
                class AddressData
 
113
                {
 
114
                        private String _address;
 
115
                        public int _type;
 
116
 
 
117
                        public AddressData( String address, int type ) {
 
118
                                _address = address;
 
119
                                _type = type;
 
120
                        }
 
121
 
 
122
                        public String getAddress() {
 
123
                                return _address;
 
124
                        }
 
125
 
 
126
                        public int getType() {
 
127
                                return _type;
 
128
                        }
 
129
                }
 
130
 
102
131
                public String _name = null;
103
132
                public HashMap< String, PhoneData > _phones = null;
104
133
                public HashMap< String, EmailData > _emails = null;
 
134
                public HashMap< String, AddressData > _addresses = null;
105
135
 
106
136
                protected void setName( String name )
107
137
                {
118
148
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
119
149
                        if( !_phones.containsKey( number ) )
120
150
                                _phones.put( number,
121
 
                                                new PhoneData( number, type, isPreferred ) );
 
151
                                        new PhoneData( number, type, isPreferred ) );
122
152
                }
123
153
 
124
154
                protected void addEmail( String email, int type, boolean isPreferred )
127
157
                        if( !_emails.containsKey( email ) )
128
158
                                _emails.put( email, new EmailData( email, type, isPreferred ) );
129
159
                }
 
160
 
 
161
                protected void addAddress( String address, int type )
 
162
                {
 
163
                        if( _addresses == null ) _addresses =
 
164
                                new HashMap< String, AddressData >();
 
165
                        if( !_addresses.containsKey( address ) )
 
166
                                _addresses.put( address, new AddressData( address, type ) );
 
167
                }
130
168
        }
131
169
 
 
170
        @SuppressWarnings("serial")
132
171
        protected class AbortImportException extends Exception { };
133
172
 
134
173
        public Importer( Doit doit )
136
175
                _doit = doit;
137
176
 
138
177
                SharedPreferences prefs = getSharedPreferences();
139
 
                _mergeSetting = prefs.getInt( "merge_setting", 0 );
 
178
                _mergeSetting = prefs.getInt( "merge_setting", Doit.ACTION_PROMPT );
140
179
        }
141
180
 
142
181
        @Override
144
183
        {
145
184
                try
146
185
                {
147
 
                        // cache current contact names
148
 
                        buildContactsCache();
 
186
                        // update UI
 
187
                        setProgressMessage( R.string.doit_caching );
 
188
 
 
189
                        // build a cache of existing contacts
 
190
                        _contactsCache = new ContactsCache();
 
191
                        _contactsCache.buildCache( _doit );
149
192
 
150
193
                        // do the import
151
194
                        onImport();
152
195
 
153
196
                        // done!
154
 
                        finish();
 
197
                        finish( ACTION_ALLDONE );
155
198
                }
156
199
                catch( AbortImportException e )
157
200
                {}
 
201
 
 
202
                // flag as finished to prevent interrupts
 
203
                setIsFinished();
 
204
        }
 
205
 
 
206
        synchronized private void setIsFinished()
 
207
        {
 
208
                _isFinished = true;
158
209
        }
159
210
 
160
211
        protected void onImport() throws AbortImportException
178
229
                notify();
179
230
        }
180
231
 
181
 
        synchronized public void setAbort()
 
232
        synchronized public boolean setAbort()
182
233
        {
183
 
                _abort = true;
 
234
                if( !_isFinished && !_abort ) {
 
235
                        _abort = true;
 
236
                        notify();
 
237
                        return true;
 
238
                }
 
239
                return false;
184
240
        }
185
241
 
186
242
        protected SharedPreferences getSharedPreferences()
198
254
        {
199
255
                checkAbort();
200
256
                _doit._handler.sendMessage( Message.obtain(
201
 
                                _doit._handler, MESSAGE_ERROR, message ) );
 
257
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
202
258
                try {
203
259
                        wait();
204
260
                }
205
261
                catch( InterruptedException e ) { }
206
 
                finish( true );
 
262
 
 
263
                // no need to check if an abortion happened during the wait, we are
 
264
                // about to finish anyway!
 
265
                finish( ACTION_ABORT );
207
266
        }
208
267
 
209
268
        protected void showFatalError( int res ) throws AbortImportException
216
275
        {
217
276
                checkAbort();
218
277
                _doit._handler.sendMessage( Message.obtain(
219
 
                                _doit._handler, MESSAGE_ERROR, message ) );
 
278
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
220
279
                try {
221
280
                        wait();
222
281
                }
223
282
                catch( InterruptedException e ) { }
224
 
                finish( false );
 
283
 
 
284
                // no need to check if an abortion happened during the wait, we are
 
285
                // about to finish anyway!
 
286
                finish( ACTION_ABORT );
225
287
        }
226
288
 
227
289
        protected boolean showContinue( int res ) throws AbortImportException
234
296
        {
235
297
                checkAbort();
236
298
                _doit._handler.sendMessage( Message.obtain(
237
 
                                _doit._handler, MESSAGE_CONTINUEORABORT, message ) );
 
299
                        _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
238
300
                try {
239
301
                        wait();
240
302
                }
241
303
                catch( InterruptedException e ) { }
 
304
 
 
305
                // check if an abortion happened during the wait
 
306
                checkAbort();
 
307
 
242
308
                return _response == RESPONSE_POSITIVE;
243
309
        }
244
310
 
246
312
        {
247
313
                checkAbort();
248
314
                _doit._handler.sendMessage( Message.obtain( _doit._handler,
249
 
                                MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
 
315
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
250
316
        }
251
317
 
252
318
        protected void setProgressMax( int maxProgress )
254
320
        {
255
321
                checkAbort();
256
322
                _doit._handler.sendMessage( Message.obtain(
257
 
                                _doit._handler, MESSAGE_SETMAXPROGRESS,
258
 
                                new Integer( maxProgress ) ) );
 
323
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
 
324
                        new Integer( maxProgress ) ) );
259
325
        }
260
326
 
261
327
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
262
328
        {
263
329
                checkAbort();
264
330
                _doit._handler.sendMessage( Message.obtain(
265
 
                                _doit._handler, MESSAGE_SETTMPPROGRESS,
266
 
                                new Integer( tmpProgress ) ) );
 
331
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
 
332
                        new Integer( tmpProgress ) ) );
267
333
        }
268
334
 
269
335
        protected void setProgress( int progress ) throws AbortImportException
270
336
        {
271
337
                checkAbort();
272
338
                _doit._handler.sendMessage( Message.obtain(
273
 
                                _doit._handler, MESSAGE_SETPROGRESS,
274
 
                                new Integer( progress ) ) );
275
 
        }
276
 
 
277
 
        protected void finish() throws AbortImportException
278
 
        {
279
 
                finish( false );
280
 
        }
281
 
 
282
 
        protected void abort() throws AbortImportException
283
 
        {
284
 
                finish( true );
 
339
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
 
340
                        new Integer( progress ) ) );
 
341
        }
 
342
 
 
343
        protected void finish( int action ) throws AbortImportException
 
344
        {
 
345
                // update UI to reflect action
 
346
                int message;
 
347
                switch( action )
 
348
                {
 
349
                case ACTION_ALLDONE:    message = Doit.MESSAGE_ALLDONE; break;
 
350
                default:        // fall through
 
351
                case ACTION_ABORT:              message = Doit.MESSAGE_ABORT; break;
 
352
                }
 
353
                _doit._handler.sendEmptyMessage( message );
 
354
 
 
355
                // stop
 
356
                throw new AbortImportException();
285
357
        }
286
358
 
287
359
        protected CharSequence getText( int res )
296
368
                return isImportRequired( name, _mergeSetting );
297
369
        }
298
370
 
299
 
        synchronized private boolean isImportRequired( String name, int mergeSetting )
 
371
        synchronized private boolean isImportRequired( String name,
 
372
                        int mergeSetting ) throws AbortImportException
300
373
        {
301
374
                _lastMergeDecision = mergeSetting;
302
375
 
303
376
                // handle special cases
304
377
                switch( mergeSetting )
305
378
                {
306
 
                case R.id.merge_keep:
 
379
                case Doit.ACTION_KEEP:
307
380
                        // if we keep contacts on duplicate, we better check for one
308
 
                        return !_contacts.containsKey( name );
 
381
                        return !_contactsCache.exists( name );
309
382
 
310
 
                case R.id.merge_prompt:
 
383
                case Doit.ACTION_PROMPT:
311
384
                        // if we are prompting on duplicate, we better check for one
312
 
                        if( !_contacts.containsKey( name ) )
 
385
                        if( !_contactsCache.exists( name ) )
313
386
                                return true;
314
387
 
315
388
                        // ok, it exists, so do prompt
316
389
                        _doit._handler.sendMessage( Message.obtain(
317
 
                                        _doit._handler, MESSAGE_MERGEPROMPT, name ) );
 
390
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
318
391
                        try {
319
392
                                wait();
320
393
                        }
321
394
                        catch( InterruptedException e ) { }
322
395
 
 
396
                        // check if an abortion happened during the wait
 
397
                        checkAbort();
 
398
 
323
399
                        // if "always" was selected, make choice permenant
324
400
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
325
401
                                _mergeSetting = _response;
326
402
 
327
 
                        // recurse, with out new merge setting
 
403
                        // recurse, with our new merge setting
328
404
                        return isImportRequired( name, _response );
329
405
                }
330
406
 
336
412
        protected void skipContact() throws AbortImportException
337
413
        {
338
414
                checkAbort();
339
 
                _doit._handler.sendEmptyMessage( MESSAGE_CONTACTSKIPPED );
 
415
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
340
416
        }
341
417
 
342
418
        protected void importContact( ContactData contact )
344
420
        {
345
421
                checkAbort();
346
422
 
347
 
                if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
348
 
                        abort();
 
423
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
 
424
//                      finish( ACTION_ABORT );
349
425
 
350
426
                ContentValues values = new ContentValues();
351
427
                boolean uiInformed = false;
353
429
                // does contact exist already?
354
430
                Uri contactUri = null;
355
431
                Long id;
356
 
                if( ( id = (Long)_contacts.get( contact._name ) ) != null )
 
432
                if( ( id = (Long)_contactsCache.getId( contact._name ) ) != null )
357
433
                {
358
434
                        // should we skip this import altogether?
359
 
                        if( _lastMergeDecision == R.id.merge_keep ) return;
 
435
                        if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
360
436
 
361
437
                        // get contact's URI
362
438
                        contactUri = ContentUris.withAppendedId(
363
 
                                        Contacts.People.CONTENT_URI, id );
 
439
                                Contacts.People.CONTENT_URI, id );
364
440
 
365
441
                        // should we destroy the existing contact before importing?
366
 
                        if( _lastMergeDecision == R.id.merge_overwrite ) {
 
442
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
367
443
                                _doit.getContentResolver().delete( contactUri, null, null );
368
444
                                contactUri = null;
369
445
 
370
 
                                // upate the UI
371
 
                                _doit._handler.sendEmptyMessage( MESSAGE_CONTACTOVERWRITTEN );
 
446
                                // update the UI
 
447
                                _doit._handler.sendEmptyMessage(
 
448
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
372
449
                                uiInformed = true;
373
450
 
374
451
                                // update cache
375
 
                                _contacts.remove( contact._name );
 
452
                                _contactsCache.remove( contact._name );
376
453
                        }
377
454
                }
378
455
 
383
460
                        // create a new contact
384
461
                        values.put( Contacts.People.NAME, contact._name );
385
462
                        contactUri = _doit.getContentResolver().insert(
386
 
                                        Contacts.People.CONTENT_URI, values );
 
463
                                Contacts.People.CONTENT_URI, values );
387
464
                        id = ContentUris.parseId( contactUri );
388
465
                        if( id <= 0 ) return;   // shouldn't happen!
389
466
 
390
 
                        // add them to the "My Contacts" group
391
 
                        Contacts.People.addToGroup(
392
 
                                        _doit.getContentResolver(), id,
393
 
                                        Contacts.Groups.GROUP_MY_CONTACTS );
 
467
                        // try to add them to the "My Contacts" group
 
468
                        try {
 
469
                                Contacts.People.addToMyContactsGroup(
 
470
                                        _doit.getContentResolver(), id );
 
471
                        }
 
472
                        catch( IllegalStateException e ) {
 
473
                                // ignore any failure
 
474
                        }
394
475
 
395
476
                        // update cache
396
 
                        _contacts.put( contact._name, id );
 
477
                        _contactsCache.put( id, contact._name );
397
478
 
398
479
                        // update UI
399
480
                        if( !uiInformed ) {
400
 
                                _doit._handler.sendEmptyMessage( MESSAGE_CONTACTCREATED );
 
481
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
401
482
                                uiInformed = true;
402
483
                        }
403
484
                }
404
485
 
405
486
                // update UI
406
487
                if( !uiInformed )
407
 
                        _doit._handler.sendEmptyMessage( MESSAGE_CONTACTMERGED );
 
488
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
408
489
 
409
490
                // import contact parts
410
491
                if( contact._phones != null )
411
492
                        importContactPhones( contactUri, contact._phones );
412
493
                if( contact._emails != null )
413
494
                        importContactEmails( contactUri, contact._emails );
 
495
                if( contact._addresses != null )
 
496
                        importContactAddresses( contactUri, contact._addresses );
414
497
        }
415
498
 
416
499
        private void importContactPhones( Uri contactUri,
419
502
                Long contactId = ContentUris.parseId( contactUri );
420
503
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
421
504
                                Contacts.People.Phones.CONTENT_DIRECTORY );
 
505
                Set< String > phonesKeys = phones.keySet();
422
506
 
423
507
                // add phone numbers
424
 
                Set phonesKeys = phones.keySet();
425
 
                Iterator i = phonesKeys.iterator();
 
508
                Iterator< String > i = phonesKeys.iterator();
426
509
                while( i.hasNext() ) {
427
510
                        ContactData.PhoneData phone = phones.get( i.next() );
428
511
 
435
518
                        // anyway, so it's not a problem).
436
519
                        String number = sanitisePhoneNumber( phone._number );
437
520
                        if( number == null ) continue;
438
 
                        HashSet< String > numbers = _contactNumbers.get( contactId );
439
 
                        if( numbers != null && numbers.contains( number ) ) continue;
 
521
                        if( _contactsCache.hasNumber( contactId, number ) ) continue;
440
522
 
441
523
                        // add phone number
442
524
                        ContentValues values = new ContentValues();
444
526
                        values.put( Contacts.Phones.NUMBER, phone._number );
445
527
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
446
528
                        _doit.getContentResolver().insert( contactPhonesUri, values );
 
529
 
 
530
                        // and add this address to the cache to prevent a addition of
 
531
                        // duplicate date from another file
 
532
                        _contactsCache.addNumber( contactId, number );
447
533
                }
448
534
        }
449
535
 
453
539
                Long contactId = ContentUris.parseId( contactUri );
454
540
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
455
541
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
 
542
                Set< String > emailsKeys = emails.keySet();
456
543
 
457
 
                // add phone numbers
458
 
                Set emailsKeys = emails.keySet();
459
 
                Iterator i = emailsKeys.iterator();
 
544
                // add email addresses
 
545
                Iterator< String > i = emailsKeys.iterator();
460
546
                while( i.hasNext() ) {
461
547
                        ContactData.EmailData email = emails.get( i.next() );
462
548
 
463
 
                        // like with phone numbers, we don't want to add this email address
464
 
                        // if it exists already or we would introduce duplicates.
 
549
                        // we don't want to add this email address if it exists already or
 
550
                        // we would introduce duplicates.
465
551
                        String address = sanitiseEmailAddress( email.getAddress() );
466
552
                        if( address == null ) continue;
467
 
                        HashSet< String > addresses = _contactEmails.get( contactId );
468
 
                        if( addresses != null && addresses.contains( address ) ) continue;
 
553
                        if( _contactsCache.hasEmail( contactId, address ) ) continue;
469
554
 
470
555
                        // add phone number
471
556
                        ContentValues values = new ContentValues();
475
560
                        if( email.isPreferred() )
476
561
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
477
562
                        _doit.getContentResolver().insert( contactContactMethodsUri,
478
 
                                        values );
 
563
                                values );
 
564
 
 
565
                        // and add this address to the cache to prevent a addition of
 
566
                        // duplicate date from another file
 
567
                        _contactsCache.addEmail( contactId, address );
479
568
                }
480
569
        }
481
570
 
482
 
        synchronized private void finish( boolean offerBack )
483
 
                        throws AbortImportException
 
571
        private void importContactAddresses( Uri contactUri,
 
572
                HashMap< String, ContactData.AddressData > addresses )
484
573
        {
485
 
                // notify Doit that we're finished
486
 
                _doit._handler.sendEmptyMessage(
487
 
                                offerBack? MESSAGE_FINISHED_BACK : MESSAGE_FINISHED );
488
 
 
489
 
                // stop
490
 
                throw new AbortImportException();
 
574
                Long contactId = ContentUris.parseId( contactUri );
 
575
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
 
576
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
 
577
                Set< String > addressesKeys = addresses.keySet();
 
578
 
 
579
                // add addresses
 
580
                Iterator< String > i = addressesKeys.iterator();
 
581
                while( i.hasNext() ) {
 
582
                        ContactData.AddressData address = addresses.get( i.next() );
 
583
 
 
584
                        // we don't want to add this address if it exists already or we
 
585
                        // would introduce duplicates
 
586
                        if( address == null ) continue;
 
587
                        if( _contactsCache.hasAddress( contactId, address.getAddress() ) )
 
588
                                continue;
 
589
 
 
590
                        // add postal address
 
591
                        ContentValues values = new ContentValues();
 
592
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
 
593
                        values.put( Contacts.ContactMethods.DATA, address.getAddress() );
 
594
                        values.put( Contacts.ContactMethods.TYPE, address.getType() );
 
595
                        _doit.getContentResolver().insert( contactContactMethodsUri,
 
596
                                values );
 
597
 
 
598
                        // and add this address to the cache to prevent a addition of
 
599
                        // duplicate date from another file
 
600
                        _contactsCache.addAddress( contactId, address.getAddress() );
 
601
                }
491
602
        }
492
603
 
493
 
        synchronized private void checkAbort() throws AbortImportException
 
604
        synchronized protected void checkAbort() throws AbortImportException
494
605
        {
495
606
                if( _abort ) {
496
607
                        // stop
498
609
                }
499
610
        }
500
611
 
501
 
        private void buildContactsCache() throws AbortImportException
502
 
        {
503
 
                // update UI
504
 
                setProgressMessage( R.string.doit_caching );
505
 
 
506
 
                String[] cols;
507
 
                Cursor cur;
508
 
 
509
 
                // init contacts caches
510
 
                _contacts = new HashMap< String, Long >();
511
 
                _contactNumbers = new HashMap< Long, HashSet< String > >();
512
 
                _contactEmails = new HashMap< Long, HashSet< String > >();
513
 
 
514
 
                // query and store map of contact names to ids
515
 
                cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
516
 
                cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
517
 
                                cols, null, null, null);
518
 
                if( cur.moveToFirst() ) {
519
 
                        int idCol = cur.getColumnIndex( Contacts.People._ID );
520
 
                        int nameCol = cur.getColumnIndex( Contacts.People.NAME );
521
 
                        do {
522
 
                                _contacts.put( cur.getString( nameCol ), cur.getLong( idCol ) );
523
 
                        } while( cur.moveToNext() );
524
 
                }
525
 
 
526
 
                // query and store map of contact ids to sets of phone numbers
527
 
                cols = new String[] { Contacts.Phones.PERSON_ID,
528
 
                                Contacts.Phones.NUMBER };
529
 
                cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
530
 
                                cols, null, null, null);
531
 
                if( cur.moveToFirst() ) {
532
 
                        int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
533
 
                        int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
534
 
                        do {
535
 
                                Long id = cur.getLong( personIdCol );
536
 
                                String number = sanitisePhoneNumber(
537
 
                                                cur.getString( numberCol ) );
538
 
                                if( number != null ) {
539
 
                                        HashSet< String > numbers = _contactNumbers.get( id );
540
 
                                        if( numbers == null ) {
541
 
                                                _contactNumbers.put( id, new HashSet< String >() );
542
 
                                                numbers = _contactNumbers.get( id );
543
 
                                        }
544
 
                                        numbers.add( number );
545
 
                                }
546
 
                        } while( cur.moveToNext() );
547
 
                }
548
 
 
549
 
                // query and store map of contact ids to sets of email addresses
550
 
                cols = new String[] { Contacts.ContactMethods.PERSON_ID,
551
 
                                Contacts.ContactMethods.DATA };
552
 
                cur = _doit.managedQuery( Contacts.ContactMethods.CONTENT_URI,
553
 
                                cols, Contacts.ContactMethods.KIND + " = ?",
554
 
                                new String[] { "" + Contacts.KIND_EMAIL }, null );
555
 
                if( cur.moveToFirst() ) {
556
 
                        int personIdCol = cur.getColumnIndex(
557
 
                                        Contacts.ContactMethods.PERSON_ID );
558
 
                        int addressCol = cur.getColumnIndex(
559
 
                                        Contacts.ContactMethods.DATA );
560
 
                        do {
561
 
                                Long id = cur.getLong( personIdCol );
562
 
                                String address = sanitiseEmailAddress(
563
 
                                                cur.getString( addressCol ) );
564
 
                                if( address != null ) {
565
 
                                        HashSet< String > addresses = _contactEmails.get( id );
566
 
                                        if( addresses == null ) {
567
 
                                                _contactEmails.put( id, new HashSet< String >() );
568
 
                                                addresses = _contactEmails.get( id );
569
 
                                        }
570
 
                                        addresses.add( address );
571
 
                                }
572
 
                        } while( cur.moveToNext() );
573
 
                }
574
 
        }
575
 
 
576
 
        private String sanitisePhoneNumber( String number )
 
612
        static public String sanitisePhoneNumber( String number )
577
613
        {
578
614
                number = number.replaceAll( "[-\\(\\) ]", "" );
579
 
                Pattern p = Pattern.compile( "^\\+?[0-9]+" );
 
615
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
580
616
                Matcher m = p.matcher( number );
581
617
                if( m.lookingAt() ) return m.group( 0 );
582
618
                return null;
583
619
        }
584
620
 
585
 
        private String sanitiseEmailAddress( String address )
 
621
        static public String sanitiseEmailAddress( String address )
586
622
        {
587
623
                address = address.trim();
588
624
                Pattern p = Pattern.compile(
589
 
                                "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
 
625
                        "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
590
626
                Matcher m = p.matcher( address );
591
627
                if( m.matches() ) {
592
628
                        String[] bits = address.split( "@" );