/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
/*
 * ContactsBackend.java
 *
 * Copyright (C) 2012 Tim Marston <tim@ed.am>
 *
 * This file is part of the Import Contacts program (hereafter referred
 * to as "this program"). For more information, see
 * http://ed.am/dev/android/import-contacts
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package am.ed.importcontacts;

import java.util.HashMap;
import java.util.HashSet;

import am.ed.importcontacts.ContactsCache.CacheIdentifier;
import am.ed.importcontacts.Importer.ContactData;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;

@TargetApi(5)
public class ContactsContractBackend implements Backend
{
	private Activity _activity = null;
	private HashMap< Long, Long > _aggregate_to_raw_ids = null;

	ContactsContractBackend( Activity activity )
	{
		_activity = activity;
		_aggregate_to_raw_ids = new HashMap< Long, Long >();
	}

	@Override
	public void populateCache( ContactsCache cache )
	{
		Cursor cur;

		// build a set of aggregate contact ids that haven't been added to the
		// cache yet
		HashSet< Long > unadded_ids = new HashSet< Long >();
		cur = _activity.managedQuery( ContactsContract.Contacts.CONTENT_URI,
			new String[] {
				ContactsContract.Contacts._ID,
			}, null, null, null );
		while( cur.moveToNext() ) {
			Long id = cur.getLong(
				cur.getColumnIndex( ContactsContract.Contacts._ID ) );
			unadded_ids.add( id );
		}

		// build a mapping of the ids of raw contacts to the ids of their
		// aggregate contacts
		HashMap< Long, Long > raw_to_aggregate_ids =
			new HashMap< Long, Long >();
		cur = _activity.managedQuery( ContactsContract.RawContacts.CONTENT_URI,
			new String[] {
				ContactsContract.RawContacts._ID,
				ContactsContract.RawContacts.CONTACT_ID,
			}, ContactsContract.RawContacts.DELETED + " = 0", null, null );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong(
				cur.getColumnIndex( ContactsContract.RawContacts._ID ) );
			Long id = cur.getLong(
				cur.getColumnIndex( ContactsContract.RawContacts.CONTACT_ID ) );
			raw_to_aggregate_ids.put( raw_id, id );
		}

		// get structured names, primary ones first
		cur = _activity.managedQuery( ContactsContract.Data.CONTENT_URI,
			new String[] {
				ContactsContract.Data.RAW_CONTACT_ID,
				CommonDataKinds.StructuredName.DISPLAY_NAME,
			},
			ContactsContract.Data.MIMETYPE + " = '" +
				CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'",
			null, ContactsContract.Data.IS_PRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong( cur.getColumnIndex(
				ContactsContract.Data.RAW_CONTACT_ID ) );
			Long id = raw_to_aggregate_ids.get( raw_id );
			if( id != null )
			{
				String name = cur.getString( cur.getColumnIndex(
					CommonDataKinds.StructuredName.DISPLAY_NAME ) );

				// if this is a name for a contact for whom we have not added a
				// lookup, add a lookup for the contact id by name
				if( unadded_ids.contains( id ) ) {
					CacheIdentifier cache_identifier = CacheIdentifier.factory(
						CacheIdentifier.Type.NAME, name );
					if( cache_identifier != null ) {
						cache.addLookup( cache_identifier, id );
						unadded_ids.remove( id );
					}
				}
			}
		}

		// get contact organisations, primary ones first
		cur = _activity.managedQuery( ContactsContract.Data.CONTENT_URI,
			new String[] {
				ContactsContract.Data.RAW_CONTACT_ID,
				CommonDataKinds.Organization.COMPANY,
			},
			ContactsContract.Data.MIMETYPE + " = '" +
				CommonDataKinds.Organization.CONTENT_ITEM_TYPE + "'",
			null, ContactsContract.Data.IS_PRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong( cur.getColumnIndex(
				ContactsContract.Data.RAW_CONTACT_ID ) );
			Long id = raw_to_aggregate_ids.get( raw_id );
			if( id != null )
			{
				String organisation = cur.getString( cur.getColumnIndex(
					CommonDataKinds.Organization.COMPANY ) );

				// if this is an organisation name for a contact for whom we
				// have not added a lookup, add a lookup for the contact id
				// by organisation
				if( unadded_ids.contains( id ) ) {
					CacheIdentifier cache_identifier = CacheIdentifier.factory(
						CacheIdentifier.Type.ORGANISATION, organisation );
					if( cache_identifier != null ) {
						cache.addLookup( cache_identifier, id );
						unadded_ids.remove( id );
					}
				}

				// add associated data
				cache.addAssociatedOrganisation( id, organisation );
			}
		}

		// get all phone numbers, primary ones first
		cur = _activity.managedQuery( ContactsContract.Data.CONTENT_URI,
			new String[] {
				ContactsContract.Data.RAW_CONTACT_ID,
				CommonDataKinds.Phone.NUMBER,
			},
			ContactsContract.Data.MIMETYPE + " = '" +
				CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
			null, ContactsContract.Data.IS_PRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong( cur.getColumnIndex(
				ContactsContract.Data.RAW_CONTACT_ID ) );
			Long id = raw_to_aggregate_ids.get( raw_id );
			if( id != null )
			{
				String number = cur.getString( cur.getColumnIndex(
					CommonDataKinds.Phone.NUMBER ) );

				// if this is a number for a contact for whom we have not
				// added a lookup, add a lookup for the contact id by phone
				// number
				if( unadded_ids.contains( id ) ) {
					CacheIdentifier cache_identifier = CacheIdentifier.factory(
						CacheIdentifier.Type.PRIMARY_NUMBER, number );
					if( cache_identifier != null ) {
						cache.addLookup( cache_identifier, id );
						unadded_ids.remove( id );
					}
				}

				// add associated data
				cache.addAssociatedNumber( id, number );
			}
		}

		// get all email addresses, primary ones first
		cur = _activity.managedQuery( ContactsContract.Data.CONTENT_URI,
			new String[] {
				ContactsContract.Data.RAW_CONTACT_ID,
				CommonDataKinds.Email.DATA,
			},
			ContactsContract.Data.MIMETYPE + " = '" +
				CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'",
			null, ContactsContract.Data.IS_PRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong( cur.getColumnIndex(
				ContactsContract.Data.RAW_CONTACT_ID ) );
			Long id = raw_to_aggregate_ids.get( raw_id );
			if( id != null )
			{
				String email = cur.getString( cur.getColumnIndex(
					CommonDataKinds.Email.DATA ) );

				// if this is an email address for a contact for whom we have
				// not added a lookup, add a lookup for the contact id by email
				// address
				if( unadded_ids.contains( id ) ) {
					CacheIdentifier cache_identifier = CacheIdentifier.factory(
						CacheIdentifier.Type.PRIMARY_EMAIL, email );
					if( cache_identifier != null ) {
						cache.addLookup( cache_identifier, id );
						unadded_ids.remove( id );
					}
				}

				// add associated data
				cache.addAssociatedEmail( id, email );
			}
		}

		// get all postal addresses, primary ones first
		cur = _activity.managedQuery( ContactsContract.Data.CONTENT_URI,
			new String[] {
				ContactsContract.Data.RAW_CONTACT_ID,
				CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
			},
			ContactsContract.Data.MIMETYPE + " = '" +
				CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE + "'",
			null, ContactsContract.Data.IS_PRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong( cur.getColumnIndex(
				ContactsContract.Data.RAW_CONTACT_ID ) );
			Long id = raw_to_aggregate_ids.get( raw_id );
			if( id != null )
			{
				String address = cur.getString( cur.getColumnIndex(
					CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS ) );

				// add associated data
				cache.addAssociatedAddress( id, address );
			}
		}

		// get all notes
		cur = _activity.managedQuery( ContactsContract.Data.CONTENT_URI,
			new String[] {
				ContactsContract.Data.RAW_CONTACT_ID,
				CommonDataKinds.Note.NOTE,
			},
			ContactsContract.Data.MIMETYPE + " = '" +
				CommonDataKinds.Note.CONTENT_ITEM_TYPE + "'",
			null, null );
		while( cur.moveToNext() ) {
			Long raw_id = cur.getLong( cur.getColumnIndex(
				ContactsContract.Data.RAW_CONTACT_ID ) );
			Long id = raw_to_aggregate_ids.get( raw_id );
			if( id != null )
			{
				String note = cur.getString( cur.getColumnIndex(
					CommonDataKinds.Note.NOTE ) );

				// add associated data
				cache.addAssociatedNote( id, note );
			}
		}
	}

	@Override
	public void deleteContact( Long id )
	{
		Uri contact_uri = ContentUris.withAppendedId(
			ContactsContract.Contacts.CONTENT_URI, id );
		_activity.getContentResolver().delete( contact_uri, null, null );
	}

	@Override
	public Long addContact( String name ) throws ContactCreationException
	{
		// create raw contact
		ContentValues values = new ContentValues();
		Uri contact_uri = _activity.getContentResolver().insert(
			ContactsContract.RawContacts.CONTENT_URI, values);
		Long raw_id = ContentUris.parseId( contact_uri );
		if( raw_id == 0 ) throw new ContactCreationException();

		// add name data for this raw contact
		if( name != null ) {
			values.put( ContactsContract.Data.RAW_CONTACT_ID, raw_id );
			values.put( ContactsContract.Data.MIMETYPE,
				CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE );
			values.put( CommonDataKinds.StructuredName.DISPLAY_NAME, name );
			_activity.getContentResolver().insert(
				ContactsContract.Data.CONTENT_URI, values );
		}

		// find corresponding aggregate contact
		contact_uri = Uri.withAppendedPath(
			ContentUris.withAppendedId(
				ContactsContract.RawContacts.CONTENT_URI, raw_id ),
			ContactsContract.RawContacts.Entity.CONTENT_DIRECTORY );
		Cursor cur = _activity.managedQuery( contact_uri,
			new String[] {
				ContactsContract.RawContacts.CONTACT_ID,
			}, null, null, null );
		Long id = null;
		if( cur.moveToNext() )
			id = cur.getLong(
				cur.getColumnIndex( ContactsContract.RawContacts.CONTACT_ID ) );
		if( id == null || id == 0 )
		{
			// we didn't find an aggregate contact id, so try to clean up (by
			// deleting the raw contact we just created) before bailing
			contact_uri = ContentUris.withAppendedId(
				ContactsContract.RawContacts.CONTENT_URI, id );
			_activity.getContentResolver().delete( contact_uri, null, null );

			throw new ContactCreationException();
		}

		return id;
	}

	/**
	 * Obtain the raw contact id for the phone-only raw contact that is
	 * associated with the aggregate contact id.  One will be created if
	 * necessary.
	 * @param id the aggregate contact id
	 * @return the raw contact id
	 * @throws ContactCreationException
	 */
	Long obtainRawContact( Long id ) throws ContactCreationException
	{
		// attempt to lookup cached value
		Long raw_id = _aggregate_to_raw_ids.get( id );
		if( raw_id != null ) return raw_id;

		// find a corresponding raw contact that has no account name/type
		Cursor cur = _activity.managedQuery(
			ContactsContract.RawContacts.CONTENT_URI,
			new String[] {
				ContactsContract.RawContacts._ID,
				ContactsContract.RawContacts.ACCOUNT_NAME,
			},
			ContactsContract.RawContacts.DELETED + " = 0 AND " +
				ContactsContract.RawContacts.CONTACT_ID + " = ? AND " +
				"IFNULL( " + ContactsContract.RawContacts.ACCOUNT_NAME +
					", '' ) = '' AND " +
				"IFNULL( " + ContactsContract.RawContacts.ACCOUNT_TYPE +
					", '' ) = ''",
			new String[] {
				String.valueOf( id ),
			}, null );
		if( cur.moveToNext() )
			raw_id = cur.getLong(
				cur.getColumnIndex( ContactsContract.RawContacts._ID ) );

		// if one wasn't found, we'll need to create one
		if( raw_id == null ) {
			ContentValues values = new ContentValues();
			Uri contact_uri = _activity.getContentResolver().insert(
				ContactsContract.RawContacts.CONTENT_URI, values);
			raw_id = ContentUris.parseId( contact_uri );
			if( raw_id == 0 ) throw new ContactCreationException();
		}

		// save value in our cache
		_aggregate_to_raw_ids.put( id, raw_id );
		return raw_id;
	}

	private int convertTypeToBackendType( Class< ? > cls, int type )
		throws ContactCreationException
	{
		if( cls == CommonDataKinds.Phone.class )
		{
			switch( type )
			{
			case ContactData.TYPE_HOME:
				return CommonDataKinds.Phone.TYPE_HOME;
			case ContactData.TYPE_WORK:
				return CommonDataKinds.Phone.TYPE_WORK;
			case ContactData.TYPE_MOBILE:
				return CommonDataKinds.Phone.TYPE_MOBILE;
			case ContactData.TYPE_FAX_HOME:
				return CommonDataKinds.Phone.TYPE_FAX_HOME;
			case ContactData.TYPE_FAX_WORK:
				return CommonDataKinds.Phone.TYPE_FAX_WORK;
			case ContactData.TYPE_PAGER:
				return CommonDataKinds.Phone.TYPE_PAGER;
			}
		}
		else if( cls == CommonDataKinds.Email.class )
		{
			switch( type )
			{
			case ContactData.TYPE_HOME:
				return CommonDataKinds.Email.TYPE_HOME;
			case ContactData.TYPE_WORK:
				return CommonDataKinds.Email.TYPE_WORK;
			}
		}
		else if( cls == CommonDataKinds.StructuredPostal.class )
		{
			switch( type )
			{
			case ContactData.TYPE_HOME:
				return CommonDataKinds.StructuredPostal.TYPE_HOME;
			case ContactData.TYPE_WORK:
				return CommonDataKinds.StructuredPostal.TYPE_WORK;
			}
		}

		// still here?
		throw new ContactCreationException();
	}

	@Override
	public void addContactPhone( Long id, String number,
		ContactData.PreferredDetail data ) throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( ContactsContract.Data.RAW_CONTACT_ID,
			obtainRawContact( id ) );
		values.put( ContactsContract.Data.MIMETYPE,
			CommonDataKinds.Phone.CONTENT_ITEM_TYPE );
		values.put( CommonDataKinds.Phone.TYPE,
			convertTypeToBackendType( CommonDataKinds.Phone.class,
				data.getType() ) );
		values.put( CommonDataKinds.Phone.NUMBER, number );
		if( data.isPreferred() )
			values.put( CommonDataKinds.Phone.IS_PRIMARY, 1 );

		_activity.getContentResolver().insert(
			ContactsContract.Data.CONTENT_URI, values );
	}

	@Override
	public void addContactEmail( Long id, String email,
		ContactData.PreferredDetail data ) throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( ContactsContract.Data.RAW_CONTACT_ID,
			obtainRawContact( id ) );
		values.put( ContactsContract.Data.MIMETYPE,
			CommonDataKinds.Email.CONTENT_ITEM_TYPE );
		values.put( CommonDataKinds.Email.TYPE,
			convertTypeToBackendType( CommonDataKinds.Email.class,
				data.getType() ) );
		values.put( CommonDataKinds.Email.DATA, email );
		if( data.isPreferred() )
			values.put( CommonDataKinds.Email.IS_PRIMARY, 1 );

		_activity.getContentResolver().insert(
			ContactsContract.Data.CONTENT_URI, values );
	}

	@Override
	public void addContactAddresses( Long id, String address,
		ContactData.TypeDetail data ) throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( ContactsContract.Data.RAW_CONTACT_ID,
			obtainRawContact( id ) );
		values.put( ContactsContract.Data.MIMETYPE,
			CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE );
		values.put( CommonDataKinds.StructuredPostal.TYPE,
			convertTypeToBackendType( CommonDataKinds.StructuredPostal.class,
				data.getType() ) );
		values.put(
			CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, address );

		_activity.getContentResolver().insert(
			ContactsContract.Data.CONTENT_URI, values );
	}

	@Override
	public void addContactOrganisation( Long id, String organisation,
		ContactData.ExtraDetail data ) throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( ContactsContract.Data.RAW_CONTACT_ID,
			obtainRawContact( id ) );
		values.put( ContactsContract.Data.MIMETYPE,
			CommonDataKinds.Organization.CONTENT_ITEM_TYPE );
		values.put( CommonDataKinds.Organization.TYPE,
			CommonDataKinds.Organization.TYPE_WORK );
		values.put(
			CommonDataKinds.Organization.COMPANY, organisation );
		if( data.getExtra() != null )
			values.put( CommonDataKinds.Organization.TITLE, data.getExtra() );

		_activity.getContentResolver().insert(
			ContactsContract.Data.CONTENT_URI, values );
	}

	@Override
	public void addContactNote( Long id, String note )
		throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( ContactsContract.Data.RAW_CONTACT_ID,
			obtainRawContact( id ) );
		values.put( ContactsContract.Data.MIMETYPE,
			CommonDataKinds.Note.CONTENT_ITEM_TYPE );
		values.put(
			CommonDataKinds.Note.NOTE, note );

		_activity.getContentResolver().insert(
			ContactsContract.Data.CONTENT_URI, values );
	}

}