/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/VcardImporter.java

  • Committer: edam
  • Date: 2011-06-04 13:16:20 UTC
  • Revision ID: edam@waxworlds.org-20110604131620-hean9j66r3f5i72h
- fix UTF-8 unencoding by default on v3.0 vCards
- proper unescaping of strings in v3.0 vCards (also works for v2.1, although the 2.1 specs don't mention it)

Show diffs side-by-side

added added

removed removed

116
116
                setProgress( 0 );
117
117
                for( int i = 0; i < files.length; i++ )
118
118
                        importVCardFile( files[ i ] );
 
119
                setProgress( _vcard_count );
119
120
        }
120
121
 
121
122
        private void countVCardFile( File file ) throws AbortImportException
168
169
                        FileInputStream istream = new FileInputStream( file );
169
170
                        byte[] content = new byte[ (int)file.length() ];
170
171
                        istream.read( content );
 
172
                        istream = null;
171
173
 
172
174
                        // import
173
175
                        importVCardFileContent( content, file.getName() );
186
188
        {
187
189
                // go through lines
188
190
                Vcard vcard = null;
 
191
                int vcard_start_line = 0;
189
192
                ContentLineIterator cli = new ContentLineIterator( content );
190
193
                while( cli.hasNext() )
191
194
                {
205
208
                        if( vcard == null ) {
206
209
                                // look for vcard beginning
207
210
                                if( line.matches( "^BEGIN:VCARD" ) ) {
208
 
                                        setProgress( ++_progress );
 
211
                                        setProgress( _progress++ );
209
212
                                        vcard = new Vcard();
 
213
                                        vcard_start_line = cli.getLineNumber();
210
214
                                }
211
215
                        }
212
216
                        else {
216
220
                                        // finalise the vcard/contact
217
221
                                        try {
218
222
                                                vcard.finaliseVcard();
 
223
 
 
224
                                                // pass the finalised contact to the importer
 
225
                                                importContact( vcard );
219
226
                                        }
220
227
                                        catch( Vcard.ParseException e ) {
221
 
                                                skipContact();
222
 
                                                if( !showContinue(
223
 
                                                        getText( R.string.error_vcf_parse ).toString()
224
 
                                                        + fileName + "\n" + e.getMessage() ) )
225
 
                                                {
226
 
                                                        finish( ACTION_ABORT );
227
 
                                                }
228
 
                                        }
229
 
 
230
 
                                        // pass the finalised contact to the importer
231
 
                                        importContact( vcard );
232
 
 
233
 
                                        // and discard it
 
228
                                                if( !showContinue(
 
229
                                                        getText( R.string.error_vcf_parse ).toString()
 
230
                                                        + fileName +
 
231
                                                        getText( R.string.error_vcf_parse_line ).toString()
 
232
                                                        + cli.getLineNumber() + ":\n" + e.getMessage() ) )
 
233
                                                {
 
234
                                                        finish( ACTION_ABORT );
 
235
                                                }
 
236
                                                else
 
237
                                                        skipContact();
 
238
                                        }
 
239
                                        catch( ContactData.ContactNotIdentifiableException e ) {
 
240
                                                if( !showContinue(
 
241
                                                        getText( R.string.error_vcf_parse ).toString()
 
242
                                                        + fileName +
 
243
                                                        getText( R.string.error_vcf_parse_line ).toString()
 
244
                                                        + vcard_start_line + ":\n" + getText(
 
245
                                                                R.string.error_vcf_notenoughinfo ).toString()
 
246
                                                ) )
 
247
                                                {
 
248
                                                        finish( ACTION_ABORT );
 
249
                                                }
 
250
                                                else
 
251
                                                        skipContact();
 
252
                                        }
 
253
 
 
254
                                        // discard this vcard
234
255
                                        vcard = null;
235
256
                                }
236
257
                                else
244
265
                                                skipContact();
245
266
                                                if( !showContinue(
246
267
                                                        getText( R.string.error_vcf_parse ).toString()
247
 
                                                        + fileName + "\n" + e.getMessage() ) )
 
268
                                                        + fileName +
 
269
                                                        getText( R.string.error_vcf_parse_line ).toString()
 
270
                                                        + cli.getLineNumber() + "\n" + e.getMessage() ) )
248
271
                                                {
249
272
                                                        finish( ACTION_ABORT );
250
273
                                                }
269
292
        {
270
293
                protected byte[] _content = null;
271
294
                protected int _pos = 0;
 
295
                protected int _line = 0;
272
296
 
273
297
                public ContentLineIterator( byte[] content )
274
298
                {
294
318
                                        int to = ( _pos > 0 && _content[ _pos - 1 ] == '\r' &&
295
319
                                                _pos > initial_pos )? _pos - 1 : _pos;
296
320
                                        _pos++;
 
321
                                        _line++;
297
322
                                        return ByteBuffer.wrap( _content, initial_pos,
298
323
                                                to - initial_pos );
299
324
                                }
302
327
                        if( _pos != initial_pos ) {
303
328
                                int to = _pos;
304
329
                                _pos++;
 
330
                                _line++;
305
331
                                return ByteBuffer.wrap( _content, initial_pos,
306
332
                                        to - initial_pos );
307
333
                        }
326
352
                        return _pos > 0 && _pos < _content.length &&
327
353
                                _content[ _pos - 1 ] == '\n' && _content[ _pos ] == ' ';
328
354
                }
 
355
 
 
356
                public int getLineNumber()
 
357
                {
 
358
                        return _line;
 
359
                }
329
360
        }
330
361
 
331
362
        private class Vcard extends ContactData
332
363
        {
333
364
                private final static int NAMELEVEL_NONE = 0;
334
 
                private final static int NAMELEVEL_FN = 1;
335
 
                private final static int NAMELEVEL_N = 2;
 
365
                private final static int NAMELEVEL_N = 1;
 
366
                private final static int NAMELEVEL_FN = 2;
336
367
 
337
368
                private final static int MULTILINE_NONE = 0;
338
369
                private final static int MULTILINE_ENCODED = 1; // v2.1 quoted-printable
535
566
                                for( int i = 0; i < name_param_parts.length; i++ )
536
567
                                        name_param_parts[ i ] = name_param_parts[ i ].trim();
537
568
 
 
569
                                // determine whether we care about this entry
 
570
                                final HashSet< String > interesting_fields =
 
571
                                        new HashSet< String >( Arrays.asList( new String[]
 
572
                                                { "N", "FN", "ORG", "TITLE", "TEL", "EMAIL", "ADR" }
 
573
                                ) );
 
574
                                boolean is_interesting_field =
 
575
                                        interesting_fields.contains( name_param_parts[ 0 ] );
 
576
 
538
577
                                // parse encoding parameter
539
578
                                String encoding = checkParam( name_param_parts, "ENCODING" );
540
579
                                if( encoding != null ) encoding = encoding.toUpperCase();
541
 
                                if( encoding != null && !encoding.equals( "8BIT" ) &&
 
580
                                if( is_interesting_field && encoding != null &&
 
581
                                        !encoding.equals( "8BIT" ) &&
542
582
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
543
583
                                        //&& !encoding.equals( "BASE64" ) )
544
584
                                {
548
588
                                // parse charset parameter
549
589
                                String charset = checkParam( name_param_parts, "CHARSET" );
550
590
                                if( charset != null ) charset = charset.toUpperCase();
551
 
                                if( charset != null && !charset.equals( "US-ASCII" ) &&
 
591
                                if( charset != null &&
 
592
                                        !charset.equals( "US-ASCII" ) &&
552
593
                                        !charset.equals( "ASCII" ) &&
553
594
                                        !charset.equals( "UTF-8" ) )
554
595
                                {
568
609
                                                _parser_multiline_state = MULTILINE_ENCODED;
569
610
                                }
570
611
 
571
 
                                // convert 8-bit ASCII charset to US-ASCII
572
 
                                if( charset == null || charset.equals( "ASCII" ) ) {
 
612
                                // convert 8-bit US-ASCII charset to UTF-8 (where no charset is
 
613
                                // specified for a v2.1 vcard entry, we assume it's US-ASCII)
 
614
                                if( ( charset == null && _version.equals( "2.1" ) ) ||
 
615
                                        ( charset != null && (
 
616
                                                charset.equals( "ASCII" ) ||
 
617
                                                charset.equals( "US-ASCII" ) ) ) )
 
618
                                {
573
619
                                        value = transcodeAsciiToUtf8( value );
574
 
                                        charset = "UTF-8";
575
620
                                }
576
621
 
577
 
                                // process charset
 
622
                                // process charset (value is now in UTF-8)
578
623
                                String string_value;
579
624
                                try {
580
625
                                        string_value = new String( value.array(), value.position(),
581
 
                                                value.limit() - value.position(), charset );
 
626
                                                value.limit() - value.position(), "UTF-8" );
582
627
                                } catch( UnsupportedEncodingException e ) {
583
628
                                        throw new ParseException( R.string.error_vcf_charset );
584
629
                                }
649
694
                        return ( count & 1 ) == 1;
650
695
                }
651
696
 
652
 
                private String[] splitValueBySemicolon( String value )
 
697
                private String[] splitValueByCharacter( String value, char character )
653
698
                {
654
 
                        // split string in to parts by semicolon
 
699
                        // split string in to parts by specified character
655
700
                        ArrayList< String > parts = new ArrayList< String >(
656
 
                                Arrays.asList( value.split(  ";" ) ) );
 
701
                                Arrays.asList( value.split( "" + character ) ) );
657
702
 
658
703
                        // go through parts
659
704
                        for( int a = 0; a < parts.size(); a++ )
667
712
                                if( a < parts.size() - 1 &&
668
713
                                        doesStringEndInAnEscapeChar( str ) )
669
714
                                {
670
 
                                        // join the next part to this part and remove the next part
 
715
                                        // append the escaped character, join the next part to this
 
716
                                        // part and remove the next part
671
717
                                        parts.set( a, str.substring( 0, str.length() - 1 ) +
672
 
                                                ';' + parts.get( a + 1 ) );
 
718
                                                character + parts.get( a + 1 ) );
673
719
                                        parts.remove( a + 1 );
674
720
 
675
721
                                        // re-visit this part
686
732
                        return parts.toArray( ret );
687
733
                }
688
734
 
 
735
                private String unescapeValue( String value )
 
736
                {
 
737
                        StringBuilder ret = new StringBuilder( value.length() );
 
738
                        boolean in_escape = false;
 
739
                        for( int a = 0; a < value.length(); a++ )
 
740
                        {
 
741
                                int c = value.codePointAt( a );
 
742
 
 
743
                                // process a normal character
 
744
                                if( !in_escape ) {
 
745
                                        if( c == '\\' )
 
746
                                                in_escape = true;
 
747
                                        else
 
748
                                                ret.append( Character.toChars( c ) );
 
749
                                        continue;
 
750
                                }
 
751
 
 
752
                                // process an escape sequence
 
753
                                in_escape = false;
 
754
                                switch( c )
 
755
                                {
 
756
                                case 'N':
 
757
                                case 'n':
 
758
                                        // add newline
 
759
                                        ret.append( '\n' );
 
760
                                        break;
 
761
                                case '\\':
 
762
                                case ',':
 
763
                                case ';':
 
764
                                        // add escaped character
 
765
                                        ret.append( Character.toChars( c ) );
 
766
                                        break;
 
767
                                default:
 
768
                                        // unknown escape sequence, so add it unescaped
 
769
                                        ret.append( "\\" );
 
770
                                        ret.append( Character.toChars( c ) );
 
771
                                        break;
 
772
                                }
 
773
                        }
 
774
 
 
775
                        return ret.toString();
 
776
                }
 
777
 
689
778
                private void parseN( String[] params, String value )
690
779
                {
691
780
                        // already got a better name?
692
781
                        if( _name_level >= NAMELEVEL_N ) return;
693
782
 
694
783
                        // get name parts
695
 
                        String[] name_parts = splitValueBySemicolon( value );
 
784
                        String[] name_parts = splitValueByCharacter( value, ';' );
696
785
 
697
786
                        // build name
698
787
                        value = "";
699
 
                        if( name_parts.length > 1 && name_parts[ 1 ].length() > 0 )
700
 
                                value += name_parts[ 1 ];
701
 
                        if( name_parts.length > 0 && name_parts[ 0 ].length() > 0 )
702
 
                                value += ( value.length() == 0? "" : " " ) + name_parts[ 0 ];
 
788
                        final int[] part_order = { 3, 1, 2, 0, 4 };
 
789
                        for( int a = 0; a < part_order.length; a++ )
 
790
                                if( name_parts.length > part_order[ a ] &&
 
791
                                        name_parts[ part_order[ a ] ].length() > 0 )
 
792
                                {
 
793
                                        // split this part in to it's comma-separated bits
 
794
                                        String[] name_part_parts = splitValueByCharacter(
 
795
                                                name_parts[ part_order[ a ] ], ',' );
 
796
                                        for( int b = 0; b < name_part_parts.length; b++ )
 
797
                                                if( name_part_parts[ b ].length() > 0 )
 
798
                                                {
 
799
                                                        if( value.length() == 0 ) value += " ";
 
800
                                                        value += name_part_parts[ b ];
 
801
                                                }
 
802
                                }
703
803
 
704
804
                        // set name
705
 
                        setName( value );
 
805
                        setName( unescapeValue( value ) );
706
806
                        _name_level = NAMELEVEL_N;
707
807
                }
708
808
 
712
812
                        if( _name_level >= NAMELEVEL_FN ) return;
713
813
 
714
814
                        // set name
715
 
                        setName( value );
 
815
                        setName( unescapeValue( value ) );
716
816
                        _name_level = NAMELEVEL_FN;
717
817
                }
718
818
 
719
819
                private void parseORG( String[] params, String value )
720
820
                {
721
821
                        // get org parts
722
 
                        String[] org_parts = splitValueBySemicolon( value );
 
822
                        String[] org_parts = splitValueByCharacter( value, ';' );
723
823
                        if( org_parts == null || org_parts.length < 1 ) return;
724
824
 
725
825
                        // build organisation name
727
827
                                String.valueOf( org_parts[ 0 ] ) );
728
828
                        for( int a = 1; a < org_parts.length; a++ )
729
829
                                builder.append( ", " ).append( org_parts[ a ] );
730
 
                        String organisation = builder.toString();
 
830
                        String organisation = unescapeValue( builder.toString() );
731
831
 
732
832
                        // set organisation name (using a title we've previously found)
733
833
                        addOrganisation( organisation, _cached_title, true );
744
844
 
745
845
                private void parseTITLE( String[] params, String value )
746
846
                {
 
847
                        value = unescapeValue( value );
 
848
 
747
849
                        // if we previously had an organisation, look it up and append this
748
850
                        // title to it
749
851
                        if( _cached_organisation != null && hasOrganisations() ) {
806
908
                        else
807
909
                                type = Contacts.ContactMethods.TYPE_HOME;
808
910
 
809
 
                        addEmail( value, type, is_preferred );
 
911
                        addEmail( unescapeValue( value ), type, is_preferred );
810
912
                }
811
913
 
812
914
                private void parseADR( String[] params, String value )
813
915
                {
814
916
                        // get address parts
815
 
                        String[] adr_parts = splitValueBySemicolon( value );
 
917
                        String[] adr_parts = splitValueByCharacter( value, ';' );
816
918
 
817
919
                        // build address
818
920
                        value = "";
819
 
                        for( int a = 0; a < adr_parts.length; a++ ) {
820
 
                                if( value.length() > 0 ) value += "\n";
821
 
                                value += adr_parts[ a ].trim();
822
 
                        }
 
921
                        for( int a = 0; a < adr_parts.length; a++ )
 
922
                                if( adr_parts[ a ].length() > 0 )
 
923
                                {
 
924
                                        // split this part in to it's comma-separated bits
 
925
                                        String[] adr_part_parts =
 
926
                                                splitValueByCharacter( adr_parts[ a ], ',' );
 
927
                                        for( int b = 0; b < adr_part_parts.length; b++ )
 
928
                                                if( adr_part_parts[ b ].length() > 0 )
 
929
                                                {
 
930
                                                        if( value.length() > 0 ) value += "\n";
 
931
                                                        value += adr_part_parts[ b ];
 
932
                                                }
 
933
                                }
823
934
 
824
935
                        Set< String > types = extractTypes( params, Arrays.asList(
825
936
                                "PREF", "WORK", "HOME", "INTERNET" ) );
831
942
                        else
832
943
                                type = Contacts.ContactMethods.TYPE_HOME;
833
944
 
834
 
                        addAddress( value, type );
 
945
                        addAddress( unescapeValue( value ), type );
835
946
                }
836
947
 
837
948
                public void finaliseVcard()
838
 
                        throws ParseException
 
949
                        throws ParseException, ContactNotIdentifiableException
839
950
                {
840
951
                        // missing version (and data is present)
841
952
                        if( _version == null && _buffers != null )
842
953
                                throw new ParseException( R.string.error_vcf_malformed );
843
954
 
844
955
                        // finalise the parent class
845
 
                        try {
846
 
                                finalise();
847
 
                        }
848
 
                        catch( ContactNotIdentifiableException e ) {
849
 
                                throw new ParseException( R.string.error_vcf_notenoughinfo );
850
 
                        }
 
956
                        finalise();
851
957
                }
852
958
 
853
959
                private String checkParam( String[] params, String name )