/android/import-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/import-contacts

« back to all changes in this revision

Viewing changes to src/org/waxworlds/edam/importcontacts/Importer.java

  • Committer: edam
  • Date: 2011-04-22 15:36:06 UTC
  • Revision ID: edam@waxworlds.org-20110422153606-9x9l0nbmvx6oxfxu
- pulled contacts cache out in to seperate class

Show diffs side-by-side

added added

removed removed

1
 
package org.waxworlds.importcontacts;
 
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;
2
25
 
3
26
import java.util.HashMap;
4
 
import java.util.HashSet;
5
27
import java.util.Iterator;
6
28
import java.util.Set;
7
29
import java.util.regex.Matcher;
10
32
import android.content.ContentUris;
11
33
import android.content.ContentValues;
12
34
import android.content.SharedPreferences;
13
 
import android.database.Cursor;
14
35
import android.net.Uri;
15
36
import android.os.Message;
16
37
import android.provider.Contacts;
17
38
 
 
39
 
18
40
public class Importer extends Thread
19
41
{
20
 
        public final static int ACTION_GOBACK = 0;
21
42
        public final static int ACTION_ABORT = 1;
22
43
        public final static int ACTION_ALLDONE = 2;
23
44
 
30
51
        private Doit _doit;
31
52
        private int _response;
32
53
        private int _responseExtra;
33
 
        private HashMap< String, Long > _contacts;
34
 
        private HashMap< Long, HashSet< String > > _contactNumbers;
35
 
        private HashMap< Long, HashSet< String > > _contactEmails;
36
54
        private int _mergeSetting;
37
55
        private int _lastMergeDecision;
38
56
        private boolean _abort = false;
39
57
        private boolean _isFinished = false;
 
58
        private ContactsCache _contactsCache = null;
40
59
 
41
60
        public class ContactData
42
61
        {
90
109
                        }
91
110
                }
92
111
 
 
112
                class AddressData
 
113
                {
 
114
                        private String _address;
 
115
                        public int _type;
 
116
 
 
117
                        public AddressData( String address, int type ) {
 
118
                                _address = address;
 
119
                                _type = type;
 
120
                        }
 
121
 
 
122
                        public String getAddress() {
 
123
                                return _address;
 
124
                        }
 
125
 
 
126
                        public int getType() {
 
127
                                return _type;
 
128
                        }
 
129
                }
 
130
 
93
131
                public String _name = null;
94
132
                public HashMap< String, PhoneData > _phones = null;
95
133
                public HashMap< String, EmailData > _emails = null;
 
134
                public HashMap< String, AddressData > _addresses = null;
96
135
 
97
136
                protected void setName( String name )
98
137
                {
109
148
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
110
149
                        if( !_phones.containsKey( number ) )
111
150
                                _phones.put( number,
112
 
                                                new PhoneData( number, type, isPreferred ) );
 
151
                                        new PhoneData( number, type, isPreferred ) );
113
152
                }
114
153
 
115
154
                protected void addEmail( String email, int type, boolean isPreferred )
118
157
                        if( !_emails.containsKey( email ) )
119
158
                                _emails.put( email, new EmailData( email, type, isPreferred ) );
120
159
                }
 
160
 
 
161
                protected void addAddress( String address, int type )
 
162
                {
 
163
                        if( _addresses == null ) _addresses =
 
164
                                new HashMap< String, AddressData >();
 
165
                        if( !_addresses.containsKey( address ) )
 
166
                                _addresses.put( address, new AddressData( address, type ) );
 
167
                }
121
168
        }
122
169
 
 
170
        @SuppressWarnings("serial")
123
171
        protected class AbortImportException extends Exception { };
124
172
 
125
173
        public Importer( Doit doit )
127
175
                _doit = doit;
128
176
 
129
177
                SharedPreferences prefs = getSharedPreferences();
130
 
                _mergeSetting = prefs.getInt( "merge_setting", 0 );
 
178
                _mergeSetting = prefs.getInt( "merge_setting", Doit.ACTION_PROMPT );
131
179
        }
132
180
 
133
181
        @Override
135
183
        {
136
184
                try
137
185
                {
138
 
                        // cache current contact names
139
 
                        buildContactsCache();
 
186
                        // update UI
 
187
                        setProgressMessage( R.string.doit_caching );
 
188
 
 
189
                        // build a cache of existing contacts
 
190
                        _contactsCache = new ContactsCache();
 
191
                        _contactsCache.buildCache( _doit );
140
192
 
141
193
                        // do the import
142
194
                        onImport();
202
254
        {
203
255
                checkAbort();
204
256
                _doit._handler.sendMessage( Message.obtain(
205
 
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
257
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
206
258
                try {
207
259
                        wait();
208
260
                }
209
261
                catch( InterruptedException e ) { }
 
262
 
210
263
                // no need to check if an abortion happened during the wait, we are
211
264
                // about to finish anyway!
212
265
                finish( ACTION_ABORT );
222
275
        {
223
276
                checkAbort();
224
277
                _doit._handler.sendMessage( Message.obtain(
225
 
                                _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
278
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
226
279
                try {
227
280
                        wait();
228
281
                }
229
282
                catch( InterruptedException e ) { }
 
283
 
230
284
                // no need to check if an abortion happened during the wait, we are
231
285
                // about to finish anyway!
232
286
                finish( ACTION_ABORT );
242
296
        {
243
297
                checkAbort();
244
298
                _doit._handler.sendMessage( Message.obtain(
245
 
                                _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
 
299
                        _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
246
300
                try {
247
301
                        wait();
248
302
                }
258
312
        {
259
313
                checkAbort();
260
314
                _doit._handler.sendMessage( Message.obtain( _doit._handler,
261
 
                                Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
 
315
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
262
316
        }
263
317
 
264
318
        protected void setProgressMax( int maxProgress )
266
320
        {
267
321
                checkAbort();
268
322
                _doit._handler.sendMessage( Message.obtain(
269
 
                                _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
270
 
                                new Integer( maxProgress ) ) );
 
323
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
 
324
                        new Integer( maxProgress ) ) );
271
325
        }
272
326
 
273
327
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
274
328
        {
275
329
                checkAbort();
276
330
                _doit._handler.sendMessage( Message.obtain(
277
 
                                _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
278
 
                                new Integer( tmpProgress ) ) );
 
331
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
 
332
                        new Integer( tmpProgress ) ) );
279
333
        }
280
334
 
281
335
        protected void setProgress( int progress ) throws AbortImportException
282
336
        {
283
337
                checkAbort();
284
338
                _doit._handler.sendMessage( Message.obtain(
285
 
                                _doit._handler, Doit.MESSAGE_SETPROGRESS,
286
 
                                new Integer( progress ) ) );
 
339
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
 
340
                        new Integer( progress ) ) );
287
341
        }
288
342
 
289
343
        protected void finish( int action ) throws AbortImportException
292
346
                int message;
293
347
                switch( action )
294
348
                {
295
 
                case ACTION_GOBACK:             message = Doit.MESSAGE_FINISHED_GOBACK; break;
296
 
                case ACTION_ALLDONE:    message = Doit.MESSAGE_FINISHED_ALLDONE; break;
 
349
                case ACTION_ALLDONE:    message = Doit.MESSAGE_ALLDONE; break;
297
350
                default:        // fall through
298
 
                case ACTION_ABORT:              message = Doit.MESSAGE_FINISHED; break;
 
351
                case ACTION_ABORT:              message = Doit.MESSAGE_ABORT; break;
299
352
                }
300
353
                _doit._handler.sendEmptyMessage( message );
301
354
 
323
376
                // handle special cases
324
377
                switch( mergeSetting )
325
378
                {
326
 
                case R.id.merge_keep:
 
379
                case Doit.ACTION_KEEP:
327
380
                        // if we keep contacts on duplicate, we better check for one
328
 
                        return !_contacts.containsKey( name );
 
381
                        return !_contactsCache.exists( name );
329
382
 
330
 
                case R.id.merge_prompt:
 
383
                case Doit.ACTION_PROMPT:
331
384
                        // if we are prompting on duplicate, we better check for one
332
 
                        if( !_contacts.containsKey( name ) )
 
385
                        if( !_contactsCache.exists( name ) )
333
386
                                return true;
334
387
 
335
388
                        // ok, it exists, so do prompt
336
389
                        _doit._handler.sendMessage( Message.obtain(
337
 
                                        _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
 
390
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
338
391
                        try {
339
392
                                wait();
340
393
                        }
347
400
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
348
401
                                _mergeSetting = _response;
349
402
 
350
 
                        // recurse, with out new merge setting
 
403
                        // recurse, with our new merge setting
351
404
                        return isImportRequired( name, _response );
352
405
                }
353
406
 
376
429
                // does contact exist already?
377
430
                Uri contactUri = null;
378
431
                Long id;
379
 
                if( ( id = (Long)_contacts.get( contact._name ) ) != null )
 
432
                if( ( id = (Long)_contactsCache.getId( contact._name ) ) != null )
380
433
                {
381
434
                        // should we skip this import altogether?
382
 
                        if( _lastMergeDecision == R.id.merge_keep ) return;
 
435
                        if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
383
436
 
384
437
                        // get contact's URI
385
438
                        contactUri = ContentUris.withAppendedId(
386
 
                                        Contacts.People.CONTENT_URI, id );
 
439
                                Contacts.People.CONTENT_URI, id );
387
440
 
388
441
                        // should we destroy the existing contact before importing?
389
 
                        if( _lastMergeDecision == R.id.merge_overwrite ) {
 
442
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
390
443
                                _doit.getContentResolver().delete( contactUri, null, null );
391
444
                                contactUri = null;
392
445
 
393
 
                                // upate the UI
394
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
 
446
                                // update the UI
 
447
                                _doit._handler.sendEmptyMessage(
 
448
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
395
449
                                uiInformed = true;
396
450
 
397
451
                                // update cache
398
 
                                _contacts.remove( contact._name );
 
452
                                _contactsCache.remove( contact._name );
399
453
                        }
400
454
                }
401
455
 
406
460
                        // create a new contact
407
461
                        values.put( Contacts.People.NAME, contact._name );
408
462
                        contactUri = _doit.getContentResolver().insert(
409
 
                                        Contacts.People.CONTENT_URI, values );
 
463
                                Contacts.People.CONTENT_URI, values );
410
464
                        id = ContentUris.parseId( contactUri );
411
465
                        if( id <= 0 ) return;   // shouldn't happen!
412
466
 
413
 
                        // add them to the "My Contacts" group
414
 
                        Contacts.People.addToGroup(
415
 
                                        _doit.getContentResolver(), id,
416
 
                                        Contacts.Groups.GROUP_MY_CONTACTS );
 
467
                        // try to add them to the "My Contacts" group
 
468
                        try {
 
469
                                Contacts.People.addToMyContactsGroup(
 
470
                                        _doit.getContentResolver(), id );
 
471
                        }
 
472
                        catch( IllegalStateException e ) {
 
473
                                // ignore any failure
 
474
                        }
417
475
 
418
476
                        // update cache
419
 
                        _contacts.put( contact._name, id );
 
477
                        _contactsCache.put( id, contact._name );
420
478
 
421
479
                        // update UI
422
480
                        if( !uiInformed ) {
434
492
                        importContactPhones( contactUri, contact._phones );
435
493
                if( contact._emails != null )
436
494
                        importContactEmails( contactUri, contact._emails );
 
495
                if( contact._addresses != null )
 
496
                        importContactAddresses( contactUri, contact._addresses );
437
497
        }
438
498
 
439
499
        private void importContactPhones( Uri contactUri,
442
502
                Long contactId = ContentUris.parseId( contactUri );
443
503
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
444
504
                                Contacts.People.Phones.CONTENT_DIRECTORY );
 
505
                Set< String > phonesKeys = phones.keySet();
445
506
 
446
507
                // add phone numbers
447
 
                Set phonesKeys = phones.keySet();
448
 
                Iterator i = phonesKeys.iterator();
 
508
                Iterator< String > i = phonesKeys.iterator();
449
509
                while( i.hasNext() ) {
450
510
                        ContactData.PhoneData phone = phones.get( i.next() );
451
511
 
458
518
                        // anyway, so it's not a problem).
459
519
                        String number = sanitisePhoneNumber( phone._number );
460
520
                        if( number == null ) continue;
461
 
                        HashSet< String > numbers = _contactNumbers.get( contactId );
462
 
                        if( numbers != null && numbers.contains( number ) ) continue;
 
521
                        if( _contactsCache.hasNumber( contactId, number ) ) continue;
463
522
 
464
523
                        // add phone number
465
524
                        ContentValues values = new ContentValues();
467
526
                        values.put( Contacts.Phones.NUMBER, phone._number );
468
527
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
469
528
                        _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 );
470
533
                }
471
534
        }
472
535
 
476
539
                Long contactId = ContentUris.parseId( contactUri );
477
540
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
478
541
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
 
542
                Set< String > emailsKeys = emails.keySet();
479
543
 
480
 
                // add phone numbers
481
 
                Set emailsKeys = emails.keySet();
482
 
                Iterator i = emailsKeys.iterator();
 
544
                // add email addresses
 
545
                Iterator< String > i = emailsKeys.iterator();
483
546
                while( i.hasNext() ) {
484
547
                        ContactData.EmailData email = emails.get( i.next() );
485
548
 
486
 
                        // like with phone numbers, we don't want to add this email address
487
 
                        // if it exists already or we would introduce duplicates.
 
549
                        // we don't want to add this email address if it exists already or
 
550
                        // we would introduce duplicates.
488
551
                        String address = sanitiseEmailAddress( email.getAddress() );
489
552
                        if( address == null ) continue;
490
 
                        HashSet< String > addresses = _contactEmails.get( contactId );
491
 
                        if( addresses != null && addresses.contains( address ) ) continue;
 
553
                        if( _contactsCache.hasEmail( contactId, address ) ) continue;
492
554
 
493
555
                        // add phone number
494
556
                        ContentValues values = new ContentValues();
498
560
                        if( email.isPreferred() )
499
561
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
500
562
                        _doit.getContentResolver().insert( contactContactMethodsUri,
501
 
                                        values );
 
563
                                values );
 
564
 
 
565
                        // and add this address to the cache to prevent a addition of
 
566
                        // duplicate date from another file
 
567
                        _contactsCache.addEmail( contactId, address );
 
568
                }
 
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();
 
581
                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() );
502
601
                }
503
602
        }
504
603
 
510
609
                }
511
610
        }
512
611
 
513
 
        private void buildContactsCache() throws AbortImportException
514
 
        {
515
 
                // update UI
516
 
                setProgressMessage( R.string.doit_caching );
517
 
 
518
 
                String[] cols;
519
 
                Cursor cur;
520
 
 
521
 
                // init contacts caches
522
 
                _contacts = new HashMap< String, Long >();
523
 
                _contactNumbers = new HashMap< Long, HashSet< String > >();
524
 
                _contactEmails = new HashMap< Long, HashSet< String > >();
525
 
 
526
 
                // query and store map of contact names to ids
527
 
                cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
528
 
                cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
529
 
                                cols, null, null, null);
530
 
                if( cur.moveToFirst() ) {
531
 
                        int idCol = cur.getColumnIndex( Contacts.People._ID );
532
 
                        int nameCol = cur.getColumnIndex( Contacts.People.NAME );
533
 
                        do {
534
 
                                _contacts.put( cur.getString( nameCol ), cur.getLong( idCol ) );
535
 
                        } while( cur.moveToNext() );
536
 
                }
537
 
 
538
 
                // query and store map of contact ids to sets of phone numbers
539
 
                cols = new String[] { Contacts.Phones.PERSON_ID,
540
 
                                Contacts.Phones.NUMBER };
541
 
                cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
542
 
                                cols, null, null, null);
543
 
                if( cur.moveToFirst() ) {
544
 
                        int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
545
 
                        int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
546
 
                        do {
547
 
                                Long id = cur.getLong( personIdCol );
548
 
                                String number = sanitisePhoneNumber(
549
 
                                                cur.getString( numberCol ) );
550
 
                                if( number != null ) {
551
 
                                        HashSet< String > numbers = _contactNumbers.get( id );
552
 
                                        if( numbers == null ) {
553
 
                                                _contactNumbers.put( id, new HashSet< String >() );
554
 
                                                numbers = _contactNumbers.get( id );
555
 
                                        }
556
 
                                        numbers.add( number );
557
 
                                }
558
 
                        } while( cur.moveToNext() );
559
 
                }
560
 
 
561
 
                // query and store map of contact ids to sets of email addresses
562
 
                cols = new String[] { Contacts.ContactMethods.PERSON_ID,
563
 
                                Contacts.ContactMethods.DATA };
564
 
                cur = _doit.managedQuery( Contacts.ContactMethods.CONTENT_URI,
565
 
                                cols, Contacts.ContactMethods.KIND + " = ?",
566
 
                                new String[] { "" + Contacts.KIND_EMAIL }, null );
567
 
                if( cur.moveToFirst() ) {
568
 
                        int personIdCol = cur.getColumnIndex(
569
 
                                        Contacts.ContactMethods.PERSON_ID );
570
 
                        int addressCol = cur.getColumnIndex(
571
 
                                        Contacts.ContactMethods.DATA );
572
 
                        do {
573
 
                                Long id = cur.getLong( personIdCol );
574
 
                                String address = sanitiseEmailAddress(
575
 
                                                cur.getString( addressCol ) );
576
 
                                if( address != null ) {
577
 
                                        HashSet< String > addresses = _contactEmails.get( id );
578
 
                                        if( addresses == null ) {
579
 
                                                _contactEmails.put( id, new HashSet< String >() );
580
 
                                                addresses = _contactEmails.get( id );
581
 
                                        }
582
 
                                        addresses.add( address );
583
 
                                }
584
 
                        } while( cur.moveToNext() );
585
 
                }
586
 
        }
587
 
 
588
 
        private String sanitisePhoneNumber( String number )
 
612
        static public String sanitisePhoneNumber( String number )
589
613
        {
590
614
                number = number.replaceAll( "[-\\(\\) ]", "" );
591
 
                Pattern p = Pattern.compile( "^\\+?[0-9]+" );
 
615
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
592
616
                Matcher m = p.matcher( number );
593
617
                if( m.lookingAt() ) return m.group( 0 );
594
618
                return null;
595
619
        }
596
620
 
597
 
        private String sanitiseEmailAddress( String address )
 
621
        static public String sanitiseEmailAddress( String address )
598
622
        {
599
623
                address = address.trim();
600
624
                Pattern p = Pattern.compile(
601
 
                                "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
 
625
                        "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
602
626
                Matcher m = p.matcher( address );
603
627
                if( m.matches() ) {
604
628
                        String[] bits = address.split( "@" );