/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-03-23 07:50:13 UTC
  • Revision ID: edam@waxworlds.org-20110323075013-qnza5odtlsjtcz0p
- updated TODO and NEWS
- handle different multiline schemes better
- import addresses
- check for escaped semi-colons and newlines in N, ADR and ORG lines
- minor optimisations

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