/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/org/waxworlds/edam/importcontacts/Importer.java

  • Committer: edam
  • Date: 2011-05-02 18:28:24 UTC
  • Revision ID: edam@waxworlds.org-20110502182824-acgdi3qfxfzqgely
- fixed logic for vcard field types (home, work, cell, etc) so it works
- updated NEWS and TODO
- rewrote most of ContactsCache, including a new ContactIdentifier class to identify contacts in the cache and new cache building code
- contacts now identified in the same way that Andoid displays them (by name, or organisation, or number, or email, in that order)
- propper handling and support for organisations and titles
- validation of imported contact now done by Importer, not VcfImporter
- separated sanitisation and normalisation (for cache lookups)
- generacised PhoneData, EmailData and AddressData classes
- ContactData is now aware of primary numbers, emails and organisations (defaults to the first prefrred one seen, or the first one seen where none is preferred)

Show diffs side-by-side

added added

removed removed

23
23
 
24
24
package org.waxworlds.edam.importcontacts;
25
25
 
26
 
import java.util.Arrays;
27
26
import java.util.HashMap;
28
 
import java.util.HashSet;
29
27
import java.util.Iterator;
30
28
import java.util.Set;
31
29
import java.util.regex.Matcher;
37
35
import android.net.Uri;
38
36
import android.os.Message;
39
37
import android.provider.Contacts;
40
 
import android.provider.Contacts.PhonesColumns;
41
38
 
42
39
 
43
40
public class Importer extends Thread
58
55
        private int _last_merge_decision;
59
56
        private boolean _abort = false;
60
57
        private boolean _is_finished = false;
61
 
        private ContactsCache _contacts_cache = null;
 
58
        private ContactsCache _contactsCache = null;
 
59
 
 
60
        @SuppressWarnings("serial")
 
61
        protected class ContactNeedsMoreInfoException extends Exception
 
62
        {
 
63
        }
62
64
 
63
65
        /**
64
66
         * Data about a contact
120
122
                        }
121
123
                }
122
124
 
123
 
                @SuppressWarnings("serial")
124
 
                protected class ContactNotIdentifiableException extends Exception
125
 
                {
126
 
                }
127
 
 
128
125
                protected String _name = null;
129
126
                protected String _primary_organisation = null;
130
 
                protected boolean _primary_organisation_is_preferred;
 
127
                protected boolean _primary_organisation_is_preferred = false;
131
128
                protected String _primary_number = null;
132
 
                protected int _primary_number_type;
133
 
                protected boolean _primary_number_is_preferred;
 
129
                protected boolean _primary_number_is_preferred = false;
134
130
                protected String _primary_email = null;
135
 
                protected boolean _primary_email_is_preferred;
 
131
                protected boolean _primary_email_is_preferred = false;
136
132
                protected HashMap< String, ExtraDetail > _organisations = null;
137
133
                protected HashMap< String, PreferredDetail > _numbers = null;
138
134
                protected HashMap< String, PreferredDetail > _emails = null;
139
135
                protected HashMap< String, TypeDetail > _addresses = null;
140
136
 
141
 
                private ContactsCache.CacheIdentifier _cache_identifier = null;
142
 
 
143
137
                protected void setName( String name )
144
138
                {
145
139
                        _name = name;
179
173
                                        new ExtraDetail( 0, false, title ) );
180
174
 
181
175
                        // if this is the first organisation added, or it's a preferred
182
 
                        // organisation and the current primary organisation isn't, then
183
 
                        // record this as the primary organisation.
 
176
                        // organisation and a previous organisation wasn't, then remember
 
177
                        // that this is the "primary organisation".
184
178
                        if( _primary_organisation == null ||
185
179
                                ( is_preferred && !_primary_organisation_is_preferred ) )
186
180
                        {
227
221
                                _numbers.put( number,
228
222
                                        new PreferredDetail( type, false ) );
229
223
 
230
 
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
231
 
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
232
 
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
233
 
 
234
224
                        // if this is the first number added, or it's a preferred number
235
 
                        // and the current primary number isn't, or this number is on equal
236
 
                        // standing with the primary number in terms of preference and it is
237
 
                        // a voice number and the primary number isn't, then record this as
238
 
                        // the primary number.
 
225
                        // and a previous number wasn't, then remember that this is the
 
226
                        // "primary number".
239
227
                        if( _primary_number == null ||
240
 
                                ( is_preferred && !_primary_number_is_preferred ) ||
241
 
                                ( is_preferred == _primary_number_is_preferred &&
242
 
                                        !non_voice_types.contains( type ) &&
243
 
                                        non_voice_types.contains( _primary_number_type ) ) )
 
228
                                ( is_preferred && !_primary_number_is_preferred ) )
244
229
                        {
245
230
                                _primary_number = number;
246
 
                                _primary_number_type = type;
247
231
                                _primary_number_is_preferred = is_preferred;
248
232
                        }
249
233
                }
285
269
                        if( !_emails.containsKey( email ) )
286
270
                                _emails.put( email, new PreferredDetail( type, false ) );
287
271
 
288
 
                        // if this is the first email added, or it's a preferred email and
289
 
                        // the current primary organisation isn't, then record this as the
290
 
                        // primary email.
 
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".
291
275
                        if( _primary_email == null ||
292
276
                                ( is_preferred && !_primary_email_is_preferred ) )
293
277
                        {
342
326
                }
343
327
 
344
328
                protected void finalise()
345
 
                        throws ContactNotIdentifiableException
346
329
                {
347
330
                        // ensure that if there is a primary number, it is preferred so
348
331
                        // that there is always one preferred number. Android will assign
366
349
                                _organisations.put( _primary_organisation,
367
350
                                        new ExtraDetail( 0, true, data.getExtra() ) );
368
351
                        }
369
 
 
370
 
                        // create a cache identifier from this contact data, which can be
371
 
                        // used to look-up an existing contact
372
 
                        _cache_identifier = ContactsCache.createIdentifier( this );
373
 
                        if( _cache_identifier == null )
374
 
                                throw new ContactNotIdentifiableException();
375
 
                }
376
 
 
377
 
                public ContactsCache.CacheIdentifier getCacheIdentifier()
378
 
                {
379
 
                        return _cache_identifier;
380
352
                }
381
353
 
382
354
                private String sanitisePhoneNumber( String number )
422
394
                        setProgressMessage( R.string.doit_caching );
423
395
 
424
396
                        // build a cache of existing contacts
425
 
                        _contacts_cache = new ContactsCache();
426
 
                        _contacts_cache.buildCache( _doit );
 
397
                        _contactsCache = new ContactsCache();
 
398
                        _contactsCache.buildCache( _doit );
427
399
 
428
400
                        // do the import
429
401
                        onImport();
550
522
                        Doit.MESSAGE_SETPROGRESSMESSAGE, getText( res ) ) );
551
523
        }
552
524
 
553
 
        protected void setProgressMax( int max_progress )
 
525
        protected void setProgressMax( int maxProgress )
554
526
                        throws AbortImportException
555
527
        {
556
528
                checkAbort();
557
529
                _doit._handler.sendMessage( Message.obtain(
558
530
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
559
 
                        new Integer( max_progress ) ) );
 
531
                        new Integer( maxProgress ) ) );
560
532
        }
561
533
 
562
 
        protected void setTmpProgress( int tmp_progress )
563
 
                throws AbortImportException
 
534
        protected void setTmpProgress( int tmpProgress ) throws AbortImportException
564
535
        {
565
536
                checkAbort();
566
537
                _doit._handler.sendMessage( Message.obtain(
567
538
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
568
 
                        new Integer( tmp_progress ) ) );
 
539
                        new Integer( tmpProgress ) ) );
569
540
        }
570
541
 
571
542
        protected void setProgress( int progress ) throws AbortImportException
597
568
                return _doit.getText( res );
598
569
        }
599
570
 
600
 
        synchronized private boolean checkForDuplicate(
601
 
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
602
 
                throws AbortImportException
 
571
        protected boolean isImportRequired( ContactData contact )
 
572
                        throws AbortImportException, ContactNeedsMoreInfoException
 
573
        {
 
574
                checkAbort();
 
575
                return isImportRequired( contact, _merge_setting );
 
576
        }
 
577
 
 
578
        synchronized private boolean isImportRequired(
 
579
                ContactData contact, int merge_setting )
 
580
                throws AbortImportException, ContactNeedsMoreInfoException
603
581
        {
604
582
                _last_merge_decision = merge_setting;
605
583
 
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)
 
584
                // create a cache identifier which we can use to detect if this contact
 
585
                // is valid for importing
 
586
                ContactsCache.CacheIdentifier identifier =
 
587
                        ContactsCache.createIdentifier( contact );
 
588
                if( identifier == null )
 
589
                        throw new ContactNeedsMoreInfoException();
609
590
 
610
591
                // handle special cases
611
592
                switch( merge_setting )
612
593
                {
613
594
                case Doit.ACTION_KEEP:
614
595
                        // if we keep contacts on duplicate, we better check for one
615
 
                        return !_contacts_cache.canLookup( cache_identifier );
 
596
                        return !_contactsCache.canLookup( identifier );
616
597
 
617
598
                case Doit.ACTION_PROMPT:
618
599
                        // if we are prompting on duplicate, we better check for one and if
619
600
                        // the contact doesn'te exist, we want to import it
620
 
                        if( !_contacts_cache.canLookup( cache_identifier ) )
 
601
                        if( !_contactsCache.canLookup( identifier ) )
621
602
                                return true;
622
603
 
623
604
                        // ok, it exists, so do prompt
624
605
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
625
 
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
 
606
                                Doit.MESSAGE_MERGEPROMPT, identifier.getDetail() ) );
626
607
                        try {
627
608
                                wait();
628
609
                        }
636
617
                                _merge_setting = _response;
637
618
 
638
619
                        // recurse, with our new merge setting
639
 
                        return checkForDuplicate( cache_identifier, _response );
 
620
                        return isImportRequired( contact, _response );
640
621
                }
641
622
 
642
623
                // for all other cases (either overwriting or merging) we will need the
655
636
        {
656
637
                checkAbort();
657
638
 
658
 
                // It is expected that we use contact.getCacheIdentifier() here. The
659
 
                // contact we are passed should have been successfully finalise()d,
660
 
                // which includes generating a valid cache identifier.
661
 
                ContactsCache.CacheIdentifier cache_identifier =
662
 
                        contact.getCacheIdentifier();
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
 
 
670
639
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
671
640
//                      finish( ACTION_ABORT );
672
641
 
673
 
                // keep track of whether we've informed the UI of what we're doing
674
 
                boolean ui_informed = false;
675
 
 
676
 
                // attempt to lookup the id of an existing contact in the cache with
677
 
                // this contact data's cache identifier
678
 
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
 
642
                ContentValues values = new ContentValues();
 
643
                boolean uiInformed = false;
 
644
                Long id = null;
 
645
 
 
646
                // give the contact a chance to finalise it's data
 
647
                contact.finalise();
 
648
 
 
649
                // create something, from the contact data, that we can use to identify
 
650
                // a cache entry and attempt to lookup the id of an existing contact in
 
651
                // the cache with it
 
652
                ContactsCache.CacheIdentifier identifier =
 
653
                        ContactsCache.createIdentifier( contact );
 
654
                if( identifier != null ) id = (Long)_contactsCache.lookup( identifier );
679
655
 
680
656
                // does contact exist already?
681
657
                if( id != null )
684
660
                        if( _last_merge_decision == Doit.ACTION_KEEP ) return;
685
661
 
686
662
                        // get contact's URI
687
 
                        Uri contact_uri = ContentUris.withAppendedId(
 
663
                        Uri contactUri = ContentUris.withAppendedId(
688
664
                                Contacts.People.CONTENT_URI, id );
689
665
 
690
666
                        // should we destroy the existing contact before importing?
691
667
                        if( _last_merge_decision == Doit.ACTION_OVERWRITE )
692
668
                        {
693
669
                                // remove from device
694
 
                                _doit.getContentResolver().delete( contact_uri, null, null );
 
670
                                _doit.getContentResolver().delete( contactUri, null, null );
695
671
 
696
672
                                // update cache
697
 
                                _contacts_cache.removeLookup( contact.getCacheIdentifier() );
698
 
                                _contacts_cache.removeAssociatedData( id );
 
673
                                _contactsCache.removeLookup( identifier );
 
674
                                _contactsCache.removeAssociatedData( id );
699
675
 
700
676
                                // show that we're overwriting a contact
701
677
                                _doit._handler.sendEmptyMessage(
702
678
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
703
 
                                ui_informed = true;
 
679
                                uiInformed = true;
704
680
 
705
681
                                // discard the contact id
706
682
                                id = null;
712
688
                if( id == null )
713
689
                {
714
690
                        // create a new contact
715
 
                        ContentValues values = new ContentValues();
716
691
                        values.put( Contacts.People.NAME, contact._name );
717
 
                        Uri contact_uri = _doit.getContentResolver().insert(
 
692
                        Uri contactUri = _doit.getContentResolver().insert(
718
693
                                Contacts.People.CONTENT_URI, values );
719
 
                        id = ContentUris.parseId( contact_uri );
 
694
                        id = ContentUris.parseId( contactUri );
720
695
                        if( id == null || id <= 0 )
721
696
                                showError( R.string.error_unabletoaddcontact );
722
697
 
730
705
                        }
731
706
 
732
707
                        // update cache
733
 
                        _contacts_cache.addLookup(
 
708
                        _contactsCache.addLookup(
734
709
                                ContactsCache.createIdentifier( contact ), id );
735
710
 
736
711
                        // if we haven't already shown that we're overwriting a contact,
737
712
                        // show that we're creating a new contact
738
 
                        if( !ui_informed ) {
 
713
                        if( !uiInformed ) {
739
714
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
740
 
                                ui_informed = true;
 
715
                                uiInformed = true;
741
716
                        }
742
717
                }
743
718
 
744
719
                // 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 )
 
720
                // contact show that we're merging a contact
 
721
                if( !uiInformed )
747
722
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
748
723
 
749
724
                // import contact parts
761
736
                        HashMap< String, ContactData.PreferredDetail > datas )
762
737
        {
763
738
                // get URI to contact's phones
764
 
                Uri contact_phones_uri = Uri.withAppendedPath(
 
739
                Uri contactPhonesUri = Uri.withAppendedPath(
765
740
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
766
741
                        Contacts.People.Phones.CONTENT_DIRECTORY );
767
 
                Set< String > datas_keys = datas.keySet();
 
742
                Set< String > datasKeys = datas.keySet();
768
743
 
769
744
                // add phone numbers
770
 
                Iterator< String > i = datas_keys.iterator();
 
745
                Iterator< String > i = datasKeys.iterator();
771
746
                while( i.hasNext() ) {
772
747
                        String number = i.next();
773
748
                        ContactData.PreferredDetail data = datas.get( number );
779
754
                        // if the number exists at all, it doesn't need importing. Because
780
755
                        // of this, we also can't update the cache (which we don't need to
781
756
                        // anyway, so it's not a problem).
782
 
                        if( _contacts_cache.hasAssociatedNumber( id, number ) )
 
757
                        if( _contactsCache.hasAssociatedNumber( id, number ) )
783
758
                                continue;
784
759
 
785
760
                        // add phone number
788
763
                        values.put( Contacts.Phones.NUMBER, number );
789
764
                        if( data.isPreferred() )
790
765
                                values.put( Contacts.Phones.ISPRIMARY, 1 );
791
 
                        _doit.getContentResolver().insert( contact_phones_uri, values );
 
766
                        _doit.getContentResolver().insert( contactPhonesUri, values );
792
767
 
793
768
                        // and add this address to the cache to prevent a addition of
794
769
                        // duplicate date from another file
795
 
                        _contacts_cache.addAssociatedNumber( id, number );
 
770
                        _contactsCache.addAssociatedNumber( id, number );
796
771
                }
797
772
        }
798
773
 
800
775
                        HashMap< String, ContactData.PreferredDetail > datas )
801
776
        {
802
777
                // get URI to contact's contact methods
803
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
 
778
                Uri contactContactMethodsUri = Uri.withAppendedPath(
804
779
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
805
780
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
806
 
                Set< String > datas_keys = datas.keySet();
 
781
                Set< String > datasKeys = datas.keySet();
807
782
 
808
783
                // add email addresses
809
 
                Iterator< String > i = datas_keys.iterator();
 
784
                Iterator< String > i = datasKeys.iterator();
810
785
                while( i.hasNext() ) {
811
786
                        String email = i.next();
812
787
                        ContactData.PreferredDetail data = datas.get( email );
813
788
 
814
789
                        // we don't want to add this email address if it exists already or
815
790
                        // we would introduce duplicates.
816
 
                        if( _contacts_cache.hasAssociatedEmail( id, email ) )
 
791
                        if( _contactsCache.hasAssociatedEmail( id, email ) )
817
792
                                continue;
818
793
 
819
794
                        // add phone number
823
798
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
824
799
                        if( data.isPreferred() )
825
800
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
826
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
 
801
                        _doit.getContentResolver().insert( contactContactMethodsUri,
827
802
                                values );
828
803
 
829
804
                        // and add this address to the cache to prevent a addition of
830
805
                        // duplicate date from another file
831
 
                        _contacts_cache.addAssociatedEmail( id, email );
 
806
                        _contactsCache.addAssociatedEmail( id, email );
832
807
                }
833
808
        }
834
809
 
836
811
                HashMap< String, ContactData.TypeDetail > datas )
837
812
        {
838
813
                // get URI to contact's contact methods
839
 
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
 
814
                Uri contactContactMethodsUri = Uri.withAppendedPath(
840
815
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
841
816
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
842
817
 
843
818
                // add addresses
844
 
                Set< String > datas_keys = datas.keySet();
845
 
                Iterator< String > i = datas_keys.iterator();
 
819
                Set< String > datasKeys = datas.keySet();
 
820
                Iterator< String > i = datasKeys.iterator();
846
821
                while( i.hasNext() ) {
847
822
                        String address = i.next();
848
823
                        ContactData.TypeDetail data = datas.get( address );
849
824
 
850
825
                        // we don't want to add this address if it exists already or we
851
826
                        // would introduce duplicates
852
 
                        if( _contacts_cache.hasAssociatedAddress( id, address ) )
 
827
                        if( _contactsCache.hasAssociatedAddress( id, address ) )
853
828
                                continue;
854
829
 
855
830
                        // add postal address
857
832
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
858
833
                        values.put( Contacts.ContactMethods.DATA, address );
859
834
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
860
 
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
 
835
                        _doit.getContentResolver().insert( contactContactMethodsUri,
861
836
                                values );
862
837
 
863
838
                        // and add this address to the cache to prevent a addition of
864
839
                        // duplicate date from another file
865
 
                        _contacts_cache.addAssociatedAddress( id, address );
 
840
                        _contactsCache.addAssociatedAddress( id, address );
866
841
                }
867
842
        }
868
843
 
870
845
                HashMap< String, ContactData.ExtraDetail > datas )
871
846
        {
872
847
                // add addresses
873
 
                Set< String > datas_keys = datas.keySet();
874
 
                Iterator< String > i = datas_keys.iterator();
 
848
                Set< String > datasKeys = datas.keySet();
 
849
                Iterator< String > i = datasKeys.iterator();
875
850
                while( i.hasNext() ) {
876
851
                        String organisation = i.next();
877
852
                        ContactData.ExtraDetail data = datas.get( organisation );
878
853
 
879
854
                        // we don't want to add this address if it exists already or we
880
855
                        // would introduce duplicates
881
 
                        if( _contacts_cache.hasAssociatedOrganisation( id, organisation ) )
 
856
                        if( _contactsCache.hasAssociatedOrganisation( id, organisation ) )
882
857
                                continue;
883
858
 
884
859
                        // add organisation address
894
869
 
895
870
                        // and add this address to the cache to prevent a addition of
896
871
                        // duplicate date from another file
897
 
                        _contacts_cache.addAssociatedOrganisation( id, organisation );
 
872
                        _contactsCache.addAssociatedOrganisation( id, organisation );
898
873
                }
899
874
        }
900
875