/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

21
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
22
 */
23
23
 
24
 
package org.waxworlds.importcontacts;
 
24
package org.waxworlds.edam.importcontacts;
25
25
 
26
26
import java.util.HashMap;
27
 
import java.util.HashSet;
28
27
import java.util.Iterator;
29
28
import java.util.Set;
30
29
import java.util.regex.Matcher;
33
32
import android.content.ContentUris;
34
33
import android.content.ContentValues;
35
34
import android.content.SharedPreferences;
36
 
import android.database.Cursor;
37
35
import android.net.Uri;
38
36
import android.os.Message;
39
37
import android.provider.Contacts;
40
38
 
 
39
 
41
40
public class Importer extends Thread
42
41
{
43
 
        public final static int ACTION_GOBACK = 0;
44
42
        public final static int ACTION_ABORT = 1;
45
43
        public final static int ACTION_ALLDONE = 2;
46
44
 
53
51
        private Doit _doit;
54
52
        private int _response;
55
53
        private int _responseExtra;
56
 
        private HashMap< String, Long > _contacts;
57
 
        private HashMap< Long, HashSet< String > > _contactNumbers;
58
 
        private HashMap< Long, HashSet< String > > _contactEmails;
59
54
        private int _mergeSetting;
60
55
        private int _lastMergeDecision;
61
56
        private boolean _abort = false;
62
57
        private boolean _isFinished = false;
 
58
        private ContactsCache _contactsCache = null;
63
59
 
64
60
        public class ContactData
65
61
        {
113
109
                        }
114
110
                }
115
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
 
116
131
                public String _name = null;
117
132
                public HashMap< String, PhoneData > _phones = null;
118
133
                public HashMap< String, EmailData > _emails = null;
 
134
                public HashMap< String, AddressData > _addresses = null;
119
135
 
120
136
                protected void setName( String name )
121
137
                {
132
148
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
133
149
                        if( !_phones.containsKey( number ) )
134
150
                                _phones.put( number,
135
 
                                                new PhoneData( number, type, isPreferred ) );
 
151
                                        new PhoneData( number, type, isPreferred ) );
136
152
                }
137
153
 
138
154
                protected void addEmail( String email, int type, boolean isPreferred )
141
157
                        if( !_emails.containsKey( email ) )
142
158
                                _emails.put( email, new EmailData( email, type, isPreferred ) );
143
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
                }
144
168
        }
145
169
 
 
170
        @SuppressWarnings("serial")
146
171
        protected class AbortImportException extends Exception { };
147
172
 
148
173
        public Importer( Doit doit )
158
183
        {
159
184
                try
160
185
                {
161
 
                        // cache current contact names
162
 
                        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 );
163
192
 
164
193
                        // do the import
165
194
                        onImport();
225
254
        {
226
255
                checkAbort();
227
256
                _doit._handler.sendMessage( Message.obtain(
228
 
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
257
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
229
258
                try {
230
259
                        wait();
231
260
                }
232
261
                catch( InterruptedException e ) { }
 
262
 
233
263
                // no need to check if an abortion happened during the wait, we are
234
264
                // about to finish anyway!
235
265
                finish( ACTION_ABORT );
245
275
        {
246
276
                checkAbort();
247
277
                _doit._handler.sendMessage( Message.obtain(
248
 
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
278
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
249
279
                try {
250
280
                        wait();
251
281
                }
252
282
                catch( InterruptedException e ) { }
 
283
 
253
284
                // no need to check if an abortion happened during the wait, we are
254
285
                // about to finish anyway!
255
286
                finish( ACTION_ABORT );
265
296
        {
266
297
                checkAbort();
267
298
                _doit._handler.sendMessage( Message.obtain(
268
 
                                _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
 
299
                        _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
269
300
                try {
270
301
                        wait();
271
302
                }
281
312
        {
282
313
                checkAbort();
283
314
                _doit._handler.sendMessage( Message.obtain( _doit._handler,
284
 
                                Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
 
315
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
285
316
        }
286
317
 
287
318
        protected void setProgressMax( int maxProgress )
289
320
        {
290
321
                checkAbort();
291
322
                _doit._handler.sendMessage( Message.obtain(
292
 
                                _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
293
 
                                new Integer( maxProgress ) ) );
 
323
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
 
324
                        new Integer( maxProgress ) ) );
294
325
        }
295
326
 
296
327
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
297
328
        {
298
329
                checkAbort();
299
330
                _doit._handler.sendMessage( Message.obtain(
300
 
                                _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
301
 
                                new Integer( tmpProgress ) ) );
 
331
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
 
332
                        new Integer( tmpProgress ) ) );
302
333
        }
303
334
 
304
335
        protected void setProgress( int progress ) throws AbortImportException
305
336
        {
306
337
                checkAbort();
307
338
                _doit._handler.sendMessage( Message.obtain(
308
 
                                _doit._handler, Doit.MESSAGE_SETPROGRESS,
309
 
                                new Integer( progress ) ) );
 
339
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
 
340
                        new Integer( progress ) ) );
310
341
        }
311
342
 
312
343
        protected void finish( int action ) throws AbortImportException
315
346
                int message;
316
347
                switch( action )
317
348
                {
318
 
                case ACTION_GOBACK:             message = Doit.MESSAGE_FINISHED_GOBACK; break;
319
 
                case ACTION_ALLDONE:    message = Doit.MESSAGE_FINISHED_ALLDONE; break;
 
349
                case ACTION_ALLDONE:    message = Doit.MESSAGE_ALLDONE; break;
320
350
                default:        // fall through
321
 
                case ACTION_ABORT:              message = Doit.MESSAGE_FINISHED; break;
 
351
                case ACTION_ABORT:              message = Doit.MESSAGE_ABORT; break;
322
352
                }
323
353
                _doit._handler.sendEmptyMessage( message );
324
354
 
348
378
                {
349
379
                case Doit.ACTION_KEEP:
350
380
                        // if we keep contacts on duplicate, we better check for one
351
 
                        return !_contacts.containsKey( name );
 
381
                        return !_contactsCache.exists( name );
352
382
 
353
383
                case Doit.ACTION_PROMPT:
354
384
                        // if we are prompting on duplicate, we better check for one
355
 
                        if( !_contacts.containsKey( name ) )
 
385
                        if( !_contactsCache.exists( name ) )
356
386
                                return true;
357
387
 
358
388
                        // ok, it exists, so do prompt
359
389
                        _doit._handler.sendMessage( Message.obtain(
360
 
                                        _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
 
390
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
361
391
                        try {
362
392
                                wait();
363
393
                        }
370
400
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
371
401
                                _mergeSetting = _response;
372
402
 
373
 
                        // recurse, with out new merge setting
 
403
                        // recurse, with our new merge setting
374
404
                        return isImportRequired( name, _response );
375
405
                }
376
406
 
399
429
                // does contact exist already?
400
430
                Uri contactUri = null;
401
431
                Long id;
402
 
                if( ( id = (Long)_contacts.get( contact._name ) ) != null )
 
432
                if( ( id = (Long)_contactsCache.getId( contact._name ) ) != null )
403
433
                {
404
434
                        // should we skip this import altogether?
405
435
                        if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
406
436
 
407
437
                        // get contact's URI
408
438
                        contactUri = ContentUris.withAppendedId(
409
 
                                        Contacts.People.CONTENT_URI, id );
 
439
                                Contacts.People.CONTENT_URI, id );
410
440
 
411
441
                        // should we destroy the existing contact before importing?
412
442
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
413
443
                                _doit.getContentResolver().delete( contactUri, null, null );
414
444
                                contactUri = null;
415
445
 
416
 
                                // upate the UI
417
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
 
446
                                // update the UI
 
447
                                _doit._handler.sendEmptyMessage(
 
448
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
418
449
                                uiInformed = true;
419
450
 
420
451
                                // update cache
421
 
                                _contacts.remove( contact._name );
 
452
                                _contactsCache.remove( contact._name );
422
453
                        }
423
454
                }
424
455
 
429
460
                        // create a new contact
430
461
                        values.put( Contacts.People.NAME, contact._name );
431
462
                        contactUri = _doit.getContentResolver().insert(
432
 
                                        Contacts.People.CONTENT_URI, values );
 
463
                                Contacts.People.CONTENT_URI, values );
433
464
                        id = ContentUris.parseId( contactUri );
434
465
                        if( id <= 0 ) return;   // shouldn't happen!
435
466
 
436
 
                        // add them to the "My Contacts" group
437
 
                        Contacts.People.addToMyContactsGroup(
 
467
                        // try to add them to the "My Contacts" group
 
468
                        try {
 
469
                                Contacts.People.addToMyContactsGroup(
438
470
                                        _doit.getContentResolver(), id );
 
471
                        }
 
472
                        catch( IllegalStateException e ) {
 
473
                                // ignore any failure
 
474
                        }
439
475
 
440
476
                        // update cache
441
 
                        _contacts.put( contact._name, id );
 
477
                        _contactsCache.put( id, contact._name );
442
478
 
443
479
                        // update UI
444
480
                        if( !uiInformed ) {
456
492
                        importContactPhones( contactUri, contact._phones );
457
493
                if( contact._emails != null )
458
494
                        importContactEmails( contactUri, contact._emails );
 
495
                if( contact._addresses != null )
 
496
                        importContactAddresses( contactUri, contact._addresses );
459
497
        }
460
498
 
461
499
        private void importContactPhones( Uri contactUri,
464
502
                Long contactId = ContentUris.parseId( contactUri );
465
503
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
466
504
                                Contacts.People.Phones.CONTENT_DIRECTORY );
467
 
                Set phonesKeys = phones.keySet();
 
505
                Set< String > phonesKeys = phones.keySet();
468
506
 
469
507
                // add phone numbers
470
 
                Iterator i = phonesKeys.iterator();
 
508
                Iterator< String > i = phonesKeys.iterator();
471
509
                while( i.hasNext() ) {
472
510
                        ContactData.PhoneData phone = phones.get( i.next() );
473
511
 
480
518
                        // anyway, so it's not a problem).
481
519
                        String number = sanitisePhoneNumber( phone._number );
482
520
                        if( number == null ) continue;
483
 
                        HashSet< String > numbers = _contactNumbers.get( contactId );
484
 
                        if( numbers != null && numbers.contains( number ) ) continue;
 
521
                        if( _contactsCache.hasNumber( contactId, number ) ) continue;
485
522
 
486
523
                        // add phone number
487
524
                        ContentValues values = new ContentValues();
489
526
                        values.put( Contacts.Phones.NUMBER, phone._number );
490
527
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
491
528
                        _doit.getContentResolver().insert( contactPhonesUri, values );
492
 
                }
493
 
 
494
 
                // now add those phone numbers to the cache to prevent the addition of
495
 
                // duplicate data from another file
496
 
                i = phonesKeys.iterator();
497
 
                while( i.hasNext() ) {
498
 
                        ContactData.PhoneData phone = phones.get( i.next() );
499
 
 
500
 
                        String number = sanitisePhoneNumber( phone._number );
501
 
                        if( number != null ) {
502
 
                                HashSet< String > numbers = _contactNumbers.get( contactId );
503
 
                                if( numbers == null ) {
504
 
                                        _contactNumbers.put( contactId, new HashSet< String >() );
505
 
                                        numbers = _contactNumbers.get( contactId );
506
 
                                }
507
 
                                numbers.add( number );
508
 
                        }
 
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 );
509
533
                }
510
534
        }
511
535
 
515
539
                Long contactId = ContentUris.parseId( contactUri );
516
540
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
517
541
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
518
 
                Set emailsKeys = emails.keySet();
 
542
                Set< String > emailsKeys = emails.keySet();
519
543
 
520
544
                // add email addresses
521
 
                Iterator i = emailsKeys.iterator();
 
545
                Iterator< String > i = emailsKeys.iterator();
522
546
                while( i.hasNext() ) {
523
547
                        ContactData.EmailData email = emails.get( i.next() );
524
548
 
525
 
                        // like with phone numbers, we don't want to add this email address
526
 
                        // 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.
527
551
                        String address = sanitiseEmailAddress( email.getAddress() );
528
552
                        if( address == null ) continue;
529
 
                        HashSet< String > addresses = _contactEmails.get( contactId );
530
 
                        if( addresses != null && addresses.contains( address ) ) continue;
 
553
                        if( _contactsCache.hasEmail( contactId, address ) ) continue;
531
554
 
532
555
                        // add phone number
533
556
                        ContentValues values = new ContentValues();
537
560
                        if( email.isPreferred() )
538
561
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
539
562
                        _doit.getContentResolver().insert( contactContactMethodsUri,
540
 
                                        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 );
541
568
                }
542
 
 
543
 
                // now add those email addresses to the cache to prevent the addition of
544
 
                // duplicate data from another file
545
 
                i = emailsKeys.iterator();
 
569
        }
 
570
 
 
571
        private void importContactAddresses( Uri contactUri,
 
572
                HashMap< String, ContactData.AddressData > addresses )
 
573
        {
 
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();
546
581
                while( i.hasNext() ) {
547
 
                        ContactData.EmailData email = emails.get( i.next() );
548
 
 
549
 
                        String address = sanitiseEmailAddress( email.getAddress() );
550
 
                        if( address != null ) {
551
 
                                HashSet< String > addresses = _contactEmails.get( contactId );
552
 
                                if( addresses == null ) {
553
 
                                        _contactEmails.put( contactId, new HashSet< String >() );
554
 
                                        addresses = _contactEmails.get( contactId );
555
 
                                }
556
 
                                addresses.add( address );
557
 
                        }
 
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() );
558
601
                }
559
602
        }
560
603
 
566
609
                }
567
610
        }
568
611
 
569
 
        private void buildContactsCache() throws AbortImportException
570
 
        {
571
 
                // update UI
572
 
                setProgressMessage( R.string.doit_caching );
573
 
 
574
 
                String[] cols;
575
 
                Cursor cur;
576
 
 
577
 
                // init contacts caches
578
 
                _contacts = new HashMap< String, Long >();
579
 
                _contactNumbers = new HashMap< Long, HashSet< String > >();
580
 
                _contactEmails = new HashMap< Long, HashSet< String > >();
581
 
 
582
 
                // query and store map of contact names to ids
583
 
                cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
584
 
                cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
585
 
                                cols, null, null, null);
586
 
                if( cur.moveToFirst() ) {
587
 
                        int idCol = cur.getColumnIndex( Contacts.People._ID );
588
 
                        int nameCol = cur.getColumnIndex( Contacts.People.NAME );
589
 
                        do {
590
 
                                _contacts.put( cur.getString( nameCol ), cur.getLong( idCol ) );
591
 
                        } while( cur.moveToNext() );
592
 
                }
593
 
 
594
 
                // query and store map of contact ids to sets of phone numbers
595
 
                cols = new String[] { Contacts.Phones.PERSON_ID,
596
 
                                Contacts.Phones.NUMBER };
597
 
                cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
598
 
                                cols, null, null, null);
599
 
                if( cur.moveToFirst() ) {
600
 
                        int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
601
 
                        int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
602
 
                        do {
603
 
                                Long id = cur.getLong( personIdCol );
604
 
                                String number = sanitisePhoneNumber(
605
 
                                                cur.getString( numberCol ) );
606
 
                                if( number != null ) {
607
 
                                        HashSet< String > numbers = _contactNumbers.get( id );
608
 
                                        if( numbers == null ) {
609
 
                                                _contactNumbers.put( id, new HashSet< String >() );
610
 
                                                numbers = _contactNumbers.get( id );
611
 
                                        }
612
 
                                        numbers.add( number );
613
 
                                }
614
 
                        } while( cur.moveToNext() );
615
 
                }
616
 
 
617
 
                // query and store map of contact ids to sets of email addresses
618
 
                cols = new String[] { Contacts.ContactMethods.PERSON_ID,
619
 
                                Contacts.ContactMethods.DATA };
620
 
                cur = _doit.managedQuery( Contacts.ContactMethods.CONTENT_URI,
621
 
                                cols, Contacts.ContactMethods.KIND + " = ?",
622
 
                                new String[] { "" + Contacts.KIND_EMAIL }, null );
623
 
                if( cur.moveToFirst() ) {
624
 
                        int personIdCol = cur.getColumnIndex(
625
 
                                        Contacts.ContactMethods.PERSON_ID );
626
 
                        int addressCol = cur.getColumnIndex(
627
 
                                        Contacts.ContactMethods.DATA );
628
 
                        do {
629
 
                                Long id = cur.getLong( personIdCol );
630
 
                                String address = sanitiseEmailAddress(
631
 
                                                cur.getString( addressCol ) );
632
 
                                if( address != null ) {
633
 
                                        HashSet< String > addresses = _contactEmails.get( id );
634
 
                                        if( addresses == null ) {
635
 
                                                _contactEmails.put( id, new HashSet< String >() );
636
 
                                                addresses = _contactEmails.get( id );
637
 
                                        }
638
 
                                        addresses.add( address );
639
 
                                }
640
 
                        } while( cur.moveToNext() );
641
 
                }
642
 
        }
643
 
 
644
 
        private String sanitisePhoneNumber( String number )
 
612
        static public String sanitisePhoneNumber( String number )
645
613
        {
646
614
                number = number.replaceAll( "[-\\(\\) ]", "" );
647
 
                Pattern p = Pattern.compile( "^\\+?[0-9]+" );
 
615
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
648
616
                Matcher m = p.matcher( number );
649
617
                if( m.lookingAt() ) return m.group( 0 );
650
618
                return null;
651
619
        }
652
620
 
653
 
        private String sanitiseEmailAddress( String address )
 
621
        static public String sanitiseEmailAddress( String address )
654
622
        {
655
623
                address = address.trim();
656
624
                Pattern p = Pattern.compile(
657
 
                                "^[^ @]+@[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])?)+$" );
658
626
                Matcher m = p.matcher( address );
659
627
                if( m.matches() ) {
660
628
                        String[] bits = address.split( "@" );