/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
26
import java.util.Arrays;
27
27
import java.util.HashMap;
28
28
import java.util.HashSet;
29
29
import java.util.Iterator;
 
30
import java.util.Locale;
30
31
import java.util.Set;
31
32
import java.util.regex.Matcher;
32
33
import java.util.regex.Pattern;
33
34
 
34
 
import android.content.ContentUris;
35
 
import android.content.ContentValues;
 
35
import am.ed.importcontacts.Backend.ContactCreationException;
36
36
import android.content.SharedPreferences;
37
 
import android.net.Uri;
38
37
import android.os.Message;
39
 
import android.provider.Contacts;
40
 
import android.provider.Contacts.PhonesColumns;
41
 
 
42
38
 
43
39
public class Importer extends Thread
44
40
{
59
55
        private boolean _abort = false;
60
56
        private boolean _is_finished = false;
61
57
        private ContactsCache _contacts_cache = null;
 
58
        private Backend _backend = null;
62
59
 
63
60
        /**
64
61
         * Data about a contact
65
62
         */
66
63
        public class ContactData
67
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
 
68
72
                class TypeDetail
69
73
                {
70
74
                        protected int _type;
228
232
                                        new PreferredDetail( type, false ) );
229
233
 
230
234
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
231
 
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
232
 
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
 
235
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
233
236
 
234
237
                        // if this is the first number added, or it's a preferred number
235
238
                        // and the current primary number isn't, or this number is on equal
274
277
                        email = sanitisesEmailAddress( email );
275
278
                        if( email == null )
276
279
                        {
277
 
                                // TODO: warn that an imported email addtrss is being ignored
 
280
                                // TODO: warn that an imported email address is being ignored
278
281
                                return;
279
282
                        }
280
283
 
396
399
                        Matcher m = p.matcher( email );
397
400
                        if( m.matches() ) {
398
401
                                String[] bits = email.split( "@" );
399
 
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
 
402
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase( Locale.US );
400
403
                        }
401
404
                        return null;
402
405
                }
421
424
                        // update UI
422
425
                        setProgressMessage( R.string.doit_caching );
423
426
 
424
 
                        // 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
425
434
                        _contacts_cache = new ContactsCache();
426
 
                        _contacts_cache.buildCache( _doit );
 
435
                        _backend.populateCache( _contacts_cache );
427
436
 
428
437
                        // do the import
429
438
                        onImport();
556
565
                checkAbort();
557
566
                _doit._handler.sendMessage( Message.obtain(
558
567
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
559
 
                        new Integer( max_progress ) ) );
 
568
                        Integer.valueOf( max_progress ) ) );
560
569
        }
561
570
 
562
571
        protected void setTmpProgress( int tmp_progress )
565
574
                checkAbort();
566
575
                _doit._handler.sendMessage( Message.obtain(
567
576
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
568
 
                        new Integer( tmp_progress ) ) );
 
577
                        Integer.valueOf( tmp_progress ) ) );
569
578
        }
570
579
 
571
580
        protected void setProgress( int progress ) throws AbortImportException
573
582
                checkAbort();
574
583
                _doit._handler.sendMessage( Message.obtain(
575
584
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
576
 
                        new Integer( progress ) ) );
 
585
                        Integer.valueOf( progress ) ) );
577
586
        }
578
587
 
579
588
        protected void finish( int action ) throws AbortImportException
597
606
                return _doit.getText( res );
598
607
        }
599
608
 
600
 
        synchronized private boolean checkForDuplicate(
601
 
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
602
 
                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
603
620
        {
604
621
                _last_merge_decision = merge_setting;
605
622
 
606
 
                // it is ok to use contact.getCacheIdentifier(). The contact has already
607
 
                // been finalised, which means a valid cache identifier will have been
608
 
                // created for it (or it would have been skipped)
609
 
 
610
623
                // handle special cases
611
624
                switch( merge_setting )
612
625
                {
613
626
                case Doit.ACTION_KEEP:
614
 
                        // if we keep contacts on duplicate, we better check for one
615
 
                        return !_contacts_cache.canLookup( cache_identifier );
 
627
                        // if we are skipping on a duplicate, check for one
 
628
                        return exists;
616
629
 
617
630
                case Doit.ACTION_PROMPT:
618
 
                        // if we are prompting on duplicate, we better check for one and if
619
 
                        // the contact doesn'te exist, we want to import it
620
 
                        if( !_contacts_cache.canLookup( cache_identifier ) )
621
 
                                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;
622
634
 
623
 
                        // ok, it exists, so do prompt
 
635
                        // ok, duplicate exists, so do prompt
624
636
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
625
 
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
 
637
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
626
638
                        try {
627
639
                                wait();
628
640
                        }
636
648
                                _merge_setting = _response;
637
649
 
638
650
                        // recurse, with our new merge setting
639
 
                        return checkForDuplicate( cache_identifier, _response );
 
651
                        return shouldWeSkipContact( contact_detail, exists, _response );
640
652
                }
641
653
 
642
 
                // for all other cases (either overwriting or merging) we will need the
643
 
                // imported data
644
 
                return true;
 
654
                // for all other cases (either overwriting or merging) we don't skip
 
655
                return false;
645
656
        }
646
657
 
647
658
        protected void skipContact() throws AbortImportException
648
659
        {
649
660
                checkAbort();
 
661
 
 
662
                // show that we're skipping a new contact
650
663
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
651
664
        }
652
665
 
661
674
                ContactsCache.CacheIdentifier cache_identifier =
662
675
                        contact.getCacheIdentifier();
663
676
 
664
 
                // check to see if this contact is a duplicate and should be skipped
665
 
                if( !checkForDuplicate( cache_identifier, _merge_setting ) ) {
666
 
                        skipContact();
667
 
                        return;
668
 
                }
669
 
 
670
677
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
671
678
//                      finish( ACTION_ABORT );
672
679
 
673
 
                // keep track of whether we've informed the UI of what we're doing
674
 
                boolean ui_informed = false;
675
 
 
676
680
                // attempt to lookup the id of an existing contact in the cache with
677
681
                // this contact data's cache identifier
678
682
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
679
683
 
680
 
                // does contact exist already?
681
 
                if( id != null )
682
 
                {
683
 
                        // should we skip this import altogether?
684
 
                        if( _last_merge_decision == Doit.ACTION_KEEP ) return;
685
 
 
686
 
                        // get contact's URI
687
 
                        Uri contact_uri = ContentUris.withAppendedId(
688
 
                                Contacts.People.CONTENT_URI, id );
689
 
 
690
 
                        // should we destroy the existing contact before importing?
691
 
                        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 )
692
718
                        {
693
 
                                // remove from device
694
 
                                _doit.getContentResolver().delete( contact_uri, null, null );
 
719
                                // create a new contact
 
720
                                id = _backend.addContact( contact._name );
695
721
 
696
722
                                // update cache
697
 
                                _contacts_cache.removeLookup( contact.getCacheIdentifier() );
698
 
                                _contacts_cache.removeAssociatedData( id );
699
 
 
700
 
                                // show that we're overwriting a contact
701
 
                                _doit._handler.sendEmptyMessage(
702
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
703
 
                                ui_informed = true;
704
 
 
705
 
                                // discard the contact id
706
 
                                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 );
707
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() );
708
744
                }
709
 
 
710
 
                // if we don't have a contact id yet (or if we did, but we destroyed it
711
 
                // when we deleted the contact), we'll have to create a new contact
712
 
                if( id == null )
 
745
                catch( Backend.ContactCreationException e )
713
746
                {
714
 
                        // create a new contact
715
 
                        ContentValues values = new ContentValues();
716
 
                        values.put( Contacts.People.NAME, contact._name );
717
 
                        Uri contact_uri = _doit.getContentResolver().insert(
718
 
                                Contacts.People.CONTENT_URI, values );
719
 
                        id = ContentUris.parseId( contact_uri );
720
 
                        if( id == null || id <= 0 )
721
 
                                showError( R.string.error_unabletoaddcontact );
722
 
 
723
 
                        // try to add them to the "My Contacts" group
724
 
                        try {
725
 
                                Contacts.People.addToMyContactsGroup(
726
 
                                        _doit.getContentResolver(), id );
727
 
                        }
728
 
                        catch( IllegalStateException e ) {
729
 
                                // ignore any failure
730
 
                        }
731
 
 
732
 
                        // update cache
733
 
                        _contacts_cache.addLookup(
734
 
                                ContactsCache.createIdentifier( contact ), id );
735
 
 
736
 
                        // if we haven't already shown that we're overwriting a contact,
737
 
                        // show that we're creating a new contact
738
 
                        if( !ui_informed ) {
739
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
740
 
                                ui_informed = true;
741
 
                        }
 
747
                        showError( R.string.error_unabletoaddcontact );
742
748
                }
743
 
 
744
 
                // if we haven't already shown that we're overwriting or creating a
745
 
                // contact, show that we're merging a contact
746
 
                if( !ui_informed )
747
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
748
 
 
749
 
                // import contact parts
750
 
                if( contact.hasNumbers() )
751
 
                        importContactPhones( id, contact.getNumbers() );
752
 
                if( contact.hasEmails() )
753
 
                        importContactEmails( id, contact.getEmails() );
754
 
                if( contact.hasAddresses() )
755
 
                        importContactAddresses( id, contact.getAddresses() );
756
 
                if( contact.hasOrganisations() )
757
 
                        importContactOrganisations( id, contact.getOrganisations() );
758
749
        }
759
750
 
760
751
        private void importContactPhones( Long id,
761
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
752
                HashMap< String, ContactData.PreferredDetail > datas )
 
753
                throws ContactCreationException
762
754
        {
763
 
                // get URI to contact's phones
764
 
                Uri contact_phones_uri = Uri.withAppendedPath(
765
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
766
 
                        Contacts.People.Phones.CONTENT_DIRECTORY );
767
 
                Set< String > datas_keys = datas.keySet();
768
 
 
769
755
                // add phone numbers
 
756
                Set< String > datas_keys = datas.keySet();
770
757
                Iterator< String > i = datas_keys.iterator();
771
758
                while( i.hasNext() ) {
772
759
                        String number = i.next();
783
770
                                continue;
784
771
 
785
772
                        // add phone number
786
 
                        ContentValues values = new ContentValues();
787
 
                        values.put( Contacts.Phones.TYPE, data.getType() );
788
 
                        values.put( Contacts.Phones.NUMBER, number );
789
 
                        if( data.isPreferred() )
790
 
                                values.put( Contacts.Phones.ISPRIMARY, 1 );
791
 
                        _doit.getContentResolver().insert( contact_phones_uri, values );
 
773
                        _backend.addContactPhone( id, number, data );
792
774
 
793
775
                        // and add this address to the cache to prevent a addition of
794
776
                        // duplicate date from another file
797
779
        }
798
780
 
799
781
        private void importContactEmails( Long id,
800
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
782
                HashMap< String, ContactData.PreferredDetail > datas )
 
783
                throws ContactCreationException
801
784
        {
802
 
                // get URI to contact's contact methods
803
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
804
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
805
 
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
806
 
                Set< String > datas_keys = datas.keySet();
807
 
 
808
785
                // add email addresses
 
786
                Set< String > datas_keys = datas.keySet();
809
787
                Iterator< String > i = datas_keys.iterator();
810
788
                while( i.hasNext() ) {
811
789
                        String email = i.next();
817
795
                                continue;
818
796
 
819
797
                        // add phone number
820
 
                        ContentValues values = new ContentValues();
821
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
822
 
                        values.put( Contacts.ContactMethods.DATA, email );
823
 
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
824
 
                        if( data.isPreferred() )
825
 
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
826
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
827
 
                                values );
 
798
                        _backend.addContactEmail( id, email, data );
828
799
 
829
800
                        // and add this address to the cache to prevent a addition of
830
801
                        // duplicate date from another file
834
805
 
835
806
        private void importContactAddresses( Long id,
836
807
                HashMap< String, ContactData.TypeDetail > datas )
 
808
                throws ContactCreationException
837
809
        {
838
 
                // get URI to contact's contact methods
839
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
840
 
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
841
 
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
842
 
 
843
810
                // add addresses
844
811
                Set< String > datas_keys = datas.keySet();
845
812
                Iterator< String > i = datas_keys.iterator();
853
820
                                continue;
854
821
 
855
822
                        // add postal address
856
 
                        ContentValues values = new ContentValues();
857
 
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
858
 
                        values.put( Contacts.ContactMethods.DATA, address );
859
 
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
860
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
861
 
                                values );
 
823
                        _backend.addContactAddresses( id, address, data );
862
824
 
863
825
                        // and add this address to the cache to prevent a addition of
864
826
                        // duplicate date from another file
868
830
 
869
831
        private void importContactOrganisations( Long id,
870
832
                HashMap< String, ContactData.ExtraDetail > datas )
 
833
                throws ContactCreationException
871
834
        {
872
835
                // add addresses
873
836
                Set< String > datas_keys = datas.keySet();
882
845
                                continue;
883
846
 
884
847
                        // add organisation address
885
 
                        ContentValues values = new ContentValues();
886
 
                        values.put( Contacts.Organizations.PERSON_ID, id );
887
 
                        values.put( Contacts.Organizations.COMPANY, organisation );
888
 
                        values.put( Contacts.ContactMethods.TYPE,
889
 
                                Contacts.OrganizationColumns.TYPE_WORK );
890
 
                        if( data.getExtra() != null )
891
 
                                values.put( Contacts.Organizations.TITLE, data.getExtra() );
892
 
                        _doit.getContentResolver().insert(
893
 
                                Contacts.Organizations.CONTENT_URI, values );
 
848
                        _backend.addContactOrganisation( id, organisation, data );
894
849
 
895
850
                        // and add this address to the cache to prevent a addition of
896
851
                        // duplicate date from another file