/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-01-11 12:58:54 UTC
  • Revision ID: edam@waxworlds.org-20090111125854-u8ofzso4jatk12me
- added "all done" message
- rewrote Importer.finish() to make the exit process more consistent
- moved Doit's message definitions to Doit
- ensure the importer is destroyed in Doit.onPause()
- only show the toaster popup if a) there is an importer to abort, and b) the abort actually did something (i.e., it's not already aborted)
- bugfix: added some checks for abortion to the Importer after wait()ing after a dialog. Importer.wake() now alsy does a notify() to break out of dialog waits.
- also, made Importer.checkAbort() protected, so it can be checked from specific importers as desired

Show diffs side-by-side

added added

removed removed

1
 
/*
2
 
 * Importer.java
3
 
 *
4
 
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
5
 
 *
6
 
 * This file is part of the Import Contacts program (hereafter referred
7
 
 * to as "this program"). For more information, see
8
 
 * http://www.waxworlds.org/edam/software/android/import-contacts
9
 
 *
10
 
 * This program is free software: you can redistribute it and/or modify
11
 
 * it under the terms of the GNU General Public License as published by
12
 
 * the Free Software Foundation, either version 3 of the License, or
13
 
 * (at your option) any later version.
14
 
 *
15
 
 * This program is distributed in the hope that it will be useful,
16
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 
 * GNU General Public License for more details.
19
 
 *
20
 
 * You should have received a copy of the GNU General Public License
21
 
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 
 */
23
 
 
24
 
package org.waxworlds.edam.importcontacts;
 
1
package org.waxworlds.importcontacts;
25
2
 
26
3
import java.util.HashMap;
27
4
import java.util.HashSet;
38
15
import android.os.Message;
39
16
import android.provider.Contacts;
40
17
 
41
 
 
42
18
public class Importer extends Thread
43
19
{
 
20
        public final static int ACTION_GOBACK = 0;
44
21
        public final static int ACTION_ABORT = 1;
45
22
        public final static int ACTION_ALLDONE = 2;
46
23
 
56
33
        private HashMap< String, Long > _contacts;
57
34
        private HashMap< Long, HashSet< String > > _contactNumbers;
58
35
        private HashMap< Long, HashSet< String > > _contactEmails;
59
 
        private HashMap< Long, HashSet< String > > _contactAddresses;
60
36
        private int _mergeSetting;
61
37
        private int _lastMergeDecision;
62
38
        private boolean _abort = false;
114
90
                        }
115
91
                }
116
92
 
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
93
                public String _name = null;
137
94
                public HashMap< String, PhoneData > _phones = null;
138
95
                public HashMap< String, EmailData > _emails = null;
139
 
                public HashMap< String, AddressData > _addresses = null;
140
96
 
141
97
                protected void setName( String name )
142
98
                {
153
109
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
154
110
                        if( !_phones.containsKey( number ) )
155
111
                                _phones.put( number,
156
 
                                        new PhoneData( number, type, isPreferred ) );
 
112
                                                new PhoneData( number, type, isPreferred ) );
157
113
                }
158
114
 
159
115
                protected void addEmail( String email, int type, boolean isPreferred )
162
118
                        if( !_emails.containsKey( email ) )
163
119
                                _emails.put( email, new EmailData( email, type, isPreferred ) );
164
120
                }
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
121
        }
174
122
 
175
 
        @SuppressWarnings("serial")
176
123
        protected class AbortImportException extends Exception { };
177
124
 
178
125
        public Importer( Doit doit )
180
127
                _doit = doit;
181
128
 
182
129
                SharedPreferences prefs = getSharedPreferences();
183
 
                _mergeSetting = prefs.getInt( "merge_setting", Doit.ACTION_PROMPT );
 
130
                _mergeSetting = prefs.getInt( "merge_setting", 0 );
184
131
        }
185
132
 
186
133
        @Override
255
202
        {
256
203
                checkAbort();
257
204
                _doit._handler.sendMessage( Message.obtain(
258
 
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
205
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
259
206
                try {
260
207
                        wait();
261
208
                }
262
209
                catch( InterruptedException e ) { }
263
 
 
264
210
                // no need to check if an abortion happened during the wait, we are
265
211
                // about to finish anyway!
266
212
                finish( ACTION_ABORT );
276
222
        {
277
223
                checkAbort();
278
224
                _doit._handler.sendMessage( Message.obtain(
279
 
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
225
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
280
226
                try {
281
227
                        wait();
282
228
                }
283
229
                catch( InterruptedException e ) { }
284
 
 
285
230
                // no need to check if an abortion happened during the wait, we are
286
231
                // about to finish anyway!
287
232
                finish( ACTION_ABORT );
297
242
        {
298
243
                checkAbort();
299
244
                _doit._handler.sendMessage( Message.obtain(
300
 
                        _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
 
245
                                _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
301
246
                try {
302
247
                        wait();
303
248
                }
313
258
        {
314
259
                checkAbort();
315
260
                _doit._handler.sendMessage( Message.obtain( _doit._handler,
316
 
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
 
261
                                Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
317
262
        }
318
263
 
319
264
        protected void setProgressMax( int maxProgress )
321
266
        {
322
267
                checkAbort();
323
268
                _doit._handler.sendMessage( Message.obtain(
324
 
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
325
 
                        new Integer( maxProgress ) ) );
 
269
                                _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
 
270
                                new Integer( maxProgress ) ) );
326
271
        }
327
272
 
328
273
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
329
274
        {
330
275
                checkAbort();
331
276
                _doit._handler.sendMessage( Message.obtain(
332
 
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
333
 
                        new Integer( tmpProgress ) ) );
 
277
                                _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
 
278
                                new Integer( tmpProgress ) ) );
334
279
        }
335
280
 
336
281
        protected void setProgress( int progress ) throws AbortImportException
337
282
        {
338
283
                checkAbort();
339
284
                _doit._handler.sendMessage( Message.obtain(
340
 
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
341
 
                        new Integer( progress ) ) );
 
285
                                _doit._handler, Doit.MESSAGE_SETPROGRESS,
 
286
                                new Integer( progress ) ) );
342
287
        }
343
288
 
344
289
        protected void finish( int action ) throws AbortImportException
347
292
                int message;
348
293
                switch( action )
349
294
                {
350
 
                case ACTION_ALLDONE:    message = Doit.MESSAGE_ALLDONE; break;
 
295
                case ACTION_GOBACK:             message = Doit.MESSAGE_FINISHED_GOBACK; break;
 
296
                case ACTION_ALLDONE:    message = Doit.MESSAGE_FINISHED_ALLDONE; break;
351
297
                default:        // fall through
352
 
                case ACTION_ABORT:              message = Doit.MESSAGE_ABORT; break;
 
298
                case ACTION_ABORT:              message = Doit.MESSAGE_FINISHED; break;
353
299
                }
354
300
                _doit._handler.sendEmptyMessage( message );
355
301
 
377
323
                // handle special cases
378
324
                switch( mergeSetting )
379
325
                {
380
 
                case Doit.ACTION_KEEP:
 
326
                case R.id.merge_keep:
381
327
                        // if we keep contacts on duplicate, we better check for one
382
328
                        return !_contacts.containsKey( name );
383
329
 
384
 
                case Doit.ACTION_PROMPT:
 
330
                case R.id.merge_prompt:
385
331
                        // if we are prompting on duplicate, we better check for one
386
332
                        if( !_contacts.containsKey( name ) )
387
333
                                return true;
388
334
 
389
335
                        // ok, it exists, so do prompt
390
336
                        _doit._handler.sendMessage( Message.obtain(
391
 
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
 
337
                                        _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
392
338
                        try {
393
339
                                wait();
394
340
                        }
401
347
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
402
348
                                _mergeSetting = _response;
403
349
 
404
 
                        // recurse, with our new merge setting
 
350
                        // recurse, with out new merge setting
405
351
                        return isImportRequired( name, _response );
406
352
                }
407
353
 
433
379
                if( ( id = (Long)_contacts.get( contact._name ) ) != null )
434
380
                {
435
381
                        // should we skip this import altogether?
436
 
                        if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
 
382
                        if( _lastMergeDecision == R.id.merge_keep ) return;
437
383
 
438
384
                        // get contact's URI
439
385
                        contactUri = ContentUris.withAppendedId(
440
 
                                Contacts.People.CONTENT_URI, id );
 
386
                                        Contacts.People.CONTENT_URI, id );
441
387
 
442
388
                        // should we destroy the existing contact before importing?
443
 
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
 
389
                        if( _lastMergeDecision == R.id.merge_overwrite ) {
444
390
                                _doit.getContentResolver().delete( contactUri, null, null );
445
391
                                contactUri = null;
446
392
 
447
 
                                // update the UI
448
 
                                _doit._handler.sendEmptyMessage(
449
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
 
393
                                // upate the UI
 
394
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
450
395
                                uiInformed = true;
451
396
 
452
397
                                // update cache
461
406
                        // create a new contact
462
407
                        values.put( Contacts.People.NAME, contact._name );
463
408
                        contactUri = _doit.getContentResolver().insert(
464
 
                                Contacts.People.CONTENT_URI, values );
 
409
                                        Contacts.People.CONTENT_URI, values );
465
410
                        id = ContentUris.parseId( contactUri );
466
411
                        if( id <= 0 ) return;   // shouldn't happen!
467
412
 
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
 
                        }
 
413
                        // add them to the "My Contacts" group
 
414
                        Contacts.People.addToGroup(
 
415
                                        _doit.getContentResolver(), id,
 
416
                                        Contacts.Groups.GROUP_MY_CONTACTS );
476
417
 
477
418
                        // update cache
478
419
                        _contacts.put( contact._name, id );
493
434
                        importContactPhones( contactUri, contact._phones );
494
435
                if( contact._emails != null )
495
436
                        importContactEmails( contactUri, contact._emails );
496
 
                if( contact._addresses != null )
497
 
                        importContactAddresses( contactUri, contact._addresses );
498
437
        }
499
438
 
500
439
        private void importContactPhones( Uri contactUri,
503
442
                Long contactId = ContentUris.parseId( contactUri );
504
443
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
505
444
                                Contacts.People.Phones.CONTENT_DIRECTORY );
506
 
                Set< String > phonesKeys = phones.keySet();
507
445
 
508
446
                // add phone numbers
509
 
                Iterator< String > i = phonesKeys.iterator();
 
447
                Set phonesKeys = phones.keySet();
 
448
                Iterator i = phonesKeys.iterator();
510
449
                while( i.hasNext() ) {
511
450
                        ContactData.PhoneData phone = phones.get( i.next() );
512
451
 
519
458
                        // anyway, so it's not a problem).
520
459
                        String number = sanitisePhoneNumber( phone._number );
521
460
                        if( number == null ) continue;
522
 
                        HashSet< String > cache = _contactNumbers.get( contactId );
523
 
                        if( cache != null && cache.contains( number ) ) continue;
 
461
                        HashSet< String > numbers = _contactNumbers.get( contactId );
 
462
                        if( numbers != null && numbers.contains( number ) ) continue;
524
463
 
525
464
                        // add phone number
526
465
                        ContentValues values = new ContentValues();
528
467
                        values.put( Contacts.Phones.NUMBER, phone._number );
529
468
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
530
469
                        _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 );
537
 
                        }
538
 
                        cache.add( number );
539
470
                }
540
471
        }
541
472
 
545
476
                Long contactId = ContentUris.parseId( contactUri );
546
477
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
547
478
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
548
 
                Set< String > emailsKeys = emails.keySet();
549
479
 
550
 
                // add email addresses
551
 
                Iterator< String > i = emailsKeys.iterator();
 
480
                // add phone numbers
 
481
                Set emailsKeys = emails.keySet();
 
482
                Iterator i = emailsKeys.iterator();
552
483
                while( i.hasNext() ) {
553
484
                        ContactData.EmailData email = emails.get( i.next() );
554
485
 
555
 
                        // we don't want to add this email address if it exists already or
556
 
                        // we would introduce duplicates.
 
486
                        // like with phone numbers, we don't want to add this email address
 
487
                        // if it exists already or we would introduce duplicates.
557
488
                        String address = sanitiseEmailAddress( email.getAddress() );
558
489
                        if( address == null ) continue;
559
 
                        HashSet< String > cache = _contactEmails.get( contactId );
560
 
                        if( cache != null && cache.contains( address ) ) continue;
 
490
                        HashSet< String > addresses = _contactEmails.get( contactId );
 
491
                        if( addresses != null && addresses.contains( address ) ) continue;
561
492
 
562
493
                        // add phone number
563
494
                        ContentValues values = new ContentValues();
567
498
                        if( email.isPreferred() )
568
499
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
569
500
                        _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 );
579
 
                }
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();
592
 
                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 );
615
 
                        }
616
 
                        cache.add( address.getAddress() );
 
501
                                        values );
617
502
                }
618
503
        }
619
504
 
637
522
                _contacts = new HashMap< String, Long >();
638
523
                _contactNumbers = new HashMap< Long, HashSet< String > >();
639
524
                _contactEmails = new HashMap< Long, HashSet< String > >();
640
 
                _contactAddresses = new HashMap< Long, HashSet< String > >();
641
525
 
642
526
                // query and store map of contact names to ids
643
527
                cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
644
528
                cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
645
 
                        cols, null, null, null);
 
529
                                cols, null, null, null);
646
530
                if( cur.moveToFirst() ) {
647
531
                        int idCol = cur.getColumnIndex( Contacts.People._ID );
648
532
                        int nameCol = cur.getColumnIndex( Contacts.People.NAME );
655
539
                cols = new String[] { Contacts.Phones.PERSON_ID,
656
540
                                Contacts.Phones.NUMBER };
657
541
                cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
658
 
                        cols, null, null, null);
 
542
                                cols, null, null, null);
659
543
                if( cur.moveToFirst() ) {
660
544
                        int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
661
545
                        int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
666
550
                                if( number != null ) {
667
551
                                        HashSet< String > numbers = _contactNumbers.get( id );
668
552
                                        if( numbers == null ) {
669
 
                                                numbers = new HashSet< String >();
670
 
                                                _contactNumbers.put( id, numbers );
 
553
                                                _contactNumbers.put( id, new HashSet< String >() );
 
554
                                                numbers = _contactNumbers.get( id );
671
555
                                        }
672
556
                                        numbers.add( number );
673
557
                                }
682
566
                                new String[] { "" + Contacts.KIND_EMAIL }, null );
683
567
                if( cur.moveToFirst() ) {
684
568
                        int personIdCol = cur.getColumnIndex(
685
 
                                Contacts.ContactMethods.PERSON_ID );
 
569
                                        Contacts.ContactMethods.PERSON_ID );
686
570
                        int addressCol = cur.getColumnIndex(
687
 
                                Contacts.ContactMethods.DATA );
 
571
                                        Contacts.ContactMethods.DATA );
688
572
                        do {
689
573
                                Long id = cur.getLong( personIdCol );
690
574
                                String address = sanitiseEmailAddress(
691
 
                                        cur.getString( addressCol ) );
 
575
                                                cur.getString( addressCol ) );
692
576
                                if( address != null ) {
693
577
                                        HashSet< String > addresses = _contactEmails.get( id );
694
578
                                        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 );
 
579
                                                _contactEmails.put( id, new HashSet< String >() );
 
580
                                                addresses = _contactEmails.get( id );
722
581
                                        }
723
582
                                        addresses.add( address );
724
583
                                }
729
588
        private String sanitisePhoneNumber( String number )
730
589
        {
731
590
                number = number.replaceAll( "[-\\(\\) ]", "" );
732
 
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
 
591
                Pattern p = Pattern.compile( "^\\+?[0-9]+" );
733
592
                Matcher m = p.matcher( number );
734
593
                if( m.lookingAt() ) return m.group( 0 );
735
594
                return null;
739
598
        {
740
599
                address = address.trim();
741
600
                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])?)+$" );
 
601
                                "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
743
602
                Matcher m = p.matcher( address );
744
603
                if( m.matches() ) {
745
604
                        String[] bits = address.split( "@" );