/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-04-24 09:56:17 UTC
  • Revision ID: tim@ed.am-20120424095617-lsfkkpkrlqk9xthn
updated all URLs, email addresses and package names to ed.am

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * Importer.java
3
3
 *
4
 
 * Copyright (C) 2009 to 2012 Tim Marston <tim@ed.am>
 
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
27
27
import java.util.HashMap;
28
28
import java.util.HashSet;
29
29
import java.util.Iterator;
30
 
import java.util.Locale;
31
30
import java.util.Set;
32
31
import java.util.regex.Matcher;
33
32
import java.util.regex.Pattern;
34
33
 
35
 
import am.ed.importcontacts.Backend.ContactCreationException;
 
34
import android.content.ContentUris;
 
35
import android.content.ContentValues;
36
36
import android.content.SharedPreferences;
 
37
import android.net.Uri;
37
38
import android.os.Message;
 
39
import android.provider.Contacts;
 
40
import android.provider.Contacts.PhonesColumns;
 
41
 
38
42
 
39
43
public class Importer extends Thread
40
44
{
55
59
        private boolean _abort = false;
56
60
        private boolean _is_finished = false;
57
61
        private ContactsCache _contacts_cache = null;
58
 
        private Backend _backend = null;
59
62
 
60
63
        /**
61
64
         * Data about a contact
62
65
         */
63
66
        public class ContactData
64
67
        {
65
 
                public final static int TYPE_HOME = 0;
66
 
                public final static int TYPE_WORK = 1;
67
 
                public final static int TYPE_MOBILE = 2;        // only used with phones
68
 
                public final static int TYPE_FAX_HOME = 3;      // only used with phones
69
 
                public final static int TYPE_FAX_WORK = 4;      // only used with phones
70
 
                public final static int TYPE_PAGER = 5;         // only used with phones
71
 
 
72
68
                class TypeDetail
73
69
                {
74
70
                        protected int _type;
141
137
                protected HashMap< String, PreferredDetail > _numbers = null;
142
138
                protected HashMap< String, PreferredDetail > _emails = null;
143
139
                protected HashMap< String, TypeDetail > _addresses = null;
144
 
                protected HashSet< String > _notes = null;
145
140
 
146
141
                private ContactsCache.CacheIdentifier _cache_identifier = null;
147
142
 
233
228
                                        new PreferredDetail( type, false ) );
234
229
 
235
230
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
236
 
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
 
231
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
 
232
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
237
233
 
238
234
                        // if this is the first number added, or it's a preferred number
239
235
                        // and the current primary number isn't, or this number is on equal
278
274
                        email = sanitisesEmailAddress( email );
279
275
                        if( email == null )
280
276
                        {
281
 
                                // TODO: warn that an imported email address is being ignored
 
277
                                // TODO: warn that an imported email addtrss is being ignored
282
278
                                return;
283
279
                        }
284
280
 
345
341
                        return _addresses;
346
342
                }
347
343
 
348
 
                protected void addNote( String note )
349
 
                {
350
 
                        if( _notes == null ) _notes = new HashSet< String >();
351
 
                        if( !_notes.contains( note ) )
352
 
                                _notes.add( note );
353
 
                }
354
 
 
355
 
                public boolean hasNotes()
356
 
                {
357
 
                        return _notes != null && _notes.size() > 0;
358
 
                }
359
 
 
360
 
                public HashSet< String > getNotes()
361
 
                {
362
 
                        return _notes;
363
 
                }
364
 
 
365
344
                protected void finalise()
366
345
                        throws ContactNotIdentifiableException
367
346
                {
390
369
 
391
370
                        // create a cache identifier from this contact data, which can be
392
371
                        // used to look-up an existing contact
393
 
                        _cache_identifier = ContactsCache.CacheIdentifier.factory( this );
 
372
                        _cache_identifier = ContactsCache.createIdentifier( this );
394
373
                        if( _cache_identifier == null )
395
374
                                throw new ContactNotIdentifiableException();
396
375
                }
417
396
                        Matcher m = p.matcher( email );
418
397
                        if( m.matches() ) {
419
398
                                String[] bits = email.split( "@" );
420
 
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase( Locale.US );
 
399
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
421
400
                        }
422
401
                        return null;
423
402
                }
442
421
                        // update UI
443
422
                        setProgressMessage( R.string.doit_caching );
444
423
 
445
 
                        // create the appropriate backend
446
 
                        if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
447
 
                                _backend = new ContactsContractBackend( _doit );
448
 
                        else
449
 
                                _backend = new ContactsBackend( _doit );
450
 
 
451
 
                        // create a cache of existing contacts and populate it
 
424
                        // build a cache of existing contacts
452
425
                        _contacts_cache = new ContactsCache();
453
 
                        _backend.populateCache( _contacts_cache );
 
426
                        _contacts_cache.buildCache( _doit );
454
427
 
455
428
                        // do the import
456
429
                        onImport();
583
556
                checkAbort();
584
557
                _doit._handler.sendMessage( Message.obtain(
585
558
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
586
 
                        Integer.valueOf( max_progress ) ) );
 
559
                        new Integer( max_progress ) ) );
587
560
        }
588
561
 
589
562
        protected void setTmpProgress( int tmp_progress )
592
565
                checkAbort();
593
566
                _doit._handler.sendMessage( Message.obtain(
594
567
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
595
 
                        Integer.valueOf( tmp_progress ) ) );
 
568
                        new Integer( tmp_progress ) ) );
596
569
        }
597
570
 
598
571
        protected void setProgress( int progress ) throws AbortImportException
600
573
                checkAbort();
601
574
                _doit._handler.sendMessage( Message.obtain(
602
575
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
603
 
                        Integer.valueOf( progress ) ) );
 
576
                        new Integer( progress ) ) );
604
577
        }
605
578
 
606
579
        protected void finish( int action ) throws AbortImportException
624
597
                return _doit.getText( res );
625
598
        }
626
599
 
627
 
        /**
628
 
         * Should we skip a contact, given whether it exists or not and the current
629
 
         * merge setting?  This routine handles throwing up a prompt, if required.
630
 
         * @param contact_detail the display name of the contact
631
 
         * @param exists true if this contact matches one in the cache
632
 
         * @param merge_setting the merge setting to use
633
 
         * @return true if the contact should be skipped outright
634
 
         * @throws AbortImportException
635
 
         */
636
 
        synchronized private boolean shouldWeSkipContact( String contact_detail,
637
 
                boolean exists, int merge_setting ) throws AbortImportException
 
600
        synchronized private boolean checkForDuplicate(
 
601
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
 
602
                throws AbortImportException
638
603
        {
639
604
                _last_merge_decision = merge_setting;
640
605
 
 
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
 
641
610
                // handle special cases
642
611
                switch( merge_setting )
643
612
                {
644
613
                case Doit.ACTION_KEEP:
645
 
                        // if we are skipping on a duplicate, check for one
646
 
                        return exists;
 
614
                        // if we keep contacts on duplicate, we better check for one
 
615
                        return !_contacts_cache.canLookup( cache_identifier );
647
616
 
648
617
                case Doit.ACTION_PROMPT:
649
 
                        // if we are prompting on duplicate, then we can say that we won't
650
 
                        // skip if there isn't one
651
 
                        if( !exists ) return false;
 
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;
652
622
 
653
 
                        // ok, duplicate exists, so do prompt
 
623
                        // ok, it exists, so do prompt
654
624
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
655
 
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
 
625
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
656
626
                        try {
657
627
                                wait();
658
628
                        }
666
636
                                _merge_setting = _response;
667
637
 
668
638
                        // recurse, with our new merge setting
669
 
                        return shouldWeSkipContact( contact_detail, exists, _response );
 
639
                        return checkForDuplicate( cache_identifier, _response );
670
640
                }
671
641
 
672
 
                // for all other cases (either overwriting or merging) we don't skip
673
 
                return false;
 
642
                // for all other cases (either overwriting or merging) we will need the
 
643
                // imported data
 
644
                return true;
674
645
        }
675
646
 
676
647
        protected void skipContact() throws AbortImportException
677
648
        {
678
649
                checkAbort();
679
 
 
680
 
                // show that we're skipping a new contact
681
650
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
682
651
        }
683
652
 
692
661
                ContactsCache.CacheIdentifier cache_identifier =
693
662
                        contact.getCacheIdentifier();
694
663
 
 
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
 
695
670
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
696
671
//                      finish( ACTION_ABORT );
697
672
 
 
673
                // keep track of whether we've informed the UI of what we're doing
 
674
                boolean ui_informed = false;
 
675
 
698
676
                // attempt to lookup the id of an existing contact in the cache with
699
677
                // this contact data's cache identifier
700
678
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
701
679
 
702
 
                // check to see if this contact should be skipped
703
 
                if( shouldWeSkipContact( cache_identifier.getDetail(), id != null,
704
 
                        _merge_setting ) )
 
680
                // does contact exist already?
 
681
                if( id != null )
705
682
                {
706
 
                        // show that we're skipping a contact
707
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
708
 
                        return;
 
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 )
 
692
                        {
 
693
                                // remove from device
 
694
                                _doit.getContentResolver().delete( contact_uri, null, null );
 
695
 
 
696
                                // 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;
 
707
                        }
709
708
                }
710
709
 
711
 
                // if a contact exists, and we're overwriting, destroy the existing
712
 
                // contact before importing
713
 
                boolean contact_deleted = false;
714
 
                if( id != null && _last_merge_decision == Doit.ACTION_OVERWRITE )
 
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 )
715
713
                {
716
 
                        contact_deleted = true;
 
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 );
717
722
 
718
 
                        // remove from device
719
 
                        _backend.deleteContact( id );
 
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
                        }
720
731
 
721
732
                        // update cache
722
 
                        _contacts_cache.removeLookup( cache_identifier );
723
 
                        _contacts_cache.removeAssociatedData( id );
724
 
 
725
 
                        // show that we're overwriting a contact
726
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
727
 
 
728
 
                        // discard the contact id
729
 
                        id = null;
730
 
                }
731
 
 
732
 
                try {
733
 
                        // if we don't have a contact id yet (or we did, but we destroyed it
734
 
                        // when we deleted the contact), we'll have to create a new contact
735
 
                        if( id == null )
736
 
                        {
737
 
                                // create a new contact
738
 
                                id = _backend.addContact( contact._name );
739
 
 
740
 
                                // update cache
741
 
                                _contacts_cache.addLookup( cache_identifier, id );
742
 
 
743
 
                                // if we haven't already shown that we're overwriting a contact,
744
 
                                // show that we're creating a new contact
745
 
                                if( !contact_deleted )
746
 
                                        _doit._handler.sendEmptyMessage(
747
 
                                                Doit.MESSAGE_CONTACTCREATED );
 
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;
748
741
                        }
749
 
                        else
750
 
                                // show that we're merging with an existing contact
751
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
752
 
 
753
 
                        // import contact parts
754
 
                        if( contact.hasNumbers() )
755
 
                                importContactPhones( id, contact.getNumbers() );
756
 
                        if( contact.hasEmails() )
757
 
                                importContactEmails( id, contact.getEmails() );
758
 
                        if( contact.hasAddresses() )
759
 
                                importContactAddresses( id, contact.getAddresses() );
760
 
                        if( contact.hasOrganisations() )
761
 
                                importContactOrganisations( id, contact.getOrganisations() );
762
 
                        if( contact.hasNotes() )
763
 
                                importContactNotes( id, contact.getNotes() );
764
 
                }
765
 
                catch( Backend.ContactCreationException e )
766
 
                {
767
 
                        showError( R.string.error_unabletoaddcontact );
768
 
                }
 
742
                }
 
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() );
769
758
        }
770
759
 
771
760
        private void importContactPhones( Long id,
772
 
                HashMap< String, ContactData.PreferredDetail > datas )
773
 
                throws ContactCreationException
 
761
                        HashMap< String, ContactData.PreferredDetail > datas )
774
762
        {
 
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
 
775
769
                // add phone numbers
776
 
                Set< String > datas_keys = datas.keySet();
777
770
                Iterator< String > i = datas_keys.iterator();
778
771
                while( i.hasNext() ) {
779
772
                        String number = i.next();
790
783
                                continue;
791
784
 
792
785
                        // add phone number
793
 
                        _backend.addContactPhone( id, number, data );
 
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 );
794
792
 
795
793
                        // and add this address to the cache to prevent a addition of
796
794
                        // duplicate date from another file
799
797
        }
800
798
 
801
799
        private void importContactEmails( Long id,
802
 
                HashMap< String, ContactData.PreferredDetail > datas )
803
 
                throws ContactCreationException
 
800
                        HashMap< String, ContactData.PreferredDetail > datas )
804
801
        {
 
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
 
805
808
                // add email addresses
806
 
                Set< String > datas_keys = datas.keySet();
807
809
                Iterator< String > i = datas_keys.iterator();
808
810
                while( i.hasNext() ) {
809
811
                        String email = i.next();
815
817
                                continue;
816
818
 
817
819
                        // add phone number
818
 
                        _backend.addContactEmail( id, email, data );
 
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 );
819
828
 
820
829
                        // and add this address to the cache to prevent a addition of
821
830
                        // duplicate date from another file
825
834
 
826
835
        private void importContactAddresses( Long id,
827
836
                HashMap< String, ContactData.TypeDetail > datas )
828
 
                throws ContactCreationException
829
837
        {
 
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
 
830
843
                // add addresses
831
844
                Set< String > datas_keys = datas.keySet();
832
845
                Iterator< String > i = datas_keys.iterator();
840
853
                                continue;
841
854
 
842
855
                        // add postal address
843
 
                        _backend.addContactAddresses( id, address, data );
 
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 );
844
862
 
845
863
                        // and add this address to the cache to prevent a addition of
846
864
                        // duplicate date from another file
850
868
 
851
869
        private void importContactOrganisations( Long id,
852
870
                HashMap< String, ContactData.ExtraDetail > datas )
853
 
                throws ContactCreationException
854
871
        {
855
872
                // add addresses
856
873
                Set< String > datas_keys = datas.keySet();
865
882
                                continue;
866
883
 
867
884
                        // add organisation address
868
 
                        _backend.addContactOrganisation( id, organisation, data );
 
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 );
869
894
 
870
895
                        // and add this address to the cache to prevent a addition of
871
896
                        // duplicate date from another file
873
898
                }
874
899
        }
875
900
 
876
 
        private void importContactNotes( Long id,
877
 
                HashSet< String > datas )
878
 
                throws ContactCreationException
879
 
        {
880
 
                // add notes
881
 
                Iterator< String > i = datas.iterator();
882
 
                while( i.hasNext() ) {
883
 
                        String note = i.next();
884
 
 
885
 
                        // we don't want to add this note if it exists already or we would
886
 
                        // introduce duplicates
887
 
                        if( _contacts_cache.hasAssociatedNote( id, note ) )
888
 
                                continue;
889
 
 
890
 
                        // add note
891
 
                        _backend.addContactNote( id, note );
892
 
 
893
 
                        // and add this note to the cache to prevent a addition of duplicate
894
 
                        // date from another file
895
 
                        _contacts_cache.addAssociatedNote( id, note );
896
 
                }
897
 
 
898
 
        }
899
 
 
900
901
        synchronized protected void checkAbort() throws AbortImportException
901
902
        {
902
903
                if( _abort ) {