/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/am/ed/importcontacts/Importer.java

  • Committer: edam
  • Date: 2012-12-19 17:51:35 UTC
  • Revision ID: tim@ed.am-20121219175135-1cpuafp76jg1ib1p
added preliminary (buggy) ContactsContract backend

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * Importer.java
3
3
 *
4
 
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
 
4
 * Copyright (C) 2009 to 2012 Tim Marston <tim@ed.am>
5
5
 *
6
6
 * This file is part of the Import Contacts program (hereafter referred
7
7
 * to as "this program"). For more information, see
8
 
 * http://www.waxworlds.org/edam/software/android/import-contacts
 
8
 * http://ed.am/dev/android/import-contacts
9
9
 *
10
10
 * This program is free software: you can redistribute it and/or modify
11
11
 * it under the terms of the GNU General Public License as published by
21
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
22
 */
23
23
 
24
 
package org.waxworlds.edam.importcontacts;
 
24
package am.ed.importcontacts;
25
25
 
 
26
import java.util.Arrays;
26
27
import java.util.HashMap;
 
28
import java.util.HashSet;
27
29
import java.util.Iterator;
 
30
import java.util.Locale;
28
31
import java.util.Set;
29
32
import java.util.regex.Matcher;
30
33
import java.util.regex.Pattern;
31
34
 
32
 
import android.content.ContentUris;
33
 
import android.content.ContentValues;
 
35
import am.ed.importcontacts.Backend.ContactCreationException;
34
36
import android.content.SharedPreferences;
35
 
import android.net.Uri;
36
37
import android.os.Message;
37
 
import android.provider.Contacts;
38
 
 
39
38
 
40
39
public class Importer extends Thread
41
40
{
50
49
 
51
50
        private Doit _doit;
52
51
        private int _response;
53
 
        private int _responseExtra;
54
 
        private int _mergeSetting;
55
 
        private int _lastMergeDecision;
 
52
        private int _response_extra;
 
53
        private int _merge_setting;
 
54
        private int _last_merge_decision;
56
55
        private boolean _abort = false;
57
 
        private boolean _isFinished = false;
58
 
        private ContactsCache _contactsCache = null;
 
56
        private boolean _is_finished = false;
 
57
        private ContactsCache _contacts_cache = null;
 
58
        private Backend _backend = null;
59
59
 
 
60
        /**
 
61
         * Data about a contact
 
62
         */
60
63
        public class ContactData
61
64
        {
62
 
                class PhoneData
63
 
                {
64
 
                        public String _number;
65
 
                        public int _type;
66
 
                        public boolean _isPreferred;
67
 
 
68
 
                        public PhoneData( String number, int type, boolean isPreferred ) {
69
 
                                _number = number;
70
 
                                _type = type;
71
 
                                _isPreferred = isPreferred;
72
 
                        }
73
 
 
74
 
                        public String getNumber() {
75
 
                                return _number;
76
 
                        }
77
 
 
78
 
                        public int getType() {
79
 
                                return _type;
80
 
                        }
81
 
 
82
 
                        public boolean isPreferred() {
83
 
                                return _isPreferred;
84
 
                        }
85
 
                }
86
 
 
87
 
                class EmailData
88
 
                {
89
 
                        private String _email;
90
 
                        public int _type;
91
 
                        private boolean _isPreferred;
92
 
 
93
 
                        public EmailData( String email, int type, boolean isPreferred ) {
94
 
                                _email = email;
95
 
                                _type = type;
96
 
                                _isPreferred = isPreferred;
97
 
                        }
98
 
 
99
 
                        public String getAddress() {
100
 
                                return _email;
101
 
                        }
102
 
 
103
 
                        public int getType() {
104
 
                                return _type;
105
 
                        }
106
 
 
107
 
                        public boolean isPreferred() {
108
 
                                return _isPreferred;
109
 
                        }
110
 
                }
111
 
 
112
 
                class AddressData
113
 
                {
114
 
                        private String _address;
115
 
                        public int _type;
116
 
 
117
 
                        public AddressData( String address, int type ) {
118
 
                                _address = address;
119
 
                                _type = type;
120
 
                        }
121
 
 
122
 
                        public String getAddress() {
123
 
                                return _address;
124
 
                        }
125
 
 
126
 
                        public int getType() {
127
 
                                return _type;
128
 
                        }
129
 
                }
130
 
 
131
 
                public String _name = null;
132
 
                public HashMap< String, PhoneData > _phones = null;
133
 
                public HashMap< String, EmailData > _emails = null;
134
 
                public HashMap< String, AddressData > _addresses = null;
 
65
                public final static int TYPE_HOME = 0;
 
66
                public final static int TYPE_WORK = 1;
 
67
                public final static int TYPE_MOBILE = 2;        // only used with phones
 
68
                public final static int TYPE_FAX_HOME = 3;      // only used with phones
 
69
                public final static int TYPE_FAX_WORK = 4;      // only used with phones
 
70
                public final static int TYPE_PAGER = 5;         // only used with phones
 
71
 
 
72
                class TypeDetail
 
73
                {
 
74
                        protected int _type;
 
75
 
 
76
                        public TypeDetail( int type )
 
77
                        {
 
78
                                _type = type;
 
79
                        }
 
80
 
 
81
                        public int getType()
 
82
                        {
 
83
                                return _type;
 
84
                        }
 
85
                }
 
86
 
 
87
                class PreferredDetail extends TypeDetail
 
88
                {
 
89
                        protected boolean _is_preferred;
 
90
 
 
91
                        public PreferredDetail( int type, boolean is_preferred )
 
92
                        {
 
93
                                super( type );
 
94
                                _is_preferred = is_preferred;
 
95
                        }
 
96
 
 
97
                        public boolean isPreferred()
 
98
                        {
 
99
                                return _is_preferred;
 
100
                        }
 
101
                }
 
102
 
 
103
                class ExtraDetail extends PreferredDetail
 
104
                {
 
105
                        protected String _extra;
 
106
 
 
107
                        public ExtraDetail( int type, boolean is_preferred, String extra )
 
108
                        {
 
109
                                super( type, is_preferred );
 
110
 
 
111
                                if( extra != null ) extra = extra.trim();
 
112
                                _extra = extra;
 
113
                        }
 
114
 
 
115
                        public String getExtra()
 
116
                        {
 
117
                                return _extra;
 
118
                        }
 
119
 
 
120
                        public void setExtra( String extra )
 
121
                        {
 
122
                                if( extra != null ) extra = extra.trim();
 
123
                                _extra = extra;
 
124
                        }
 
125
                }
 
126
 
 
127
                @SuppressWarnings("serial")
 
128
                protected class ContactNotIdentifiableException extends Exception
 
129
                {
 
130
                }
 
131
 
 
132
                protected String _name = null;
 
133
                protected String _primary_organisation = null;
 
134
                protected boolean _primary_organisation_is_preferred;
 
135
                protected String _primary_number = null;
 
136
                protected int _primary_number_type;
 
137
                protected boolean _primary_number_is_preferred;
 
138
                protected String _primary_email = null;
 
139
                protected boolean _primary_email_is_preferred;
 
140
                protected HashMap< String, ExtraDetail > _organisations = null;
 
141
                protected HashMap< String, PreferredDetail > _numbers = null;
 
142
                protected HashMap< String, PreferredDetail > _emails = null;
 
143
                protected HashMap< String, TypeDetail > _addresses = null;
 
144
 
 
145
                private ContactsCache.CacheIdentifier _cache_identifier = null;
135
146
 
136
147
                protected void setName( String name )
137
148
                {
138
149
                        _name = name;
139
150
                }
140
151
 
 
152
                public boolean hasName()
 
153
                {
 
154
                        return _name != null;
 
155
                }
 
156
 
141
157
                public String getName()
142
158
                {
143
159
                        return _name;
144
160
                }
145
161
 
146
 
                protected void addPhone( String number, int type, boolean isPreferred )
147
 
                {
148
 
                        if( _phones == null ) _phones = new HashMap< String, PhoneData >();
149
 
                        if( !_phones.containsKey( number ) )
150
 
                                _phones.put( number,
151
 
                                        new PhoneData( number, type, isPreferred ) );
152
 
                }
153
 
 
154
 
                protected void addEmail( String email, int type, boolean isPreferred )
155
 
                {
156
 
                        if( _emails == null ) _emails = new HashMap< String, EmailData >();
 
162
                protected void addOrganisation( String organisation, String title,
 
163
                        boolean is_preferred )
 
164
                {
 
165
                        organisation = organisation.trim();
 
166
                        if( organisation.length() <= 0 )
 
167
                        {
 
168
                                // TODO: warn that an imported organisation is being ignored
 
169
                                return;
 
170
                        }
 
171
 
 
172
                        if( title != null ) {
 
173
                                title = title.trim();
 
174
                                if( title.length() <= 0 ) title = null;
 
175
                        }
 
176
 
 
177
                        // add the organisation, as non-preferred (we prefer only one
 
178
                        // organisation in finalise() after they're all imported)
 
179
                        if( _organisations == null )
 
180
                                _organisations = new HashMap< String, ExtraDetail >();
 
181
                        if( !_organisations.containsKey( organisation ) )
 
182
                                _organisations.put( organisation,
 
183
                                        new ExtraDetail( 0, false, title ) );
 
184
 
 
185
                        // if this is the first organisation added, or it's a preferred
 
186
                        // organisation and the current primary organisation isn't, then
 
187
                        // record this as the primary organisation.
 
188
                        if( _primary_organisation == null ||
 
189
                                ( is_preferred && !_primary_organisation_is_preferred ) )
 
190
                        {
 
191
                                _primary_organisation = organisation;
 
192
                                _primary_organisation_is_preferred = is_preferred;
 
193
                        }
 
194
                }
 
195
 
 
196
                public boolean hasOrganisations()
 
197
                {
 
198
                        return _organisations != null && _organisations.size() > 0;
 
199
                }
 
200
 
 
201
                public HashMap< String, ExtraDetail > getOrganisations()
 
202
                {
 
203
                        return _organisations;
 
204
                }
 
205
 
 
206
                public boolean hasPrimaryOrganisation()
 
207
                {
 
208
                        return _primary_organisation != null;
 
209
                }
 
210
 
 
211
                public String getPrimaryOrganisation()
 
212
                {
 
213
                        return _primary_organisation;
 
214
                }
 
215
 
 
216
                protected void addNumber( String number, int type,
 
217
                        boolean is_preferred )
 
218
                {
 
219
                        number = sanitisePhoneNumber( number );
 
220
                        if( number == null )
 
221
                        {
 
222
                                // TODO: warn that an imported phone number is being ignored
 
223
                                return;
 
224
                        }
 
225
 
 
226
                        // add the number, as non-preferred (we prefer only one number
 
227
                        // in finalise() after they're all imported)
 
228
                        if( _numbers == null )
 
229
                                _numbers = new HashMap< String, PreferredDetail >();
 
230
                        if( !_numbers.containsKey( number ) )
 
231
                                _numbers.put( number,
 
232
                                        new PreferredDetail( type, false ) );
 
233
 
 
234
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
 
235
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
 
236
 
 
237
                        // if this is the first number added, or it's a preferred number
 
238
                        // and the current primary number isn't, or this number is on equal
 
239
                        // standing with the primary number in terms of preference and it is
 
240
                        // a voice number and the primary number isn't, then record this as
 
241
                        // the primary number.
 
242
                        if( _primary_number == null ||
 
243
                                ( is_preferred && !_primary_number_is_preferred ) ||
 
244
                                ( is_preferred == _primary_number_is_preferred &&
 
245
                                        !non_voice_types.contains( type ) &&
 
246
                                        non_voice_types.contains( _primary_number_type ) ) )
 
247
                        {
 
248
                                _primary_number = number;
 
249
                                _primary_number_type = type;
 
250
                                _primary_number_is_preferred = is_preferred;
 
251
                        }
 
252
                }
 
253
 
 
254
                public boolean hasNumbers()
 
255
                {
 
256
                        return _numbers != null && _numbers.size() > 0;
 
257
                }
 
258
 
 
259
                public HashMap< String, PreferredDetail > getNumbers()
 
260
                {
 
261
                        return _numbers;
 
262
                }
 
263
 
 
264
                public boolean hasPrimaryNumber()
 
265
                {
 
266
                        return _primary_number != null;
 
267
                }
 
268
 
 
269
                public String getPrimaryNumber()
 
270
                {
 
271
                        return _primary_number;
 
272
                }
 
273
 
 
274
                protected void addEmail( String email, int type, boolean is_preferred )
 
275
                {
 
276
 
 
277
                        email = sanitisesEmailAddress( email );
 
278
                        if( email == null )
 
279
                        {
 
280
                                // TODO: warn that an imported email address is being ignored
 
281
                                return;
 
282
                        }
 
283
 
 
284
                        // add the email, as non-preferred (we prefer only one email in
 
285
                        // finalise() after they're all imported)
 
286
                        if( _emails == null )
 
287
                                _emails = new HashMap< String, PreferredDetail >();
157
288
                        if( !_emails.containsKey( email ) )
158
 
                                _emails.put( email, new EmailData( email, type, isPreferred ) );
 
289
                                _emails.put( email, new PreferredDetail( type, false ) );
 
290
 
 
291
                        // if this is the first email added, or it's a preferred email and
 
292
                        // the current primary organisation isn't, then record this as the
 
293
                        // primary email.
 
294
                        if( _primary_email == null ||
 
295
                                ( is_preferred && !_primary_email_is_preferred ) )
 
296
                        {
 
297
                                _primary_email = email;
 
298
                                _primary_email_is_preferred = is_preferred;
 
299
                        }
 
300
                }
 
301
 
 
302
                public boolean hasEmails()
 
303
                {
 
304
                        return _emails != null && _emails.size() > 0;
 
305
                }
 
306
 
 
307
                public HashMap< String, PreferredDetail > getEmails()
 
308
                {
 
309
                        return _emails;
 
310
                }
 
311
 
 
312
                public boolean hasPrimaryEmail()
 
313
                {
 
314
                        return _primary_email != null;
 
315
                }
 
316
 
 
317
                public String getPrimaryEmail()
 
318
                {
 
319
                        return _primary_email;
159
320
                }
160
321
 
161
322
                protected void addAddress( String address, int type )
162
323
                {
 
324
                        address = address.trim();
 
325
                        if( address.length() <= 0 )
 
326
                        {
 
327
                                // TODO: warn that an imported address is being ignored
 
328
                                return;
 
329
                        }
 
330
 
163
331
                        if( _addresses == null ) _addresses =
164
 
                                new HashMap< String, AddressData >();
 
332
                                new HashMap< String, TypeDetail >();
165
333
                        if( !_addresses.containsKey( address ) )
166
 
                                _addresses.put( address, new AddressData( address, type ) );
 
334
                                _addresses.put( address, new TypeDetail( type ) );
 
335
                }
 
336
 
 
337
                public boolean hasAddresses()
 
338
                {
 
339
                        return _addresses != null && _addresses.size() > 0;
 
340
                }
 
341
 
 
342
                public HashMap< String, TypeDetail > getAddresses()
 
343
                {
 
344
                        return _addresses;
 
345
                }
 
346
 
 
347
                protected void finalise()
 
348
                        throws ContactNotIdentifiableException
 
349
                {
 
350
                        // ensure that if there is a primary number, it is preferred so
 
351
                        // that there is always one preferred number. Android will assign
 
352
                        // preference to one anyway so we might as well decide one sensibly.
 
353
                        if( _primary_number != null ) {
 
354
                                PreferredDetail data = _numbers.get( _primary_number );
 
355
                                _numbers.put( _primary_number,
 
356
                                        new PreferredDetail( data.getType(), true ) );
 
357
                        }
 
358
 
 
359
                        // do the same for the primary email
 
360
                        if( _primary_email != null ) {
 
361
                                PreferredDetail data = _emails.get( _primary_email );
 
362
                                _emails.put( _primary_email,
 
363
                                        new PreferredDetail( data.getType(), true ) );
 
364
                        }
 
365
 
 
366
                        // do the same for the primary organisation
 
367
                        if( _primary_organisation != null ) {
 
368
                                ExtraDetail data = _organisations.get( _primary_organisation );
 
369
                                _organisations.put( _primary_organisation,
 
370
                                        new ExtraDetail( 0, true, data.getExtra() ) );
 
371
                        }
 
372
 
 
373
                        // create a cache identifier from this contact data, which can be
 
374
                        // used to look-up an existing contact
 
375
                        _cache_identifier = ContactsCache.createIdentifier( this );
 
376
                        if( _cache_identifier == null )
 
377
                                throw new ContactNotIdentifiableException();
 
378
                }
 
379
 
 
380
                public ContactsCache.CacheIdentifier getCacheIdentifier()
 
381
                {
 
382
                        return _cache_identifier;
 
383
                }
 
384
 
 
385
                private String sanitisePhoneNumber( String number )
 
386
                {
 
387
                        number = number.trim();
 
388
                        Pattern p = Pattern.compile( "^[-\\(\\) \\+0-9#*]+" );
 
389
                        Matcher m = p.matcher( number );
 
390
                        if( m.lookingAt() ) return m.group( 0 );
 
391
                        return null;
 
392
                }
 
393
 
 
394
                private String sanitisesEmailAddress( String email )
 
395
                {
 
396
                        email = email.trim();
 
397
                        Pattern p = Pattern.compile(
 
398
                                "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
 
399
                        Matcher m = p.matcher( email );
 
400
                        if( m.matches() ) {
 
401
                                String[] bits = email.split( "@" );
 
402
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase( Locale.US );
 
403
                        }
 
404
                        return null;
167
405
                }
168
406
        }
169
407
 
175
413
                _doit = doit;
176
414
 
177
415
                SharedPreferences prefs = getSharedPreferences();
178
 
                _mergeSetting = prefs.getInt( "merge_setting", Doit.ACTION_PROMPT );
 
416
                _merge_setting = prefs.getInt( "merge_setting", Doit.ACTION_PROMPT );
179
417
        }
180
418
 
181
419
        @Override
186
424
                        // update UI
187
425
                        setProgressMessage( R.string.doit_caching );
188
426
 
189
 
                        // build a cache of existing contacts
190
 
                        _contactsCache = new ContactsCache();
191
 
                        _contactsCache.buildCache( _doit );
 
427
                        // create the appropriate backend
 
428
                        if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
 
429
                                _backend = new ContactsContractBackend( _doit );
 
430
                        else
 
431
                                _backend = new ContactsBackend( _doit );
 
432
 
 
433
                        // create a cache of existing contacts and populate it
 
434
                        _contacts_cache = new ContactsCache();
 
435
                        _backend.populateCache( _contacts_cache );
192
436
 
193
437
                        // do the import
194
438
                        onImport();
205
449
 
206
450
        synchronized private void setIsFinished()
207
451
        {
208
 
                _isFinished = true;
 
452
                _is_finished = true;
209
453
        }
210
454
 
211
455
        protected void onImport() throws AbortImportException
222
466
                wake( response, RESPONSEEXTRA_NONE );
223
467
        }
224
468
 
225
 
        synchronized public void wake( int response, int responseExtra )
 
469
        synchronized public void wake( int response, int response_extra )
226
470
        {
227
471
                _response = response;
228
 
                _responseExtra = responseExtra;
 
472
                _response_extra = response_extra;
229
473
                notify();
230
474
        }
231
475
 
232
476
        synchronized public boolean setAbort()
233
477
        {
234
 
                if( !_isFinished && !_abort ) {
 
478
                if( !_is_finished && !_abort ) {
235
479
                        _abort = true;
236
480
                        notify();
237
481
                        return true;
315
559
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
316
560
        }
317
561
 
318
 
        protected void setProgressMax( int maxProgress )
 
562
        protected void setProgressMax( int max_progress )
319
563
                        throws AbortImportException
320
564
        {
321
565
                checkAbort();
322
566
                _doit._handler.sendMessage( Message.obtain(
323
567
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
324
 
                        new Integer( maxProgress ) ) );
 
568
                        Integer.valueOf( max_progress ) ) );
325
569
        }
326
570
 
327
 
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
 
571
        protected void setTmpProgress( int tmp_progress )
 
572
                throws AbortImportException
328
573
        {
329
574
                checkAbort();
330
575
                _doit._handler.sendMessage( Message.obtain(
331
576
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
332
 
                        new Integer( tmpProgress ) ) );
 
577
                        Integer.valueOf( tmp_progress ) ) );
333
578
        }
334
579
 
335
580
        protected void setProgress( int progress ) throws AbortImportException
337
582
                checkAbort();
338
583
                _doit._handler.sendMessage( Message.obtain(
339
584
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
340
 
                        new Integer( progress ) ) );
 
585
                        Integer.valueOf( progress ) ) );
341
586
        }
342
587
 
343
588
        protected void finish( int action ) throws AbortImportException
361
606
                return _doit.getText( res );
362
607
        }
363
608
 
364
 
        protected boolean isImportRequired( String name )
365
 
                        throws AbortImportException
366
 
        {
367
 
                checkAbort();
368
 
                return isImportRequired( name, _mergeSetting );
369
 
        }
370
 
 
371
 
        synchronized private boolean isImportRequired( String name,
372
 
                        int mergeSetting ) throws AbortImportException
373
 
        {
374
 
                _lastMergeDecision = mergeSetting;
 
609
        /**
 
610
         * Should we skip a contact, given whether it exists or not and the current
 
611
         * merge setting?  This routine handles throwing up a prompt, if required.
 
612
         * @param contact_detail the display name of the contact
 
613
         * @param exists true if this contact matches one in the cache
 
614
         * @param merge_setting the merge setting to use
 
615
         * @return true if the contact should be skipped outright
 
616
         * @throws AbortImportException
 
617
         */
 
618
        synchronized private boolean shouldWeSkipContact( String contact_detail,
 
619
                boolean exists, int merge_setting ) throws AbortImportException
 
620
        {
 
621
                _last_merge_decision = merge_setting;
375
622
 
376
623
                // handle special cases
377
 
                switch( mergeSetting )
 
624
                switch( merge_setting )
378
625
                {
379
626
                case Doit.ACTION_KEEP:
380
 
                        // if we keep contacts on duplicate, we better check for one
381
 
                        return !_contactsCache.exists( name );
 
627
                        // if we are skipping on a duplicate, check for one
 
628
                        return exists;
382
629
 
383
630
                case Doit.ACTION_PROMPT:
384
 
                        // if we are prompting on duplicate, we better check for one
385
 
                        if( !_contactsCache.exists( name ) )
386
 
                                return true;
 
631
                        // if we are prompting on duplicate, then we can say that we won't
 
632
                        // skip if there isn't one
 
633
                        if( !exists ) return false;
387
634
 
388
 
                        // ok, it exists, so do prompt
389
 
                        _doit._handler.sendMessage( Message.obtain(
390
 
                                _doit._handler, Doit.MESSAGE_MERGEPROMPT, name ) );
 
635
                        // ok, duplicate exists, so do prompt
 
636
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
 
637
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
391
638
                        try {
392
639
                                wait();
393
640
                        }
396
643
                        // check if an abortion happened during the wait
397
644
                        checkAbort();
398
645
 
399
 
                        // if "always" was selected, make choice permenant
400
 
                        if( _responseExtra == RESPONSEEXTRA_ALWAYS )
401
 
                                _mergeSetting = _response;
 
646
                        // if "always" was selected, make choice permanent
 
647
                        if( _response_extra == RESPONSEEXTRA_ALWAYS )
 
648
                                _merge_setting = _response;
402
649
 
403
650
                        // recurse, with our new merge setting
404
 
                        return isImportRequired( name, _response );
 
651
                        return shouldWeSkipContact( contact_detail, exists, _response );
405
652
                }
406
653
 
407
 
                // for all other cases (either overwriting or merging) we will need the
408
 
                // imported data
409
 
                return true;
 
654
                // for all other cases (either overwriting or merging) we don't skip
 
655
                return false;
410
656
        }
411
657
 
412
658
        protected void skipContact() throws AbortImportException
413
659
        {
414
660
                checkAbort();
 
661
 
 
662
                // show that we're skipping a new contact
415
663
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
416
664
        }
417
665
 
420
668
        {
421
669
                checkAbort();
422
670
 
 
671
                // It is expected that we use contact.getCacheIdentifier() here. The
 
672
                // contact we are passed should have been successfully finalise()d,
 
673
                // which includes generating a valid cache identifier.
 
674
                ContactsCache.CacheIdentifier cache_identifier =
 
675
                        contact.getCacheIdentifier();
 
676
 
423
677
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
424
678
//                      finish( ACTION_ABORT );
425
679
 
426
 
                ContentValues values = new ContentValues();
427
 
                boolean uiInformed = false;
428
 
 
429
 
                // does contact exist already?
430
 
                Uri contactUri = null;
431
 
                Long id;
432
 
                if( ( id = (Long)_contactsCache.getId( contact._name ) ) != null )
433
 
                {
434
 
                        // should we skip this import altogether?
435
 
                        if( _lastMergeDecision == Doit.ACTION_KEEP ) return;
436
 
 
437
 
                        // get contact's URI
438
 
                        contactUri = ContentUris.withAppendedId(
439
 
                                Contacts.People.CONTENT_URI, id );
440
 
 
441
 
                        // should we destroy the existing contact before importing?
442
 
                        if( _lastMergeDecision == Doit.ACTION_OVERWRITE ) {
443
 
                                _doit.getContentResolver().delete( contactUri, null, null );
444
 
                                contactUri = null;
445
 
 
446
 
                                // update the UI
447
 
                                _doit._handler.sendEmptyMessage(
448
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
449
 
                                uiInformed = true;
 
680
                // attempt to lookup the id of an existing contact in the cache with
 
681
                // this contact data's cache identifier
 
682
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
 
683
 
 
684
                // check to see if this contact should be skipped
 
685
                if( shouldWeSkipContact( cache_identifier.getDetail(), id != null,
 
686
                        _merge_setting ) )
 
687
                {
 
688
                        // show that we're skipping a contact
 
689
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
 
690
                        return;
 
691
                }
 
692
 
 
693
                // if a contact exists, and we're overwriting, destroy the existing
 
694
                // contact before importing
 
695
                boolean contact_deleted = false;
 
696
                if( id != null && _last_merge_decision == Doit.ACTION_OVERWRITE )
 
697
                {
 
698
                        contact_deleted = true;
 
699
 
 
700
                        // remove from device
 
701
                        _backend.deleteContact( id );
 
702
 
 
703
                        // update cache
 
704
                        _contacts_cache.removeLookup( cache_identifier );
 
705
                        _contacts_cache.removeAssociatedData( id );
 
706
 
 
707
                        // show that we're overwriting a contact
 
708
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
 
709
 
 
710
                        // discard the contact id
 
711
                        id = null;
 
712
                }
 
713
 
 
714
                try {
 
715
                        // if we don't have a contact id yet (or we did, but we destroyed it
 
716
                        // when we deleted the contact), we'll have to create a new contact
 
717
                        if( id == null )
 
718
                        {
 
719
                                // create a new contact
 
720
                                id = _backend.addContact( contact._name );
450
721
 
451
722
                                // update cache
452
 
                                _contactsCache.remove( contact._name );
 
723
                                _contacts_cache.addLookup( cache_identifier, id );
 
724
 
 
725
                                // if we haven't already shown that we're overwriting a contact,
 
726
                                // show that we're creating a new contact
 
727
                                if( !contact_deleted )
 
728
                                        _doit._handler.sendEmptyMessage(
 
729
                                                Doit.MESSAGE_CONTACTCREATED );
453
730
                        }
 
731
                        else
 
732
                                // show that we're merging with an existing contact
 
733
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
 
734
 
 
735
                        // import contact parts
 
736
                        if( contact.hasNumbers() )
 
737
                                importContactPhones( id, contact.getNumbers() );
 
738
                        if( contact.hasEmails() )
 
739
                                importContactEmails( id, contact.getEmails() );
 
740
                        if( contact.hasAddresses() )
 
741
                                importContactAddresses( id, contact.getAddresses() );
 
742
                        if( contact.hasOrganisations() )
 
743
                                importContactOrganisations( id, contact.getOrganisations() );
454
744
                }
455
 
 
456
 
                // if we don't have a contact URI it is because the contact never
457
 
                // existed or because we deleted it
458
 
                if( contactUri == null )
 
745
                catch( Backend.ContactCreationException e )
459
746
                {
460
 
                        // create a new contact
461
 
                        values.put( Contacts.People.NAME, contact._name );
462
 
                        contactUri = _doit.getContentResolver().insert(
463
 
                                Contacts.People.CONTENT_URI, values );
464
 
                        id = ContentUris.parseId( contactUri );
465
 
                        if( id <= 0 ) return;   // shouldn't happen!
466
 
 
467
 
                        // try to add them to the "My Contacts" group
468
 
                        try {
469
 
                                Contacts.People.addToMyContactsGroup(
470
 
                                        _doit.getContentResolver(), id );
471
 
                        }
472
 
                        catch( IllegalStateException e ) {
473
 
                                // ignore any failure
474
 
                        }
475
 
 
476
 
                        // update cache
477
 
                        _contactsCache.put( id, contact._name );
478
 
 
479
 
                        // update UI
480
 
                        if( !uiInformed ) {
481
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
482
 
                                uiInformed = true;
483
 
                        }
 
747
                        showError( R.string.error_unabletoaddcontact );
484
748
                }
485
 
 
486
 
                // update UI
487
 
                if( !uiInformed )
488
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
489
 
 
490
 
                // import contact parts
491
 
                if( contact._phones != null )
492
 
                        importContactPhones( contactUri, contact._phones );
493
 
                if( contact._emails != null )
494
 
                        importContactEmails( contactUri, contact._emails );
495
 
                if( contact._addresses != null )
496
 
                        importContactAddresses( contactUri, contact._addresses );
497
749
        }
498
750
 
499
 
        private void importContactPhones( Uri contactUri,
500
 
                        HashMap< String, ContactData.PhoneData > phones )
 
751
        private void importContactPhones( Long id,
 
752
                HashMap< String, ContactData.PreferredDetail > datas )
 
753
                throws ContactCreationException
501
754
        {
502
 
                Long contactId = ContentUris.parseId( contactUri );
503
 
                Uri contactPhonesUri = Uri.withAppendedPath( contactUri,
504
 
                                Contacts.People.Phones.CONTENT_DIRECTORY );
505
 
                Set< String > phonesKeys = phones.keySet();
506
 
 
507
755
                // add phone numbers
508
 
                Iterator< String > i = phonesKeys.iterator();
 
756
                Set< String > datas_keys = datas.keySet();
 
757
                Iterator< String > i = datas_keys.iterator();
509
758
                while( i.hasNext() ) {
510
 
                        ContactData.PhoneData phone = phones.get( i.next() );
 
759
                        String number = i.next();
 
760
                        ContactData.PreferredDetail data = datas.get( number );
511
761
 
512
762
                        // we don't want to add this number if it's crap, or it already
513
763
                        // exists (which would cause a duplicate to be created). We don't
516
766
                        // if the number exists at all, it doesn't need importing. Because
517
767
                        // of this, we also can't update the cache (which we don't need to
518
768
                        // anyway, so it's not a problem).
519
 
                        String number = sanitisePhoneNumber( phone._number );
520
 
                        if( number == null ) continue;
521
 
                        if( _contactsCache.hasNumber( contactId, number ) ) continue;
 
769
                        if( _contacts_cache.hasAssociatedNumber( id, number ) )
 
770
                                continue;
522
771
 
523
772
                        // add phone number
524
 
                        ContentValues values = new ContentValues();
525
 
                        values.put( Contacts.Phones.TYPE, phone._type );
526
 
                        values.put( Contacts.Phones.NUMBER, phone._number );
527
 
                        if( phone._isPreferred ) values.put( Contacts.Phones.ISPRIMARY, 1 );
528
 
                        _doit.getContentResolver().insert( contactPhonesUri, values );
 
773
                        _backend.addContactPhone( id, number, data );
529
774
 
530
775
                        // and add this address to the cache to prevent a addition of
531
776
                        // duplicate date from another file
532
 
                        _contactsCache.addNumber( contactId, number );
 
777
                        _contacts_cache.addAssociatedNumber( id, number );
533
778
                }
534
779
        }
535
780
 
536
 
        private void importContactEmails( Uri contactUri,
537
 
                        HashMap< String, ContactData.EmailData > emails )
 
781
        private void importContactEmails( Long id,
 
782
                HashMap< String, ContactData.PreferredDetail > datas )
 
783
                throws ContactCreationException
538
784
        {
539
 
                Long contactId = ContentUris.parseId( contactUri );
540
 
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
541
 
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
542
 
                Set< String > emailsKeys = emails.keySet();
543
 
 
544
785
                // add email addresses
545
 
                Iterator< String > i = emailsKeys.iterator();
 
786
                Set< String > datas_keys = datas.keySet();
 
787
                Iterator< String > i = datas_keys.iterator();
546
788
                while( i.hasNext() ) {
547
 
                        ContactData.EmailData email = emails.get( i.next() );
 
789
                        String email = i.next();
 
790
                        ContactData.PreferredDetail data = datas.get( email );
548
791
 
549
792
                        // we don't want to add this email address if it exists already or
550
793
                        // we would introduce duplicates.
551
 
                        String address = sanitiseEmailAddress( email.getAddress() );
552
 
                        if( address == null ) continue;
553
 
                        if( _contactsCache.hasEmail( contactId, address ) ) continue;
 
794
                        if( _contacts_cache.hasAssociatedEmail( id, email ) )
 
795
                                continue;
554
796
 
555
797
                        // add phone number
556
 
                        ContentValues values = new ContentValues();
557
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
558
 
                        values.put( Contacts.ContactMethods.DATA, email.getAddress() );
559
 
                        values.put( Contacts.ContactMethods.TYPE, email.getType() );
560
 
                        if( email.isPreferred() )
561
 
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
562
 
                        _doit.getContentResolver().insert( contactContactMethodsUri,
563
 
                                values );
 
798
                        _backend.addContactEmail( id, email, data );
564
799
 
565
800
                        // and add this address to the cache to prevent a addition of
566
801
                        // duplicate date from another file
567
 
                        _contactsCache.addEmail( contactId, address );
 
802
                        _contacts_cache.addAssociatedEmail( id, email );
568
803
                }
569
804
        }
570
805
 
571
 
        private void importContactAddresses( Uri contactUri,
572
 
                HashMap< String, ContactData.AddressData > addresses )
 
806
        private void importContactAddresses( Long id,
 
807
                HashMap< String, ContactData.TypeDetail > datas )
 
808
                throws ContactCreationException
573
809
        {
574
 
                Long contactId = ContentUris.parseId( contactUri );
575
 
                Uri contactContactMethodsUri = Uri.withAppendedPath( contactUri,
576
 
                                Contacts.People.ContactMethods.CONTENT_DIRECTORY );
577
 
                Set< String > addressesKeys = addresses.keySet();
578
 
 
579
810
                // add addresses
580
 
                Iterator< String > i = addressesKeys.iterator();
 
811
                Set< String > datas_keys = datas.keySet();
 
812
                Iterator< String > i = datas_keys.iterator();
581
813
                while( i.hasNext() ) {
582
 
                        ContactData.AddressData address = addresses.get( i.next() );
 
814
                        String address = i.next();
 
815
                        ContactData.TypeDetail data = datas.get( address );
583
816
 
584
817
                        // we don't want to add this address if it exists already or we
585
818
                        // would introduce duplicates
586
 
                        if( address == null ) continue;
587
 
                        if( _contactsCache.hasAddress( contactId, address.getAddress() ) )
 
819
                        if( _contacts_cache.hasAssociatedAddress( id, address ) )
588
820
                                continue;
589
821
 
590
822
                        // 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,
596
 
                                values );
597
 
 
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() );
 
823
                        _backend.addContactAddresses( id, address, data );
 
824
 
 
825
                        // and add this address to the cache to prevent a addition of
 
826
                        // duplicate date from another file
 
827
                        _contacts_cache.addAssociatedAddress( id, address );
 
828
                }
 
829
        }
 
830
 
 
831
        private void importContactOrganisations( Long id,
 
832
                HashMap< String, ContactData.ExtraDetail > datas )
 
833
                throws ContactCreationException
 
834
        {
 
835
                // add addresses
 
836
                Set< String > datas_keys = datas.keySet();
 
837
                Iterator< String > i = datas_keys.iterator();
 
838
                while( i.hasNext() ) {
 
839
                        String organisation = i.next();
 
840
                        ContactData.ExtraDetail data = datas.get( organisation );
 
841
 
 
842
                        // we don't want to add this address if it exists already or we
 
843
                        // would introduce duplicates
 
844
                        if( _contacts_cache.hasAssociatedOrganisation( id, organisation ) )
 
845
                                continue;
 
846
 
 
847
                        // add organisation address
 
848
                        _backend.addContactOrganisation( id, organisation, data );
 
849
 
 
850
                        // and add this address to the cache to prevent a addition of
 
851
                        // duplicate date from another file
 
852
                        _contacts_cache.addAssociatedOrganisation( id, organisation );
601
853
                }
602
854
        }
603
855
 
608
860
                        throw new AbortImportException();
609
861
                }
610
862
        }
611
 
 
612
 
        static public String sanitisePhoneNumber( String number )
613
 
        {
614
 
                number = number.replaceAll( "[-\\(\\) ]", "" );
615
 
                Pattern p = Pattern.compile( "^[\\+0-9#*]+" );
616
 
                Matcher m = p.matcher( number );
617
 
                if( m.lookingAt() ) return m.group( 0 );
618
 
                return null;
619
 
        }
620
 
 
621
 
        static public String sanitiseEmailAddress( String address )
622
 
        {
623
 
                address = address.trim();
624
 
                Pattern p = Pattern.compile(
625
 
                        "^[^ @]+@[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?(\\.[a-zA-Z]([-a-zA-Z0-9]*[a-zA-z0-9])?)+$" );
626
 
                Matcher m = p.matcher( address );
627
 
                if( m.matches() ) {
628
 
                        String[] bits = address.split( "@" );
629
 
                        return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
630
 
                }
631
 
                return null;
632
 
        }
633
863
}