/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 to 2011 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;
 
28
import java.util.HashSet;
27
29
import java.util.Iterator;
28
30
import java.util.Set;
29
31
import java.util.regex.Matcher;
30
32
import java.util.regex.Pattern;
31
33
 
32
 
import android.content.ContentUris;
33
 
import android.content.ContentValues;
34
34
import android.content.SharedPreferences;
35
 
import android.net.Uri;
36
35
import android.os.Message;
37
 
import android.provider.Contacts;
 
36
import android.provider.Contacts.PhonesColumns;
38
37
 
39
38
 
40
39
public class Importer extends Thread
56
55
        private boolean _abort = false;
57
56
        private boolean _is_finished = false;
58
57
        private ContactsCache _contacts_cache = null;
59
 
 
60
 
        @SuppressWarnings("serial")
61
 
        protected class ContactNeedsMoreInfoException extends Exception
62
 
        {
63
 
        }
 
58
        private Backend _backend = null;
64
59
 
65
60
        /**
66
61
         * Data about a contact
122
117
                        }
123
118
                }
124
119
 
 
120
                @SuppressWarnings("serial")
 
121
                protected class ContactNotIdentifiableException extends Exception
 
122
                {
 
123
                }
 
124
 
125
125
                protected String _name = null;
126
126
                protected String _primary_organisation = null;
127
 
                protected boolean _primary_organisation_is_preferred = false;
 
127
                protected boolean _primary_organisation_is_preferred;
128
128
                protected String _primary_number = null;
129
 
                protected boolean _primary_number_is_preferred = false;
 
129
                protected int _primary_number_type;
 
130
                protected boolean _primary_number_is_preferred;
130
131
                protected String _primary_email = null;
131
 
                protected boolean _primary_email_is_preferred = false;
 
132
                protected boolean _primary_email_is_preferred;
132
133
                protected HashMap< String, ExtraDetail > _organisations = null;
133
134
                protected HashMap< String, PreferredDetail > _numbers = null;
134
135
                protected HashMap< String, PreferredDetail > _emails = null;
135
136
                protected HashMap< String, TypeDetail > _addresses = null;
136
137
 
 
138
                private ContactsCache.CacheIdentifier _cache_identifier = null;
 
139
 
137
140
                protected void setName( String name )
138
141
                {
139
142
                        _name = name;
173
176
                                        new ExtraDetail( 0, false, title ) );
174
177
 
175
178
                        // if this is the first organisation added, or it's a preferred
176
 
                        // organisation and a previous organisation wasn't, then remember
177
 
                        // that this is the "primary organisation".
 
179
                        // organisation and the current primary organisation isn't, then
 
180
                        // record this as the primary organisation.
178
181
                        if( _primary_organisation == null ||
179
182
                                ( is_preferred && !_primary_organisation_is_preferred ) )
180
183
                        {
221
224
                                _numbers.put( number,
222
225
                                        new PreferredDetail( type, false ) );
223
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
 
224
231
                        // if this is the first number added, or it's a preferred number
225
 
                        // and a previous number wasn't, then remember that this is the
226
 
                        // "primary 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.
227
236
                        if( _primary_number == null ||
228
 
                                ( is_preferred && !_primary_number_is_preferred ) )
 
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 ) ) )
229
241
                        {
230
242
                                _primary_number = number;
 
243
                                _primary_number_type = type;
231
244
                                _primary_number_is_preferred = is_preferred;
232
245
                        }
233
246
                }
269
282
                        if( !_emails.containsKey( email ) )
270
283
                                _emails.put( email, new PreferredDetail( type, false ) );
271
284
 
272
 
                        // if this is the first email added, or it's a preferred email
273
 
                        // and a previous email wasn't, then remember that this is the
274
 
                        // "primary email".
 
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.
275
288
                        if( _primary_email == null ||
276
289
                                ( is_preferred && !_primary_email_is_preferred ) )
277
290
                        {
326
339
                }
327
340
 
328
341
                protected void finalise()
 
342
                        throws ContactNotIdentifiableException
329
343
                {
330
344
                        // ensure that if there is a primary number, it is preferred so
331
345
                        // that there is always one preferred number. Android will assign
349
363
                                _organisations.put( _primary_organisation,
350
364
                                        new ExtraDetail( 0, true, data.getExtra() ) );
351
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;
352
377
                }
353
378
 
354
379
                private String sanitisePhoneNumber( String number )
393
418
                        // update UI
394
419
                        setProgressMessage( R.string.doit_caching );
395
420
 
396
 
                        // build a cache of existing contacts
 
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
397
427
                        _contacts_cache = new ContactsCache();
398
 
                        _contacts_cache.buildCache( _doit );
 
428
                        _backend.populateCache( _contacts_cache );
399
429
 
400
430
                        // do the import
401
431
                        onImport();
569
599
                return _doit.getText( res );
570
600
        }
571
601
 
572
 
        protected boolean isImportRequired( ContactData contact )
573
 
                        throws AbortImportException, ContactNeedsMoreInfoException
574
 
        {
575
 
                checkAbort();
576
 
                return isImportRequired( contact, _merge_setting );
577
 
        }
578
 
 
579
 
        synchronized private boolean isImportRequired(
580
 
                ContactData contact, int merge_setting )
581
 
                throws AbortImportException, ContactNeedsMoreInfoException
 
602
        synchronized private boolean checkForDuplicate(
 
603
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
 
604
                throws AbortImportException
582
605
        {
583
606
                _last_merge_decision = merge_setting;
584
607
 
585
 
                // create a cache identifier which we can use to detect if this contact
586
 
                // is valid for importing
587
 
                ContactsCache.CacheIdentifier identifier =
588
 
                        ContactsCache.createIdentifier( contact );
589
 
                if( identifier == null )
590
 
                        throw new ContactNeedsMoreInfoException();
 
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)
591
611
 
592
612
                // handle special cases
593
613
                switch( merge_setting )
594
614
                {
595
615
                case Doit.ACTION_KEEP:
596
616
                        // if we keep contacts on duplicate, we better check for one
597
 
                        return !_contacts_cache.canLookup( identifier );
 
617
                        return !_contacts_cache.canLookup( cache_identifier );
598
618
 
599
619
                case Doit.ACTION_PROMPT:
600
620
                        // if we are prompting on duplicate, we better check for one and if
601
621
                        // the contact doesn'te exist, we want to import it
602
 
                        if( !_contacts_cache.canLookup( identifier ) )
 
622
                        if( !_contacts_cache.canLookup( cache_identifier ) )
603
623
                                return true;
604
624
 
605
625
                        // ok, it exists, so do prompt
606
626
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
607
 
                                Doit.MESSAGE_MERGEPROMPT, identifier.getDetail() ) );
 
627
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
608
628
                        try {
609
629
                                wait();
610
630
                        }
618
638
                                _merge_setting = _response;
619
639
 
620
640
                        // recurse, with our new merge setting
621
 
                        return isImportRequired( contact, _response );
 
641
                        return checkForDuplicate( cache_identifier, _response );
622
642
                }
623
643
 
624
644
                // for all other cases (either overwriting or merging) we will need the
637
657
        {
638
658
                checkAbort();
639
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
 
640
672
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
641
673
//                      finish( ACTION_ABORT );
642
674
 
643
 
                ContentValues values = new ContentValues();
 
675
                // keep track of whether we've informed the UI of what we're doing
644
676
                boolean ui_informed = false;
645
 
                Long id = null;
646
 
 
647
 
                // give the contact a chance to finalise it's data
648
 
                contact.finalise();
649
 
 
650
 
                // create something, from the contact data, that we can use to identify
651
 
                // a cache entry and attempt to lookup the id of an existing contact in
652
 
                // the cache with it
653
 
                ContactsCache.CacheIdentifier identifier =
654
 
                        ContactsCache.createIdentifier( contact );
655
 
                if( identifier != null ) id = (Long)_contacts_cache.lookup( identifier );
 
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 );
656
681
 
657
682
                // does contact exist already?
658
683
                if( id != null )
660
685
                        // should we skip this import altogether?
661
686
                        if( _last_merge_decision == Doit.ACTION_KEEP ) return;
662
687
 
663
 
                        // get contact's URI
664
 
                        Uri contact_uri = ContentUris.withAppendedId(
665
 
                                Contacts.People.CONTENT_URI, id );
666
 
 
667
688
                        // should we destroy the existing contact before importing?
668
689
                        if( _last_merge_decision == Doit.ACTION_OVERWRITE )
669
690
                        {
670
691
                                // remove from device
671
 
                                _doit.getContentResolver().delete( contact_uri, null, null );
 
692
                                _backend.deleteContact( id );
672
693
 
673
694
                                // update cache
674
 
                                _contacts_cache.removeLookup( identifier );
 
695
                                _contacts_cache.removeLookup( contact.getCacheIdentifier() );
675
696
                                _contacts_cache.removeAssociatedData( id );
676
697
 
677
698
                                // show that we're overwriting a contact
684
705
                        }
685
706
                }
686
707
 
687
 
                // if we don't have a contact id yet (or if we did, but we destroyed it
 
708
                // if we don't have a contact id yet (or we did, but we destroyed it
688
709
                // when we deleted the contact), we'll have to create a new contact
689
710
                if( id == null )
690
711
                {
691
712
                        // create a new contact
692
 
                        values.put( Contacts.People.NAME, contact._name );
693
 
                        Uri contact_uri = _doit.getContentResolver().insert(
694
 
                                Contacts.People.CONTENT_URI, values );
695
 
                        id = ContentUris.parseId( contact_uri );
 
713
                        id = _backend.addContact( contact._name );
696
714
                        if( id == null || id <= 0 )
697
715
                                showError( R.string.error_unabletoaddcontact );
698
716
 
699
 
                        // try to add them to the "My Contacts" group
700
 
                        try {
701
 
                                Contacts.People.addToMyContactsGroup(
702
 
                                        _doit.getContentResolver(), id );
703
 
                        }
704
 
                        catch( IllegalStateException e ) {
705
 
                                // ignore any failure
706
 
                        }
707
 
 
708
717
                        // update cache
709
718
                        _contacts_cache.addLookup(
710
719
                                ContactsCache.createIdentifier( contact ), id );
718
727
                }
719
728
 
720
729
                // if we haven't already shown that we're overwriting or creating a
721
 
                // contact show that we're merging a contact
 
730
                // contact, show that we're merging a contact
722
731
                if( !ui_informed )
723
732
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
724
733
 
736
745
        private void importContactPhones( Long id,
737
746
                        HashMap< String, ContactData.PreferredDetail > datas )
738
747
        {
739
 
                // get URI to contact's phones
740
 
                Uri contact_phones_uri = Uri.withAppendedPath(
741
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
742
 
                        Contacts.People.Phones.CONTENT_DIRECTORY );
743
 
                Set< String > datas_keys = datas.keySet();
744
 
 
745
748
                // add phone numbers
 
749
                Set< String > datas_keys = datas.keySet();
746
750
                Iterator< String > i = datas_keys.iterator();
747
751
                while( i.hasNext() ) {
748
752
                        String number = i.next();
759
763
                                continue;
760
764
 
761
765
                        // add phone number
762
 
                        ContentValues values = new ContentValues();
763
 
                        values.put( Contacts.Phones.TYPE, data.getType() );
764
 
                        values.put( Contacts.Phones.NUMBER, number );
765
 
                        if( data.isPreferred() )
766
 
                                values.put( Contacts.Phones.ISPRIMARY, 1 );
767
 
                        _doit.getContentResolver().insert( contact_phones_uri, values );
 
766
                        _backend.addContactPhone( id, number, data );
768
767
 
769
768
                        // and add this address to the cache to prevent a addition of
770
769
                        // duplicate date from another file
775
774
        private void importContactEmails( Long id,
776
775
                        HashMap< String, ContactData.PreferredDetail > datas )
777
776
        {
778
 
                // get URI to contact's contact methods
779
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
780
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
781
 
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
782
 
                Set< String > datas_keys = datas.keySet();
783
 
 
784
777
                // add email addresses
 
778
                Set< String > datas_keys = datas.keySet();
785
779
                Iterator< String > i = datas_keys.iterator();
786
780
                while( i.hasNext() ) {
787
781
                        String email = i.next();
793
787
                                continue;
794
788
 
795
789
                        // add phone number
796
 
                        ContentValues values = new ContentValues();
797
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
798
 
                        values.put( Contacts.ContactMethods.DATA, email );
799
 
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
800
 
                        if( data.isPreferred() )
801
 
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
802
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
803
 
                                values );
 
790
                        _backend.addContactEmail( id, email, data );
804
791
 
805
792
                        // and add this address to the cache to prevent a addition of
806
793
                        // duplicate date from another file
811
798
        private void importContactAddresses( Long id,
812
799
                HashMap< String, ContactData.TypeDetail > datas )
813
800
        {
814
 
                // get URI to contact's contact methods
815
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
816
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
817
 
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
818
 
 
819
801
                // add addresses
820
802
                Set< String > datas_keys = datas.keySet();
821
803
                Iterator< String > i = datas_keys.iterator();
829
811
                                continue;
830
812
 
831
813
                        // add postal address
832
 
                        ContentValues values = new ContentValues();
833
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
834
 
                        values.put( Contacts.ContactMethods.DATA, address );
835
 
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
836
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
837
 
                                values );
 
814
                        _backend.addContactAddresses( id, address, data );
838
815
 
839
816
                        // and add this address to the cache to prevent a addition of
840
817
                        // duplicate date from another file
858
835
                                continue;
859
836
 
860
837
                        // add organisation address
861
 
                        ContentValues values = new ContentValues();
862
 
                        values.put( Contacts.Organizations.PERSON_ID, id );
863
 
                        values.put( Contacts.Organizations.COMPANY, organisation );
864
 
                        values.put( Contacts.ContactMethods.TYPE,
865
 
                                Contacts.OrganizationColumns.TYPE_WORK );
866
 
                        if( data.getExtra() != null )
867
 
                                values.put( Contacts.Organizations.TITLE, data.getExtra() );
868
 
                        _doit.getContentResolver().insert(
869
 
                                Contacts.Organizations.CONTENT_URI, values );
 
838
                        _backend.addContactOrganisation( id, organisation, data );
870
839
 
871
840
                        // and add this address to the cache to prevent a addition of
872
841
                        // duplicate date from another file