1
package org.waxworlds.importcontacts;
4
* Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
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
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.
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.
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/>.
24
package org.waxworlds.edam.importcontacts;
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;
18
40
public class Importer extends Thread
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;
42
public final static int ACTION_ABORT = 1;
43
public final static int ACTION_ALLDONE = 2;
34
45
public final static int RESPONSE_NEGATIVE = 0;
35
46
public final static int RESPONSE_POSITIVE = 1;
127
157
if( !_emails.containsKey( email ) )
128
158
_emails.put( email, new EmailData( email, type, isPreferred ) );
161
protected void addAddress( String address, int type )
163
if( _addresses == null ) _addresses =
164
new HashMap< String, AddressData >();
165
if( !_addresses.containsKey( address ) )
166
_addresses.put( address, new AddressData( address, type ) );
170
@SuppressWarnings("serial")
132
171
protected class AbortImportException extends Exception { };
134
173
public Importer( Doit doit )
256
322
_doit._handler.sendMessage( Message.obtain(
257
_doit._handler, MESSAGE_SETMAXPROGRESS,
258
new Integer( maxProgress ) ) );
323
_doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
324
new Integer( maxProgress ) ) );
261
327
protected void setTmpProgress( int tmpProgress ) throws AbortImportException
264
330
_doit._handler.sendMessage( Message.obtain(
265
_doit._handler, MESSAGE_SETTMPPROGRESS,
266
new Integer( tmpProgress ) ) );
331
_doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
332
new Integer( tmpProgress ) ) );
269
335
protected void setProgress( int progress ) throws AbortImportException
272
338
_doit._handler.sendMessage( Message.obtain(
273
_doit._handler, MESSAGE_SETPROGRESS,
274
new Integer( progress ) ) );
277
protected void finish() throws AbortImportException
282
protected void abort() throws AbortImportException
339
_doit._handler, Doit.MESSAGE_SETPROGRESS,
340
new Integer( progress ) ) );
343
protected void finish( int action ) throws AbortImportException
345
// update UI to reflect action
349
case ACTION_ALLDONE: message = Doit.MESSAGE_ALLDONE; break;
350
default: // fall through
351
case ACTION_ABORT: message = Doit.MESSAGE_ABORT; break;
353
_doit._handler.sendEmptyMessage( message );
356
throw new AbortImportException();
287
359
protected CharSequence getText( int res )
296
368
return isImportRequired( name, _mergeSetting );
299
synchronized private boolean isImportRequired( String name, int mergeSetting )
371
synchronized private boolean isImportRequired( String name,
372
int mergeSetting ) throws AbortImportException
301
374
_lastMergeDecision = mergeSetting;
303
376
// handle special cases
304
377
switch( mergeSetting )
306
case R.id.merge_keep:
379
case Doit.ACTION_KEEP:
307
380
// if we keep contacts on duplicate, we better check for one
308
return !_contacts.containsKey( name );
381
return !_contactsCache.exists( name );
310
case R.id.merge_prompt:
383
case Doit.ACTION_PROMPT:
311
384
// if we are prompting on duplicate, we better check for one
312
if( !_contacts.containsKey( name ) )
385
if( !_contactsCache.exists( name ) )
315
388
// ok, it exists, so do prompt
316
389
_doit._handler.sendMessage( Message.obtain(
317
_doit._handler, MESSAGE_MERGEPROMPT, name ) );
390
_doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
321
394
catch( InterruptedException e ) { }
396
// check if an abortion happened during the wait
323
399
// if "always" was selected, make choice permenant
324
400
if( _responseExtra == RESPONSEEXTRA_ALWAYS )
325
401
_mergeSetting = _response;
327
// recurse, with out new merge setting
403
// recurse, with our new merge setting
328
404
return isImportRequired( name, _response );
353
429
// does contact exist already?
354
430
Uri contactUri = null;
356
if( ( id = (Long)_contacts.get( contact._name ) ) != null )
432
if( ( id = (Long)_contactsCache.getId( contact._name ) ) != null )
358
434
// should we skip this import altogether?
359
if( _lastMergeDecision == R.id.merge_keep ) return;
435
if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
361
437
// get contact's URI
362
438
contactUri = ContentUris.withAppendedId(
363
Contacts.People.CONTENT_URI, id );
439
Contacts.People.CONTENT_URI, id );
365
441
// should we destroy the existing contact before importing?
366
if( _lastMergeDecision == R.id.merge_overwrite ) {
442
if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
367
443
_doit.getContentResolver().delete( contactUri, null, null );
368
444
contactUri = null;
371
_doit._handler.sendEmptyMessage( MESSAGE_CONTACTOVERWRITTEN );
447
_doit._handler.sendEmptyMessage(
448
Doit.MESSAGE_CONTACTOVERWRITTEN );
372
449
uiInformed = true;
375
_contacts.remove( contact._name );
452
_contactsCache.remove( contact._name );
383
460
// create a new contact
384
461
values.put( Contacts.People.NAME, contact._name );
385
462
contactUri = _doit.getContentResolver().insert(
386
Contacts.People.CONTENT_URI, values );
463
Contacts.People.CONTENT_URI, values );
387
464
id = ContentUris.parseId( contactUri );
388
465
if( id <= 0 ) return; // shouldn't happen!
390
// add them to the "My Contacts" group
391
Contacts.People.addToGroup(
392
_doit.getContentResolver(), id,
393
Contacts.Groups.GROUP_MY_CONTACTS );
467
// try to add them to the "My Contacts" group
469
Contacts.People.addToMyContactsGroup(
470
_doit.getContentResolver(), id );
472
catch( IllegalStateException e ) {
473
// ignore any failure
396
_contacts.put( contact._name, id );
477
_contactsCache.put( id, contact._name );
399
480
if( !uiInformed ) {
400
_doit._handler.sendEmptyMessage( MESSAGE_CONTACTCREATED );
481
_doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
401
482
uiInformed = true;
406
487
if( !uiInformed )
407
_doit._handler.sendEmptyMessage( MESSAGE_CONTACTMERGED );
488
_doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
409
490
// import contact parts
410
491
if( contact._phones != null )
411
492
importContactPhones( contactUri, contact._phones );
412
493
if( contact._emails != null )
413
494
importContactEmails( contactUri, contact._emails );
495
if( contact._addresses != null )
496
importContactAddresses( contactUri, contact._addresses );
416
499
private void importContactPhones( Uri contactUri,
453
539
Long contactId = ContentUris.parseId( contactUri );
454
540
Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
455
541
Contacts.People.ContactMethods.CONTENT_DIRECTORY );
542
Set< String > emailsKeys = emails.keySet();
458
Set emailsKeys = emails.keySet();
459
Iterator i = emailsKeys.iterator();
544
// add email addresses
545
Iterator< String > i = emailsKeys.iterator();
460
546
while( i.hasNext() ) {
461
547
ContactData.EmailData email = emails.get( i.next() );
463
// like with phone numbers, we don't want to add this email address
464
// 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.
465
551
String address = sanitiseEmailAddress( email.getAddress() );
466
552
if( address == null ) continue;
467
HashSet< String > addresses = _contactEmails.get( contactId );
468
if( addresses != null && addresses.contains( address ) ) continue;
553
if( _contactsCache.hasEmail( contactId, address ) ) continue;
470
555
// add phone number
471
556
ContentValues values = new ContentValues();
475
560
if( email.isPreferred() )
476
561
values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
477
562
_doit.getContentResolver().insert( contactContactMethodsUri,
565
// and add this address to the cache to prevent a addition of
566
// duplicate date from another file
567
_contactsCache.addEmail( contactId, address );
482
synchronized private void finish( boolean offerBack )
483
throws AbortImportException
571
private void importContactAddresses( Uri contactUri,
572
HashMap< String, ContactData.AddressData > addresses )
485
// notify Doit that we're finished
486
_doit._handler.sendEmptyMessage(
487
offerBack? MESSAGE_FINISHED_BACK : MESSAGE_FINISHED );
490
throw new AbortImportException();
574
Long contactId = ContentUris.parseId( contactUri );
575
Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
576
Contacts.People.ContactMethods.CONTENT_DIRECTORY );
577
Set< String > addressesKeys = addresses.keySet();
580
Iterator< String > i = addressesKeys.iterator();
581
while( i.hasNext() ) {
582
ContactData.AddressData address = addresses.get( i.next() );
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() ) )
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,
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() );
493
synchronized private void checkAbort() throws AbortImportException
604
synchronized protected void checkAbort() throws AbortImportException
501
private void buildContactsCache() throws AbortImportException
504
setProgressMessage( R.string.doit_caching );
509
// init contacts caches
510
_contacts = new HashMap< String, Long >();
511
_contactNumbers = new HashMap< Long, HashSet< String > >();
512
_contactEmails = new HashMap< Long, HashSet< String > >();
514
// query and store map of contact names to ids
515
cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
516
cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
517
cols, null, null, null);
518
if( cur.moveToFirst() ) {
519
int idCol = cur.getColumnIndex( Contacts.People._ID );
520
int nameCol = cur.getColumnIndex( Contacts.People.NAME );
522
_contacts.put( cur.getString( nameCol ), cur.getLong( idCol ) );
523
} while( cur.moveToNext() );
526
// query and store map of contact ids to sets of phone numbers
527
cols = new String[] { Contacts.Phones.PERSON_ID,
528
Contacts.Phones.NUMBER };
529
cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
530
cols, null, null, null);
531
if( cur.moveToFirst() ) {
532
int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
533
int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
535
Long id = cur.getLong( personIdCol );
536
String number = sanitisePhoneNumber(
537
cur.getString( numberCol ) );
538
if( number != null ) {
539
HashSet< String > numbers = _contactNumbers.get( id );
540
if( numbers == null ) {
541
_contactNumbers.put( id, new HashSet< String >() );
542
numbers = _contactNumbers.get( id );
544
numbers.add( number );
546
} while( cur.moveToNext() );
549
// query and store map of contact ids to sets of email addresses
550
cols = new String[] { Contacts.ContactMethods.PERSON_ID,
551
Contacts.ContactMethods.DATA };
552
cur = _doit.managedQuery( Contacts.ContactMethods.CONTENT_URI,
553
cols, Contacts.ContactMethods.KIND + " = ?",
554
new String[] { "" + Contacts.KIND_EMAIL }, null );
555
if( cur.moveToFirst() ) {
556
int personIdCol = cur.getColumnIndex(
557
Contacts.ContactMethods.PERSON_ID );
558
int addressCol = cur.getColumnIndex(
559
Contacts.ContactMethods.DATA );
561
Long id = cur.getLong( personIdCol );
562
String address = sanitiseEmailAddress(
563
cur.getString( addressCol ) );
564
if( address != null ) {
565
HashSet< String > addresses = _contactEmails.get( id );
566
if( addresses == null ) {
567
_contactEmails.put( id, new HashSet< String >() );
568
addresses = _contactEmails.get( id );
570
addresses.add( address );
572
} while( cur.moveToNext() );
576
private String sanitisePhoneNumber( String number )
612
static public String sanitisePhoneNumber( String number )
578
614
number = number.replaceAll( "[-\\(\\) ]", "" );
579
Pattern p = Pattern.compile( "^\\+?[0-9]+" );
615
Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
580
616
Matcher m = p.matcher( number );
581
617
if( m.lookingAt() ) return m.group( 0 );
585
private String sanitiseEmailAddress( String address )
621
static public String sanitiseEmailAddress( String address )
587
623
address = address.trim();
588
624
Pattern p = Pattern.compile(
589
"^[^ @]+@[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])?)+$" );
590
626
Matcher m = p.matcher( address );
591
627
if( m.matches() ) {
592
628
String[] bits = address.split( "@" );