/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-10 16:14:11 UTC
  • Revision ID: edam@waxworlds.org-20090110161411-4d17l9hs9d6j277q
Initial import

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;
40
17
 
41
18
public class Importer extends Thread
42
19
{
43
 
        public final static int ACTION_ABORT = 1;
44
 
        public final static int ACTION_ALLDONE = 2;
 
20
        public final static int MESSAGE_FINISHED = 0;
 
21
        public final static int MESSAGE_FINISHED_BACK = 1;
 
22
        public final static int MESSAGE_ERROR = 2;
 
23
        public final static int MESSAGE_CONTINUEORABORT = 3;
 
24
        public final static int MESSAGE_SETPROGRESSMESSAGE = 4;
 
25
        public final static int MESSAGE_SETMAXPROGRESS = 5;
 
26
        public final static int MESSAGE_SETTMPPROGRESS = 6;
 
27
        public final static int MESSAGE_SETPROGRESS = 7;
 
28
        public final static int MESSAGE_MERGEPROMPT = 8;
 
29
        public final static int MESSAGE_CONTACTOVERWRITTEN = 9;
 
30
        public final static int MESSAGE_CONTACTCREATED = 10;
 
31
        public final static int MESSAGE_CONTACTMERGED = 11;
 
32
        public final static int MESSAGE_CONTACTSKIPPED = 12;
45
33
 
46
34
        public final static int RESPONSE_NEGATIVE = 0;
47
35
        public final static int RESPONSE_POSITIVE = 1;
58
46
        private int _mergeSetting;
59
47
        private int _lastMergeDecision;
60
48
        private boolean _abort = false;
61
 
        private boolean _isFinished = false;
62
49
 
63
50
        public class ContactData
64
51
        {
131
118
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
132
119
                        if( !_phones.containsKey( number ) )
133
120
                                _phones.put( number,
134
 
                                        new PhoneData( number, type, isPreferred ) );
 
121
                                                new PhoneData( number, type, isPreferred ) );
135
122
                }
136
123
 
137
124
                protected void addEmail( String email, int type, boolean isPreferred )
142
129
                }
143
130
        }
144
131
 
145
 
        @SuppressWarnings("serial")
146
132
        protected class AbortImportException extends Exception { };
147
133
 
148
134
        public Importer( Doit doit )
150
136
                _doit = doit;
151
137
 
152
138
                SharedPreferences prefs = getSharedPreferences();
153
 
                _mergeSetting = prefs.getInt( "merge_setting", Doit.ACTION_PROMPT );
 
139
                _mergeSetting = prefs.getInt( "merge_setting", 0 );
154
140
        }
155
141
 
156
142
        @Override
165
151
                        onImport();
166
152
 
167
153
                        // done!
168
 
                        finish( ACTION_ALLDONE );
 
154
                        finish();
169
155
                }
170
156
                catch( AbortImportException e )
171
157
                {}
172
 
 
173
 
                // flag as finished to prevent interrupts
174
 
                setIsFinished();
175
 
        }
176
 
 
177
 
        synchronized private void setIsFinished()
178
 
        {
179
 
                _isFinished = true;
180
158
        }
181
159
 
182
160
        protected void onImport() throws AbortImportException
200
178
                notify();
201
179
        }
202
180
 
203
 
        synchronized public boolean setAbort()
 
181
        synchronized public void setAbort()
204
182
        {
205
 
                if( !_isFinished && !_abort ) {
206
 
                        _abort = true;
207
 
                        notify();
208
 
                        return true;
209
 
                }
210
 
                return false;
 
183
                _abort = true;
211
184
        }
212
185
 
213
186
        protected SharedPreferences getSharedPreferences()
225
198
        {
226
199
                checkAbort();
227
200
                _doit._handler.sendMessage( Message.obtain(
228
 
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
201
                                _doit._handler, MESSAGE_ERROR, message ) );
229
202
                try {
230
203
                        wait();
231
204
                }
232
205
                catch( InterruptedException e ) { }
233
 
 
234
 
                // no need to check if an abortion happened during the wait, we are
235
 
                // about to finish anyway!
236
 
                finish( ACTION_ABORT );
 
206
                finish( true );
237
207
        }
238
208
 
239
209
        protected void showFatalError( int res ) throws AbortImportException
246
216
        {
247
217
                checkAbort();
248
218
                _doit._handler.sendMessage( Message.obtain(
249
 
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
219
                                _doit._handler, MESSAGE_ERROR, message ) );
250
220
                try {
251
221
                        wait();
252
222
                }
253
223
                catch( InterruptedException e ) { }
254
 
 
255
 
                // no need to check if an abortion happened during the wait, we are
256
 
                // about to finish anyway!
257
 
                finish( ACTION_ABORT );
 
224
                finish( false );
258
225
        }
259
226
 
260
227
        protected boolean showContinue( int res ) throws AbortImportException
267
234
        {
268
235
                checkAbort();
269
236
                _doit._handler.sendMessage( Message.obtain(
270
 
                        _doit._handler, Doit.MESSAGE_CONTINUEORABORT, message ) );
 
237
                                _doit._handler, MESSAGE_CONTINUEORABORT, message ) );
271
238
                try {
272
239
                        wait();
273
240
                }
274
241
                catch( InterruptedException e ) { }
275
 
 
276
 
                // check if an abortion happened during the wait
277
 
                checkAbort();
278
 
 
279
242
                return _response == RESPONSE_POSITIVE;
280
243
        }
281
244
 
283
246
        {
284
247
                checkAbort();
285
248
                _doit._handler.sendMessage( Message.obtain( _doit._handler,
286
 
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
 
249
                                MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
287
250
        }
288
251
 
289
252
        protected void setProgressMax( int maxProgress )
291
254
        {
292
255
                checkAbort();
293
256
                _doit._handler.sendMessage( Message.obtain(
294
 
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
295
 
                        new Integer( maxProgress ) ) );
 
257
                                _doit._handler, MESSAGE_SETMAXPROGRESS,
 
258
                                new Integer( maxProgress ) ) );
296
259
        }
297
260
 
298
261
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
299
262
        {
300
263
                checkAbort();
301
264
                _doit._handler.sendMessage( Message.obtain(
302
 
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
303
 
                        new Integer( tmpProgress ) ) );
 
265
                                _doit._handler, MESSAGE_SETTMPPROGRESS,
 
266
                                new Integer( tmpProgress ) ) );
304
267
        }
305
268
 
306
269
        protected void setProgress( int progress ) throws AbortImportException
307
270
        {
308
271
                checkAbort();
309
272
                _doit._handler.sendMessage( Message.obtain(
310
 
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
311
 
                        new Integer( progress ) ) );
312
 
        }
313
 
 
314
 
        protected void finish( int action ) throws AbortImportException
315
 
        {
316
 
                // update UI to reflect action
317
 
                int message;
318
 
                switch( action )
319
 
                {
320
 
                case ACTION_ALLDONE:    message = Doit.MESSAGE_ALLDONE; break;
321
 
                default:        // fall through
322
 
                case ACTION_ABORT:              message = Doit.MESSAGE_ABORT; break;
323
 
                }
324
 
                _doit._handler.sendEmptyMessage( message );
325
 
 
326
 
                // stop
327
 
                throw new AbortImportException();
 
273
                                _doit._handler, MESSAGE_SETPROGRESS,
 
274
                                new Integer( progress ) ) );
 
275
        }
 
276
 
 
277
        protected void finish() throws AbortImportException
 
278
        {
 
279
                finish( false );
 
280
        }
 
281
 
 
282
        protected void abort() throws AbortImportException
 
283
        {
 
284
                finish( true );
328
285
        }
329
286
 
330
287
        protected CharSequence getText( int res )
339
296
                return isImportRequired( name, _mergeSetting );
340
297
        }
341
298
 
342
 
        synchronized private boolean isImportRequired( String name,
343
 
                        int mergeSetting ) throws AbortImportException
 
299
        synchronized private boolean isImportRequired( String name, int mergeSetting )
344
300
        {
345
301
                _lastMergeDecision = mergeSetting;
346
302
 
347
303
                // handle special cases
348
304
                switch( mergeSetting )
349
305
                {
350
 
                case Doit.ACTION_KEEP:
 
306
                case R.id.merge_keep:
351
307
                        // if we keep contacts on duplicate, we better check for one
352
308
                        return !_contacts.containsKey( name );
353
309
 
354
 
                case Doit.ACTION_PROMPT:
 
310
                case R.id.merge_prompt:
355
311
                        // if we are prompting on duplicate, we better check for one
356
312
                        if( !_contacts.containsKey( name ) )
357
313
                                return true;
358
314
 
359
315
                        // ok, it exists, so do prompt
360
316
                        _doit._handler.sendMessage( Message.obtain(
361
 
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
 
317
                                        _doit._handler, MESSAGE_MERGEPROMPT, name ) );
362
318
                        try {
363
319
                                wait();
364
320
                        }
365
321
                        catch( InterruptedException e ) { }
366
322
 
367
 
                        // check if an abortion happened during the wait
368
 
                        checkAbort();
369
 
 
370
323
                        // if "always" was selected, make choice permenant
371
324
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
372
325
                                _mergeSetting = _response;
373
326
 
374
 
                        // recurse, with our new merge setting
 
327
                        // recurse, with out new merge setting
375
328
                        return isImportRequired( name, _response );
376
329
                }
377
330
 
383
336
        protected void skipContact() throws AbortImportException
384
337
        {
385
338
                checkAbort();
386
 
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
 
339
                _doit._handler.sendEmptyMessage( MESSAGE_CONTACTSKIPPED );
387
340
        }
388
341
 
389
342
        protected void importContact( ContactData contact )
391
344
        {
392
345
                checkAbort();
393
346
 
394
 
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
395
 
//                      finish( ACTION_ABORT );
 
347
                if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
 
348
                        abort();
396
349
 
397
350
                ContentValues values = new ContentValues();
398
351
                boolean uiInformed = false;
403
356
                if( ( id = (Long)_contacts.get( contact._name ) ) != null )
404
357
                {
405
358
                        // should we skip this import altogether?
406
 
                        if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
 
359
                        if( _lastMergeDecision == R.id.merge_keep ) return;
407
360
 
408
361
                        // get contact's URI
409
362
                        contactUri = ContentUris.withAppendedId(
410
 
                                Contacts.People.CONTENT_URI, id );
 
363
                                        Contacts.People.CONTENT_URI, id );
411
364
 
412
365
                        // should we destroy the existing contact before importing?
413
 
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
 
366
                        if( _lastMergeDecision == R.id.merge_overwrite ) {
414
367
                                _doit.getContentResolver().delete( contactUri, null, null );
415
368
                                contactUri = null;
416
369
 
417
 
                                // update the UI
418
 
                                _doit._handler.sendEmptyMessage(
419
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
 
370
                                // upate the UI
 
371
                                _doit._handler.sendEmptyMessage( MESSAGE_CONTACTOVERWRITTEN );
420
372
                                uiInformed = true;
421
373
 
422
374
                                // update cache
431
383
                        // create a new contact
432
384
                        values.put( Contacts.People.NAME, contact._name );
433
385
                        contactUri = _doit.getContentResolver().insert(
434
 
                                Contacts.People.CONTENT_URI, values );
 
386
                                        Contacts.People.CONTENT_URI, values );
435
387
                        id = ContentUris.parseId( contactUri );
436
388
                        if( id <= 0 ) return;   // shouldn't happen!
437
389
 
438
 
                        // try to add them to the "My Contacts" group
439
 
                        try {
440
 
                                Contacts.People.addToMyContactsGroup(
441
 
                                        _doit.getContentResolver(), id );
442
 
                        }
443
 
                        catch( IllegalStateException e ) {
444
 
                                // ignore any failure
445
 
                        }
 
390
                        // add them to the "My Contacts" group
 
391
                        Contacts.People.addToGroup(
 
392
                                        _doit.getContentResolver(), id,
 
393
                                        Contacts.Groups.GROUP_MY_CONTACTS );
446
394
 
447
395
                        // update cache
448
396
                        _contacts.put( contact._name, id );
449
397
 
450
398
                        // update UI
451
399
                        if( !uiInformed ) {
452
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
 
400
                                _doit._handler.sendEmptyMessage( MESSAGE_CONTACTCREATED );
453
401
                                uiInformed = true;
454
402
                        }
455
403
                }
456
404
 
457
405
                // update UI
458
406
                if( !uiInformed )
459
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
 
407
                        _doit._handler.sendEmptyMessage( MESSAGE_CONTACTMERGED );
460
408
 
461
409
                // import contact parts
462
410
                if( contact._phones != null )
471
419
                Long contactId = ContentUris.parseId( contactUri );
472
420
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
473
421
                                Contacts.People.Phones.CONTENT_DIRECTORY );
474
 
                Set< String > phonesKeys = phones.keySet();
475
422
 
476
423
                // add phone numbers
477
 
                Iterator< String > i = phonesKeys.iterator();
 
424
                Set phonesKeys = phones.keySet();
 
425
                Iterator i = phonesKeys.iterator();
478
426
                while( i.hasNext() ) {
479
427
                        ContactData.PhoneData phone = phones.get( i.next() );
480
428
 
497
445
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
498
446
                        _doit.getContentResolver().insert( contactPhonesUri, values );
499
447
                }
500
 
 
501
 
                // now add those phone numbers to the cache to prevent the addition of
502
 
                // duplicate data from another file
503
 
                i = phonesKeys.iterator();
504
 
                while( i.hasNext() ) {
505
 
                        ContactData.PhoneData phone = phones.get( i.next() );
506
 
 
507
 
                        String number = sanitisePhoneNumber( phone._number );
508
 
                        if( number != null ) {
509
 
                                HashSet< String > numbers = _contactNumbers.get( contactId );
510
 
                                if( numbers == null ) {
511
 
                                        _contactNumbers.put( contactId, new HashSet< String >() );
512
 
                                        numbers = _contactNumbers.get( contactId );
513
 
                                }
514
 
                                numbers.add( number );
515
 
                        }
516
 
                }
517
448
        }
518
449
 
519
450
        private void importContactEmails( Uri contactUri,
522
453
                Long contactId = ContentUris.parseId( contactUri );
523
454
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
524
455
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
525
 
                Set< String > emailsKeys = emails.keySet();
526
456
 
527
 
                // add email addresses
528
 
                Iterator< String > i = emailsKeys.iterator();
 
457
                // add phone numbers
 
458
                Set emailsKeys = emails.keySet();
 
459
                Iterator i = emailsKeys.iterator();
529
460
                while( i.hasNext() ) {
530
461
                        ContactData.EmailData email = emails.get( i.next() );
531
462
 
544
475
                        if( email.isPreferred() )
545
476
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
546
477
                        _doit.getContentResolver().insert( contactContactMethodsUri,
547
 
                                values );
548
 
                }
549
 
 
550
 
                // now add those email addresses to the cache to prevent the addition of
551
 
                // duplicate data from another file
552
 
                i = emailsKeys.iterator();
553
 
                while( i.hasNext() ) {
554
 
                        ContactData.EmailData email = emails.get( i.next() );
555
 
 
556
 
                        String address = sanitiseEmailAddress( email.getAddress() );
557
 
                        if( address != null ) {
558
 
                                HashSet< String > addresses = _contactEmails.get( contactId );
559
 
                                if( addresses == null ) {
560
 
                                        _contactEmails.put( contactId, new HashSet< String >() );
561
 
                                        addresses = _contactEmails.get( contactId );
562
 
                                }
563
 
                                addresses.add( address );
564
 
                        }
565
 
                }
566
 
        }
567
 
 
568
 
        synchronized protected void checkAbort() throws AbortImportException
 
478
                                        values );
 
479
                }
 
480
        }
 
481
 
 
482
        synchronized private void finish( boolean offerBack )
 
483
                        throws AbortImportException
 
484
        {
 
485
                // notify Doit that we're finished
 
486
                _doit._handler.sendEmptyMessage(
 
487
                                offerBack? MESSAGE_FINISHED_BACK : MESSAGE_FINISHED );
 
488
 
 
489
                // stop
 
490
                throw new AbortImportException();
 
491
        }
 
492
 
 
493
        synchronized private void checkAbort() throws AbortImportException
569
494
        {
570
495
                if( _abort ) {
571
496
                        // stop
589
514
                // query and store map of contact names to ids
590
515
                cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
591
516
                cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
592
 
                        cols, null, null, null);
 
517
                                cols, null, null, null);
593
518
                if( cur.moveToFirst() ) {
594
519
                        int idCol = cur.getColumnIndex( Contacts.People._ID );
595
520
                        int nameCol = cur.getColumnIndex( Contacts.People.NAME );
602
527
                cols = new String[] { Contacts.Phones.PERSON_ID,
603
528
                                Contacts.Phones.NUMBER };
604
529
                cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
605
 
                        cols, null, null, null);
 
530
                                cols, null, null, null);
606
531
                if( cur.moveToFirst() ) {
607
532
                        int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
608
533
                        int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
629
554
                                new String[] { "" + Contacts.KIND_EMAIL }, null );
630
555
                if( cur.moveToFirst() ) {
631
556
                        int personIdCol = cur.getColumnIndex(
632
 
                                Contacts.ContactMethods.PERSON_ID );
 
557
                                        Contacts.ContactMethods.PERSON_ID );
633
558
                        int addressCol = cur.getColumnIndex(
634
 
                                Contacts.ContactMethods.DATA );
 
559
                                        Contacts.ContactMethods.DATA );
635
560
                        do {
636
561
                                Long id = cur.getLong( personIdCol );
637
562
                                String address = sanitiseEmailAddress(
638
 
                                        cur.getString( addressCol ) );
 
563
                                                cur.getString( addressCol ) );
639
564
                                if( address != null ) {
640
565
                                        HashSet< String > addresses = _contactEmails.get( id );
641
566
                                        if( addresses == null ) {
651
576
        private String sanitisePhoneNumber( String number )
652
577
        {
653
578
                number = number.replaceAll( "[-\\(\\) ]", "" );
654
 
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
 
579
                Pattern p = Pattern.compile( "^\\+?[0-9]+" );
655
580
                Matcher m = p.matcher( number );
656
581
                if( m.lookingAt() ) return m.group( 0 );
657
582
                return null;
661
586
        {
662
587
                address = address.trim();
663
588
                Pattern p = Pattern.compile(
664
 
                        "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
 
589
                                "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
665
590
                Matcher m = p.matcher( address );
666
591
                if( m.matches() ) {
667
592
                        String[] bits = address.split( "@" );