/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-05-08 15:09:13 UTC
  • Revision ID: tim@ed.am-20120508150913-t9qzbbs1kld691dy
abstracted the android contacts API in to an interface, ready to be switched to
another depending on the platform version.

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