/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-05 21:49:43 UTC
  • Revision ID: edam@waxworlds.org-20110505214943-bg0cn6qz0gr49dlk
- updated TODO
- made varibale names consistent (camelCaseVariables now_use_underscores)

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 <tim@ed.am>
 
4
 * Copyright (C) 2009 to 2011 Tim Marston <edam@waxworlds.org>
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://ed.am/dev/android/import-contacts
 
8
 * http://www.waxworlds.org/edam/software/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 am.ed.importcontacts;
 
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;
32
30
import java.util.regex.Pattern;
33
31
 
 
32
import android.content.ContentUris;
 
33
import android.content.ContentValues;
34
34
import android.content.SharedPreferences;
 
35
import android.net.Uri;
35
36
import android.os.Message;
36
 
import android.provider.Contacts.PhonesColumns;
 
37
import android.provider.Contacts;
37
38
 
38
39
 
39
40
public class Importer extends Thread
55
56
        private boolean _abort = false;
56
57
        private boolean _is_finished = false;
57
58
        private ContactsCache _contacts_cache = null;
58
 
        private Backend _backend = null;
 
59
 
 
60
        @SuppressWarnings("serial")
 
61
        protected class ContactNeedsMoreInfoException extends Exception
 
62
        {
 
63
        }
59
64
 
60
65
        /**
61
66
         * Data about a contact
117
122
                        }
118
123
                }
119
124
 
120
 
                @SuppressWarnings("serial")
121
 
                protected class ContactNotIdentifiableException extends Exception
122
 
                {
123
 
                }
124
 
 
125
125
                protected String _name = null;
126
126
                protected String _primary_organisation = null;
127
 
                protected boolean _primary_organisation_is_preferred;
 
127
                protected boolean _primary_organisation_is_preferred = false;
128
128
                protected String _primary_number = null;
129
 
                protected int _primary_number_type;
130
 
                protected boolean _primary_number_is_preferred;
 
129
                protected boolean _primary_number_is_preferred = false;
131
130
                protected String _primary_email = null;
132
 
                protected boolean _primary_email_is_preferred;
 
131
                protected boolean _primary_email_is_preferred = false;
133
132
                protected HashMap< String, ExtraDetail > _organisations = null;
134
133
                protected HashMap< String, PreferredDetail > _numbers = null;
135
134
                protected HashMap< String, PreferredDetail > _emails = null;
136
135
                protected HashMap< String, TypeDetail > _addresses = null;
137
136
 
138
 
                private ContactsCache.CacheIdentifier _cache_identifier = null;
139
 
 
140
137
                protected void setName( String name )
141
138
                {
142
139
                        _name = name;
176
173
                                        new ExtraDetail( 0, false, title ) );
177
174
 
178
175
                        // if this is the first organisation added, or it's a preferred
179
 
                        // organisation and the current primary organisation isn't, then
180
 
                        // record this as the primary organisation.
 
176
                        // organisation and a previous organisation wasn't, then remember
 
177
                        // that this is the "primary organisation".
181
178
                        if( _primary_organisation == null ||
182
179
                                ( is_preferred && !_primary_organisation_is_preferred ) )
183
180
                        {
224
221
                                _numbers.put( number,
225
222
                                        new PreferredDetail( type, false ) );
226
223
 
227
 
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
228
 
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
229
 
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
230
 
 
231
224
                        // if this is the first number added, or it's a preferred number
232
 
                        // and the current primary number isn't, or this number is on equal
233
 
                        // standing with the primary number in terms of preference and it is
234
 
                        // a voice number and the primary number isn't, then record this as
235
 
                        // the primary number.
 
225
                        // and a previous number wasn't, then remember that this is the
 
226
                        // "primary number".
236
227
                        if( _primary_number == null ||
237
 
                                ( is_preferred && !_primary_number_is_preferred ) ||
238
 
                                ( is_preferred == _primary_number_is_preferred &&
239
 
                                        !non_voice_types.contains( type ) &&
240
 
                                        non_voice_types.contains( _primary_number_type ) ) )
 
228
                                ( is_preferred && !_primary_number_is_preferred ) )
241
229
                        {
242
230
                                _primary_number = number;
243
 
                                _primary_number_type = type;
244
231
                                _primary_number_is_preferred = is_preferred;
245
232
                        }
246
233
                }
282
269
                        if( !_emails.containsKey( email ) )
283
270
                                _emails.put( email, new PreferredDetail( type, false ) );
284
271
 
285
 
                        // if this is the first email added, or it's a preferred email and
286
 
                        // the current primary organisation isn't, then record this as the
287
 
                        // 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".
288
275
                        if( _primary_email == null ||
289
276
                                ( is_preferred && !_primary_email_is_preferred ) )
290
277
                        {
339
326
                }
340
327
 
341
328
                protected void finalise()
342
 
                        throws ContactNotIdentifiableException
343
329
                {
344
330
                        // ensure that if there is a primary number, it is preferred so
345
331
                        // that there is always one preferred number. Android will assign
363
349
                                _organisations.put( _primary_organisation,
364
350
                                        new ExtraDetail( 0, true, data.getExtra() ) );
365
351
                        }
366
 
 
367
 
                        // create a cache identifier from this contact data, which can be
368
 
                        // used to look-up an existing contact
369
 
                        _cache_identifier = ContactsCache.createIdentifier( this );
370
 
                        if( _cache_identifier == null )
371
 
                                throw new ContactNotIdentifiableException();
372
 
                }
373
 
 
374
 
                public ContactsCache.CacheIdentifier getCacheIdentifier()
375
 
                {
376
 
                        return _cache_identifier;
377
352
                }
378
353
 
379
354
                private String sanitisePhoneNumber( String number )
418
393
                        // update UI
419
394
                        setProgressMessage( R.string.doit_caching );
420
395
 
421
 
//                      if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
422
 
//                              _backend = new ContactsContractBackend();
423
 
//                      else
424
 
                                _backend = new ContactsBackend( _doit );
425
 
 
426
 
                        // create a cache of existing contacts and populate it
 
396
                        // build a cache of existing contacts
427
397
                        _contacts_cache = new ContactsCache();
428
 
                        _backend.populateCache( _contacts_cache );
 
398
                        _contacts_cache.buildCache( _doit );
429
399
 
430
400
                        // do the import
431
401
                        onImport();
599
569
                return _doit.getText( res );
600
570
        }
601
571
 
602
 
        synchronized private boolean checkForDuplicate(
603
 
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
604
 
                throws AbortImportException
 
572
        protected boolean isImportRequired( ContactData contact )
 
573
                        throws AbortImportException, ContactNeedsMoreInfoException
 
574
        {
 
575
                checkAbort();
 
576
                return isImportRequired( contact, _merge_setting );
 
577
        }
 
578
 
 
579
        synchronized private boolean isImportRequired(
 
580
                ContactData contact, int merge_setting )
 
581
                throws AbortImportException, ContactNeedsMoreInfoException
605
582
        {
606
583
                _last_merge_decision = merge_setting;
607
584
 
608
 
                // it is ok to use contact.getCacheIdentifier(). The contact has already
609
 
                // been finalised, which means a valid cache identifier will have been
610
 
                // created for it (or it would have been skipped)
 
585
                // create a cache identifier which we can use to detect if this contact
 
586
                // is valid for importing
 
587
                ContactsCache.CacheIdentifier identifier =
 
588
                        ContactsCache.createIdentifier( contact );
 
589
                if( identifier == null )
 
590
                        throw new ContactNeedsMoreInfoException();
611
591
 
612
592
                // handle special cases
613
593
                switch( merge_setting )
614
594
                {
615
595
                case Doit.ACTION_KEEP:
616
596
                        // if we keep contacts on duplicate, we better check for one
617
 
                        return !_contacts_cache.canLookup( cache_identifier );
 
597
                        return !_contacts_cache.canLookup( identifier );
618
598
 
619
599
                case Doit.ACTION_PROMPT:
620
600
                        // if we are prompting on duplicate, we better check for one and if
621
601
                        // the contact doesn'te exist, we want to import it
622
 
                        if( !_contacts_cache.canLookup( cache_identifier ) )
 
602
                        if( !_contacts_cache.canLookup( identifier ) )
623
603
                                return true;
624
604
 
625
605
                        // ok, it exists, so do prompt
626
606
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
627
 
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
 
607
                                Doit.MESSAGE_MERGEPROMPT, identifier.getDetail() ) );
628
608
                        try {
629
609
                                wait();
630
610
                        }
638
618
                                _merge_setting = _response;
639
619
 
640
620
                        // recurse, with our new merge setting
641
 
                        return checkForDuplicate( cache_identifier, _response );
 
621
                        return isImportRequired( contact, _response );
642
622
                }
643
623
 
644
624
                // for all other cases (either overwriting or merging) we will need the
657
637
        {
658
638
                checkAbort();
659
639
 
660
 
                // It is expected that we use contact.getCacheIdentifier() here. The
661
 
                // contact we are passed should have been successfully finalise()d,
662
 
                // which includes generating a valid cache identifier.
663
 
                ContactsCache.CacheIdentifier cache_identifier =
664
 
                        contact.getCacheIdentifier();
665
 
 
666
 
                // check to see if this contact is a duplicate and should be skipped
667
 
                if( !checkForDuplicate( cache_identifier, _merge_setting ) ) {
668
 
                        skipContact();
669
 
                        return;
670
 
                }
671
 
 
672
640
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
673
641
//                      finish( ACTION_ABORT );
674
642
 
675
 
                // keep track of whether we've informed the UI of what we're doing
 
643
                ContentValues values = new ContentValues();
676
644
                boolean ui_informed = false;
677
 
 
678
 
                // attempt to lookup the id of an existing contact in the cache with
679
 
                // this contact data's cache identifier
680
 
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
 
645
                Long id = null;
 
646
 
 
647
                // give the contact a chance to finalise it's data
 
648
                contact.finalise();
 
649
 
 
650
                // create something, from the contact data, that we can use to identify
 
651
                // a cache entry and attempt to lookup the id of an existing contact in
 
652
                // the cache with it
 
653
                ContactsCache.CacheIdentifier identifier =
 
654
                        ContactsCache.createIdentifier( contact );
 
655
                if( identifier != null ) id = (Long)_contacts_cache.lookup( identifier );
681
656
 
682
657
                // does contact exist already?
683
658
                if( id != null )
685
660
                        // should we skip this import altogether?
686
661
                        if( _last_merge_decision == Doit.ACTION_KEEP ) return;
687
662
 
 
663
                        // get contact's URI
 
664
                        Uri contact_uri = ContentUris.withAppendedId(
 
665
                                Contacts.People.CONTENT_URI, id );
 
666
 
688
667
                        // should we destroy the existing contact before importing?
689
668
                        if( _last_merge_decision == Doit.ACTION_OVERWRITE )
690
669
                        {
691
670
                                // remove from device
692
 
                                _backend.deleteContact( id );
 
671
                                _doit.getContentResolver().delete( contact_uri, null, null );
693
672
 
694
673
                                // update cache
695
 
                                _contacts_cache.removeLookup( contact.getCacheIdentifier() );
 
674
                                _contacts_cache.removeLookup( identifier );
696
675
                                _contacts_cache.removeAssociatedData( id );
697
676
 
698
677
                                // show that we're overwriting a contact
705
684
                        }
706
685
                }
707
686
 
708
 
                // if we don't have a contact id yet (or we did, but we destroyed it
 
687
                // if we don't have a contact id yet (or if we did, but we destroyed it
709
688
                // when we deleted the contact), we'll have to create a new contact
710
689
                if( id == null )
711
690
                {
712
691
                        // create a new contact
713
 
                        id = _backend.addContact( contact._name );
 
692
                        values.put( Contacts.People.NAME, contact._name );
 
693
                        Uri contact_uri = _doit.getContentResolver().insert(
 
694
                                Contacts.People.CONTENT_URI, values );
 
695
                        id = ContentUris.parseId( contact_uri );
714
696
                        if( id == null || id <= 0 )
715
697
                                showError( R.string.error_unabletoaddcontact );
716
698
 
 
699
                        // try to add them to the "My Contacts" group
 
700
                        try {
 
701
                                Contacts.People.addToMyContactsGroup(
 
702
                                        _doit.getContentResolver(), id );
 
703
                        }
 
704
                        catch( IllegalStateException e ) {
 
705
                                // ignore any failure
 
706
                        }
 
707
 
717
708
                        // update cache
718
709
                        _contacts_cache.addLookup(
719
710
                                ContactsCache.createIdentifier( contact ), id );
727
718
                }
728
719
 
729
720
                // if we haven't already shown that we're overwriting or creating a
730
 
                // contact, show that we're merging a contact
 
721
                // contact show that we're merging a contact
731
722
                if( !ui_informed )
732
723
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
733
724
 
745
736
        private void importContactPhones( Long id,
746
737
                        HashMap< String, ContactData.PreferredDetail > datas )
747
738
        {
 
739
                // get URI to contact's phones
 
740
                Uri contact_phones_uri = Uri.withAppendedPath(
 
741
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
 
742
                        Contacts.People.Phones.CONTENT_DIRECTORY );
 
743
                Set< String > datas_keys = datas.keySet();
 
744
 
748
745
                // add phone numbers
749
 
                Set< String > datas_keys = datas.keySet();
750
746
                Iterator< String > i = datas_keys.iterator();
751
747
                while( i.hasNext() ) {
752
748
                        String number = i.next();
763
759
                                continue;
764
760
 
765
761
                        // add phone number
766
 
                        _backend.addContactPhone( id, number, data );
 
762
                        ContentValues values = new ContentValues();
 
763
                        values.put( Contacts.Phones.TYPE, data.getType() );
 
764
                        values.put( Contacts.Phones.NUMBER, number );
 
765
                        if( data.isPreferred() )
 
766
                                values.put( Contacts.Phones.ISPRIMARY, 1 );
 
767
                        _doit.getContentResolver().insert( contact_phones_uri, values );
767
768
 
768
769
                        // and add this address to the cache to prevent a addition of
769
770
                        // duplicate date from another file
774
775
        private void importContactEmails( Long id,
775
776
                        HashMap< String, ContactData.PreferredDetail > datas )
776
777
        {
 
778
                // get URI to contact's contact methods
 
779
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
 
780
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
 
781
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
 
782
                Set< String > datas_keys = datas.keySet();
 
783
 
777
784
                // add email addresses
778
 
                Set< String > datas_keys = datas.keySet();
779
785
                Iterator< String > i = datas_keys.iterator();
780
786
                while( i.hasNext() ) {
781
787
                        String email = i.next();
787
793
                                continue;
788
794
 
789
795
                        // add phone number
790
 
                        _backend.addContactEmail( id, email, data );
 
796
                        ContentValues values = new ContentValues();
 
797
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL );
 
798
                        values.put( Contacts.ContactMethods.DATA, email );
 
799
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
 
800
                        if( data.isPreferred() )
 
801
                                values.put( Contacts.ContactMethods.ISPRIMARY, 1 );
 
802
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
 
803
                                values );
791
804
 
792
805
                        // and add this address to the cache to prevent a addition of
793
806
                        // duplicate date from another file
798
811
        private void importContactAddresses( Long id,
799
812
                HashMap< String, ContactData.TypeDetail > datas )
800
813
        {
 
814
                // get URI to contact's contact methods
 
815
                Uri contact_contact_methods_uri = Uri.withAppendedPath(
 
816
                        ContentUris.withAppendedId( Contacts.People.CONTENT_URI, id ),
 
817
                        Contacts.People.ContactMethods.CONTENT_DIRECTORY );
 
818
 
801
819
                // add addresses
802
820
                Set< String > datas_keys = datas.keySet();
803
821
                Iterator< String > i = datas_keys.iterator();
811
829
                                continue;
812
830
 
813
831
                        // add postal address
814
 
                        _backend.addContactAddresses( id, address, data );
 
832
                        ContentValues values = new ContentValues();
 
833
                        values.put( Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL );
 
834
                        values.put( Contacts.ContactMethods.DATA, address );
 
835
                        values.put( Contacts.ContactMethods.TYPE, data.getType() );
 
836
                        _doit.getContentResolver().insert( contact_contact_methods_uri,
 
837
                                values );
815
838
 
816
839
                        // and add this address to the cache to prevent a addition of
817
840
                        // duplicate date from another file
835
858
                                continue;
836
859
 
837
860
                        // add organisation address
838
 
                        _backend.addContactOrganisation( id, organisation, data );
 
861
                        ContentValues values = new ContentValues();
 
862
                        values.put( Contacts.Organizations.PERSON_ID, id );
 
863
                        values.put( Contacts.Organizations.COMPANY, organisation );
 
864
                        values.put( Contacts.ContactMethods.TYPE,
 
865
                                Contacts.OrganizationColumns.TYPE_WORK );
 
866
                        if( data.getExtra() != null )
 
867
                                values.put( Contacts.Organizations.TITLE, data.getExtra() );
 
868
                        _doit.getContentResolver().insert(
 
869
                                Contacts.Organizations.CONTENT_URI, values );
839
870
 
840
871
                        // and add this address to the cache to prevent a addition of
841
872
                        // duplicate date from another file