/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: Tim Marston
  • Date: 2013-06-22 17:29:31 UTC
  • Revision ID: tim@ed.am-20130622172931-ujydoni23t3a543b
minor style tweaks

Show diffs side-by-side

added added

removed removed

4
4
 * Copyright (C) 2009 to 2012 Tim Marston <tim@ed.am>
5
5
 *
6
6
 * This file is part of the Import Contacts program (hereafter referred
7
 
 * to as "this program"). For more information, see
 
7
 * to as "this program").  For more information, see
8
8
 * http://ed.am/dev/android/import-contacts
9
9
 *
10
10
 * This program is free software: you can redistribute it and/or modify
27
27
import java.util.HashMap;
28
28
import java.util.HashSet;
29
29
import java.util.Iterator;
 
30
import java.util.Locale;
30
31
import java.util.Set;
31
32
import java.util.regex.Matcher;
32
33
import java.util.regex.Pattern;
33
34
 
 
35
import am.ed.importcontacts.Backend.ContactCreationException;
34
36
import android.content.SharedPreferences;
35
37
import android.os.Message;
36
 
import android.provider.Contacts.PhonesColumns;
37
38
 
38
39
public class Importer extends Thread
39
40
{
61
62
         */
62
63
        public class ContactData
63
64
        {
 
65
                public final static int TYPE_HOME = 0;
 
66
                public final static int TYPE_WORK = 1;
 
67
                public final static int TYPE_MOBILE = 2;        // only used with phones
 
68
                public final static int TYPE_FAX_HOME = 3;      // only used with phones
 
69
                public final static int TYPE_FAX_WORK = 4;      // only used with phones
 
70
                public final static int TYPE_PAGER = 5;         // only used with phones
 
71
 
64
72
                class TypeDetail
65
73
                {
66
74
                        protected int _type;
133
141
                protected HashMap< String, PreferredDetail > _numbers = null;
134
142
                protected HashMap< String, PreferredDetail > _emails = null;
135
143
                protected HashMap< String, TypeDetail > _addresses = null;
 
144
                protected HashSet< String > _notes = null;
136
145
 
137
146
                private ContactsCache.CacheIdentifier _cache_identifier = null;
138
147
 
176
185
 
177
186
                        // if this is the first organisation added, or it's a preferred
178
187
                        // organisation and the current primary organisation isn't, then
179
 
                        // record this as the primary organisation.
 
188
                        // record this as the primary organisation
180
189
                        if( _primary_organisation == null ||
181
190
                                ( is_preferred && !_primary_organisation_is_preferred ) )
182
191
                        {
224
233
                                        new PreferredDetail( type, false ) );
225
234
 
226
235
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
227
 
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
228
 
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
 
236
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
229
237
 
230
238
                        // if this is the first number added, or it's a preferred number
231
239
                        // and the current primary number isn't, or this number is on equal
232
240
                        // standing with the primary number in terms of preference and it is
233
241
                        // a voice number and the primary number isn't, then record this as
234
 
                        // the primary number.
 
242
                        // the primary number
235
243
                        if( _primary_number == null ||
236
244
                                ( is_preferred && !_primary_number_is_preferred ) ||
237
245
                                ( is_preferred == _primary_number_is_preferred &&
283
291
 
284
292
                        // if this is the first email added, or it's a preferred email and
285
293
                        // the current primary organisation isn't, then record this as the
286
 
                        // primary email.
 
294
                        // primary email
287
295
                        if( _primary_email == null ||
288
296
                                ( is_preferred && !_primary_email_is_preferred ) )
289
297
                        {
337
345
                        return _addresses;
338
346
                }
339
347
 
 
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
 
340
365
                protected void finalise()
341
366
                        throws ContactNotIdentifiableException
342
367
                {
343
 
                        // ensure that if there is a primary number, it is preferred so
344
 
                        // that there is always one preferred number. Android will assign
 
368
                        // Ensure that if there is a primary number, it is preferred so
 
369
                        // that there is always one preferred number.  Android will assign
345
370
                        // preference to one anyway so we might as well decide one sensibly.
346
371
                        if( _primary_number != null ) {
347
372
                                PreferredDetail data = _numbers.get( _primary_number );
365
390
 
366
391
                        // create a cache identifier from this contact data, which can be
367
392
                        // used to look-up an existing contact
368
 
                        _cache_identifier = ContactsCache.createIdentifier( this );
 
393
                        _cache_identifier = ContactsCache.CacheIdentifier.factory( this );
369
394
                        if( _cache_identifier == null )
370
395
                                throw new ContactNotIdentifiableException();
371
396
                }
392
417
                        Matcher m = p.matcher( email );
393
418
                        if( m.matches() ) {
394
419
                                String[] bits = email.split( "@" );
395
 
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
 
420
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase( Locale.US );
396
421
                        }
397
422
                        return null;
398
423
                }
418
443
                        setProgressMessage( R.string.doit_caching );
419
444
 
420
445
                        // create the appropriate backend
421
 
//                      if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
422
 
//                              _backend = new ContactsContractBackend( _doit );
423
 
//                      else
 
446
                        if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
 
447
                                _backend = new ContactsContractBackend( _doit );
 
448
                        else
424
449
                                _backend = new ContactsBackend( _doit );
425
450
 
426
451
                        // create a cache of existing contacts and populate it
558
583
                checkAbort();
559
584
                _doit._handler.sendMessage( Message.obtain(
560
585
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
561
 
                        new Integer( max_progress ) ) );
 
586
                        Integer.valueOf( max_progress ) ) );
562
587
        }
563
588
 
564
589
        protected void setTmpProgress( int tmp_progress )
567
592
                checkAbort();
568
593
                _doit._handler.sendMessage( Message.obtain(
569
594
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
570
 
                        new Integer( tmp_progress ) ) );
 
595
                        Integer.valueOf( tmp_progress ) ) );
571
596
        }
572
597
 
573
598
        protected void setProgress( int progress ) throws AbortImportException
575
600
                checkAbort();
576
601
                _doit._handler.sendMessage( Message.obtain(
577
602
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
578
 
                        new Integer( progress ) ) );
 
603
                        Integer.valueOf( progress ) ) );
579
604
        }
580
605
 
581
606
        protected void finish( int action ) throws AbortImportException
599
624
                return _doit.getText( res );
600
625
        }
601
626
 
602
 
        synchronized private boolean checkForDuplicate(
603
 
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
604
 
                throws AbortImportException
 
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
         *
 
631
         * @param contact_detail the display name of the contact
 
632
         * @param exists true if this contact matches one in the cache
 
633
         * @param merge_setting the merge setting to use
 
634
         * @return true if the contact should be skipped outright
 
635
         * @throws AbortImportException
 
636
         */
 
637
        synchronized private boolean shouldWeSkipContact( String contact_detail,
 
638
                boolean exists, int merge_setting ) throws AbortImportException
605
639
        {
606
640
                _last_merge_decision = merge_setting;
607
641
 
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)
611
 
 
612
642
                // handle special cases
613
643
                switch( merge_setting )
614
644
                {
615
645
                case Doit.ACTION_KEEP:
616
 
                        // if we keep contacts on duplicate, we better check for one
617
 
                        return !_contacts_cache.canLookup( cache_identifier );
 
646
                        // if we are skipping on a duplicate, check for one
 
647
                        return exists;
618
648
 
619
649
                case Doit.ACTION_PROMPT:
620
 
                        // if we are prompting on duplicate, we better check for one and if
621
 
                        // the contact doesn'te exist, we want to import it
622
 
                        if( !_contacts_cache.canLookup( cache_identifier ) )
623
 
                                return true;
 
650
                        // if we are prompting on duplicate, then we can say that we won't
 
651
                        // skip if there isn't one
 
652
                        if( !exists ) return false;
624
653
 
625
 
                        // ok, it exists, so do prompt
 
654
                        // ok, duplicate exists, so do prompt
626
655
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
627
 
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
 
656
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
628
657
                        try {
629
658
                                wait();
630
659
                        }
638
667
                                _merge_setting = _response;
639
668
 
640
669
                        // recurse, with our new merge setting
641
 
                        return checkForDuplicate( cache_identifier, _response );
 
670
                        return shouldWeSkipContact( contact_detail, exists, _response );
642
671
                }
643
672
 
644
 
                // for all other cases (either overwriting or merging) we will need the
645
 
                // imported data
646
 
                return true;
 
673
                // for all other cases (either overwriting or merging) we don't skip
 
674
                return false;
647
675
        }
648
676
 
649
677
        protected void skipContact() throws AbortImportException
650
678
        {
651
679
                checkAbort();
 
680
 
 
681
                // show that we're skipping a new contact
652
682
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
653
683
        }
654
684
 
657
687
        {
658
688
                checkAbort();
659
689
 
660
 
                // It is expected that we use contact.getCacheIdentifier() here. The
 
690
                // It is expected that we use contact.getCacheIdentifier() here.  The
661
691
                // contact we are passed should have been successfully finalise()d,
662
692
                // which includes generating a valid cache identifier.
663
693
                ContactsCache.CacheIdentifier cache_identifier =
664
694
                        contact.getCacheIdentifier();
665
695
 
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
696
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
673
697
//                      finish( ACTION_ABORT );
674
698
 
675
 
                // keep track of whether we've informed the UI of what we're doing
676
 
                boolean ui_informed = false;
677
 
 
678
699
                // attempt to lookup the id of an existing contact in the cache with
679
700
                // this contact data's cache identifier
680
701
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
681
702
 
682
 
                // does contact exist already?
683
 
                if( id != null )
684
 
                {
685
 
                        // should we skip this import altogether?
686
 
                        if( _last_merge_decision == Doit.ACTION_KEEP ) return;
687
 
 
688
 
                        // should we destroy the existing contact before importing?
689
 
                        if( _last_merge_decision == Doit.ACTION_OVERWRITE )
 
703
                // check to see if this contact should be skipped
 
704
                if( shouldWeSkipContact( cache_identifier.getDetail(), id != null,
 
705
                        _merge_setting ) )
 
706
                {
 
707
                        // show that we're skipping a contact
 
708
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
 
709
                        return;
 
710
                }
 
711
 
 
712
                // if a contact exists, and we're overwriting, destroy the existing
 
713
                // contact before importing
 
714
                boolean contact_deleted = false;
 
715
                if( id != null && _last_merge_decision == Doit.ACTION_OVERWRITE )
 
716
                {
 
717
                        contact_deleted = true;
 
718
 
 
719
                        // remove from device
 
720
                        _backend.deleteContact( id );
 
721
 
 
722
                        // update cache
 
723
                        _contacts_cache.removeLookup( cache_identifier );
 
724
                        _contacts_cache.removeAssociatedData( id );
 
725
 
 
726
                        // show that we're overwriting a contact
 
727
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
 
728
 
 
729
                        // discard the contact id
 
730
                        id = null;
 
731
                }
 
732
 
 
733
                try {
 
734
                        // if we don't have a contact id yet (or we did, but we destroyed it
 
735
                        // when we deleted the contact), we'll have to create a new contact
 
736
                        if( id == null )
690
737
                        {
691
 
                                // remove from device
692
 
                                _backend.deleteContact( id );
 
738
                                // create a new contact
 
739
                                id = _backend.addContact( contact._name );
693
740
 
694
741
                                // update cache
695
 
                                _contacts_cache.removeLookup( contact.getCacheIdentifier() );
696
 
                                _contacts_cache.removeAssociatedData( id );
697
 
 
698
 
                                // show that we're overwriting a contact
699
 
                                _doit._handler.sendEmptyMessage(
700
 
                                                Doit.MESSAGE_CONTACTOVERWRITTEN );
701
 
                                ui_informed = true;
702
 
 
703
 
                                // discard the contact id
704
 
                                id = null;
 
742
                                _contacts_cache.addLookup( cache_identifier, id );
 
743
 
 
744
                                // if we haven't already shown that we're overwriting a contact,
 
745
                                // show that we're creating a new contact
 
746
                                if( !contact_deleted )
 
747
                                        _doit._handler.sendEmptyMessage(
 
748
                                                Doit.MESSAGE_CONTACTCREATED );
705
749
                        }
 
750
                        else
 
751
                                // show that we're merging with an existing contact
 
752
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
 
753
 
 
754
                        // import contact parts
 
755
                        if( contact.hasNumbers() )
 
756
                                importContactPhones( id, contact.getNumbers() );
 
757
                        if( contact.hasEmails() )
 
758
                                importContactEmails( id, contact.getEmails() );
 
759
                        if( contact.hasAddresses() )
 
760
                                importContactAddresses( id, contact.getAddresses() );
 
761
                        if( contact.hasOrganisations() )
 
762
                                importContactOrganisations( id, contact.getOrganisations() );
 
763
                        if( contact.hasNotes() )
 
764
                                importContactNotes( id, contact.getNotes() );
706
765
                }
707
 
 
708
 
                // if we don't have a contact id yet (or we did, but we destroyed it
709
 
                // when we deleted the contact), we'll have to create a new contact
710
 
                if( id == null )
 
766
                catch( Backend.ContactCreationException e )
711
767
                {
712
 
                        // create a new contact
713
 
                        id = _backend.addContact( contact._name );
714
 
                        if( id == null )
715
 
                                showError( R.string.error_unabletoaddcontact );
716
 
 
717
 
                        // update cache
718
 
                        _contacts_cache.addLookup(
719
 
                                ContactsCache.createIdentifier( contact ), id );
720
 
 
721
 
                        // if we haven't already shown that we're overwriting a contact,
722
 
                        // show that we're creating a new contact
723
 
                        if( !ui_informed ) {
724
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
725
 
                                ui_informed = true;
726
 
                        }
 
768
                        showError( R.string.error_unabletoaddcontact );
727
769
                }
728
 
 
729
 
                // if we haven't already shown that we're overwriting or creating a
730
 
                // contact, show that we're merging a contact
731
 
                if( !ui_informed )
732
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
733
 
 
734
 
                // import contact parts
735
 
                if( contact.hasNumbers() )
736
 
                        importContactPhones( id, contact.getNumbers() );
737
 
                if( contact.hasEmails() )
738
 
                        importContactEmails( id, contact.getEmails() );
739
 
                if( contact.hasAddresses() )
740
 
                        importContactAddresses( id, contact.getAddresses() );
741
 
                if( contact.hasOrganisations() )
742
 
                        importContactOrganisations( id, contact.getOrganisations() );
743
770
        }
744
771
 
745
772
        private void importContactPhones( Long id,
746
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
773
                HashMap< String, ContactData.PreferredDetail > datas )
 
774
                throws ContactCreationException
747
775
        {
748
776
                // add phone numbers
749
777
                Set< String > datas_keys = datas.keySet();
752
780
                        String number = i.next();
753
781
                        ContactData.PreferredDetail data = datas.get( number );
754
782
 
755
 
                        // we don't want to add this number if it's crap, or it already
756
 
                        // exists (which would cause a duplicate to be created). We don't
757
 
                        // take in to account the type when checking for duplicates. This is
758
 
                        // intentional: types aren't really very reliable. We assume that
759
 
                        // if the number exists at all, it doesn't need importing. Because
760
 
                        // of this, we also can't update the cache (which we don't need to
761
 
                        // anyway, so it's not a problem).
 
783
                        // We don't want to add this number if it's crap, or it already
 
784
                        // exists (which would cause a duplicate to be created).  We don't
 
785
                        // take in to account the type when checking for duplicates.  This
 
786
                        // is intentional: types aren't really very reliable.  We assume
 
787
                        // that if the number exists at all, it doesn't need importing.
 
788
                        // Because of this, we also can't update the cache (which we don't
 
789
                        // need to anyway, so it's not a problem).
762
790
                        if( _contacts_cache.hasAssociatedNumber( id, number ) )
763
791
                                continue;
764
792
 
772
800
        }
773
801
 
774
802
        private void importContactEmails( Long id,
775
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
803
                HashMap< String, ContactData.PreferredDetail > datas )
 
804
                throws ContactCreationException
776
805
        {
777
806
                // add email addresses
778
807
                Set< String > datas_keys = datas.keySet();
782
811
                        ContactData.PreferredDetail data = datas.get( email );
783
812
 
784
813
                        // we don't want to add this email address if it exists already or
785
 
                        // we would introduce duplicates.
 
814
                        // we would introduce duplicates
786
815
                        if( _contacts_cache.hasAssociatedEmail( id, email ) )
787
816
                                continue;
788
817
 
797
826
 
798
827
        private void importContactAddresses( Long id,
799
828
                HashMap< String, ContactData.TypeDetail > datas )
 
829
                throws ContactCreationException
800
830
        {
801
831
                // add addresses
802
832
                Set< String > datas_keys = datas.keySet();
821
851
 
822
852
        private void importContactOrganisations( Long id,
823
853
                HashMap< String, ContactData.ExtraDetail > datas )
 
854
                throws ContactCreationException
824
855
        {
825
856
                // add addresses
826
857
                Set< String > datas_keys = datas.keySet();
843
874
                }
844
875
        }
845
876
 
 
877
        private void importContactNotes( Long id,
 
878
                HashSet< String > datas )
 
879
                throws ContactCreationException
 
880
        {
 
881
                // add notes
 
882
                Iterator< String > i = datas.iterator();
 
883
                while( i.hasNext() ) {
 
884
                        String note = i.next();
 
885
 
 
886
                        // we don't want to add this note if it exists already or we would
 
887
                        // introduce duplicates
 
888
                        if( _contacts_cache.hasAssociatedNote( id, note ) )
 
889
                                continue;
 
890
 
 
891
                        // add note
 
892
                        _backend.addContactNote( id, note );
 
893
 
 
894
                        // and add this note to the cache to prevent a addition of duplicate
 
895
                        // date from another file
 
896
                        _contacts_cache.addAssociatedNote( id, note );
 
897
                }
 
898
 
 
899
        }
 
900
 
846
901
        synchronized protected void checkAbort() throws AbortImportException
847
902
        {
848
903
                if( _abort ) {