/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 to 2011 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
{
56
55
        private boolean _abort = false;
57
56
        private boolean _is_finished = false;
58
57
        private ContactsCache _contacts_cache = null;
 
58
        private Backend _backend = null;
59
59
 
60
60
        /**
61
61
         * Data about a contact
62
62
         */
63
63
        public class ContactData
64
64
        {
 
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
 
65
72
                class TypeDetail
66
73
                {
67
74
                        protected int _type;
124
131
 
125
132
                protected String _name = null;
126
133
                protected String _primary_organisation = null;
127
 
                protected boolean _primary_organisation_is_preferred = false;
 
134
                protected boolean _primary_organisation_is_preferred;
128
135
                protected String _primary_number = null;
129
 
                protected boolean _primary_number_is_preferred = false;
 
136
                protected int _primary_number_type;
 
137
                protected boolean _primary_number_is_preferred;
130
138
                protected String _primary_email = null;
131
 
                protected boolean _primary_email_is_preferred = false;
 
139
                protected boolean _primary_email_is_preferred;
132
140
                protected HashMap< String, ExtraDetail > _organisations = null;
133
141
                protected HashMap< String, PreferredDetail > _numbers = null;
134
142
                protected HashMap< String, PreferredDetail > _emails = null;
175
183
                                        new ExtraDetail( 0, false, title ) );
176
184
 
177
185
                        // if this is the first organisation added, or it's a preferred
178
 
                        // organisation and a previous organisation wasn't, then remember
179
 
                        // that this is the "primary organisation".
 
186
                        // organisation and the current primary organisation isn't, then
 
187
                        // record this as the primary organisation.
180
188
                        if( _primary_organisation == null ||
181
189
                                ( is_preferred && !_primary_organisation_is_preferred ) )
182
190
                        {
223
231
                                _numbers.put( number,
224
232
                                        new PreferredDetail( type, false ) );
225
233
 
 
234
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
 
235
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
 
236
 
226
237
                        // if this is the first number added, or it's a preferred number
227
 
                        // and a previous number wasn't, then remember that this is the
228
 
                        // "primary 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.
229
242
                        if( _primary_number == null ||
230
 
                                ( is_preferred && !_primary_number_is_preferred ) )
 
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 ) ) )
231
247
                        {
232
248
                                _primary_number = number;
 
249
                                _primary_number_type = type;
233
250
                                _primary_number_is_preferred = is_preferred;
234
251
                        }
235
252
                }
260
277
                        email = sanitisesEmailAddress( email );
261
278
                        if( email == null )
262
279
                        {
263
 
                                // TODO: warn that an imported email addtrss is being ignored
 
280
                                // TODO: warn that an imported email address is being ignored
264
281
                                return;
265
282
                        }
266
283
 
271
288
                        if( !_emails.containsKey( email ) )
272
289
                                _emails.put( email, new PreferredDetail( type, false ) );
273
290
 
274
 
                        // if this is the first email added, or it's a preferred email
275
 
                        // and a previous email wasn't, then remember that this is the
276
 
                        // "primary email".
 
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.
277
294
                        if( _primary_email == null ||
278
295
                                ( is_preferred && !_primary_email_is_preferred ) )
279
296
                        {
382
399
                        Matcher m = p.matcher( email );
383
400
                        if( m.matches() ) {
384
401
                                String[] bits = email.split( "@" );
385
 
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
 
402
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase( Locale.US );
386
403
                        }
387
404
                        return null;
388
405
                }
407
424
                        // update UI
408
425
                        setProgressMessage( R.string.doit_caching );
409
426
 
410
 
                        // build a cache of existing contacts
 
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
411
434
                        _contacts_cache = new ContactsCache();
412
 
                        _contacts_cache.buildCache( _doit );
 
435
                        _backend.populateCache( _contacts_cache );
413
436
 
414
437
                        // do the import
415
438
                        onImport();
542
565
                checkAbort();
543
566
                _doit._handler.sendMessage( Message.obtain(
544
567
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
545
 
                        new Integer( max_progress ) ) );
 
568
                        Integer.valueOf( max_progress ) ) );
546
569
        }
547
570
 
548
571
        protected void setTmpProgress( int tmp_progress )
551
574
                checkAbort();
552
575
                _doit._handler.sendMessage( Message.obtain(
553
576
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
554
 
                        new Integer( tmp_progress ) ) );
 
577
                        Integer.valueOf( tmp_progress ) ) );
555
578
        }
556
579
 
557
580
        protected void setProgress( int progress ) throws AbortImportException
559
582
                checkAbort();
560
583
                _doit._handler.sendMessage( Message.obtain(
561
584
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
562
 
                        new Integer( progress ) ) );
 
585
                        Integer.valueOf( progress ) ) );
563
586
        }
564
587
 
565
588
        protected void finish( int action ) throws AbortImportException
583
606
                return _doit.getText( res );
584
607
        }
585
608
 
586
 
        synchronized private boolean checkForDuplicate(
587
 
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
588
 
                throws AbortImportException
 
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
589
620
        {
590
621
                _last_merge_decision = merge_setting;
591
622
 
592
 
                // it is ok to use contact.getCacheIdentifier(). The contact has already
593
 
                // been finalised, which means a valid cache identifier will have been
594
 
                // created for it (or it would have been skipped)
595
 
 
596
623
                // handle special cases
597
624
                switch( merge_setting )
598
625
                {
599
626
                case Doit.ACTION_KEEP:
600
 
                        // if we keep contacts on duplicate, we better check for one
601
 
                        return !_contacts_cache.canLookup( cache_identifier );
 
627
                        // if we are skipping on a duplicate, check for one
 
628
                        return exists;
602
629
 
603
630
                case Doit.ACTION_PROMPT:
604
 
                        // if we are prompting on duplicate, we better check for one and if
605
 
                        // the contact doesn'te exist, we want to import it
606
 
                        if( !_contacts_cache.canLookup( cache_identifier ) )
607
 
                                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;
608
634
 
609
 
                        // ok, it exists, so do prompt
 
635
                        // ok, duplicate exists, so do prompt
610
636
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
611
 
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
 
637
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
612
638
                        try {
613
639
                                wait();
614
640
                        }
622
648
                                _merge_setting = _response;
623
649
 
624
650
                        // recurse, with our new merge setting
625
 
                        return checkForDuplicate( cache_identifier, _response );
 
651
                        return shouldWeSkipContact( contact_detail, exists, _response );
626
652
                }
627
653
 
628
 
                // for all other cases (either overwriting or merging) we will need the
629
 
                // imported data
630
 
                return true;
 
654
                // for all other cases (either overwriting or merging) we don't skip
 
655
                return false;
631
656
        }
632
657
 
633
658
        protected void skipContact() throws AbortImportException
634
659
        {
635
660
                checkAbort();
 
661
 
 
662
                // show that we're skipping a new contact
636
663
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
637
664
        }
638
665
 
647
674
                ContactsCache.CacheIdentifier cache_identifier =
648
675
                        contact.getCacheIdentifier();
649
676
 
650
 
                // check to see if this contact is a duplicate and should be skipped
651
 
                if( !checkForDuplicate( cache_identifier, _merge_setting ) ) {
652
 
                        skipContact();
653
 
                        return;
654
 
                }
655
 
 
656
677
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
657
678
//                      finish( ACTION_ABORT );
658
679
 
659
 
                // keep track of whether we've informed the UI of what we're doing
660
 
                boolean ui_informed = false;
661
 
 
662
680
                // attempt to lookup the id of an existing contact in the cache with
663
681
                // this contact data's cache identifier
664
682
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
665
683
 
666
 
                // does contact exist already?
667
 
                if( id != null )
668
 
                {
669
 
                        // should we skip this import altogether?
670
 
                        if( _last_merge_decision == Doit.ACTION_KEEP ) return;
671
 
 
672
 
                        // get contact's URI
673
 
                        Uri contact_uri = ContentUris.withAppendedId(
674
 
                                Contacts.People.CONTENT_URI, id );
675
 
 
676
 
                        // should we destroy the existing contact before importing?
677
 
                        if( _last_merge_decision == Doit.ACTION_OVERWRITE )
 
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 )
678
718
                        {
679
 
                                // remove from device
680
 
                                _doit.getContentResolver().delete( contact_uri, null, null );
 
719
                                // create a new contact
 
720
                                id = _backend.addContact( contact._name );
681
721
 
682
722
                                // update cache
683
 
                                _contacts_cache.removeLookup( contact.getCacheIdentifier() );
684
 
                                _contacts_cache.removeAssociatedData( id );
685
 
 
686
 
                                // show that we're overwriting a contact
687
 
                                _doit._handler.sendEmptyMessage(
688
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
689
 
                                ui_informed = true;
690
 
 
691
 
                                // discard the contact id
692
 
                                id = null;
 
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 );
693
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() );
694
744
                }
695
 
 
696
 
                // if we don't have a contact id yet (or if we did, but we destroyed it
697
 
                // when we deleted the contact), we'll have to create a new contact
698
 
                if( id == null )
 
745
                catch( Backend.ContactCreationException e )
699
746
                {
700
 
                        // create a new contact
701
 
                        ContentValues values = new ContentValues();
702
 
                        values.put( Contacts.People.NAME, contact._name );
703
 
                        Uri contact_uri = _doit.getContentResolver().insert(
704
 
                                Contacts.People.CONTENT_URI, values );
705
 
                        id = ContentUris.parseId( contact_uri );
706
 
                        if( id == null || id <= 0 )
707
 
                                showError( R.string.error_unabletoaddcontact );
708
 
 
709
 
                        // try to add them to the "My Contacts" group
710
 
                        try {
711
 
                                Contacts.People.addToMyContactsGroup(
712
 
                                        _doit.getContentResolver(), id );
713
 
                        }
714
 
                        catch( IllegalStateException e ) {
715
 
                                // ignore any failure
716
 
                        }
717
 
 
718
 
                        // update cache
719
 
                        _contacts_cache.addLookup(
720
 
                                ContactsCache.createIdentifier( contact ), id );
721
 
 
722
 
                        // if we haven't already shown that we're overwriting a contact,
723
 
                        // show that we're creating a new contact
724
 
                        if( !ui_informed ) {
725
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
726
 
                                ui_informed = true;
727
 
                        }
 
747
                        showError( R.string.error_unabletoaddcontact );
728
748
                }
729
 
 
730
 
                // if we haven't already shown that we're overwriting or creating a
731
 
                // contact, show that we're merging a contact
732
 
                if( !ui_informed )
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() );
744
749
        }
745
750
 
746
751
        private void importContactPhones( Long id,
747
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
752
                HashMap< String, ContactData.PreferredDetail > datas )
 
753
                throws ContactCreationException
748
754
        {
749
 
                // get URI to contact's phones
750
 
                Uri contact_phones_uri = Uri.withAppendedPath(
751
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
752
 
                        Contacts.People.Phones.CONTENT_DIRECTORY );
753
 
                Set< String > datas_keys = datas.keySet();
754
 
 
755
755
                // add phone numbers
 
756
                Set< String > datas_keys = datas.keySet();
756
757
                Iterator< String > i = datas_keys.iterator();
757
758
                while( i.hasNext() ) {
758
759
                        String number = i.next();
769
770
                                continue;
770
771
 
771
772
                        // add phone number
772
 
                        ContentValues values = new ContentValues();
773
 
                        values.put( Contacts.Phones.TYPE, data.getType() );
774
 
                        values.put( Contacts.Phones.NUMBER, number );
775
 
                        if( data.isPreferred() )
776
 
                                values.put( Contacts.Phones.ISPRIMARY, 1 );
777
 
                        _doit.getContentResolver().insert( contact_phones_uri, values );
 
773
                        _backend.addContactPhone( id, number, data );
778
774
 
779
775
                        // and add this address to the cache to prevent a addition of
780
776
                        // duplicate date from another file
783
779
        }
784
780
 
785
781
        private void importContactEmails( Long id,
786
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
782
                HashMap< String, ContactData.PreferredDetail > datas )
 
783
                throws ContactCreationException
787
784
        {
788
 
                // get URI to contact's contact methods
789
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
790
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
791
 
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
792
 
                Set< String > datas_keys = datas.keySet();
793
 
 
794
785
                // add email addresses
 
786
                Set< String > datas_keys = datas.keySet();
795
787
                Iterator< String > i = datas_keys.iterator();
796
788
                while( i.hasNext() ) {
797
789
                        String email = i.next();
803
795
                                continue;
804
796
 
805
797
                        // add phone number
806
 
                        ContentValues values = new ContentValues();
807
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
808
 
                        values.put( Contacts.ContactMethods.DATA, email );
809
 
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
810
 
                        if( data.isPreferred() )
811
 
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
812
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
813
 
                                values );
 
798
                        _backend.addContactEmail( id, email, data );
814
799
 
815
800
                        // and add this address to the cache to prevent a addition of
816
801
                        // duplicate date from another file
820
805
 
821
806
        private void importContactAddresses( Long id,
822
807
                HashMap< String, ContactData.TypeDetail > datas )
 
808
                throws ContactCreationException
823
809
        {
824
 
                // get URI to contact's contact methods
825
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
826
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
827
 
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
828
 
 
829
810
                // add addresses
830
811
                Set< String > datas_keys = datas.keySet();
831
812
                Iterator< String > i = datas_keys.iterator();
839
820
                                continue;
840
821
 
841
822
                        // add postal address
842
 
                        ContentValues values = new ContentValues();
843
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
844
 
                        values.put( Contacts.ContactMethods.DATA, address );
845
 
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
846
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
847
 
                                values );
 
823
                        _backend.addContactAddresses( id, address, data );
848
824
 
849
825
                        // and add this address to the cache to prevent a addition of
850
826
                        // duplicate date from another file
854
830
 
855
831
        private void importContactOrganisations( Long id,
856
832
                HashMap< String, ContactData.ExtraDetail > datas )
 
833
                throws ContactCreationException
857
834
        {
858
835
                // add addresses
859
836
                Set< String > datas_keys = datas.keySet();
868
845
                                continue;
869
846
 
870
847
                        // add organisation address
871
 
                        ContentValues values = new ContentValues();
872
 
                        values.put( Contacts.Organizations.PERSON_ID, id );
873
 
                        values.put( Contacts.Organizations.COMPANY, organisation );
874
 
                        values.put( Contacts.ContactMethods.TYPE,
875
 
                                Contacts.OrganizationColumns.TYPE_WORK );
876
 
                        if( data.getExtra() != null )
877
 
                                values.put( Contacts.Organizations.TITLE, data.getExtra() );
878
 
                        _doit.getContentResolver().insert(
879
 
                                Contacts.Organizations.CONTENT_URI, values );
 
848
                        _backend.addContactOrganisation( id, organisation, data );
880
849
 
881
850
                        // and add this address to the cache to prevent a addition of
882
851
                        // duplicate date from another file