/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
/*
 * 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 java.util.Iterator;

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

@SuppressWarnings( "deprecation" )
public class ContactsBackend implements Backend
{
	private Activity _activity = null;

	ContactsBackend( Activity activity )
	{
		_activity = activity;
	}

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

		// set of contact ids that we have not yet added
		HashSet< Long > unadded_ids = new HashSet< Long >();

		// notes
		HashMap< Long, String > notes = new HashMap< Long, String >();

		// get all contacts
		cur = _activity.getContentResolver().query(
			Contacts.People.CONTENT_URI,
			new String[] {
				Contacts.People._ID,
				Contacts.People.NAME,
				Contacts.People.NOTES,
			}, null, null, null );
		while( cur.moveToNext() ) {
			Long id = cur.getLong(
				cur.getColumnIndex( Contacts.People._ID ) );
			String name = cur.getString(
					cur.getColumnIndex( Contacts.People.NAME ) );
			String note = cur.getString(
					cur.getColumnIndex( Contacts.People.NOTES ) );

			// if we can, add a lookup for the contact id by name
			CacheIdentifier cache_identifier = CacheIdentifier.factory(
				CacheIdentifier.Type.NAME, name );
			if( cache_identifier != null ) {
				cache.addLookup( cache_identifier, id );

				// add any associated notes (this would get done at the end but,
				// since it is most common that contacts are identified by name,
				// it is worth doing a special case here
				cache.addAssociatedNote( id, note );
			}
			else
			{
				// record that a lookup for this contact's id still needs to be
				// added by some other means
				unadded_ids.add( id );

				// store this contact's notes, so that they can be added to the
				// cache at the end, after this contact has been added (by
				// whatever identifying means)
				if( note != null && note.length() > 0 )
					notes.put( id, note );
			}
		}
		cur.close();

		// get contact organisations, primary ones first
		cur = _activity.getContentResolver().query(
			Contacts.Organizations.CONTENT_URI,
			new String[] {
				Contacts.Phones.PERSON_ID,
				Contacts.Organizations.COMPANY,
			}, null, null, Contacts.Organizations.ISPRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long id = cur.getLong( cur.getColumnIndex(
				Contacts.Organizations.PERSON_ID ) );
			String organisation = cur.getString(
				cur.getColumnIndex( Contacts.Organizations.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 );
		}
		cur.close();

		// get all phone numbers, primary ones first
		cur = _activity.getContentResolver().query(
			Contacts.Phones.CONTENT_URI,
			new String[] {
				Contacts.Phones.PERSON_ID,
				Contacts.Phones.NUMBER,
			}, null, null, Contacts.Phones.ISPRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long id = cur.getLong(
				cur.getColumnIndex( Contacts.Phones.PERSON_ID ) );
			String number = cur.getString(
				cur.getColumnIndex( Contacts.Phones.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 );
		}
		cur.close();

		// now get all email addresses, primary ones first, and postal addresses
		cur = _activity.getContentResolver().query(
			Contacts.ContactMethods.CONTENT_URI,
			new String[] {
				Contacts.ContactMethods.PERSON_ID,
				Contacts.ContactMethods.DATA,
				Contacts.ContactMethods.KIND,
			}, Contacts.ContactMethods.KIND + " IN( ?, ? )",
			new String[] {
				"" + Contacts.KIND_EMAIL,
				"" + Contacts.KIND_POSTAL,
			}, Contacts.ContactMethods.ISPRIMARY + " DESC" );
		while( cur.moveToNext() ) {
			Long id = cur.getLong(
				cur.getColumnIndex( Contacts.ContactMethods.PERSON_ID ) );
			int kind = cur.getInt(
				cur.getColumnIndex( Contacts.ContactMethods.KIND ) );
			if( kind == Contacts.KIND_EMAIL )
			{
				String email = cur.getString(
					cur.getColumnIndex( Contacts.ContactMethods.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 );
			}
			else if( kind == Contacts.KIND_POSTAL )
			{
				String address = cur.getString(
					cur.getColumnIndex( Contacts.ContactMethods.DATA ) );

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

		// finally, add the notes that we stored earlier (we have to add these
		// at the end because we can't be sure which piece of contact data will
		// cause the contact to be added to the cache
		Iterator< Long > i = notes.keySet().iterator();
		while( i.hasNext() ) {
			Long id = i.next();
			cache.addAssociatedNote( id, notes.get( id ) );
		}
	}

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

	@Override
	public Long addContact( String name ) throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		if( name != null )
			values.put( Contacts.People.NAME, name );
		Uri contact_uri = _activity.getContentResolver().insert(
			Contacts.People.CONTENT_URI, values );
		Long id = ContentUris.parseId( contact_uri );
		if( id == 0 )
			throw new ContactCreationException();

		// try to add them to the "My Contacts" group
		try {
			Contacts.People.addToMyContactsGroup(
				_activity.getContentResolver(), id );
		}
		catch( IllegalStateException e ) {
			// ignore any failure
		}

		return id;
	}

	private int convertTypeToBackendType( Class< ? > cls, int type )
		throws ContactCreationException
	{
		if( cls == Contacts.Phones.class )
		{
			switch( type )
			{
			case ContactData.TYPE_HOME:
				return Contacts.PhonesColumns.TYPE_HOME;
			case ContactData.TYPE_WORK:
				return Contacts.PhonesColumns.TYPE_WORK;
			case ContactData.TYPE_MOBILE:
				return Contacts.PhonesColumns.TYPE_MOBILE;
			case ContactData.TYPE_FAX_HOME:
				return Contacts.PhonesColumns.TYPE_FAX_HOME;
			case ContactData.TYPE_FAX_WORK:
				return Contacts.PhonesColumns.TYPE_FAX_WORK;
			case ContactData.TYPE_PAGER:
				return Contacts.PhonesColumns.TYPE_PAGER;
			}
		}
		else if( cls == Contacts.ContactMethods.class )
		{
			switch( type )
			{
			case ContactData.TYPE_HOME:
				return Contacts.ContactMethodsColumns.TYPE_HOME;
			case ContactData.TYPE_WORK:
				return Contacts.ContactMethodsColumns.TYPE_WORK;
			}
		}

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

	@Override
	public void addContactPhone( Long id, String number,
		ContactData.PreferredDetail data ) throws ContactCreationException
	{
		Uri contact_phones_uri = Uri.withAppendedPath(
			ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
			Contacts.People.Phones.CONTENT_DIRECTORY );

		ContentValues values = new ContentValues();
		values.put( Contacts.Phones.TYPE,
			convertTypeToBackendType( Contacts.Phones.class,
				data.getType() ) );
		values.put( Contacts.Phones.NUMBER, number );
		if( data.isPreferred() )
			values.put( Contacts.Phones.ISPRIMARY, 1 );

		_activity.getContentResolver().insert( contact_phones_uri, values );
	}

	@Override
	public void addContactEmail( Long id, String email,
		ContactData.PreferredDetail data ) throws ContactCreationException
	{
		Uri contact_contact_methods_uri = Uri.withAppendedPath(
			ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
			Contacts.People.ContactMethods.CONTENT_DIRECTORY );

		ContentValues values = new ContentValues();
		values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
		values.put( Contacts.ContactMethods.DATA, email );
		values.put( Contacts.ContactMethods.TYPE,
			convertTypeToBackendType( Contacts.ContactMethods.class,
				data.getType() ) );
		if( data.isPreferred() )
			values.put( Contacts.ContactMethods.ISPRIMARY, 1 );

		_activity.getContentResolver().insert( contact_contact_methods_uri,
			values );
	}

	@Override
	public void addContactAddresses( Long id, String address,
		ContactData.TypeDetail data ) throws ContactCreationException
	{
		Uri contact_contact_methods_uri = Uri.withAppendedPath(
			ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
			Contacts.People.ContactMethods.CONTENT_DIRECTORY );

		ContentValues values = new ContentValues();
		values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
		values.put( Contacts.ContactMethods.DATA, address );
		values.put( Contacts.ContactMethods.TYPE,
			convertTypeToBackendType( Contacts.ContactMethods.class,
				data.getType() ) );

		_activity.getContentResolver().insert( contact_contact_methods_uri,
			values );
	}

	@Override
	public void addContactOrganisation( Long id, String organisation,
		ContactData.ExtraDetail data ) throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( Contacts.Organizations.PERSON_ID, id );
		values.put( Contacts.Organizations.COMPANY, organisation );
		values.put( Contacts.ContactMethods.TYPE,
			Contacts.OrganizationColumns.TYPE_WORK );
		if( data.getExtra() != null )
			values.put( Contacts.Organizations.TITLE, data.getExtra() );

		_activity.getContentResolver().insert(
			Contacts.Organizations.CONTENT_URI, values );
	}

	@Override
	public void addContactNote( Long id, String note )
		throws ContactCreationException
	{
		ContentValues values = new ContentValues();
		values.put( Contacts.People.NOTES, note );
		_activity.getContentResolver().update(
			ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
			values, null, null );
	}

}