/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: 2014-03-02 10:58:49 UTC
  • Revision ID: tim@ed.am-20140302105849-m542carzc1d4m1t2
added permission to write to sdcard (how did this ever work!?)

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * Importer.java
3
3
 *
4
 
 * Copyright (C) 2009 to 2012 Tim Marston <tim@ed.am>
 
4
 * Copyright (C) 2009 to 2013 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;
 
145
                protected String _birthday = null;
136
146
 
137
147
                private ContactsCache.CacheIdentifier _cache_identifier = null;
138
148
 
176
186
 
177
187
                        // if this is the first organisation added, or it's a preferred
178
188
                        // organisation and the current primary organisation isn't, then
179
 
                        // record this as the primary organisation.
 
189
                        // record this as the primary organisation
180
190
                        if( _primary_organisation == null ||
181
191
                                ( is_preferred && !_primary_organisation_is_preferred ) )
182
192
                        {
224
234
                                        new PreferredDetail( type, false ) );
225
235
 
226
236
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
227
 
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
228
 
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
 
237
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
229
238
 
230
239
                        // if this is the first number added, or it's a preferred number
231
240
                        // and the current primary number isn't, or this number is on equal
232
241
                        // standing with the primary number in terms of preference and it is
233
242
                        // a voice number and the primary number isn't, then record this as
234
 
                        // the primary number.
 
243
                        // the primary number
235
244
                        if( _primary_number == null ||
236
245
                                ( is_preferred && !_primary_number_is_preferred ) ||
237
246
                                ( is_preferred == _primary_number_is_preferred &&
283
292
 
284
293
                        // if this is the first email added, or it's a preferred email and
285
294
                        // the current primary organisation isn't, then record this as the
286
 
                        // primary email.
 
295
                        // primary email
287
296
                        if( _primary_email == null ||
288
297
                                ( is_preferred && !_primary_email_is_preferred ) )
289
298
                        {
337
346
                        return _addresses;
338
347
                }
339
348
 
 
349
                protected void addNote( String note )
 
350
                {
 
351
                        if( _notes == null ) _notes = new HashSet< String >();
 
352
                        if( !_notes.contains( note ) )
 
353
                                _notes.add( note );
 
354
                }
 
355
 
 
356
                public boolean hasNotes()
 
357
                {
 
358
                        return _notes != null && _notes.size() > 0;
 
359
                }
 
360
 
 
361
                public HashSet< String > getNotes()
 
362
                {
 
363
                        return _notes;
 
364
                }
 
365
 
 
366
                public void setBirthday( String birthday )
 
367
                {
 
368
                        _birthday = birthday;
 
369
                }
 
370
 
 
371
                public boolean hasBirthday()
 
372
                {
 
373
                        return _birthday != null;
 
374
                }
 
375
 
 
376
                public String getBirthday()
 
377
                {
 
378
                        return _birthday;
 
379
                }
 
380
 
340
381
                protected void finalise()
341
382
                        throws ContactNotIdentifiableException
342
383
                {
343
 
                        // ensure that if there is a primary number, it is preferred so
344
 
                        // that there is always one preferred number. Android will assign
 
384
                        // Ensure that if there is a primary number, it is preferred so
 
385
                        // that there is always one preferred number.  Android will assign
345
386
                        // preference to one anyway so we might as well decide one sensibly.
346
387
                        if( _primary_number != null ) {
347
388
                                PreferredDetail data = _numbers.get( _primary_number );
365
406
 
366
407
                        // create a cache identifier from this contact data, which can be
367
408
                        // used to look-up an existing contact
368
 
                        _cache_identifier = ContactsCache.createIdentifier( this );
 
409
                        _cache_identifier = ContactsCache.CacheIdentifier.factory( this );
369
410
                        if( _cache_identifier == null )
370
411
                                throw new ContactNotIdentifiableException();
371
412
                }
392
433
                        Matcher m = p.matcher( email );
393
434
                        if( m.matches() ) {
394
435
                                String[] bits = email.split( "@" );
395
 
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
 
436
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase( Locale.US );
396
437
                        }
397
438
                        return null;
398
439
                }
418
459
                        setProgressMessage( R.string.doit_caching );
419
460
 
420
461
                        // create the appropriate backend
421
 
//                      if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
422
 
//                              _backend = new ContactsContractBackend( _doit );
423
 
//                      else
 
462
                        if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
 
463
                                _backend = new ContactsContractBackend( _doit );
 
464
                        else
424
465
                                _backend = new ContactsBackend( _doit );
425
466
 
426
467
                        // create a cache of existing contacts and populate it
558
599
                checkAbort();
559
600
                _doit._handler.sendMessage( Message.obtain(
560
601
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
561
 
                        new Integer( max_progress ) ) );
 
602
                        Integer.valueOf( max_progress ) ) );
562
603
        }
563
604
 
564
605
        protected void setTmpProgress( int tmp_progress )
567
608
                checkAbort();
568
609
                _doit._handler.sendMessage( Message.obtain(
569
610
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
570
 
                        new Integer( tmp_progress ) ) );
 
611
                        Integer.valueOf( tmp_progress ) ) );
571
612
        }
572
613
 
573
614
        protected void setProgress( int progress ) throws AbortImportException
575
616
                checkAbort();
576
617
                _doit._handler.sendMessage( Message.obtain(
577
618
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
578
 
                        new Integer( progress ) ) );
 
619
                        Integer.valueOf( progress ) ) );
579
620
        }
580
621
 
581
622
        protected void finish( int action ) throws AbortImportException
599
640
                return _doit.getText( res );
600
641
        }
601
642
 
602
 
        synchronized private boolean checkForDuplicate(
603
 
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
604
 
                throws AbortImportException
 
643
        /**
 
644
         * Should we skip a contact, given whether it exists or not and the current
 
645
         * merge setting?  This routine handles throwing up a prompt, if required.
 
646
         *
 
647
         * @param contact_detail the display name of the contact
 
648
         * @param exists true if this contact matches one in the cache
 
649
         * @param merge_setting the merge setting to use
 
650
         * @return true if the contact should be skipped outright
 
651
         * @throws AbortImportException
 
652
         */
 
653
        synchronized private boolean shouldWeSkipContact( String contact_detail,
 
654
                boolean exists, int merge_setting ) throws AbortImportException
605
655
        {
606
656
                _last_merge_decision = merge_setting;
607
657
 
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
658
                // handle special cases
613
659
                switch( merge_setting )
614
660
                {
615
661
                case Doit.ACTION_KEEP:
616
 
                        // if we keep contacts on duplicate, we better check for one
617
 
                        return !_contacts_cache.canLookup( cache_identifier );
 
662
                        // if we are skipping on a duplicate, check for one
 
663
                        return exists;
618
664
 
619
665
                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;
 
666
                        // if we are prompting on duplicate, then we can say that we won't
 
667
                        // skip if there isn't one
 
668
                        if( !exists ) return false;
624
669
 
625
 
                        // ok, it exists, so do prompt
 
670
                        // ok, duplicate exists, so do prompt
626
671
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
627
 
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
 
672
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
628
673
                        try {
629
674
                                wait();
630
675
                        }
638
683
                                _merge_setting = _response;
639
684
 
640
685
                        // recurse, with our new merge setting
641
 
                        return checkForDuplicate( cache_identifier, _response );
 
686
                        return shouldWeSkipContact( contact_detail, exists, _response );
642
687
                }
643
688
 
644
 
                // for all other cases (either overwriting or merging) we will need the
645
 
                // imported data
646
 
                return true;
 
689
                // for all other cases (either overwriting or merging) we don't skip
 
690
                return false;
647
691
        }
648
692
 
649
693
        protected void skipContact() throws AbortImportException
650
694
        {
651
695
                checkAbort();
 
696
 
 
697
                // show that we're skipping a new contact
652
698
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
653
699
        }
654
700
 
657
703
        {
658
704
                checkAbort();
659
705
 
660
 
                // It is expected that we use contact.getCacheIdentifier() here. The
 
706
                // It is expected that we use contact.getCacheIdentifier() here.  The
661
707
                // contact we are passed should have been successfully finalise()d,
662
708
                // which includes generating a valid cache identifier.
663
709
                ContactsCache.CacheIdentifier cache_identifier =
664
710
                        contact.getCacheIdentifier();
665
711
 
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
712
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
673
713
//                      finish( ACTION_ABORT );
674
714
 
675
 
                // keep track of whether we've informed the UI of what we're doing
676
 
                boolean ui_informed = false;
677
 
 
678
715
                // attempt to lookup the id of an existing contact in the cache with
679
716
                // this contact data's cache identifier
680
717
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
681
718
 
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 )
 
719
                // check to see if this contact should be skipped
 
720
                if( shouldWeSkipContact( cache_identifier.getDetail(), id != null,
 
721
                        _merge_setting ) )
 
722
                {
 
723
                        // show that we're skipping a contact
 
724
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
 
725
                        return;
 
726
                }
 
727
 
 
728
                // if a contact exists, and we're overwriting, destroy the existing
 
729
                // contact before importing
 
730
                boolean contact_deleted = false;
 
731
                if( id != null && _last_merge_decision == Doit.ACTION_OVERWRITE )
 
732
                {
 
733
                        contact_deleted = true;
 
734
 
 
735
                        // remove from device
 
736
                        _backend.deleteContact( id );
 
737
 
 
738
                        // update cache
 
739
                        _contacts_cache.removeLookup( cache_identifier );
 
740
                        _contacts_cache.removeAssociatedData( id );
 
741
 
 
742
                        // show that we're overwriting a contact
 
743
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
 
744
 
 
745
                        // discard the contact id
 
746
                        id = null;
 
747
                }
 
748
 
 
749
                try {
 
750
                        // if we don't have a contact id yet (or we did, but we destroyed it
 
751
                        // when we deleted the contact), we'll have to create a new contact
 
752
                        if( id == null )
690
753
                        {
691
 
                                // remove from device
692
 
                                _backend.deleteContact( id );
 
754
                                // create a new contact
 
755
                                id = _backend.addContact( contact._name );
693
756
 
694
757
                                // update cache
695
 
                                _contacts_cache.removeLookup( cache_identifier );
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;
 
758
                                _contacts_cache.addLookup( cache_identifier, id );
 
759
 
 
760
                                // if we haven't already shown that we're overwriting a contact,
 
761
                                // show that we're creating a new contact
 
762
                                if( !contact_deleted )
 
763
                                        _doit._handler.sendEmptyMessage(
 
764
                                                Doit.MESSAGE_CONTACTCREATED );
705
765
                        }
 
766
                        else
 
767
                                // show that we're merging with an existing contact
 
768
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
 
769
 
 
770
                        // import contact parts
 
771
                        if( contact.hasNumbers() )
 
772
                                importContactPhones( id, contact.getNumbers() );
 
773
                        if( contact.hasEmails() )
 
774
                                importContactEmails( id, contact.getEmails() );
 
775
                        if( contact.hasAddresses() )
 
776
                                importContactAddresses( id, contact.getAddresses() );
 
777
                        if( contact.hasOrganisations() )
 
778
                                importContactOrganisations( id, contact.getOrganisations() );
 
779
                        if( contact.hasNotes() )
 
780
                                importContactNotes( id, contact.getNotes() );
 
781
                        if( contact.hasBirthday() )
 
782
                                importContactBirthday( id, contact.getBirthday() );
706
783
                }
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 )
 
784
                catch( Backend.ContactCreationException e )
711
785
                {
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( cache_identifier, id );
719
 
 
720
 
                        // if we haven't already shown that we're overwriting a contact,
721
 
                        // show that we're creating a new contact
722
 
                        if( !ui_informed ) {
723
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTCREATED );
724
 
                                ui_informed = true;
725
 
                        }
 
786
                        showError( R.string.error_unabletoaddcontact );
726
787
                }
727
 
 
728
 
                // if we haven't already shown that we're overwriting or creating a
729
 
                // contact, show that we're merging a contact
730
 
                if( !ui_informed )
731
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
732
 
 
733
 
                // import contact parts
734
 
                if( contact.hasNumbers() )
735
 
                        importContactPhones( id, contact.getNumbers() );
736
 
                if( contact.hasEmails() )
737
 
                        importContactEmails( id, contact.getEmails() );
738
 
                if( contact.hasAddresses() )
739
 
                        importContactAddresses( id, contact.getAddresses() );
740
 
                if( contact.hasOrganisations() )
741
 
                        importContactOrganisations( id, contact.getOrganisations() );
742
788
        }
743
789
 
744
790
        private void importContactPhones( Long id,
745
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
791
                HashMap< String, ContactData.PreferredDetail > datas )
 
792
                throws ContactCreationException
746
793
        {
747
794
                // add phone numbers
748
795
                Set< String > datas_keys = datas.keySet();
751
798
                        String number = i.next();
752
799
                        ContactData.PreferredDetail data = datas.get( number );
753
800
 
754
 
                        // we don't want to add this number if it's crap, or it already
755
 
                        // exists (which would cause a duplicate to be created). We don't
756
 
                        // take in to account the type when checking for duplicates. This is
757
 
                        // intentional: types aren't really very reliable. We assume that
758
 
                        // if the number exists at all, it doesn't need importing. Because
759
 
                        // of this, we also can't update the cache (which we don't need to
760
 
                        // anyway, so it's not a problem).
 
801
                        // We don't want to add this number if it's crap, or it already
 
802
                        // exists (which would cause a duplicate to be created).  We don't
 
803
                        // take in to account the type when checking for duplicates.  This
 
804
                        // is intentional: types aren't really very reliable.  We assume
 
805
                        // that if the number exists at all, it doesn't need importing.
 
806
                        // Because of this, we also can't update the cache (which we don't
 
807
                        // need to anyway, so it's not a problem).
761
808
                        if( _contacts_cache.hasAssociatedNumber( id, number ) )
762
809
                                continue;
763
810
 
771
818
        }
772
819
 
773
820
        private void importContactEmails( Long id,
774
 
                        HashMap< String, ContactData.PreferredDetail > datas )
 
821
                HashMap< String, ContactData.PreferredDetail > datas )
 
822
                throws ContactCreationException
775
823
        {
776
824
                // add email addresses
777
825
                Set< String > datas_keys = datas.keySet();
781
829
                        ContactData.PreferredDetail data = datas.get( email );
782
830
 
783
831
                        // we don't want to add this email address if it exists already or
784
 
                        // we would introduce duplicates.
 
832
                        // we would introduce duplicates
785
833
                        if( _contacts_cache.hasAssociatedEmail( id, email ) )
786
834
                                continue;
787
835
 
796
844
 
797
845
        private void importContactAddresses( Long id,
798
846
                HashMap< String, ContactData.TypeDetail > datas )
 
847
                throws ContactCreationException
799
848
        {
800
849
                // add addresses
801
850
                Set< String > datas_keys = datas.keySet();
820
869
 
821
870
        private void importContactOrganisations( Long id,
822
871
                HashMap< String, ContactData.ExtraDetail > datas )
 
872
                throws ContactCreationException
823
873
        {
824
874
                // add addresses
825
875
                Set< String > datas_keys = datas.keySet();
842
892
                }
843
893
        }
844
894
 
 
895
        private void importContactNotes( Long id, HashSet< String > datas )
 
896
                throws ContactCreationException
 
897
        {
 
898
                // add notes
 
899
                Iterator< String > i = datas.iterator();
 
900
                while( i.hasNext() ) {
 
901
                        String note = i.next();
 
902
 
 
903
                        // we don't want to add this note if it exists already or we would
 
904
                        // introduce duplicates
 
905
                        if( _contacts_cache.hasAssociatedNote( id, note ) )
 
906
                                continue;
 
907
 
 
908
                        // add note
 
909
                        _backend.addContactNote( id, note );
 
910
 
 
911
                        // and add this note to the cache to prevent a addition of duplicate
 
912
                        // date from another file
 
913
                        _contacts_cache.addAssociatedNote( id, note );
 
914
                }
 
915
        }
 
916
 
 
917
        private void importContactBirthday( Long id, String birthday )
 
918
                throws ContactCreationException
 
919
        {
 
920
                // we don't want to import this birthday if it already exists
 
921
                if( _contacts_cache.hasAssociatedBirthday( id, birthday ) )
 
922
                        return;
 
923
 
 
924
                // add birthday
 
925
                _backend.addContactBirthday( id, birthday );
 
926
 
 
927
                // and update the cache
 
928
                _contacts_cache.addAssociatedBirthday( id, birthday );
 
929
        }
 
930
 
845
931
        synchronized protected void checkAbort() throws AbortImportException
846
932
        {
847
933
                if( _abort ) {