/android/import-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/import-contacts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package org.waxworlds.importcontacts;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Message;
import android.provider.Contacts;

public class Importer extends Thread
{
	public final static int MESSAGE_FINISHED = 0;
	public final static int MESSAGE_FINISHED_BACK = 1;
	public final static int MESSAGE_ERROR = 2;
	public final static int MESSAGE_CONTINUEORABORT = 3;
	public final static int MESSAGE_SETPROGRESSMESSAGE = 4;
	public final static int MESSAGE_SETMAXPROGRESS = 5;
	public final static int MESSAGE_SETTMPPROGRESS = 6;
	public final static int MESSAGE_SETPROGRESS = 7;
	public final static int MESSAGE_MERGEPROMPT = 8;
	public final static int MESSAGE_CONTACTOVERWRITTEN = 9;
	public final static int MESSAGE_CONTACTCREATED = 10;
	public final static int MESSAGE_CONTACTMERGED = 11;
	public final static int MESSAGE_CONTACTSKIPPED = 12;

	public final static int RESPONSE_NEGATIVE = 0;
	public final static int RESPONSE_POSITIVE = 1;

	public final static int RESPONSEEXTRA_NONE = 0;
	public final static int RESPONSEEXTRA_ALWAYS = 1;

	private Doit _doit;
	private int _response;
	private int _responseExtra;
	private HashMap< String, Long > _contacts;
	private HashMap< Long, HashSet< String > > _contactNumbers;
	private HashMap< Long, HashSet< String > > _contactEmails;
	private int _mergeSetting;
	private int _lastMergeDecision;
	private boolean _abort = false;

	public class ContactData
	{
		class PhoneData
		{
			public String _number;
			public int _type;
			public boolean _isPreferred;

			public PhoneData( String number, int type, boolean isPreferred ) {
				_number = number;
				_type = type;
				_isPreferred = isPreferred;
			}

			public String getNumber() {
				return _number;
			}

			public int getType() {
				return _type;
			}

			public boolean isPreferred() {
				return _isPreferred;
			}
		}

		class EmailData
		{
			private String _email;
			public int _type;
			private boolean _isPreferred;

			public EmailData( String email, int type, boolean isPreferred ) {
				_email = email;
				_type = type;
				_isPreferred = isPreferred;
			}

			public String getAddress() {
				return _email;
			}

			public int getType() {
				return _type;
			}

			public boolean isPreferred() {
				return _isPreferred;
			}
		}

		public String _name = null;
		public HashMap< String, PhoneData > _phones = null;
		public HashMap< String, EmailData > _emails = null;

		protected void setName( String name )
		{
			_name = name;
		}

		public String getName()
		{
			return _name;
		}

		protected void addPhone( String number, int type, boolean isPreferred )
		{
			if( _phones == null ) _phones = new HashMap< String, PhoneData >();
			if( !_phones.containsKey( number ) )
				_phones.put( number,
						new PhoneData( number, type, isPreferred ) );
		}

		protected void addEmail( String email, int type, boolean isPreferred )
		{
			if( _emails == null ) _emails = new HashMap< String, EmailData >();
			if( !_emails.containsKey( email ) )
				_emails.put( email, new EmailData( email, type, isPreferred ) );
		}
	}

	protected class AbortImportException extends Exception { };

	public Importer( Doit doit )
	{
		_doit = doit;

		SharedPreferences prefs = getSharedPreferences();
		_mergeSetting = prefs.getInt( "merge_setting", 0 );
	}

	@Override
	public void run()
	{
		try
		{
			// cache current contact names
			buildContactsCache();

			// do the import
			onImport();

			// done!
			finish();
		}
		catch( AbortImportException e )
		{}
	}

	protected void onImport() throws AbortImportException
	{
	}

	public void wake()
	{
		wake( 0, RESPONSEEXTRA_NONE );
	}

	public void wake( int response )
	{
		wake( response, RESPONSEEXTRA_NONE );
	}

	synchronized public void wake( int response, int responseExtra )
	{
		_response = response;
		_responseExtra = responseExtra;
		notify();
	}

	synchronized public void setAbort()
	{
		_abort = true;
	}

	protected SharedPreferences getSharedPreferences()
	{
		return _doit.getSharedPreferences();
	}

	protected void showError( int res ) throws AbortImportException
	{
		showError( _doit.getText( res ).toString() );
	}

	synchronized protected void showError( String message )
			throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain(
				_doit._handler, MESSAGE_ERROR, message ) );
		try {
			wait();
		}
		catch( InterruptedException e ) { }
		finish( true );
	}

	protected void showFatalError( int res ) throws AbortImportException
	{
		showFatalError( _doit.getText( res ).toString() );
	}

	synchronized protected void showFatalError( String message )
			throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain(
				_doit._handler, MESSAGE_ERROR, message ) );
		try {
			wait();
		}
		catch( InterruptedException e ) { }
		finish( false );
	}

	protected boolean showContinue( int res ) throws AbortImportException
	{
		return showContinue( _doit.getText( res ).toString() );
	}

	synchronized protected boolean showContinue( String message )
			throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain(
				_doit._handler, MESSAGE_CONTINUEORABORT, message ) );
		try {
			wait();
		}
		catch( InterruptedException e ) { }
		return _response == RESPONSE_POSITIVE;
	}

	protected void setProgressMessage( int res ) throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain( _doit._handler,
				MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
	}

	protected void setProgressMax( int maxProgress )
			throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain(
				_doit._handler, MESSAGE_SETMAXPROGRESS,
				new Integer( maxProgress ) ) );
	}

	protected void setTmpProgress( int tmpProgress ) throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain(
				_doit._handler, MESSAGE_SETTMPPROGRESS,
				new Integer( tmpProgress ) ) );
	}

	protected void setProgress( int progress ) throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendMessage( Message.obtain(
				_doit._handler, MESSAGE_SETPROGRESS,
				new Integer( progress ) ) );
	}

	protected void finish() throws AbortImportException
	{
		finish( false );
	}

	protected void abort() throws AbortImportException
	{
		finish( true );
	}

	protected CharSequence getText( int res )
	{
		return _doit.getText( res );
	}

	protected boolean isImportRequired( String name )
			throws AbortImportException
	{
		checkAbort();
		return isImportRequired( name, _mergeSetting );
	}

	synchronized private boolean isImportRequired( String name, int mergeSetting )
	{
		_lastMergeDecision = mergeSetting;

		// handle special cases
		switch( mergeSetting )
		{
		case R.id.merge_keep:
			// if we keep contacts on duplicate, we better check for one
			return !_contacts.containsKey( name );

		case R.id.merge_prompt:
			// if we are prompting on duplicate, we better check for one
			if( !_contacts.containsKey( name ) )
				return true;

			// ok, it exists, so do prompt
			_doit._handler.sendMessage( Message.obtain(
					_doit._handler, MESSAGE_MERGEPROMPT, name ) );
			try {
				wait();
			}
			catch( InterruptedException e ) { }

			// if "always" was selected, make choice permenant
			if( _responseExtra == RESPONSEEXTRA_ALWAYS )
				_mergeSetting = _response;

			// recurse, with out new merge setting
			return isImportRequired( name, _response );
		}

		// for all other cases (either overwriting or merging) we will need the
		// imported data
		return true;
	}

	protected void skipContact() throws AbortImportException
	{
		checkAbort();
		_doit._handler.sendEmptyMessage( MESSAGE_CONTACTSKIPPED );
	}

	protected void importContact( ContactData contact )
			throws AbortImportException
	{
		checkAbort();

		if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
			abort();

		ContentValues values = new ContentValues();
		boolean uiInformed = false;

		// does contact exist already?
		Uri contactUri = null;
		Long id;
		if( ( id = (Long)_contacts.get( contact._name ) ) != null )
		{
			// should we skip this import altogether?
			if( _lastMergeDecision == R.id.merge_keep ) return;

			// get contact's URI
			contactUri = ContentUris.withAppendedId(
					Contacts.People.CONTENT_URI, id );

			// should we destroy the existing contact before importing?
			if( _lastMergeDecision == R.id.merge_overwrite ) {
				_doit.getContentResolver().delete( contactUri, null, null );
				contactUri = null;

				// upate the UI
				_doit._handler.sendEmptyMessage( MESSAGE_CONTACTOVERWRITTEN );
				uiInformed = true;

				// update cache
				_contacts.remove( contact._name );
			}
		}

		// if we don't have a contact URI it is because the contact never
		// existed or because we deleted it
		if( contactUri == null )
		{
			// create a new contact
			values.put( Contacts.People.NAME, contact._name );
			contactUri = _doit.getContentResolver().insert(
					Contacts.People.CONTENT_URI, values );
			id = ContentUris.parseId( contactUri );
			if( id <= 0 ) return;	// shouldn't happen!

			// add them to the "My Contacts" group
			Contacts.People.addToGroup(
					_doit.getContentResolver(), id,
					Contacts.Groups.GROUP_MY_CONTACTS );

			// update cache
			_contacts.put( contact._name, id );

			// update UI
			if( !uiInformed ) {
				_doit._handler.sendEmptyMessage( MESSAGE_CONTACTCREATED );
				uiInformed = true;
			}
		}

		// update UI
		if( !uiInformed )
			_doit._handler.sendEmptyMessage( MESSAGE_CONTACTMERGED );

		// import contact parts
		if( contact._phones != null )
			importContactPhones( contactUri, contact._phones );
		if( contact._emails != null )
			importContactEmails( contactUri, contact._emails );
	}

	private void importContactPhones( Uri contactUri,
			HashMap< String, ContactData.PhoneData > phones )
	{
		Long contactId = ContentUris.parseId( contactUri );
		Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
				Contacts.People.Phones.CONTENT_DIRECTORY );

		// add phone numbers
		Set phonesKeys = phones.keySet();
		Iterator i = phonesKeys.iterator();
		while( i.hasNext() ) {
			ContactData.PhoneData phone = phones.get( i.next() );

			// we don't want to add this number if it's crap, or it already
			// exists (which would cause a duplicate to be created). We don't
			// take in to account the type when checking for duplicates. This is
			// intentional: types aren't really very reliable. We assume that
			// if the number exists at all, it doesn't need importing. Because
			// of this, we also can't update the cache (which we don't need to
			// anyway, so it's not a problem).
			String number = sanitisePhoneNumber( phone._number );
			if( number == null ) continue;
			HashSet< String > numbers = _contactNumbers.get( contactId );
			if( numbers != null && numbers.contains( number ) ) continue;

			// add phone number
			ContentValues values = new ContentValues();
			values.put( Contacts.Phones.TYPE, phone._type );
			values.put( Contacts.Phones.NUMBER, phone._number );
			if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
			_doit.getContentResolver().insert( contactPhonesUri, values );
		}
	}

	private void importContactEmails( Uri contactUri,
			HashMap< String, ContactData.EmailData > emails )
	{
		Long contactId = ContentUris.parseId( contactUri );
		Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
				Contacts.People.ContactMethods.CONTENT_DIRECTORY );

		// add phone numbers
		Set emailsKeys = emails.keySet();
		Iterator i = emailsKeys.iterator();
		while( i.hasNext() ) {
			ContactData.EmailData email = emails.get( i.next() );

			// like with phone numbers, we don't want to add this email address
			// if it exists already or we would introduce duplicates.
			String address = sanitiseEmailAddress( email.getAddress() );
			if( address == null ) continue;
			HashSet< String > addresses = _contactEmails.get( contactId );
			if( addresses != null && addresses.contains( address ) ) continue;

			// add phone number
			ContentValues values = new ContentValues();
			values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
			values.put( Contacts.ContactMethods.DATA, email.getAddress() );
			values.put( Contacts.ContactMethods.TYPE, email.getType() );
			if( email.isPreferred() )
				values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
			_doit.getContentResolver().insert( contactContactMethodsUri,
					values );
		}
	}

	synchronized private void finish( boolean offerBack )
			throws AbortImportException
	{
		// notify Doit that we're finished
		_doit._handler.sendEmptyMessage(
				offerBack? MESSAGE_FINISHED_BACK : MESSAGE_FINISHED );

		// stop
		throw new AbortImportException();
	}

	synchronized private void checkAbort() throws AbortImportException
	{
		if( _abort ) {
			// stop
			throw new AbortImportException();
		}
	}

	private void buildContactsCache() throws AbortImportException
	{
		// update UI
		setProgressMessage( R.string.doit_caching );

		String[] cols;
		Cursor cur;

		// init contacts caches
		_contacts = new HashMap< String, Long >();
		_contactNumbers = new HashMap< Long, HashSet< String > >();
		_contactEmails = new HashMap< Long, HashSet< String > >();

		// query and store map of contact names to ids
		cols = new String[] { Contacts.People._ID, Contacts.People.NAME };
		cur = _doit.managedQuery( Contacts.People.CONTENT_URI,
				cols, null, null, null);
		if( cur.moveToFirst() ) {
			int idCol = cur.getColumnIndex( Contacts.People._ID );
			int nameCol = cur.getColumnIndex( Contacts.People.NAME );
			do {
				_contacts.put( cur.getString( nameCol ), cur.getLong( idCol ) );
			} while( cur.moveToNext() );
		}

		// query and store map of contact ids to sets of phone numbers
		cols = new String[] { Contacts.Phones.PERSON_ID,
				Contacts.Phones.NUMBER };
		cur = _doit.managedQuery( Contacts.Phones.CONTENT_URI,
				cols, null, null, null);
		if( cur.moveToFirst() ) {
			int personIdCol = cur.getColumnIndex( Contacts.Phones.PERSON_ID );
			int numberCol = cur.getColumnIndex( Contacts.Phones.NUMBER );
			do {
				Long id = cur.getLong( personIdCol );
				String number = sanitisePhoneNumber(
						cur.getString( numberCol ) );
				if( number != null ) {
					HashSet< String > numbers = _contactNumbers.get( id );
					if( numbers == null ) {
						_contactNumbers.put( id, new HashSet< String >() );
						numbers = _contactNumbers.get( id );
					}
					numbers.add( number );
				}
			} while( cur.moveToNext() );
		}

		// query and store map of contact ids to sets of email addresses
		cols = new String[] { Contacts.ContactMethods.PERSON_ID,
				Contacts.ContactMethods.DATA };
		cur = _doit.managedQuery( Contacts.ContactMethods.CONTENT_URI,
				cols, Contacts.ContactMethods.KIND + " = ?",
				new String[] { "" + Contacts.KIND_EMAIL }, null );
		if( cur.moveToFirst() ) {
			int personIdCol = cur.getColumnIndex(
					Contacts.ContactMethods.PERSON_ID );
			int addressCol = cur.getColumnIndex(
					Contacts.ContactMethods.DATA );
			do {
				Long id = cur.getLong( personIdCol );
				String address = sanitiseEmailAddress(
						cur.getString( addressCol ) );
				if( address != null ) {
					HashSet< String > addresses = _contactEmails.get( id );
					if( addresses == null ) {
						_contactEmails.put( id, new HashSet< String >() );
						addresses = _contactEmails.get( id );
					}
					addresses.add( address );
				}
			} while( cur.moveToNext() );
		}
	}

	private String sanitisePhoneNumber( String number )
	{
		number = number.replaceAll( "[-\\(\\) ]", "" );
		Pattern p = Pattern.compile( "^\\+?[0-9]+" );
		Matcher m = p.matcher( number );
		if( m.lookingAt() ) return m.group( 0 );
		return null;
	}

	private String sanitiseEmailAddress( String address )
	{
		address = address.trim();
		Pattern p = Pattern.compile(
				"^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
		Matcher m = p.matcher( address );
		if( m.matches() ) {
			String[] bits = address.split( "@" );
			return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
		}
		return null;
	}
}