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

  • Committer: edam
  • Date: 2011-03-19 20:33:09 UTC
  • Revision ID: edam@waxworlds.org-20110319203309-5dzfyqrxwk94jtin
- formatting: removed some double-indents on overrunning lines
- updated TODO and NEWS
- rewrote central logic of parser so it makes more sense, looks nicer and has a small optimisation (getting name and params from line only when necessary)
- optimised unnecessary mutliple converting of lines to US-ASCII
- re-wrote line extraction from vcards so that we can lookahead for v3 folded lines
- added support for v3 folded lines

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * VCFImporter.java
3
3
 *
4
 
 * Copyright (C) 2009 to 2011 Tim Marston <tim@ed.am>
 
4
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
5
5
 *
6
6
 * This file is part of the Import Contacts program (hereafter referred
7
7
 * to as "this program"). For more information, see
8
 
 * http://ed.am/dev/android/import-contacts
 
8
 * http://www.waxworlds.org/edam/software/android/import-contacts
9
9
 *
10
10
 * This program is free software: you can redistribute it and/or modify
11
11
 * it under the terms of the GNU General Public License as published by
21
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
22
 */
23
23
 
24
 
package am.ed.importcontacts;
 
24
package org.waxworlds.edam.importcontacts;
25
25
 
26
26
import java.io.BufferedReader;
27
27
import java.io.File;
32
32
import java.io.IOException;
33
33
import java.io.UnsupportedEncodingException;
34
34
import java.nio.ByteBuffer;
35
 
import java.util.ArrayList;
36
35
import java.util.Arrays;
37
 
import java.util.HashMap;
38
36
import java.util.HashSet;
39
37
import java.util.Iterator;
40
38
import java.util.List;
41
 
import java.util.NoSuchElementException;
42
39
import java.util.Set;
43
40
import java.util.Vector;
44
41
import java.util.regex.Matcher;
45
42
import java.util.regex.Pattern;
 
43
import java.util.NoSuchElementException;
 
44
import java.lang.UnsupportedOperationException;
46
45
 
47
46
import android.content.SharedPreferences;
48
47
import android.provider.Contacts;
49
48
import android.provider.Contacts.PhonesColumns;
50
49
 
51
 
public class VcardImporter extends Importer
 
50
public class VCFImporter extends Importer
52
51
{
53
 
        private int _vcard_count = 0;
 
52
        private int _vCardCount = 0;
54
53
        private int _progress = 0;
55
54
 
56
 
        public VcardImporter( Doit doit )
 
55
        public VCFImporter( Doit doit )
57
56
        {
58
57
                super( doit );
59
58
        }
110
109
                        countVCardFile( files[ i ] );
111
110
                        setTmpProgress( i );
112
111
                }
113
 
                setProgressMax( _vcard_count ); // will also update tmp progress
 
112
                setProgressMax( _vCardCount );  // will also update tmp progress
114
113
 
115
114
                // import them
116
115
                setProgress( 0 );
117
116
                for( int i = 0; i < files.length; i++ )
118
117
                        importVCardFile( files[ i ] );
119
 
                setProgress( _vcard_count );
120
118
        }
121
119
 
122
120
        private void countVCardFile( File file ) throws AbortImportException
129
127
 
130
128
                        // read
131
129
                        String line;
132
 
                        boolean in_vcard = false;
 
130
                        boolean inVCard = false;
133
131
                        while( ( line = reader.readLine() ) != null )
134
132
                        {
135
 
                                if( !in_vcard ) {
 
133
                                if( !inVCard ) {
136
134
                                        // look for vcard beginning
137
135
                                        if( line.matches( "^BEGIN:VCARD" ) ) {
138
 
                                                in_vcard = true;
139
 
                                                _vcard_count++;
 
136
                                                inVCard = true;
 
137
                                                _vCardCount++;
140
138
                                        }
141
139
                                }
142
140
                                else if( line.matches( "^END:VCARD" ) )
143
 
                                        in_vcard = false;
 
141
                                        inVCard = false;
144
142
                        }
145
143
 
146
144
                }
169
167
                        FileInputStream istream = new FileInputStream( file );
170
168
                        byte[] content = new byte[ (int)file.length() ];
171
169
                        istream.read( content );
172
 
                        istream = null;
173
170
 
174
171
                        // import
175
172
                        importVCardFileContent( content, file.getName() );
187
184
                throws AbortImportException
188
185
        {
189
186
                // go through lines
190
 
                Vcard vcard = null;
191
 
                int vcard_start_line = 0;
 
187
                VCard vCard = null;
192
188
                ContentLineIterator cli = new ContentLineIterator( content );
193
189
                while( cli.hasNext() )
194
190
                {
205
201
                                line = "";
206
202
                        }
207
203
 
208
 
                        if( vcard == null ) {
 
204
                        if( vCard == null ) {
209
205
                                // look for vcard beginning
210
206
                                if( line.matches( "^BEGIN:VCARD" ) ) {
211
 
                                        setProgress( _progress++ );
212
 
                                        vcard = new Vcard();
213
 
                                        vcard_start_line = cli.getLineNumber();
 
207
                                        setProgress( ++_progress );
 
208
                                        vCard = new VCard();
214
209
                                }
215
210
                        }
216
211
                        else {
217
212
                                // look for vcard content or ending
218
213
                                if( line.matches( "^END:VCARD" ) )
219
214
                                {
220
 
                                        // finalise the vcard/contact
 
215
                                        // store vcard and do away with it
221
216
                                        try {
222
 
                                                vcard.finaliseVcard();
223
 
 
224
 
                                                // pass the finalised contact to the importer
225
 
                                                importContact( vcard );
226
 
                                        }
227
 
                                        catch( Vcard.ParseException e ) {
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
255
 
                                        vcard = null;
 
217
                                                vCard.finaliseParsing();
 
218
                                                importContact( vCard );
 
219
                                        }
 
220
                                        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
                                        catch( VCard.SkipContactException e ) {
 
230
                                                skipContact();
 
231
                                                // do nothing
 
232
                                        }
 
233
                                        vCard = null;
256
234
                                }
257
235
                                else
258
236
                                {
259
237
                                        // try giving the line to the vcard
260
238
                                        try {
261
 
                                                vcard.parseLine( buffer, line,
 
239
                                                vCard.parseLine( buffer, line,
262
240
                                                        cli.doesNextLineLookFolded() );
263
241
                                        }
264
 
                                        catch( Vcard.ParseException e ) {
 
242
                                        catch( VCard.ParseException e ) {
265
243
                                                skipContact();
266
244
                                                if( !showContinue(
267
245
                                                        getText( R.string.error_vcf_parse ).toString()
268
 
                                                        + fileName +
269
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
270
 
                                                        + cli.getLineNumber() + "\n" + e.getMessage() ) )
 
246
                                                        + fileName + "\n" + e.getMessage() ) )
271
247
                                                {
272
248
                                                        finish( ACTION_ABORT );
273
249
                                                }
275
251
                                                // although we're continuing, we still need to abort
276
252
                                                // this vCard. Further lines will be ignored until we
277
253
                                                // get to another BEGIN:VCARD line.
278
 
                                                vcard = null;
 
254
                                                vCard = null;
279
255
                                        }
280
 
                                        catch( Vcard.SkipImportException e ) {
 
256
                                        catch( VCard.SkipContactException e ) {
281
257
                                                skipContact();
282
258
                                                // abort this vCard. Further lines will be ignored until
283
259
                                                // we get to another BEGIN:VCARD line.
284
 
                                                vcard = null;
 
260
                                                vCard = null;
285
261
                                        }
286
262
                                }
287
263
                        }
292
268
        {
293
269
                protected byte[] _content = null;
294
270
                protected int _pos = 0;
295
 
                protected int _line = 0;
296
271
 
297
272
                public ContentLineIterator( byte[] content )
298
273
                {
318
293
                                        int to = ( _pos > 0 && _content[ _pos - 1 ] == '\r' &&
319
294
                                                _pos > initial_pos )? _pos - 1 : _pos;
320
295
                                        _pos++;
321
 
                                        _line++;
322
296
                                        return ByteBuffer.wrap( _content, initial_pos,
323
297
                                                to - initial_pos );
324
298
                                }
327
301
                        if( _pos != initial_pos ) {
328
302
                                int to = _pos;
329
303
                                _pos++;
330
 
                                _line++;
331
304
                                return ByteBuffer.wrap( _content, initial_pos,
332
305
                                        to - initial_pos );
333
306
                        }
352
325
                        return _pos > 0 && _pos < _content.length &&
353
326
                                _content[ _pos - 1 ] == '\n' && _content[ _pos ] == ' ';
354
327
                }
355
 
 
356
 
                public int getLineNumber()
357
 
                {
358
 
                        return _line;
359
 
                }
360
328
        }
361
329
 
362
 
        private class Vcard extends ContactData
 
330
        private class VCard extends ContactData
363
331
        {
364
332
                private final static int NAMELEVEL_NONE = 0;
365
 
                private final static int NAMELEVEL_N = 1;
 
333
                private final static int NAMELEVEL_ORG = 1;
366
334
                private final static int NAMELEVEL_FN = 2;
367
 
 
368
 
                private final static int MULTILINE_NONE = 0;
369
 
                private final static int MULTILINE_ENCODED = 1; // v2.1 quoted-printable
370
 
                private final static int MULTILINE_ESCAPED = 2; // v2.1 \\CRLF
371
 
                private final static int MULTILINE_FOLDED = 3;  // v3.0 folding
 
335
                private final static int NAMELEVEL_N = 3;
372
336
 
373
337
                private String _version = null;
374
338
                private Vector< ByteBuffer > _buffers = null;
375
339
                private int _name_level = NAMELEVEL_NONE;
376
 
                private int _parser_multiline_state = MULTILINE_NONE;
 
340
                private boolean _parser_in_encoded_multiline = false;
 
341
                private boolean _parser_in_folded_multiline = false;
377
342
                private String _parser_current_name_and_params = null;
378
343
                private String _parser_buffered_value_so_far = "";
379
 
                private String _cached_organisation = null;
380
 
                private String _cached_title = null;
381
344
 
382
345
                protected class UnencodeResult
383
346
                {
413
376
 
414
377
                        public ParseException( int res )
415
378
                        {
416
 
                                super( VcardImporter.this.getText( res ).toString() );
 
379
                                super( VCFImporter.this.getText( res ).toString() );
417
380
                        }
418
381
                }
419
382
 
420
383
                @SuppressWarnings("serial")
421
 
                protected class SkipImportException extends Exception { }
 
384
                protected class SkipContactException extends Exception { }
422
385
 
423
386
                private String extractCollonPartFromLine( ByteBuffer buffer,
424
387
                        String line, boolean former )
460
423
 
461
424
                public void parseLine( ByteBuffer buffer, String line,
462
425
                        boolean next_line_looks_folded )
463
 
                        throws ParseException, SkipImportException,
 
426
                        throws ParseException, SkipContactException,
464
427
                        AbortImportException
465
428
                {
466
429
                        // do we have a version yet?
506
469
                                String name_and_params;
507
470
                                int pos;
508
471
 
509
 
                                if( _parser_multiline_state != MULTILINE_NONE )
 
472
                                if( _parser_in_encoded_multiline ||
 
473
                                        _parser_in_folded_multiline )
510
474
                                {
511
475
                                        // if we're currently in a multi-line value, use the stored
512
476
                                        // property name and parameters
513
477
                                        name_and_params = _parser_current_name_and_params;
514
478
 
515
 
                                        // skip some initial line characters, depending on the type
516
 
                                        // of multi-line we're handling
517
479
                                        pos = buffer.position();
518
 
                                        switch( _parser_multiline_state )
519
 
                                        {
520
 
                                        case MULTILINE_FOLDED:
 
480
 
 
481
                                        // for folded multi-lines, skip the single space at the
 
482
                                        // start of the next line
 
483
                                        if( _parser_in_folded_multiline )
521
484
                                                pos++;
522
 
                                                break;
523
 
                                        case MULTILINE_ENCODED:
 
485
 
 
486
                                        // else, this must be an encoded multi-line, so skip any
 
487
                                        // whitespace we find at the start of the next line
 
488
                                        else
524
489
                                                while( pos < buffer.limit() && (
525
490
                                                        buffer.get( pos ) == ' ' ||
526
491
                                                        buffer.get( pos ) == '\t' ) )
527
492
                                                {
528
493
                                                        pos++;
529
494
                                                }
530
 
                                                break;
531
 
                                        default:
532
 
                                                // do nothing
533
 
                                        }
534
 
 
535
 
                                        // take us out of multi-line so that we can re-detect that
536
 
                                        // this line is a multi-line or not
537
 
                                        _parser_multiline_state = MULTILINE_NONE;
538
495
                                }
539
496
                                else
540
497
                                {
566
523
                                for( int i = 0; i < name_param_parts.length; i++ )
567
524
                                        name_param_parts[ i ] = name_param_parts[ i ].trim();
568
525
 
569
 
                                // determine whether we care about this entry
570
 
                                final HashSet< String > interesting_fields =
571
 
                                        new HashSet< String >( Arrays.asList( new String[] { "N",
572
 
                                                "FN", "ORG", "TITLE", "TEL", "EMAIL", "ADR", "LABEL" }
573
 
                                ) );
574
 
                                boolean is_interesting_field =
575
 
                                        interesting_fields.contains( name_param_parts[ 0 ] );
576
 
 
577
526
                                // parse encoding parameter
578
527
                                String encoding = checkParam( name_param_parts, "ENCODING" );
579
528
                                if( encoding != null ) encoding = encoding.toUpperCase();
580
 
                                if( is_interesting_field && encoding != null &&
581
 
                                        !encoding.equals( "8BIT" ) &&
 
529
                                if( encoding != null && !encoding.equals( "8BIT" ) &&
582
530
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
583
531
                                        //&& !encoding.equals( "BASE64" ) )
584
532
                                {
588
536
                                // parse charset parameter
589
537
                                String charset = checkParam( name_param_parts, "CHARSET" );
590
538
                                if( charset != null ) charset = charset.toUpperCase();
591
 
                                if( charset != null &&
592
 
                                        !charset.equals( "US-ASCII" ) &&
 
539
                                if( charset != null && !charset.equals( "US-ASCII" ) &&
593
540
                                        !charset.equals( "ASCII" ) &&
594
541
                                        !charset.equals( "UTF-8" ) )
595
542
                                {
605
552
//                                      unencoding_result = unencodeBase64( props[ 1 ], charset );
606
553
                                if( unencoding_result != null ) {
607
554
                                        value = unencoding_result.getBuffer();
608
 
                                        if( unencoding_result.isAnotherLineRequired() )
609
 
                                                _parser_multiline_state = MULTILINE_ENCODED;
 
555
                                        _parser_in_encoded_multiline =
 
556
                                                unencoding_result.isAnotherLineRequired();
610
557
                                }
611
558
 
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
 
                                {
 
559
                                // convert 8-bit ASCII charset to US-ASCII
 
560
                                if( charset == null || charset.equals( "ASCII" ) ) {
619
561
                                        value = transcodeAsciiToUtf8( value );
 
562
                                        charset = "UTF-8";
620
563
                                }
621
564
 
622
 
                                // process charset (value is now in UTF-8)
 
565
                                // process charset
623
566
                                String string_value;
624
567
                                try {
625
568
                                        string_value = new String( value.array(), value.position(),
626
 
                                                value.limit() - value.position(), "UTF-8" );
 
569
                                                value.limit() - value.position(), charset );
627
570
                                } catch( UnsupportedEncodingException e ) {
628
571
                                        throw new ParseException( R.string.error_vcf_charset );
629
572
                                }
630
573
 
631
 
                                // for some entries that have semicolon-separated value parts,
632
 
                                // check to see if the value ends in an escape character, which
633
 
                                // indicates that we have a multi-line value
634
 
                                if( ( name_param_parts[ 0 ].equals( "N" ) ||
635
 
                                        name_param_parts[ 0 ].equals( "ORG" ) ||
636
 
                                        name_param_parts[ 0 ].equals( "ADR" ) ) &&
637
 
                                        doesStringEndInAnEscapeChar( string_value ) )
638
 
                                {
639
 
                                        _parser_multiline_state = MULTILINE_ESCAPED;
640
 
                                        string_value = string_value.substring( 0,
641
 
                                                string_value.length() - 1 );
642
 
                                }
643
 
 
644
574
                                // now we know whether we're in an encoding multi-line,
645
575
                                // determine if we're in a v3 folded multi-line or not
646
 
                                if( _parser_multiline_state == MULTILINE_NONE &&
647
 
                                        _version.equals( "3.0" ) && next_line_looks_folded )
 
576
                                _parser_in_folded_multiline = !_parser_in_encoded_multiline &&
 
577
                                        _version.equals( "3.0" ) && next_line_looks_folded;
 
578
 
 
579
                                // handle multi-line requests
 
580
                                if( _parser_in_encoded_multiline ||
 
581
                                        _parser_in_folded_multiline )
648
582
                                {
649
 
                                        _parser_multiline_state = MULTILINE_FOLDED;
650
 
                                }
651
 
 
652
 
                                // handle multi-lines by buffering them and parsing them when we
653
 
                                // are processing the last line in a multi-line sequence
654
 
                                if( _parser_multiline_state != MULTILINE_NONE ) {
655
583
                                        _parser_buffered_value_so_far += string_value;
656
584
                                        return;
657
585
                                }
 
586
 
 
587
                                // add on buffered multi-line content
658
588
                                String complete_value =
659
 
                                        ( _parser_buffered_value_so_far + string_value ).trim();
 
589
                                        _parser_buffered_value_so_far + string_value;
660
590
 
661
591
                                // ignore empty values
662
592
                                if( complete_value.length() < 1 ) return;
668
598
                                        parseFN( name_param_parts, complete_value );
669
599
                                else if( name_param_parts[ 0 ].equals( "ORG" ) )
670
600
                                        parseORG( name_param_parts, complete_value );
671
 
                                else if( name_param_parts[ 0 ].equals( "TITLE" ) )
672
 
                                        parseTITLE( name_param_parts, complete_value );
673
601
                                else if( name_param_parts[ 0 ].equals( "TEL" ) )
674
602
                                        parseTEL( name_param_parts, complete_value );
675
603
                                else if( name_param_parts[ 0 ].equals( "EMAIL" ) )
676
604
                                        parseEMAIL( name_param_parts, complete_value );
677
 
                                else if( name_param_parts[ 0 ].equals( "ADR" ) )
678
 
                                        parseADR( name_param_parts, complete_value );
679
 
                                else if( name_param_parts[ 0 ].equals( "LABEL" ) )
680
 
                                        parseLABEL( name_param_parts, complete_value );
681
 
                        }
682
 
                }
683
 
 
684
 
                private boolean doesStringEndInAnEscapeChar( String string )
685
 
                {
686
 
                        // count the number of backslashes at the end of the string
687
 
                        int count = 0;
688
 
                        for( int a = string.length() - 1; a >= 0; a-- )
689
 
                                if( string.charAt( a ) == '\\' )
690
 
                                        count++;
691
 
                                else
692
 
                                        break;
693
 
 
694
 
                        // if there are an even number of backslashes then the final one
695
 
                        // doesn't count
696
 
                        return ( count & 1 ) == 1;
697
 
                }
698
 
 
699
 
                private String[] splitValueByCharacter( String value, char character )
700
 
                {
701
 
                        // split string in to parts by specified character
702
 
                        ArrayList< String > parts = new ArrayList< String >(
703
 
                                Arrays.asList( value.split( "" + character ) ) );
704
 
 
705
 
                        // go through parts
706
 
                        for( int a = 0; a < parts.size(); a++ )
707
 
                        {
708
 
                                String str = parts.get( a );
709
 
 
710
 
                                // look for parts that end in an escape character, but ignore
711
 
                                // the final part. We've already detected escape chars at the
712
 
                                // end of the final part in parseLine() and handled multi-lines
713
 
                                // accordingly.
714
 
                                if( a < parts.size() - 1 &&
715
 
                                        doesStringEndInAnEscapeChar( str ) )
716
 
                                {
717
 
                                        // append the escaped character, join the next part to this
718
 
                                        // part and remove the next part
719
 
                                        parts.set( a, str.substring( 0, str.length() - 1 ) +
720
 
                                                character + parts.get( a + 1 ) );
721
 
                                        parts.remove( a + 1 );
722
 
 
723
 
                                        // re-visit this part
724
 
                                        a--;
725
 
                                        continue;
726
 
                                }
727
 
 
728
 
                                // trim and replace string
729
 
                                str = str.trim();
730
 
                                parts.set( a, str );
731
 
                        }
732
 
 
733
 
                        String[] ret = new String[ parts.size() ];
734
 
                        return parts.toArray( ret );
735
 
                }
736
 
 
737
 
                private String unescapeValue( String value )
738
 
                {
739
 
                        StringBuilder ret = new StringBuilder( value.length() );
740
 
                        boolean in_escape = false;
741
 
                        for( int a = 0; a < value.length(); a++ )
742
 
                        {
743
 
                                int c = value.codePointAt( a );
744
 
 
745
 
                                // process a normal character
746
 
                                if( !in_escape ) {
747
 
                                        if( c == '\\' )
748
 
                                                in_escape = true;
749
 
                                        else
750
 
                                                ret.append( Character.toChars( c ) );
751
 
                                        continue;
752
 
                                }
753
 
 
754
 
                                // process an escape sequence
755
 
                                in_escape = false;
756
 
                                switch( c )
757
 
                                {
758
 
                                case 'N':
759
 
                                case 'n':
760
 
                                        // add newline
761
 
                                        ret.append( '\n' );
762
 
                                        break;
763
 
                                case '\\':
764
 
                                case ',':
765
 
                                case ';':
766
 
                                        // add escaped character
767
 
                                        ret.append( Character.toChars( c ) );
768
 
                                        break;
769
 
                                default:
770
 
                                        // unknown escape sequence, so add it unescaped
771
 
                                        ret.append( "\\" );
772
 
                                        ret.append( Character.toChars( c ) );
773
 
                                        break;
774
 
                                }
775
 
                        }
776
 
 
777
 
                        return ret.toString();
 
605
                        }
778
606
                }
779
607
 
780
608
                private void parseN( String[] params, String value )
 
609
                        throws ParseException, SkipContactException,
 
610
                        AbortImportException
781
611
                {
782
612
                        // already got a better name?
783
613
                        if( _name_level >= NAMELEVEL_N ) return;
784
614
 
785
615
                        // get name parts
786
 
                        String[] name_parts = splitValueByCharacter( value, ';' );
 
616
                        String[] name_parts = value.split( ";" );
 
617
                        for( int i = 0; i < name_parts.length; i++ )
 
618
                                name_parts[ i ] = name_parts[ i ].trim();
787
619
 
788
620
                        // build name
789
621
                        value = "";
790
 
                        final int[] part_order = { 3, 1, 2, 0, 4 };
791
 
                        for( int a = 0; a < part_order.length; a++ )
792
 
                                if( name_parts.length > part_order[ a ] &&
793
 
                                        name_parts[ part_order[ a ] ].length() > 0 )
794
 
                                {
795
 
                                        // split this part in to it's comma-separated bits
796
 
                                        String[] name_part_parts = splitValueByCharacter(
797
 
                                                name_parts[ part_order[ a ] ], ',' );
798
 
                                        for( int b = 0; b < name_part_parts.length; b++ )
799
 
                                                if( name_part_parts[ b ].length() > 0 )
800
 
                                                {
801
 
                                                        if( value.length() == 0 ) value += " ";
802
 
                                                        value += name_part_parts[ b ];
803
 
                                                }
804
 
                                }
 
622
                        if( name_parts.length > 1 && name_parts[ 1 ].length() > 0 )
 
623
                                value += name_parts[ 1 ];
 
624
                        if( name_parts.length > 0 && name_parts[ 0 ].length() > 0 )
 
625
                                value += ( value.length() == 0? "" : " " ) + name_parts[ 0 ];
805
626
 
806
627
                        // set name
807
 
                        setName( unescapeValue( value ) );
 
628
                        setName( value );
808
629
                        _name_level = NAMELEVEL_N;
 
630
 
 
631
                        // check now to see if we need to import this contact (to avoid
 
632
                        // parsing the rest of the vCard unnecessarily)
 
633
                        if( !isImportRequired( getName() ) )
 
634
                                throw new SkipContactException();
809
635
                }
810
636
 
811
637
                private void parseFN( String[] params, String value )
 
638
                        throws ParseException, SkipContactException
812
639
                {
813
640
                        // already got a better name?
814
641
                        if( _name_level >= NAMELEVEL_FN ) return;
815
642
 
816
643
                        // set name
817
 
                        setName( unescapeValue( value ) );
 
644
                        setName( value );
818
645
                        _name_level = NAMELEVEL_FN;
819
646
                }
820
647
 
821
648
                private void parseORG( String[] params, String value )
 
649
                        throws ParseException, SkipContactException
822
650
                {
 
651
                        // already got a better name?
 
652
                        if( _name_level >= NAMELEVEL_ORG ) return;
 
653
 
823
654
                        // get org parts
824
 
                        String[] org_parts = splitValueByCharacter( value, ';' );
825
 
                        if( org_parts == null || org_parts.length < 1 ) return;
826
 
 
827
 
                        // build organisation name
828
 
                        StringBuilder builder = new StringBuilder(
829
 
                                String.valueOf( org_parts[ 0 ] ) );
830
 
                        for( int a = 1; a < org_parts.length; a++ )
831
 
                                builder.append( ", " ).append( org_parts[ a ] );
832
 
                        String organisation = unescapeValue( builder.toString() );
833
 
 
834
 
                        // set organisation name (using a title we've previously found)
835
 
                        addOrganisation( organisation, _cached_title, true );
836
 
 
837
 
                        // if we've not previously found a title, store this organisation
838
 
                        // name (we'll need it when we find a title to update the
839
 
                        // organisation, by name), else if we *have* previously found a
840
 
                        // title, clear it (since we just used it)
841
 
                        if( _cached_title == null )
842
 
                                _cached_organisation = organisation;
843
 
                        else
844
 
                                _cached_title = null;
845
 
                }
846
 
 
847
 
                private void parseTITLE( String[] params, String value )
848
 
                {
849
 
                        value = unescapeValue( value );
850
 
 
851
 
                        // if we previously had an organisation, look it up and append this
852
 
                        // title to it
853
 
                        if( _cached_organisation != null && hasOrganisations() ) {
854
 
                                HashMap< String, ExtraDetail > datas = getOrganisations();
855
 
                                ExtraDetail detail = datas.get( _cached_organisation );
856
 
                                if( detail != null )
857
 
                                        detail.setExtra( value );
858
 
                        }
859
 
 
860
 
                        // same as when handling organisation, if we've not previously found
861
 
                        // an organisation we store this title, else we clear it (since we
862
 
                        // just appended this title to it)
863
 
                        if( _cached_organisation == null )
864
 
                                _cached_title = value;
865
 
                        else
866
 
                                _cached_organisation = null;
 
655
                        String[] org_parts = value.split( ";" );
 
656
                        for( int i = 0; i < org_parts.length; i++ )
 
657
                                org_parts[ i ] = org_parts[ i ].trim();
 
658
 
 
659
                        // build name
 
660
                        if( org_parts.length > 1 && org_parts[ 0 ].length() == 0 )
 
661
                                value = org_parts[ 1 ];
 
662
                        else
 
663
                                value = org_parts[ 0 ];
 
664
 
 
665
                        // set name
 
666
                        setName( value );
 
667
                        _name_level = NAMELEVEL_ORG;
867
668
                }
868
669
 
869
670
                private void parseTEL( String[] params, String value )
 
671
                        throws ParseException
870
672
                {
871
673
                        if( value.length() == 0 ) return;
872
674
 
875
677
                                "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
876
678
 
877
679
                        // here's the logic...
878
 
                        boolean is_preferred = types.contains( "PREF" );
879
 
                        int type;
 
680
                        boolean preferred = types.contains( "PREF" );
 
681
                        int type = PhonesColumns.TYPE_MOBILE;
 
682
                        if( types.contains( "VOICE" ) )
 
683
                                if( types.contains( "WORK" ) )
 
684
                                        type = PhonesColumns.TYPE_WORK;
 
685
                                else
 
686
                                        type = PhonesColumns.TYPE_HOME;
 
687
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
 
688
                                type = PhonesColumns.TYPE_MOBILE;
880
689
                        if( types.contains( "FAX" ) )
881
690
                                if( types.contains( "HOME" ) )
882
691
                                        type = PhonesColumns.TYPE_FAX_HOME;
883
692
                                else
884
693
                                        type = PhonesColumns.TYPE_FAX_WORK;
885
 
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
886
 
                                type = PhonesColumns.TYPE_MOBILE;
887
 
                        else if( types.contains( "PAGER" ) )
 
694
                        if( types.contains( "PAGER" ) )
888
695
                                type = PhonesColumns.TYPE_PAGER;
889
 
                        else if( types.contains( "WORK" ) )
890
 
                                type = PhonesColumns.TYPE_WORK;
891
 
                        else
892
 
                                type = PhonesColumns.TYPE_HOME;
893
696
 
894
697
                        // add phone number
895
 
                        addNumber( value, type, is_preferred );
 
698
                        addPhone( value, type, preferred );
896
699
                }
897
700
 
898
701
                public void parseEMAIL( String[] params, String value )
 
702
                        throws ParseException
899
703
                {
900
704
                        if( value.length() == 0 ) return;
901
705
 
902
706
                        Set< String > types = extractTypes( params, Arrays.asList(
903
707
                                "PREF", "WORK", "HOME", "INTERNET" ) );
904
708
 
905
 
                        // add email address
906
 
                        boolean is_preferred = types.contains( "PREF" );
907
 
                        int type;
908
 
                        if( types.contains( "WORK" ) )
909
 
                                type = Contacts.ContactMethods.TYPE_WORK;
910
 
                        else
911
 
                                type = Contacts.ContactMethods.TYPE_HOME;
912
 
 
913
 
                        addEmail( unescapeValue( value ), type, is_preferred );
914
 
                }
915
 
 
916
 
                private void parseADR( String[] params, String value )
917
 
                {
918
 
                        // get address parts
919
 
                        String[] adr_parts = splitValueByCharacter( value, ';' );
920
 
 
921
 
                        // build address
922
 
                        value = "";
923
 
                        for( int a = 0; a < adr_parts.length; a++ )
924
 
                                if( adr_parts[ a ].length() > 0 )
925
 
                                {
926
 
                                        // split this part in to it's comma-separated bits
927
 
                                        String[] adr_part_parts =
928
 
                                                splitValueByCharacter( adr_parts[ a ], ',' );
929
 
                                        for( int b = 0; b < adr_part_parts.length; b++ )
930
 
                                                if( adr_part_parts[ b ].length() > 0 )
931
 
                                                {
932
 
                                                        if( value.length() > 0 ) value += "\n";
933
 
                                                        value += adr_part_parts[ b ];
934
 
                                                }
935
 
                                }
936
 
 
937
 
                        Set< String > types = extractTypes( params, Arrays.asList(
938
 
                                "PREF", "WORK", "HOME" ) );
939
 
 
940
 
                        // add address
941
 
                        int type;
942
 
                        if( types.contains( "WORK" ) )
943
 
                                type = Contacts.ContactMethods.TYPE_WORK;
944
 
                        else
945
 
                                type = Contacts.ContactMethods.TYPE_HOME;
946
 
 
947
 
                        addAddress( unescapeValue( value ), type );
948
 
                }
949
 
 
950
 
                private void parseLABEL( String[] params, String value )
951
 
                {
952
 
                        Set< String > types = extractTypes( params, Arrays.asList(
953
 
                                "PREF", "WORK", "HOME" ) );
954
 
 
955
 
                        // add address
956
 
                        int type;
957
 
                        if( types.contains( "WORK" ) )
958
 
                                type = Contacts.ContactMethods.TYPE_WORK;
959
 
                        else
960
 
                                type = Contacts.ContactMethods.TYPE_HOME;
961
 
 
962
 
                        addAddress( unescapeValue( value ), type );
963
 
                }
964
 
 
965
 
                public void finaliseVcard()
966
 
                        throws ParseException, ContactNotIdentifiableException
 
709
                        // here's the logic...
 
710
                        boolean preferred = types.contains( "PREF" );
 
711
                        if( types.contains( "WORK" ) )
 
712
                                addEmail( value, Contacts.ContactMethods.TYPE_WORK, preferred );
 
713
                        else
 
714
                                addEmail( value, Contacts.ContactMethods.TYPE_HOME, preferred );
 
715
                }
 
716
 
 
717
                public void finaliseParsing()
 
718
                        throws ParseException, SkipContactException,
 
719
                        AbortImportException
967
720
                {
968
721
                        // missing version (and data is present)
969
722
                        if( _version == null && _buffers != null )
970
723
                                throw new ParseException( R.string.error_vcf_malformed );
971
724
 
972
 
                        // finalise the parent class
973
 
                        finalise();
 
725
                        //  missing name properties?
 
726
                        if( _name_level == NAMELEVEL_NONE )
 
727
                                throw new ParseException( R.string.error_vcf_noname );
 
728
 
 
729
                        // check if we should import this one? If we've already got an 'N'-
 
730
                        // type name, this will already have been done by parseN() so we
 
731
                        // mustn't do this here (or it could prompt twice!)
 
732
                        if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
 
733
                                throw new SkipContactException();
974
734
                }
975
735
 
976
 
                /**
977
 
                 * Amongst the params, find the value of the first, only, of any with
978
 
                 * the specified name
979
 
                 * @param params
980
 
                 * @param name
981
 
                 * @return a value, or null
982
 
                 */
983
736
                private String checkParam( String[] params, String name )
984
737
                {
985
 
                        String[] res = checkParams( params, name );
986
 
                        return res.length > 0? res[ 0 ] : null;
987
 
                }
988
 
 
989
 
                /**
990
 
                 * Amongst the params, find the values of any with the specified name
991
 
                 * @param params
992
 
                 * @param name
993
 
                 * @return an array of values, or null
994
 
                 */
995
 
                private String[] checkParams( String[] params, String name )
996
 
                {
997
 
                        HashSet< String > ret = new HashSet< String >();
998
 
 
999
738
                        Pattern p = Pattern.compile(
1000
739
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$" );
1001
740
                        for( int i = 0; i < params.length; i++ ) {
1002
741
                                Matcher m = p.matcher( params[ i ] );
1003
742
                                if( m.matches() )
1004
 
                                        ret.add( m.group( 2 ) );
 
743
                                        return m.group( 2 );
1005
744
                        }
1006
 
 
1007
 
                        return (String[]) ret.toArray( new String[ ret.size() ] );
 
745
                        return null;
1008
746
                }
1009
747
 
1010
 
                /**
1011
 
                 * Amongst the params, return any type values present. For v2.1 vCards,
1012
 
                 * those types are just parameters. For v3.0, they are prefixed with
1013
 
                 * "TYPE=". There may also be multiple type parameters.
1014
 
                 * @param params
1015
 
                 * @param a list of type values to look for
1016
 
                 * @return a set of present type values
1017
 
                 */
1018
748
                private Set< String > extractTypes( String[] params,
1019
749
                        List< String > valid_types )
1020
750
                {
1021
751
                        HashSet< String > types = new HashSet< String >();
1022
752
 
1023
753
                        // get 3.0-style TYPE= param
1024
 
                        String type_params[] = checkParams( params, "TYPE" );
1025
 
                        for( int a = 0; a < type_params.length; a++ )
1026
 
                        {
1027
 
                                // check for a comma-separated list of types (why? this isn't in
1028
 
                                // the specs!)
1029
 
                                String[] parts = type_params[ a ].split( "," );
 
754
                        String type_param;
 
755
                        if( ( type_param = checkParam( params, "TYPE" ) ) != null ) {
 
756
                                String[] parts = type_param.split( "," );
1030
757
                                for( int i = 0; i < parts.length; i++ )
1031
758
                                        if( valid_types.contains( parts[ i ] ) )
1032
759
                                                types.add( parts[ i ] );