/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: edam
  • Date: 2012-12-19 17:41:04 UTC
  • Revision ID: tim@ed.am-20121219174104-ly9xyjxdhqt0tu9b
ignore temporary files in eclipse project

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * Importer.java
3
3
 *
4
 
 * Copyright (C) 2009 to 2013 Tim Marston <tim@ed.am>
 
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;
31
30
import java.util.Set;
32
31
import java.util.regex.Matcher;
33
32
import java.util.regex.Pattern;
34
33
 
35
 
import am.ed.importcontacts.Backend.ContactCreationException;
36
34
import android.content.SharedPreferences;
37
35
import android.os.Message;
 
36
import android.provider.Contacts.PhonesColumns;
38
37
 
39
38
public class Importer extends Thread
40
39
{
62
61
         */
63
62
        public class ContactData
64
63
        {
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
 
 
72
64
                class TypeDetail
73
65
                {
74
66
                        protected int _type;
141
133
                protected HashMap< String, PreferredDetail > _numbers = null;
142
134
                protected HashMap< String, PreferredDetail > _emails = null;
143
135
                protected HashMap< String, TypeDetail > _addresses = null;
144
 
                protected HashSet< String > _notes = null;
145
 
                protected String _birthday = null;
146
136
 
147
137
                private ContactsCache.CacheIdentifier _cache_identifier = null;
148
138
 
186
176
 
187
177
                        // if this is the first organisation added, or it's a preferred
188
178
                        // organisation and the current primary organisation isn't, then
189
 
                        // record this as the primary organisation
 
179
                        // record this as the primary organisation.
190
180
                        if( _primary_organisation == null ||
191
181
                                ( is_preferred && !_primary_organisation_is_preferred ) )
192
182
                        {
234
224
                                        new PreferredDetail( type, false ) );
235
225
 
236
226
                        final Set< Integer > non_voice_types = new HashSet< Integer >(
237
 
                                Arrays.asList( TYPE_FAX_HOME, TYPE_FAX_WORK, TYPE_PAGER ) );
 
227
                                Arrays.asList( PhonesColumns.TYPE_FAX_HOME,
 
228
                                        PhonesColumns.TYPE_FAX_WORK, PhonesColumns.TYPE_PAGER ) );
238
229
 
239
230
                        // if this is the first number added, or it's a preferred number
240
231
                        // and the current primary number isn't, or this number is on equal
241
232
                        // standing with the primary number in terms of preference and it is
242
233
                        // a voice number and the primary number isn't, then record this as
243
 
                        // the primary number
 
234
                        // the primary number.
244
235
                        if( _primary_number == null ||
245
236
                                ( is_preferred && !_primary_number_is_preferred ) ||
246
237
                                ( is_preferred == _primary_number_is_preferred &&
292
283
 
293
284
                        // if this is the first email added, or it's a preferred email and
294
285
                        // the current primary organisation isn't, then record this as the
295
 
                        // primary email
 
286
                        // primary email.
296
287
                        if( _primary_email == null ||
297
288
                                ( is_preferred && !_primary_email_is_preferred ) )
298
289
                        {
346
337
                        return _addresses;
347
338
                }
348
339
 
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
 
 
381
340
                protected void finalise()
382
341
                        throws ContactNotIdentifiableException
383
342
                {
384
 
                        // Ensure that if there is a primary number, it is preferred so
385
 
                        // that there is always one preferred number.  Android will assign
 
343
                        // ensure that if there is a primary number, it is preferred so
 
344
                        // that there is always one preferred number. Android will assign
386
345
                        // preference to one anyway so we might as well decide one sensibly.
387
346
                        if( _primary_number != null ) {
388
347
                                PreferredDetail data = _numbers.get( _primary_number );
406
365
 
407
366
                        // create a cache identifier from this contact data, which can be
408
367
                        // used to look-up an existing contact
409
 
                        _cache_identifier = ContactsCache.CacheIdentifier.factory( this );
 
368
                        _cache_identifier = ContactsCache.createIdentifier( this );
410
369
                        if( _cache_identifier == null )
411
370
                                throw new ContactNotIdentifiableException();
412
371
                }
433
392
                        Matcher m = p.matcher( email );
434
393
                        if( m.matches() ) {
435
394
                                String[] bits = email.split( "@" );
436
 
                                return bits[ 0 ] + "@" +
437
 
                                        bits[ 1 ].toLowerCase( Locale.ENGLISH );
 
395
                                return bits[ 0 ] + "@" + bits[ 1 ].toLowerCase();
438
396
                        }
439
397
                        return null;
440
398
                }
460
418
                        setProgressMessage( R.string.doit_caching );
461
419
 
462
420
                        // create the appropriate backend
463
 
                        if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
464
 
                                _backend = new ContactsContractBackend( _doit );
465
 
                        else
 
421
//                      if( Integer.parseInt( android.os.Build.VERSION.SDK ) >= 5 )
 
422
//                              _backend = new ContactsContractBackend( _doit );
 
423
//                      else
466
424
                                _backend = new ContactsBackend( _doit );
467
425
 
468
426
                        // create a cache of existing contacts and populate it
544
502
                finish( ACTION_ABORT );
545
503
        }
546
504
 
547
 
        protected void showContinueOrAbort( int res ) throws AbortImportException
548
 
        {
549
 
                showContinueOrAbort( _doit.getText( res ).toString() );
550
 
        }
551
 
 
552
 
        synchronized protected void showContinueOrAbort( String message )
 
505
        protected void showFatalError( int res ) throws AbortImportException
 
506
        {
 
507
                showFatalError( _doit.getText( res ).toString() );
 
508
        }
 
509
 
 
510
        synchronized protected void showFatalError( String message )
 
511
                        throws AbortImportException
 
512
        {
 
513
                checkAbort();
 
514
                _doit._handler.sendMessage( Message.obtain(
 
515
                        _doit._handler, Doit.MESSAGE_ERROR, message ) );
 
516
                try {
 
517
                        wait();
 
518
                }
 
519
                catch( InterruptedException e ) { }
 
520
 
 
521
                // no need to check if an abortion happened during the wait, we are
 
522
                // about to finish anyway!
 
523
                finish( ACTION_ABORT );
 
524
        }
 
525
 
 
526
        protected boolean showContinue( int res ) throws AbortImportException
 
527
        {
 
528
                return showContinue( _doit.getText( res ).toString() );
 
529
        }
 
530
 
 
531
        synchronized protected boolean showContinue( String message )
553
532
                        throws AbortImportException
554
533
        {
555
534
                checkAbort();
560
539
                }
561
540
                catch( InterruptedException e ) { }
562
541
 
563
 
                // if we're aborting, there's no need to check if an abortion happened
564
 
                // during the wait
565
 
                if( _response == RESPONSE_NEGATIVE )
566
 
                        finish( ACTION_ABORT );
567
 
                else
568
 
                        checkAbort();
 
542
                // check if an abortion happened during the wait
 
543
                checkAbort();
 
544
 
 
545
                return _response == RESPONSE_POSITIVE;
569
546
        }
570
547
 
571
548
        protected void setProgressMessage( int res ) throws AbortImportException
581
558
                checkAbort();
582
559
                _doit._handler.sendMessage( Message.obtain(
583
560
                        _doit._handler, Doit.MESSAGE_SETMAXPROGRESS,
584
 
                        Integer.valueOf( max_progress ) ) );
 
561
                        new Integer( max_progress ) ) );
585
562
        }
586
563
 
587
564
        protected void setTmpProgress( int tmp_progress )
590
567
                checkAbort();
591
568
                _doit._handler.sendMessage( Message.obtain(
592
569
                        _doit._handler, Doit.MESSAGE_SETTMPPROGRESS,
593
 
                        Integer.valueOf( tmp_progress ) ) );
 
570
                        new Integer( tmp_progress ) ) );
594
571
        }
595
572
 
596
573
        protected void setProgress( int progress ) throws AbortImportException
598
575
                checkAbort();
599
576
                _doit._handler.sendMessage( Message.obtain(
600
577
                        _doit._handler, Doit.MESSAGE_SETPROGRESS,
601
 
                        Integer.valueOf( progress ) ) );
 
578
                        new Integer( progress ) ) );
602
579
        }
603
580
 
604
581
        protected void finish( int action ) throws AbortImportException
622
599
                return _doit.getText( res );
623
600
        }
624
601
 
625
 
        /**
626
 
         * Should we skip a contact, given whether it exists or not and the current
627
 
         * merge setting?  This routine handles throwing up a prompt, if required.
628
 
         *
629
 
         * @param contact_detail the display name of the contact
630
 
         * @param exists true if this contact matches one in the cache
631
 
         * @param merge_setting the merge setting to use
632
 
         * @return true if the contact should be skipped outright
633
 
         * @throws AbortImportException
634
 
         */
635
 
        synchronized private boolean shouldWeSkipContact( String contact_detail,
636
 
                boolean exists, int merge_setting ) throws AbortImportException
 
602
        synchronized private boolean checkForDuplicate(
 
603
                ContactsCache.CacheIdentifier cache_identifier, int merge_setting )
 
604
                throws AbortImportException
637
605
        {
638
606
                _last_merge_decision = merge_setting;
639
607
 
 
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
 
640
612
                // handle special cases
641
613
                switch( merge_setting )
642
614
                {
643
615
                case Doit.ACTION_KEEP:
644
 
                        // if we are skipping on a duplicate, check for one
645
 
                        return exists;
 
616
                        // if we keep contacts on duplicate, we better check for one
 
617
                        return !_contacts_cache.canLookup( cache_identifier );
646
618
 
647
619
                case Doit.ACTION_PROMPT:
648
 
                        // if we are prompting on duplicate, then we can say that we won't
649
 
                        // skip if there isn't one
650
 
                        if( !exists ) return false;
 
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;
651
624
 
652
 
                        // ok, duplicate exists, so do prompt
 
625
                        // ok, it exists, so do prompt
653
626
                        _doit._handler.sendMessage( Message.obtain( _doit._handler,
654
 
                                Doit.MESSAGE_MERGEPROMPT, contact_detail ) );
 
627
                                Doit.MESSAGE_MERGEPROMPT, cache_identifier.getDetail() ) );
655
628
                        try {
656
629
                                wait();
657
630
                        }
665
638
                                _merge_setting = _response;
666
639
 
667
640
                        // recurse, with our new merge setting
668
 
                        return shouldWeSkipContact( contact_detail, exists, _response );
 
641
                        return checkForDuplicate( cache_identifier, _response );
669
642
                }
670
643
 
671
 
                // for all other cases (either overwriting or merging) we don't skip
672
 
                return false;
 
644
                // for all other cases (either overwriting or merging) we will need the
 
645
                // imported data
 
646
                return true;
673
647
        }
674
648
 
675
649
        protected void skipContact() throws AbortImportException
676
650
        {
677
651
                checkAbort();
678
 
 
679
 
                // show that we're skipping a new contact
680
652
                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
681
653
        }
682
654
 
685
657
        {
686
658
                checkAbort();
687
659
 
688
 
                // It is expected that we use contact.getCacheIdentifier() here.  The
 
660
                // It is expected that we use contact.getCacheIdentifier() here. The
689
661
                // contact we are passed should have been successfully finalise()d,
690
662
                // which includes generating a valid cache identifier.
691
663
                ContactsCache.CacheIdentifier cache_identifier =
692
664
                        contact.getCacheIdentifier();
693
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
 
694
672
//              if( !showContinue( "====[ IMPORTING ]====\n: " + contact._name ) )
695
673
//                      finish( ACTION_ABORT );
696
674
 
 
675
                // keep track of whether we've informed the UI of what we're doing
 
676
                boolean ui_informed = false;
 
677
 
697
678
                // attempt to lookup the id of an existing contact in the cache with
698
679
                // this contact data's cache identifier
699
680
                Long id = (Long)_contacts_cache.lookup( cache_identifier );
700
681
 
701
 
                // check to see if this contact should be skipped
702
 
                if( shouldWeSkipContact( cache_identifier.getDetail(), id != null,
703
 
                        _merge_setting ) )
 
682
                // does contact exist already?
 
683
                if( id != null )
704
684
                {
705
 
                        // show that we're skipping a contact
706
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTSKIPPED );
707
 
                        return;
 
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 )
 
690
                        {
 
691
                                // remove from device
 
692
                                _backend.deleteContact( id );
 
693
 
 
694
                                // 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;
 
705
                        }
708
706
                }
709
707
 
710
 
                // if a contact exists, and we're overwriting, destroy the existing
711
 
                // contact before importing
712
 
                boolean contact_deleted = false;
713
 
                if( id != null && _last_merge_decision == Doit.ACTION_OVERWRITE )
 
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 )
714
711
                {
715
 
                        contact_deleted = true;
716
 
 
717
 
                        // remove from device
718
 
                        _backend.deleteContact( id );
 
712
                        // create a new contact
 
713
                        id = _backend.addContact( contact._name );
 
714
                        if( id == null )
 
715
                                showError( R.string.error_unabletoaddcontact );
719
716
 
720
717
                        // update cache
721
 
                        _contacts_cache.removeLookup( cache_identifier );
722
 
                        _contacts_cache.removeAssociatedData( id );
723
 
 
724
 
                        // show that we're overwriting a contact
725
 
                        _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTOVERWRITTEN );
726
 
 
727
 
                        // discard the contact id
728
 
                        id = null;
729
 
                }
730
 
 
731
 
                try {
732
 
                        // if we don't have a contact id yet (or we did, but we destroyed it
733
 
                        // when we deleted the contact), we'll have to create a new contact
734
 
                        if( id == null )
735
 
                        {
736
 
                                // create a new contact
737
 
                                id = _backend.addContact( contact._name );
738
 
 
739
 
                                // update cache
740
 
                                _contacts_cache.addLookup( cache_identifier, id );
741
 
 
742
 
                                // if we haven't already shown that we're overwriting a contact,
743
 
                                // show that we're creating a new contact
744
 
                                if( !contact_deleted )
745
 
                                        _doit._handler.sendEmptyMessage(
746
 
                                                Doit.MESSAGE_CONTACTCREATED );
 
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;
747
725
                        }
748
 
                        else
749
 
                                // show that we're merging with an existing contact
750
 
                                _doit._handler.sendEmptyMessage( Doit.MESSAGE_CONTACTMERGED );
751
 
 
752
 
                        // import contact parts
753
 
                        if( contact.hasNumbers() )
754
 
                                importContactPhones( id, contact.getNumbers() );
755
 
                        if( contact.hasEmails() )
756
 
                                importContactEmails( id, contact.getEmails() );
757
 
                        if( contact.hasAddresses() )
758
 
                                importContactAddresses( id, contact.getAddresses() );
759
 
                        if( contact.hasOrganisations() )
760
 
                                importContactOrganisations( id, contact.getOrganisations() );
761
 
                        if( contact.hasNotes() )
762
 
                                importContactNotes( id, contact.getNotes() );
763
 
                        if( contact.hasBirthday() )
764
 
                                importContactBirthday( id, contact.getBirthday() );
765
 
                }
766
 
                catch( Backend.ContactCreationException e )
767
 
                {
768
 
                        showError( R.string.error_unabletoaddcontact );
769
 
                }
 
726
                }
 
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() );
770
742
        }
771
743
 
772
744
        private void importContactPhones( Long id,
773
 
                HashMap< String, ContactData.PreferredDetail > datas )
774
 
                throws ContactCreationException
 
745
                        HashMap< String, ContactData.PreferredDetail > datas )
775
746
        {
776
747
                // add phone numbers
777
748
                Set< String > datas_keys = datas.keySet();
780
751
                        String number = i.next();
781
752
                        ContactData.PreferredDetail data = datas.get( number );
782
753
 
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).
 
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).
790
761
                        if( _contacts_cache.hasAssociatedNumber( id, number ) )
791
762
                                continue;
792
763
 
800
771
        }
801
772
 
802
773
        private void importContactEmails( Long id,
803
 
                HashMap< String, ContactData.PreferredDetail > datas )
804
 
                throws ContactCreationException
 
774
                        HashMap< String, ContactData.PreferredDetail > datas )
805
775
        {
806
776
                // add email addresses
807
777
                Set< String > datas_keys = datas.keySet();
811
781
                        ContactData.PreferredDetail data = datas.get( email );
812
782
 
813
783
                        // we don't want to add this email address if it exists already or
814
 
                        // we would introduce duplicates
 
784
                        // we would introduce duplicates.
815
785
                        if( _contacts_cache.hasAssociatedEmail( id, email ) )
816
786
                                continue;
817
787
 
826
796
 
827
797
        private void importContactAddresses( Long id,
828
798
                HashMap< String, ContactData.TypeDetail > datas )
829
 
                throws ContactCreationException
830
799
        {
831
800
                // add addresses
832
801
                Set< String > datas_keys = datas.keySet();
851
820
 
852
821
        private void importContactOrganisations( Long id,
853
822
                HashMap< String, ContactData.ExtraDetail > datas )
854
 
                throws ContactCreationException
855
823
        {
856
824
                // add addresses
857
825
                Set< String > datas_keys = datas.keySet();
874
842
                }
875
843
        }
876
844
 
877
 
        private void importContactNotes( Long id, HashSet< String > datas )
878
 
                throws ContactCreationException
879
 
        {
880
 
                // add notes
881
 
                Iterator< String > i = datas.iterator();
882
 
                while( i.hasNext() ) {
883
 
                        String note = i.next();
884
 
 
885
 
                        // we don't want to add this note if it exists already or we would
886
 
                        // introduce duplicates
887
 
                        if( _contacts_cache.hasAssociatedNote( id, note ) )
888
 
                                continue;
889
 
 
890
 
                        // add note
891
 
                        _backend.addContactNote( id, note );
892
 
 
893
 
                        // and add this note to the cache to prevent a addition of duplicate
894
 
                        // date from another file
895
 
                        _contacts_cache.addAssociatedNote( id, note );
896
 
                }
897
 
        }
898
 
 
899
 
        private void importContactBirthday( Long id, String birthday )
900
 
                throws ContactCreationException
901
 
        {
902
 
                // we don't want to import this birthday if it already exists
903
 
                if( _contacts_cache.hasAssociatedBirthday( id, birthday ) )
904
 
                        return;
905
 
 
906
 
                // add birthday
907
 
                _backend.addContactBirthday( id, birthday );
908
 
 
909
 
                // and update the cache
910
 
                _contacts_cache.addAssociatedBirthday( id, birthday );
911
 
        }
912
 
 
913
845
        synchronized protected void checkAbort() throws AbortImportException
914
846
        {
915
847
                if( _abort ) {