/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-06-04 16:52:28 UTC
  • Revision ID: edam@waxworlds.org-20110604165228-jam230oo29u1m06u
- properly handle multiple TYPE= params in one entry in a v3.0 vCard
- when deciding which phone number to use as the pimary number, a voice number takes precedence over a non-voice (fax or pager) number of the same standing in terms of being preferred or not.

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