/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: 2010-10-28 15:49:21 UTC
  • Revision ID: edam@waxworlds.org-20101028154921-98svlxlpno3cpzb8
- added file chooser
- changed file/dir entry box for a button that opens the file chooser
- added dialog to ask if you want to select a dir to scan or a file
- fixed bug where you could abort as dialog opened and the dialog wasn't cancelled
- fixed crash where you could abort as the merge prompt opened and it would try to use the just-destroyed importer
- fixed bug where closing the application at the end would show "aborted!" erroniously

Show diffs side-by-side

added added

removed removed

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