/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/importcontacts/Importer.java

  • Committer: edam
  • Date: 2009-10-03 16:58:29 UTC
  • Revision ID: edam@waxworlds.org-20091003165829-vxhwdodf3400ugs3
Tags: 0.9
- converted project to use Android 1.5 SDK
- cleaned-up some whitespace/newlines in source

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.edam.importcontacts;
 
24
package org.waxworlds.importcontacts;
25
25
 
26
26
import java.util.HashMap;
27
27
import java.util.HashSet;
38
38
import android.os.Message;
39
39
import android.provider.Contacts;
40
40
 
41
 
 
42
41
public class Importer extends Thread
43
42
{
 
43
        public final static int ACTION_GOBACK = 0;
44
44
        public final static int ACTION_ABORT = 1;
45
45
        public final static int ACTION_ALLDONE = 2;
46
46
 
56
56
        private HashMap< String, Long > _contacts;
57
57
        private HashMap< Long, HashSet< String > > _contactNumbers;
58
58
        private HashMap< Long, HashSet< String > > _contactEmails;
59
 
        private HashMap< Long, HashSet< String > > _contactAddresses;
60
59
        private int _mergeSetting;
61
60
        private int _lastMergeDecision;
62
61
        private boolean _abort = false;
114
113
                        }
115
114
                }
116
115
 
117
 
                class AddressData
118
 
                {
119
 
                        private String _address;
120
 
                        public int _type;
121
 
 
122
 
                        public AddressData( String address, int type ) {
123
 
                                _address = address;
124
 
                                _type = type;
125
 
                        }
126
 
 
127
 
                        public String getAddress() {
128
 
                                return _address;
129
 
                        }
130
 
 
131
 
                        public int getType() {
132
 
                                return _type;
133
 
                        }
134
 
                }
135
 
 
136
116
                public String _name = null;
137
117
                public HashMap< String, PhoneData > _phones = null;
138
118
                public HashMap< String, EmailData > _emails = null;
139
 
                public HashMap< String, AddressData > _addresses = null;
140
119
 
141
120
                protected void setName( String name )
142
121
                {
153
132
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
154
133
                        if( !_phones.containsKey( number ) )
155
134
                                _phones.put( number,
156
 
                                        new PhoneData( number, type, isPreferred ) );
 
135
                                                new PhoneData( number, type, isPreferred ) );
157
136
                }
158
137
 
159
138
                protected void addEmail( String email, int type, boolean isPreferred )
162
141
                        if( !_emails.containsKey( email ) )
163
142
                                _emails.put( email, new EmailData( email, type, isPreferred ) );
164
143
                }
165
 
 
166
 
                protected void addAddress( String address, int type )
167
 
                {
168
 
                        if( _addresses == null ) _addresses =
169
 
                                new HashMap< String, AddressData >();
170
 
                        if( !_addresses.containsKey( address ) )
171
 
                                _addresses.put( address, new AddressData( address, type ) );
172
 
                }
173
144
        }
174
145
 
175
 
        @SuppressWarnings("serial")
176
146
        protected class AbortImportException extends Exception { };
177
147
 
178
148
        public Importer( Doit doit )
255
225
        {
256
226
                checkAbort();
257
227
                _doit._handler.sendMessage( Message.obtain(
258
 
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
228
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
259
229
                try {
260
230
                        wait();
261
231
                }
262
232
                catch( InterruptedException e ) { }
263
 
 
264
233
                // no need to check if an abortion happened during the wait, we are
265
234
                // about to finish anyway!
266
235
                finish( ACTION_ABORT );
276
245
        {
277
246
                checkAbort();
278
247
                _doit._handler.sendMessage( Message.obtain(
279
 
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
248
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
280
249
                try {
281
250
                        wait();
282
251
                }
283
252
                catch( InterruptedException e ) { }
284
 
 
285
253
                // no need to check if an abortion happened during the wait, we are
286
254
                // about to finish anyway!
287
255
                finish( ACTION_ABORT );
297
265
        {
298
266
                checkAbort();
299
267
                _doit._handler.sendMessage( Message.obtain(
300
 
                        _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
 
268
                                _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
301
269
                try {
302
270
                        wait();
303
271
                }
313
281
        {
314
282
                checkAbort();
315
283
                _doit._handler.sendMessage( Message.obtain( _doit._handler,
316
 
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
 
284
                                Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
317
285
        }
318
286
 
319
287
        protected void setProgressMax( int maxProgress )
321
289
        {
322
290
                checkAbort();
323
291
                _doit._handler.sendMessage( Message.obtain(
324
 
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
325
 
                        new Integer( maxProgress ) ) );
 
292
                                _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
 
293
                                new Integer( maxProgress ) ) );
326
294
        }
327
295
 
328
296
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
329
297
        {
330
298
                checkAbort();
331
299
                _doit._handler.sendMessage( Message.obtain(
332
 
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
333
 
                        new Integer( tmpProgress ) ) );
 
300
                                _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
 
301
                                new Integer( tmpProgress ) ) );
334
302
        }
335
303
 
336
304
        protected void setProgress( int progress ) throws AbortImportException
337
305
        {
338
306
                checkAbort();
339
307
                _doit._handler.sendMessage( Message.obtain(
340
 
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
341
 
                        new Integer( progress ) ) );
 
308
                                _doit._handler, Doit.MESSAGE_SETPROGRESS,
 
309
                                new Integer( progress ) ) );
342
310
        }
343
311
 
344
312
        protected void finish( int action ) throws AbortImportException
347
315
                int message;
348
316
                switch( action )
349
317
                {
350
 
                case ACTION_ALLDONE:    message = Doit.MESSAGE_ALLDONE; break;
 
318
                case ACTION_GOBACK:             message = Doit.MESSAGE_FINISHED_GOBACK; break;
 
319
                case ACTION_ALLDONE:    message = Doit.MESSAGE_FINISHED_ALLDONE; break;
351
320
                default:        // fall through
352
 
                case ACTION_ABORT:              message = Doit.MESSAGE_ABORT; break;
 
321
                case ACTION_ABORT:              message = Doit.MESSAGE_FINISHED; break;
353
322
                }
354
323
                _doit._handler.sendEmptyMessage( message );
355
324
 
388
357
 
389
358
                        // ok, it exists, so do prompt
390
359
                        _doit._handler.sendMessage( Message.obtain(
391
 
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
 
360
                                        _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
392
361
                        try {
393
362
                                wait();
394
363
                        }
401
370
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
402
371
                                _mergeSetting = _response;
403
372
 
404
 
                        // recurse, with our new merge setting
 
373
                        // recurse, with out new merge setting
405
374
                        return isImportRequired( name, _response );
406
375
                }
407
376
 
437
406
 
438
407
                        // get contact's URI
439
408
                        contactUri = ContentUris.withAppendedId(
440
 
                                Contacts.People.CONTENT_URI, id );
 
409
                                        Contacts.People.CONTENT_URI, id );
441
410
 
442
411
                        // should we destroy the existing contact before importing?
443
412
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
444
413
                                _doit.getContentResolver().delete( contactUri, null, null );
445
414
                                contactUri = null;
446
415
 
447
 
                                // update the UI
448
 
                                _doit._handler.sendEmptyMessage(
449
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
 
416
                                // upate the UI
 
417
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
450
418
                                uiInformed = true;
451
419
 
452
420
                                // update cache
461
429
                        // create a new contact
462
430
                        values.put( Contacts.People.NAME, contact._name );
463
431
                        contactUri = _doit.getContentResolver().insert(
464
 
                                Contacts.People.CONTENT_URI, values );
 
432
                                        Contacts.People.CONTENT_URI, values );
465
433
                        id = ContentUris.parseId( contactUri );
466
434
                        if( id <= 0 ) return;   // shouldn't happen!
467
435
 
468
 
                        // try to add them to the "My Contacts" group
469
 
                        try {
470
 
                                Contacts.People.addToMyContactsGroup(
 
436
                        // add them to the "My Contacts" group
 
437
                        Contacts.People.addToMyContactsGroup(
471
438
                                        _doit.getContentResolver(), id );
472
 
                        }
473
 
                        catch( IllegalStateException e ) {
474
 
                                // ignore any failure
475
 
                        }
476
439
 
477
440
                        // update cache
478
441
                        _contacts.put( contact._name, id );
493
456
                        importContactPhones( contactUri, contact._phones );
494
457
                if( contact._emails != null )
495
458
                        importContactEmails( contactUri, contact._emails );
496
 
                if( contact._addresses != null )
497
 
                        importContactAddresses( contactUri, contact._addresses );
498
459
        }
499
460
 
500
461
        private void importContactPhones( Uri contactUri,
503
464
                Long contactId = ContentUris.parseId( contactUri );
504
465
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
505
466
                                Contacts.People.Phones.CONTENT_DIRECTORY );
506
 
                Set< String > phonesKeys = phones.keySet();
 
467
                Set phonesKeys = phones.keySet();
507
468
 
508
469
                // add phone numbers
509
 
                Iterator< String > i = phonesKeys.iterator();
 
470
                Iterator i = phonesKeys.iterator();
510
471
                while( i.hasNext() ) {
511
472
                        ContactData.PhoneData phone = phones.get( i.next() );
512
473
 
519
480
                        // anyway, so it's not a problem).
520
481
                        String number = sanitisePhoneNumber( phone._number );
521
482
                        if( number == null ) continue;
522
 
                        HashSet< String > cache = _contactNumbers.get( contactId );
523
 
                        if( cache != null && cache.contains( number ) ) continue;
 
483
                        HashSet< String > numbers = _contactNumbers.get( contactId );
 
484
                        if( numbers != null && numbers.contains( number ) ) continue;
524
485
 
525
486
                        // add phone number
526
487
                        ContentValues values = new ContentValues();
528
489
                        values.put( Contacts.Phones.NUMBER, phone._number );
529
490
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
530
491
                        _doit.getContentResolver().insert( contactPhonesUri, values );
531
 
 
532
 
                        // and add this address to the cache to prevent a addition of
533
 
                        // duplicate date from another file
534
 
                        if( cache == null ) {
535
 
                                cache = new HashSet< String >();
536
 
                                _contactNumbers.put( contactId, cache );
 
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 );
537
508
                        }
538
 
                        cache.add( number );
539
509
                }
540
510
        }
541
511
 
545
515
                Long contactId = ContentUris.parseId( contactUri );
546
516
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
547
517
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
548
 
                Set< String > emailsKeys = emails.keySet();
 
518
                Set emailsKeys = emails.keySet();
549
519
 
550
520
                // add email addresses
551
 
                Iterator< String > i = emailsKeys.iterator();
 
521
                Iterator i = emailsKeys.iterator();
552
522
                while( i.hasNext() ) {
553
523
                        ContactData.EmailData email = emails.get( i.next() );
554
524
 
555
 
                        // we don't want to add this email address if it exists already or
556
 
                        // we would introduce duplicates.
 
525
                        // like with phone numbers, we don't want to add this email address
 
526
                        // if it exists already or we would introduce duplicates.
557
527
                        String address = sanitiseEmailAddress( email.getAddress() );
558
528
                        if( address == null ) continue;
559
 
                        HashSet< String > cache = _contactEmails.get( contactId );
560
 
                        if( cache != null && cache.contains( address ) ) continue;
 
529
                        HashSet< String > addresses = _contactEmails.get( contactId );
 
530
                        if( addresses != null && addresses.contains( address ) ) continue;
561
531
 
562
532
                        // add phone number
563
533
                        ContentValues values = new ContentValues();
567
537
                        if( email.isPreferred() )
568
538
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
569
539
                        _doit.getContentResolver().insert( contactContactMethodsUri,
570
 
                                values );
571
 
 
572
 
                        // and add this address to the cache to prevent a addition of
573
 
                        // duplicate date from another file
574
 
                        if( cache == null ) {
575
 
                                cache = new HashSet< String >();
576
 
                                _contactEmails.put( contactId, cache );
577
 
                        }
578
 
                        cache.add( address );
 
540
                                        values );
579
541
                }
580
 
        }
581
 
 
582
 
        private void importContactAddresses( Uri contactUri,
583
 
                HashMap< String, ContactData.AddressData > addresses )
584
 
        {
585
 
                Long contactId = ContentUris.parseId( contactUri );
586
 
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
587
 
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
588
 
                Set< String > addressesKeys = addresses.keySet();
589
 
 
590
 
                // add addresses
591
 
                Iterator< String > i = addressesKeys.iterator();
 
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();
592
546
                while( i.hasNext() ) {
593
 
                        ContactData.AddressData address = addresses.get( i.next() );
594
 
 
595
 
                        // we don't want to add this address if it exists already or we
596
 
                        // would introduce duplicates
597
 
                        if( address == null ) continue;
598
 
                        HashSet< String > cache = _contactAddresses.get( contactId );
599
 
                        if( cache != null && cache.contains( address.getAddress() ) )
600
 
                                continue;
601
 
 
602
 
                        // add postal address
603
 
                        ContentValues values = new ContentValues();
604
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
605
 
                        values.put( Contacts.ContactMethods.DATA, address.getAddress() );
606
 
                        values.put( Contacts.ContactMethods.TYPE, address.getType() );
607
 
                        _doit.getContentResolver().insert( contactContactMethodsUri,
608
 
                                values );
609
 
 
610
 
                        // and add this address to the cache to prevent a addition of
611
 
                        // duplicate date from another file
612
 
                        if( cache == null ) {
613
 
                                cache = new HashSet< String >();
614
 
                                _contactAddresses.put( contactId, cache );
 
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 );
615
557
                        }
616
 
                        cache.add( address.getAddress() );
617
558
                }
618
559
        }
619
560
 
637
578
                _contacts = new HashMap< String, Long >();
638
579
                _contactNumbers = new HashMap< Long, HashSet< String > >();
639
580
                _contactEmails = new HashMap< Long, HashSet< String > >();
640
 
                _contactAddresses = new HashMap< Long, HashSet< String > >();
641
581
 
642
582
                // query and store map of contact names to ids
643
583
                cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
644
584
                cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
645
 
                        cols, null, null, null);
 
585
                                cols, null, null, null);
646
586
                if( cur.moveToFirst() ) {
647
587
                        int idCol = cur.getColumnIndex( Contacts.People._ID );
648
588
                        int nameCol = cur.getColumnIndex( Contacts.People.NAME );
655
595
                cols = new String[] { Contacts.Phones.PERSON_ID,
656
596
                                Contacts.Phones.NUMBER };
657
597
                cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
658
 
                        cols, null, null, null);
 
598
                                cols, null, null, null);
659
599
                if( cur.moveToFirst() ) {
660
600
                        int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
661
601
                        int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
666
606
                                if( number != null ) {
667
607
                                        HashSet< String > numbers = _contactNumbers.get( id );
668
608
                                        if( numbers == null ) {
669
 
                                                numbers = new HashSet< String >();
670
 
                                                _contactNumbers.put( id, numbers );
 
609
                                                _contactNumbers.put( id, new HashSet< String >() );
 
610
                                                numbers = _contactNumbers.get( id );
671
611
                                        }
672
612
                                        numbers.add( number );
673
613
                                }
682
622
                                new String[] { "" + Contacts.KIND_EMAIL }, null );
683
623
                if( cur.moveToFirst() ) {
684
624
                        int personIdCol = cur.getColumnIndex(
685
 
                                Contacts.ContactMethods.PERSON_ID );
 
625
                                        Contacts.ContactMethods.PERSON_ID );
686
626
                        int addressCol = cur.getColumnIndex(
687
 
                                Contacts.ContactMethods.DATA );
 
627
                                        Contacts.ContactMethods.DATA );
688
628
                        do {
689
629
                                Long id = cur.getLong( personIdCol );
690
630
                                String address = sanitiseEmailAddress(
691
 
                                        cur.getString( addressCol ) );
 
631
                                                cur.getString( addressCol ) );
692
632
                                if( address != null ) {
693
633
                                        HashSet< String > addresses = _contactEmails.get( id );
694
634
                                        if( addresses == null ) {
695
 
                                                addresses = new HashSet< String >();
696
 
                                                _contactEmails.put( id, addresses );
697
 
                                        }
698
 
                                        addresses.add( address );
699
 
                                }
700
 
                        } while( cur.moveToNext() );
701
 
                }
702
 
 
703
 
                // query and store map of contact ids to sets of postal addresses
704
 
                cols = new String[] { Contacts.ContactMethods.PERSON_ID,
705
 
                        Contacts.ContactMethods.DATA };
706
 
                cur = _doit.managedQuery( Contacts.ContactMethods.CONTENT_URI,
707
 
                        cols, Contacts.ContactMethods.KIND + " = ?",
708
 
                        new String[] { "" + Contacts.KIND_POSTAL }, null );
709
 
                if( cur.moveToFirst() ) {
710
 
                        int personIdCol = cur.getColumnIndex(
711
 
                                Contacts.ContactMethods.PERSON_ID );
712
 
                        int addressCol = cur.getColumnIndex(
713
 
                                Contacts.ContactMethods.DATA );
714
 
                        do {
715
 
                                Long id = cur.getLong( personIdCol );
716
 
                                String address = cur.getString( addressCol );
717
 
                                if( address != null ) {
718
 
                                        HashSet< String > addresses = _contactAddresses.get( id );
719
 
                                        if( addresses == null ) {
720
 
                                                addresses = new HashSet< String >();
721
 
                                                _contactAddresses.put( id, addresses );
 
635
                                                _contactEmails.put( id, new HashSet< String >() );
 
636
                                                addresses = _contactEmails.get( id );
722
637
                                        }
723
638
                                        addresses.add( address );
724
639
                                }
729
644
        private String sanitisePhoneNumber( String number )
730
645
        {
731
646
                number = number.replaceAll( "[-\\(\\) ]", "" );
732
 
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
 
647
                Pattern p = Pattern.compile( "^\\+?[0-9]+" );
733
648
                Matcher m = p.matcher( number );
734
649
                if( m.lookingAt() ) return m.group( 0 );
735
650
                return null;
739
654
        {
740
655
                address = address.trim();
741
656
                Pattern p = Pattern.compile(
742
 
                        "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
 
657
                                "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
743
658
                Matcher m = p.matcher( address );
744
659
                if( m.matches() ) {
745
660
                        String[] bits = address.split( "@" );