/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: 2010-10-30 09:55:31 UTC
  • Revision ID: edam@waxworlds.org-20101030095531-63vf9g84z5ol8qk9
- fixed bug in file chooser where "ok" button could remain disabled

Show diffs side-by-side

added added

removed removed

25
25
 
26
26
import java.io.BufferedReader;
27
27
import java.io.File;
28
 
import java.io.FileInputStream;
29
28
import java.io.FileNotFoundException;
30
29
import java.io.FileReader;
31
30
import java.io.FilenameFilter;
32
31
import java.io.IOException;
33
32
import java.io.UnsupportedEncodingException;
34
 
import java.nio.ByteBuffer;
35
 
import java.util.ArrayList;
36
33
import java.util.Arrays;
37
34
import java.util.HashSet;
38
 
import java.util.Iterator;
39
35
import java.util.List;
40
 
import java.util.NoSuchElementException;
41
36
import java.util.Set;
42
37
import java.util.Vector;
43
38
import java.util.regex.Matcher;
123
118
                {
124
119
                        // open file
125
120
                        BufferedReader reader = new BufferedReader(
126
 
                                new FileReader( file ) );
 
121
                                        new FileReader( file ) );
127
122
 
128
123
                        // read
129
124
                        String line;
132
127
                        {
133
128
                                if( !inVCard ) {
134
129
                                        // look for vcard beginning
135
 
                                        if( line.matches( "^BEGIN:VCARD" ) ) {
 
130
                                        if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
136
131
                                                inVCard = true;
137
132
                                                _vCardCount++;
138
133
                                        }
139
134
                                }
140
 
                                else if( line.matches( "^END:VCARD" ) )
 
135
                                else if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
141
136
                                        inVCard = false;
142
137
                        }
143
138
 
153
148
 
154
149
        private void importVCardFile( File file ) throws AbortImportException
155
150
        {
156
 
                // check file is good
157
 
                if( !file.exists() )
158
 
                        showError( getText( R.string.error_filenotfound ) +
159
 
                                file.getName() );
160
 
                if( file.length() == 0 )
161
 
                        showError( getText( R.string.error_fileisempty ) +
162
 
                                file.getName() );
163
 
 
164
151
                try
165
152
                {
166
 
                        // open/read file
167
 
                        FileInputStream istream = new FileInputStream( file );
168
 
                        byte[] content = new byte[ (int)file.length() ];
169
 
                        istream.read( content );
170
 
 
171
 
                        // import
172
 
                        importVCardFileContent( content, file.getName() );
 
153
                        // open file
 
154
                        BufferedReader reader = new BufferedReader(
 
155
                                        new FileReader( file ) );
 
156
 
 
157
                        // read
 
158
                        StringBuffer content = new StringBuffer();
 
159
                        String line;
 
160
                        while( ( line = reader.readLine() ) != null )
 
161
                                content.append( line ).append( "\n" );
 
162
 
 
163
                        importVCardFileContent( content.toString(), file.getName() );
173
164
                }
174
165
                catch( FileNotFoundException e ) {
175
166
                        showError( getText( R.string.error_filenotfound ) +
180
171
                }
181
172
        }
182
173
 
183
 
        private void importVCardFileContent( byte[] content, String fileName )
184
 
                throws AbortImportException
 
174
        private void importVCardFileContent( String content, String fileName )
 
175
                        throws AbortImportException
185
176
        {
186
 
                // go through lines
 
177
                // get lines and parse them
 
178
                String[] lines = content.split( "\n" );
187
179
                VCard vCard = null;
188
 
                ContentLineIterator cli = new ContentLineIterator( content );
189
 
                while( cli.hasNext() )
 
180
                for( int i = 0; i < lines.length; i++ )
190
181
                {
191
 
                        ByteBuffer buffer = cli.next();
192
 
 
193
 
                        // get a US-ASCII version of the line for processing
194
 
                        String line;
195
 
                        try {
196
 
                                line = new String( buffer.array(), buffer.position(),
197
 
                                        buffer.limit() - buffer.position(), "US-ASCII" );
198
 
                        }
199
 
                        catch( UnsupportedEncodingException e ) {
200
 
                                // we know US-ASCII is supported, so appease the compiler...
201
 
                                line = "";
202
 
                        }
 
182
                        String line = lines[ i ];
203
183
 
204
184
                        if( vCard == null ) {
205
185
                                // look for vcard beginning
206
 
                                if( line.matches( "^BEGIN:VCARD" ) ) {
 
186
                                if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
207
187
                                        setProgress( ++_progress );
208
188
                                        vCard = new VCard();
209
189
                                }
210
190
                        }
211
191
                        else {
212
192
                                // look for vcard content or ending
213
 
                                if( line.matches( "^END:VCARD" ) )
 
193
                                if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
214
194
                                {
215
195
                                        // store vcard and do away with it
216
196
                                        try {
220
200
                                        catch( VCard.ParseException e ) {
221
201
                                                skipContact();
222
202
                                                if( !showContinue(
223
 
                                                        getText( R.string.error_vcf_parse ).toString()
224
 
                                                        + fileName + "\n" + e.getMessage() ) )
225
 
                                                {
 
203
                                                                getText( R.string.error_vcf_parse ).toString()
 
204
                                                                + fileName + "\n" + e.getMessage() ) )
226
205
                                                        finish( ACTION_ABORT );
227
 
                                                }
228
206
                                        }
229
207
                                        catch( VCard.SkipContactException e ) {
230
208
                                                skipContact();
236
214
                                {
237
215
                                        // try giving the line to the vcard
238
216
                                        try {
239
 
                                                vCard.parseLine( buffer, line,
240
 
                                                        cli.doesNextLineLookFolded() );
 
217
                                                vCard.parseLine( line );
241
218
                                        }
242
219
                                        catch( VCard.ParseException e ) {
243
220
                                                skipContact();
244
221
                                                if( !showContinue(
245
 
                                                        getText( R.string.error_vcf_parse ).toString()
246
 
                                                        + fileName + "\n" + e.getMessage() ) )
247
 
                                                {
 
222
                                                                getText( R.string.error_vcf_parse ).toString()
 
223
                                                                + fileName + "\n" + e.getMessage() ) )
248
224
                                                        finish( ACTION_ABORT );
249
 
                                                }
250
225
 
251
226
                                                // although we're continuing, we still need to abort
252
227
                                                // this vCard. Further lines will be ignored until we
264
239
                }
265
240
        }
266
241
 
267
 
        class ContentLineIterator implements Iterator< ByteBuffer >
268
 
        {
269
 
                protected byte[] _content = null;
270
 
                protected int _pos = 0;
271
 
 
272
 
                public ContentLineIterator( byte[] content )
273
 
                {
274
 
                        _content = content;
275
 
                }
276
 
 
277
 
                @Override
278
 
                public boolean hasNext()
279
 
                {
280
 
                        return _pos < _content.length;
281
 
                }
282
 
 
283
 
                @Override
284
 
                public ByteBuffer next()
285
 
                {
286
 
                        int initial_pos = _pos;
287
 
 
288
 
                        // find newline
289
 
                        for( ; _pos < _content.length; _pos++ )
290
 
                                if( _content[ _pos ] == '\n' )
291
 
                                {
292
 
                                        // adjust for a \r preceding the \n
293
 
                                        int to = ( _pos > 0 && _content[ _pos - 1 ] == '\r' &&
294
 
                                                _pos > initial_pos )? _pos - 1 : _pos;
295
 
                                        _pos++;
296
 
                                        return ByteBuffer.wrap( _content, initial_pos,
297
 
                                                to - initial_pos );
298
 
                                }
299
 
 
300
 
                        // we didn't find one, but were there bytes left?
301
 
                        if( _pos != initial_pos ) {
302
 
                                int to = _pos;
303
 
                                _pos++;
304
 
                                return ByteBuffer.wrap( _content, initial_pos,
305
 
                                        to - initial_pos );
306
 
                        }
307
 
 
308
 
                        // no bytes left
309
 
                        throw new NoSuchElementException();
310
 
                }
311
 
 
312
 
                @Override
313
 
                public void remove()
314
 
                {
315
 
                        throw new UnsupportedOperationException();
316
 
                }
317
 
 
318
 
                /**
319
 
                 * Does the next line, if there is one, look like it should be folded
320
 
                 * onto the end of this one?
321
 
                 * @return
322
 
                 */
323
 
                public boolean doesNextLineLookFolded()
324
 
                {
325
 
                        return _pos > 0 && _pos < _content.length &&
326
 
                                _content[ _pos - 1 ] == '\n' && _content[ _pos ] == ' ';
327
 
                }
328
 
        }
329
 
 
330
242
        private class VCard extends ContactData
331
243
        {
332
244
                private final static int NAMELEVEL_NONE = 0;
334
246
                private final static int NAMELEVEL_FN = 2;
335
247
                private final static int NAMELEVEL_N = 3;
336
248
 
337
 
                private final static int MULTILINE_NONE = 0;
338
 
                private final static int MULTILINE_ENCODED = 1; // v2.1 quoted-printable
339
 
                private final static int MULTILINE_ESCAPED = 2; // v2.1 \\CRLF
340
 
                private final static int MULTILINE_FOLDED = 3;  // v3.0 folding
341
 
 
342
249
                private String _version = null;
343
 
                private Vector< ByteBuffer > _buffers = null;
 
250
                private Vector< String > _lines = null;
344
251
                private int _name_level = NAMELEVEL_NONE;
345
 
                private int _parser_multiline_state = MULTILINE_NONE;
 
252
                private boolean _parser_in_multiline = false;
346
253
                private String _parser_current_name_and_params = null;
347
254
                private String _parser_buffered_value_so_far = "";
348
255
 
349
256
                protected class UnencodeResult
350
257
                {
351
258
                        private boolean _another_line_required;
352
 
                        private ByteBuffer _buffer;
 
259
                        private byte[] _bytes;
 
260
                        private int _num_bytes;
353
261
 
354
 
                        public UnencodeResult( boolean another_line_required,
355
 
                                ByteBuffer buffer )
 
262
                        public UnencodeResult( boolean another_line_required, byte[] bytes,
 
263
                                int num_bytes )
356
264
                        {
357
265
                                _another_line_required = another_line_required;
358
 
                                _buffer = buffer;
 
266
                                _bytes = bytes;
 
267
                                _num_bytes = num_bytes;
359
268
                        }
360
269
 
361
270
                        public boolean isAnotherLineRequired()
363
272
                                return _another_line_required;
364
273
                        }
365
274
 
366
 
                        public ByteBuffer getBuffer()
367
 
                        {
368
 
                                return _buffer;
 
275
                        public byte[] getBytes()
 
276
                        {
 
277
                                return _bytes;
 
278
                        }
 
279
 
 
280
                        public int getNumBytes()
 
281
                        {
 
282
                                return _num_bytes;
369
283
                        }
370
284
                }
371
285
 
387
301
                @SuppressWarnings("serial")
388
302
                protected class SkipContactException extends Exception { }
389
303
 
390
 
                private String extractCollonPartFromLine( ByteBuffer buffer,
391
 
                        String line, boolean former )
392
 
                {
393
 
                        String ret = null;
394
 
 
395
 
                        // get a US-ASCII version of the line for processing, unless we were
396
 
                        // supplied with one
397
 
                        if( line == null ) {
398
 
                                try {
399
 
                                        line = new String( buffer.array(), buffer.position(),
400
 
                                                buffer.limit() - buffer.position(), "US-ASCII" );
401
 
                                }
402
 
                                catch( UnsupportedEncodingException e ) {
403
 
                                        // we know US-ASCII is supported, so appease the compiler...
404
 
                                        line = "";
405
 
                                }
406
 
                        }
407
 
 
408
 
                        // split line into name and value parts and check to make sure we
409
 
                        // only got 2 parts and that the first part is not zero in length
410
 
                        String[] parts = line.split( ":", 2 );
411
 
                        if( parts.length == 2 && parts[ 0 ].length() > 0 )
412
 
                                ret = parts[ former? 0 : 1 ];
413
 
 
414
 
                        return ret;
415
 
                }
416
 
 
417
 
                private String extractNameAndParamsFromLine( ByteBuffer buffer,
418
 
                        String line )
419
 
                {
420
 
                        return extractCollonPartFromLine( buffer, line, true );
421
 
                }
422
 
 
423
 
                private String extractValueFromLine( ByteBuffer buffer, String line )
424
 
                {
425
 
                        return extractCollonPartFromLine( buffer, line, false );
426
 
                }
427
 
 
428
 
                public void parseLine( ByteBuffer buffer, String line,
429
 
                        boolean next_line_looks_folded )
430
 
                        throws ParseException, SkipContactException,
431
 
                        AbortImportException
432
 
                {
433
 
                        // do we have a version yet?
 
304
                public void parseLine( String line )
 
305
                                throws ParseException, SkipContactException,
 
306
                                AbortImportException
 
307
                {
 
308
                        // ignore empty lines
 
309
                        if( line.trim() == "" ) return;
 
310
 
 
311
                        // split line into name and value parts (this may turn out to be
 
312
                        // unwanted if the line is a subsequent line in a multi-line
 
313
                        // value, but we have to do this now to check for and handle VCF
 
314
                        // versions first)
 
315
                        String[] props = line.split(  ":", 2 );
 
316
                        for( int i = 0; i < props.length; i++ )
 
317
                                props[ i ] = props[ i ].trim();
 
318
 
 
319
                        // if we haven't yet got a version, we won't be paring anything!
434
320
                        if( _version == null )
435
321
                        {
436
 
                                // tentatively get name and params from line
437
 
                                String name_and_params =
438
 
                                        extractNameAndParamsFromLine( buffer, line );
439
 
 
440
 
                                // is it a version line?
441
 
                                if( name_and_params != null &&
442
 
                                        name_and_params.equals( "VERSION" ) )
 
322
                                // is this a version?
 
323
                                if( props.length == 2 && props[ 0 ].equals( "VERSION" ) )
443
324
                                {
444
 
                                        // yes, get it!
445
 
                                        String value = extractValueFromLine( buffer, line );
446
 
                                        if( !value.equals( "2.1" ) && !value.equals( "3.0" ) )
 
325
                                        // yes, check/store it
 
326
                                        if( !props[ 1 ].equals( "2.1" ) &&
 
327
                                                        !props[ 1 ].equals( "3.0" ) )
447
328
                                                throw new ParseException( R.string.error_vcf_version );
448
 
                                        _version = value;
 
329
                                        _version = props[ 1 ];
449
330
 
450
 
                                        // parse any buffers we've been accumulating while we waited
451
 
                                        // for a version
452
 
                                        if( _buffers != null )
453
 
                                                for( int i = 0; i < _buffers.size(); i++ )
454
 
                                                        parseLine( _buffers.get( i ), null,
455
 
                                                                i + 1 < _buffers.size() &&
456
 
                                                                _buffers.get( i + 1 ).hasRemaining() &&
457
 
                                                                _buffers.get( i + 1 ).get(
458
 
                                                                        _buffers.get( i + 1 ).position() ) == ' ' );
459
 
                                        _buffers = null;
 
331
                                        // parse any other lines we've accumulated so far
 
332
                                        if( _lines != null )
 
333
                                                for( int i = 0; i < _lines.size(); i++ )
 
334
                                                        parseLine( _lines.get( i ) );
 
335
                                        _lines = null;
460
336
                                }
461
337
                                else
462
338
                                {
463
 
                                        // no, so stash this line till we get a version
464
 
                                        if( _buffers == null )
465
 
                                                _buffers = new Vector< ByteBuffer >();
466
 
                                        _buffers.add( buffer );
 
339
                                        // no, so stash this line till we have a version
 
340
                                        if( _lines == null )
 
341
                                                _lines = new Vector< String >();
 
342
                                        _lines.add( line );
467
343
                                }
468
344
                        }
469
345
                        else
470
346
                        {
471
 
                                // name and params and the position in the buffer where the
472
 
                                // "value" part of the line start
473
 
                                String name_and_params;
474
 
                                int pos;
475
 
 
476
 
                                if( _parser_multiline_state != MULTILINE_NONE )
 
347
                                if( _parser_in_multiline )
477
348
                                {
478
349
                                        // if we're currently in a multi-line value, use the stored
479
350
                                        // property name and parameters
480
 
                                        name_and_params = _parser_current_name_and_params;
481
 
 
482
 
                                        // skip some initial line characters, depending on the type
483
 
                                        // of multi-line we're handling
484
 
                                        pos = buffer.position();
485
 
                                        switch( _parser_multiline_state )
486
 
                                        {
487
 
                                        case MULTILINE_FOLDED:
488
 
                                                pos++;
489
 
                                                break;
490
 
                                        case MULTILINE_ENCODED:
491
 
                                                while( pos < buffer.limit() && (
492
 
                                                        buffer.get( pos ) == ' ' ||
493
 
                                                        buffer.get( pos ) == '\t' ) )
494
 
                                                {
495
 
                                                        pos++;
496
 
                                                }
497
 
                                                break;
498
 
                                        default:
499
 
                                                // do nothing
500
 
                                        }
501
 
 
502
 
                                        // take us out of multi-line so that we can re-detect that
503
 
                                        // this line is a multi-line or not
504
 
                                        _parser_multiline_state = MULTILINE_NONE;
 
351
                                        props = new String[ 2 ];
 
352
                                        props[ 0 ] = _parser_current_name_and_params;
 
353
                                        props[ 1 ] = line.trim();
505
354
                                }
506
355
                                else
507
356
                                {
508
 
                                        // get name and params from line, and since we're not
509
 
                                        // parsing a subsequent line in a multi-line, this should
510
 
                                        // not fail, or it's an error
511
 
                                        name_and_params =
512
 
                                                extractNameAndParamsFromLine( buffer, line );
513
 
                                        if( name_and_params == null )
 
357
                                        // for normal lines, check the property name/value bits
 
358
                                        if( props.length < 2 || props[ 0 ].length() == 0 )
514
359
                                                throw new ParseException(
515
360
                                                        R.string.error_vcf_malformed );
516
361
 
517
 
                                        // calculate how many chars to skip from beginning of line
518
 
                                        // so we skip the property "name:" part
519
 
                                        pos = buffer.position() + name_and_params.length() + 1;
 
362
                                        // ignore empty properties
 
363
                                        if( props[ 1 ].length() < 1 )
 
364
                                                return;
520
365
 
521
366
                                        // reset the saved multi-line state
522
 
                                        _parser_current_name_and_params = name_and_params;
 
367
                                        _parser_current_name_and_params = props[ 0 ];
523
368
                                        _parser_buffered_value_so_far = "";
524
369
                                }
525
370
 
526
 
                                // get value from buffer, as raw bytes
527
 
                                ByteBuffer value;
528
 
                                value = ByteBuffer.wrap( buffer.array(), pos,
529
 
                                        buffer.limit() - pos );
530
 
 
531
371
                                // get parameter parts
532
 
                                String[] name_param_parts = name_and_params.split( ";", -1 );
533
 
                                for( int i = 0; i < name_param_parts.length; i++ )
534
 
                                        name_param_parts[ i ] = name_param_parts[ i ].trim();
 
372
                                String[] params = props[ 0 ].split( ";" );
 
373
                                for( int i = 0; i < params.length; i++ )
 
374
                                        params[ i ] = params[ i ].trim();
535
375
 
536
 
                                // parse encoding parameter
537
 
                                String encoding = checkParam( name_param_parts, "ENCODING" );
538
 
                                if( encoding != null ) encoding = encoding.toUpperCase();
539
 
                                if( encoding != null && !encoding.equals( "8BIT" ) &&
540
 
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
 
376
                                // parse charset and encoding parameters
 
377
                                String charset, encoding;
 
378
                                if( ( charset = checkParam( params, "CHARSET" ) ) != null &&
 
379
                                        !charset.equals( "UTF-8" ) && !charset.equals( "UTF-16" ) )
 
380
                                {
 
381
                                        throw new ParseException( R.string.error_vcf_charset );
 
382
                                }
 
383
                                if( ( encoding = checkParam( params, "ENCODING" ) ) != null &&
 
384
                                        !encoding.equals( "QUOTED-PRINTABLE" ) &&
 
385
                                        !encoding.equals( "8BIT" ) )
541
386
                                        //&& !encoding.equals( "BASE64" ) )
542
387
                                {
543
388
                                        throw new ParseException( R.string.error_vcf_encoding );
544
389
                                }
545
390
 
546
 
                                // parse charset parameter
547
 
                                String charset = checkParam( name_param_parts, "CHARSET" );
548
 
                                if( charset != null ) charset = charset.toUpperCase();
549
 
                                if( charset != null && !charset.equals( "US-ASCII" ) &&
550
 
                                        !charset.equals( "ASCII" ) &&
551
 
                                        !charset.equals( "UTF-8" ) )
552
 
                                {
553
 
                                        throw new ParseException( R.string.error_vcf_charset );
554
 
                                }
555
 
 
556
391
                                // do unencoding (or default to a fake unencoding result with
557
392
                                // the raw string)
558
 
                                UnencodeResult unencoding_result = null;
 
393
                                UnencodeResult result;
559
394
                                if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
560
 
                                        unencoding_result = unencodeQuotedPrintable( value );
 
395
                                        result = unencodeQuotedPrintable( props[ 1 ], charset );
561
396
//                              else if( encoding != null && encoding.equals( "BASE64" ) )
562
 
//                                      unencoding_result = unencodeBase64( props[ 1 ], charset );
563
 
                                if( unencoding_result != null ) {
564
 
                                        value = unencoding_result.getBuffer();
565
 
                                        if( unencoding_result.isAnotherLineRequired() )
566
 
                                                _parser_multiline_state = MULTILINE_ENCODED;
567
 
                                }
568
 
 
569
 
                                // convert 8-bit ASCII charset to US-ASCII
570
 
                                if( charset == null || charset.equals( "ASCII" ) ) {
571
 
                                        value = transcodeAsciiToUtf8( value );
572
 
                                        charset = "UTF-8";
573
 
                                }
 
397
//                                      result = unencodeBase64( props[ 1 ], charset );
 
398
                                else
 
399
                                        result = new UnencodeResult( false, props[ 1 ].getBytes(),
 
400
                                                props[ 1 ].getBytes().length );
574
401
 
575
402
                                // process charset
576
 
                                String string_value;
577
403
                                try {
578
 
                                        string_value = new String( value.array(), value.position(),
579
 
                                                value.limit() - value.position(), charset );
 
404
                                        props[ 1 ] = new String( result.getBytes(), 0,
 
405
                                                result.getNumBytes(),
 
406
                                                charset == null? "UTF-8" : charset );
580
407
                                } catch( UnsupportedEncodingException e ) {
581
408
                                        throw new ParseException( R.string.error_vcf_charset );
582
409
                                }
583
410
 
584
 
                                // for some entries that have semicolon-separated value parts,
585
 
                                // check to see if the value ends in an escape character, which
586
 
                                // indicates that we have a multi-line value
587
 
                                if( ( name_param_parts[ 0 ].equals( "N" ) ||
588
 
                                        name_param_parts[ 0 ].equals( "ORG" ) ||
589
 
                                        name_param_parts[ 0 ].equals( "ADR" ) ) &&
590
 
                                        doesStringEndInAnEscapeChar( string_value ) )
591
 
                                {
592
 
                                        _parser_multiline_state = MULTILINE_ESCAPED;
593
 
                                        string_value = string_value.substring( 0,
594
 
                                                string_value.length() - 1 );
595
 
                                }
596
 
 
597
 
                                // now we know whether we're in an encoding multi-line,
598
 
                                // determine if we're in a v3 folded multi-line or not
599
 
                                if( _parser_multiline_state == MULTILINE_NONE &&
600
 
                                        _version.equals( "3.0" ) && next_line_looks_folded )
601
 
                                {
602
 
                                        _parser_multiline_state = MULTILINE_FOLDED;
603
 
                                }
604
 
 
605
 
                                // handle multi-lines by buffering them and parsing them when we
606
 
                                // are processing the last line in a multi-line sequence
607
 
                                if( _parser_multiline_state != MULTILINE_NONE ) {
608
 
                                        _parser_buffered_value_so_far += string_value;
 
411
                                // handle multi-line requests
 
412
                                _parser_in_multiline = result.isAnotherLineRequired();
 
413
                                if( _parser_in_multiline ) {
 
414
                                        _parser_buffered_value_so_far += props[ 1 ];
609
415
                                        return;
610
416
                                }
611
 
                                String complete_value =
612
 
                                        ( _parser_buffered_value_so_far + string_value ).trim();
613
417
 
614
 
                                // ignore empty values
615
 
                                if( complete_value.length() < 1 ) return;
 
418
                                // add on buffered multi-line content
 
419
                                String value = _parser_buffered_value_so_far + props[ 1 ];
616
420
 
617
421
                                // parse some properties
618
 
                                if( name_param_parts[ 0 ].equals( "N" ) )
619
 
                                        parseN( name_param_parts, complete_value );
620
 
                                else if( name_param_parts[ 0 ].equals( "FN" ) )
621
 
                                        parseFN( name_param_parts, complete_value );
622
 
                                else if( name_param_parts[ 0 ].equals( "ORG" ) )
623
 
                                        parseORG( name_param_parts, complete_value );
624
 
                                else if( name_param_parts[ 0 ].equals( "TEL" ) )
625
 
                                        parseTEL( name_param_parts, complete_value );
626
 
                                else if( name_param_parts[ 0 ].equals( "EMAIL" ) )
627
 
                                        parseEMAIL( name_param_parts, complete_value );
628
 
                                else if( name_param_parts[ 0 ].equals( "ADR" ) )
629
 
                                        parseADR( name_param_parts, complete_value );
630
 
                        }
631
 
                }
632
 
 
633
 
                private boolean doesStringEndInAnEscapeChar( String string )
634
 
                {
635
 
                        // count the number of backslashes at the end of the string
636
 
                        int count = 0;
637
 
                        for( int a = string.length() - 1; a >= 0; a-- )
638
 
                                if( string.charAt( a ) == '\\' )
639
 
                                        count++;
640
 
                                else
641
 
                                        break;
642
 
 
643
 
                        // if there are an even number of backslashes then the final one
644
 
                        // doesn't count
645
 
                        return ( count & 1 ) == 1;
646
 
                }
647
 
 
648
 
                private String[] splitValueBySemicolon( String value )
649
 
                {
650
 
                        // split string in to parts by semicolon
651
 
                        ArrayList< String > parts = new ArrayList< String >(
652
 
                                Arrays.asList( value.split(  ";" ) ) );
653
 
 
654
 
                        // go through parts
655
 
                        for( int a = 0; a < parts.size(); a++ )
656
 
                        {
657
 
                                String str = parts.get( a );
658
 
 
659
 
                                // look for parts that end in an escape character, but ignore
660
 
                                // the final part. We've already detected escape chars at the
661
 
                                // end of the final part in parseLine() and handled multi-lines
662
 
                                // accordingly.
663
 
                                if( a < parts.size() - 1 &&
664
 
                                        doesStringEndInAnEscapeChar( str ) )
665
 
                                {
666
 
                                        // join the next part to this part and remove the next part
667
 
                                        parts.set( a, str.substring( 0, str.length() - 1 ) +
668
 
                                                ';' + parts.get( a + 1 ) );
669
 
                                        parts.remove( a + 1 );
670
 
 
671
 
                                        // re-visit this part
672
 
                                        a--;
673
 
                                        continue;
674
 
                                }
675
 
 
676
 
                                // trim and replace string
677
 
                                str = str.trim();
678
 
                                parts.set( a, str );
679
 
                        }
680
 
 
681
 
                        String[] ret = new String[ parts.size() ];
682
 
                        return parts.toArray( ret );
 
422
                                if( params[ 0 ].equals( "N" ) )
 
423
                                        parseN( params, value );
 
424
                                else if( params[ 0 ].equals( "FN" ) )
 
425
                                        parseFN( params, value );
 
426
                                else if( params[ 0 ].equals( "ORG" ) )
 
427
                                        parseORG( params, value );
 
428
                                else if( params[ 0 ].equals( "TEL" ) )
 
429
                                        parseTEL( params, value );
 
430
                                else if( params[ 0 ].equals( "EMAIL" ) )
 
431
                                        parseEMAIL( params, value );
 
432
                        }
683
433
                }
684
434
 
685
435
                private void parseN( String[] params, String value )
686
 
                        throws ParseException, SkipContactException,
687
 
                        AbortImportException
 
436
                                throws ParseException, SkipContactException,
 
437
                                AbortImportException
688
438
                {
689
439
                        // already got a better name?
690
440
                        if( _name_level >= NAMELEVEL_N ) return;
691
441
 
692
442
                        // get name parts
693
 
                        String[] name_parts = splitValueBySemicolon( value );
 
443
                        String[] nameparts = value.split( ";" );
 
444
                        for( int i = 0; i < nameparts.length; i++ )
 
445
                                nameparts[ i ] = nameparts[ i ].trim();
694
446
 
695
447
                        // build name
696
448
                        value = "";
697
 
                        if( name_parts.length > 1 && name_parts[ 1 ].length() > 0 )
698
 
                                value += name_parts[ 1 ];
699
 
                        if( name_parts.length > 0 && name_parts[ 0 ].length() > 0 )
700
 
                                value += ( value.length() == 0? "" : " " ) + name_parts[ 0 ];
 
449
                        if( nameparts.length > 1 && nameparts[ 1 ].length() > 0 )
 
450
                                value += nameparts[ 1 ];
 
451
                        if( nameparts[ 0 ].length() > 0 )
 
452
                                value += ( value.length() == 0? "" : " " ) + nameparts[ 0 ];
701
453
 
702
454
                        // set name
703
455
                        setName( value );
710
462
                }
711
463
 
712
464
                private void parseFN( String[] params, String value )
713
 
                        throws ParseException, SkipContactException
 
465
                                throws ParseException, SkipContactException
714
466
                {
715
467
                        // already got a better name?
716
468
                        if( _name_level >= NAMELEVEL_FN ) return;
721
473
                }
722
474
 
723
475
                private void parseORG( String[] params, String value )
724
 
                        throws ParseException, SkipContactException
 
476
                                throws ParseException, SkipContactException
725
477
                {
726
478
                        // already got a better name?
727
479
                        if( _name_level >= NAMELEVEL_ORG ) return;
728
480
 
729
481
                        // get org parts
730
 
                        String[] org_parts = splitValueBySemicolon( value );
 
482
                        String[] orgparts = value.split( ";" );
 
483
                        for( int i = 0; i < orgparts.length; i++ )
 
484
                                orgparts[ i ] = orgparts[ i ].trim();
731
485
 
732
486
                        // build name
733
 
                        if( org_parts.length > 1 && org_parts[ 0 ].length() == 0 )
734
 
                                value = org_parts[ 1 ];
735
 
                        else if( org_parts.length > 1 && org_parts[ 1 ].length() > 0 )
736
 
                                value = org_parts[ 0 ] + ", " + org_parts[ 1 ];
 
487
                        if( orgparts[ 0 ].length() == 0 && orgparts.length > 1 )
 
488
                                value = orgparts[ 1 ];
737
489
                        else
738
 
                                value = org_parts[ 0 ];
 
490
                                value = orgparts[ 0 ];
739
491
 
740
492
                        // set name
741
493
                        setName( value );
743
495
                }
744
496
 
745
497
                private void parseTEL( String[] params, String value )
746
 
                        throws ParseException
 
498
                                throws ParseException
747
499
                {
748
500
                        if( value.length() == 0 ) return;
749
501
 
750
502
                        Set< String > types = extractTypes( params, Arrays.asList(
751
 
                                "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
752
 
                                "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
 
503
                                        "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
 
504
                                        "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
753
505
 
754
506
                        // here's the logic...
755
507
                        boolean preferred = types.contains( "PREF" );
756
 
                        int type = PhonesColumns.TYPE_MOBILE;
757
508
                        if( types.contains( "VOICE" ) )
758
509
                                if( types.contains( "WORK" ) )
759
 
                                        type = PhonesColumns.TYPE_WORK;
 
510
                                        addPhone( value, PhonesColumns.TYPE_WORK, preferred );
760
511
                                else
761
 
                                        type = PhonesColumns.TYPE_HOME;
 
512
                                        addPhone( value, PhonesColumns.TYPE_HOME, preferred );
762
513
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
763
 
                                type = PhonesColumns.TYPE_MOBILE;
 
514
                                addPhone( value, PhonesColumns.TYPE_MOBILE, preferred );
764
515
                        if( types.contains( "FAX" ) )
765
516
                                if( types.contains( "HOME" ) )
766
 
                                        type = PhonesColumns.TYPE_FAX_HOME;
 
517
                                        addPhone( value, PhonesColumns.TYPE_FAX_HOME, preferred );
767
518
                                else
768
 
                                        type = PhonesColumns.TYPE_FAX_WORK;
 
519
                                        addPhone( value, PhonesColumns.TYPE_FAX_WORK, preferred );
769
520
                        if( types.contains( "PAGER" ) )
770
 
                                type = PhonesColumns.TYPE_PAGER;
771
 
 
772
 
                        // add phone number
773
 
                        addPhone( value, type, preferred );
 
521
                                addPhone( value, PhonesColumns.TYPE_PAGER, preferred );
774
522
                }
775
523
 
776
524
                public void parseEMAIL( String[] params, String value )
777
 
                        throws ParseException
 
525
                                throws ParseException
778
526
                {
779
527
                        if( value.length() == 0 ) return;
780
528
 
781
529
                        Set< String > types = extractTypes( params, Arrays.asList(
782
 
                                "PREF", "WORK", "HOME", "INTERNET" ) );
 
530
                                        "PREF", "WORK", "HOME", "INTERNET" ) );
783
531
 
784
 
                        // add email address
 
532
                        // here's the logic...
785
533
                        boolean preferred = types.contains( "PREF" );
786
534
                        if( types.contains( "WORK" ) )
787
535
                                addEmail( value, Contacts.ContactMethods.TYPE_WORK, preferred );
789
537
                                addEmail( value, Contacts.ContactMethods.TYPE_HOME, preferred );
790
538
                }
791
539
 
792
 
                private void parseADR( String[] params, String value )
793
 
                        throws ParseException, SkipContactException
794
 
                {
795
 
                        // get address parts
796
 
                        String[] adr_parts = splitValueBySemicolon( value );
797
 
 
798
 
                        // build address
799
 
                        value = "";
800
 
                        for( int a = 0; a < adr_parts.length; a++ ) {
801
 
                                if( value.length() > 0 ) value += "\n";
802
 
                                value += adr_parts[ a ].trim();
803
 
                        }
804
 
 
805
 
                        Set< String > types = extractTypes( params, Arrays.asList(
806
 
                                "PREF", "WORK", "HOME", "INTERNET" ) );
807
 
 
808
 
                        // add address
809
 
                        if( types.contains( "WORK" ) )
810
 
                                addAddress( value, Contacts.ContactMethods.TYPE_WORK );
811
 
                        else
812
 
                                addAddress( value, Contacts.ContactMethods.TYPE_HOME);
813
 
                }
814
 
 
815
540
                public void finaliseParsing()
816
 
                        throws ParseException, SkipContactException,
817
 
                        AbortImportException
 
541
                                throws ParseException, SkipContactException,
 
542
                                AbortImportException
818
543
                {
819
544
                        // missing version (and data is present)
820
 
                        if( _version == null && _buffers != null )
 
545
                        if( _version == null && _lines != null )
821
546
                                throw new ParseException( R.string.error_vcf_malformed );
822
547
 
823
548
                        //  missing name properties?
833
558
 
834
559
                private String checkParam( String[] params, String name )
835
560
                {
836
 
                        Pattern p = Pattern.compile(
837
 
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$" );
 
561
                        Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
838
562
                        for( int i = 0; i < params.length; i++ ) {
839
563
                                Matcher m = p.matcher( params[ i ] );
840
564
                                if( m.matches() )
841
 
                                        return m.group( 2 );
 
565
                                        return m.group( 1 );
842
566
                        }
843
567
                        return null;
844
568
                }
845
569
 
846
570
                private Set< String > extractTypes( String[] params,
847
 
                        List< String > valid_types )
 
571
                                List< String > validTypes )
848
572
                {
849
573
                        HashSet< String > types = new HashSet< String >();
850
574
 
851
575
                        // get 3.0-style TYPE= param
852
 
                        String type_param;
853
 
                        if( ( type_param = checkParam( params, "TYPE" ) ) != null ) {
854
 
                                String[] parts = type_param.split( "," );
855
 
                                for( int i = 0; i < parts.length; i++ )
856
 
                                        if( valid_types.contains( parts[ i ] ) )
857
 
                                                types.add( parts[ i ] );
 
576
                        String typeParam;
 
577
                        if( ( typeParam = checkParam( params, "TYPE" ) ) != null ) {
 
578
                                String[] bits = typeParam.split( "," );
 
579
                                for( int i = 0; i < bits.length; i++ )
 
580
                                        if( validTypes.contains( bits[ i ] ) )
 
581
                                                types.add( bits[ i ] );
858
582
                        }
859
583
 
860
584
                        // get 2.1-style type param
861
585
                        if( _version.equals( "2.1" ) ) {
862
586
                                for( int i = 1; i < params.length; i++ )
863
 
                                        if( valid_types.contains( params[ i ] ) )
 
587
                                        if( validTypes.contains( params[ i ] ) )
864
588
                                                types.add( params[ i ] );
865
589
                        }
866
590
 
867
591
                        return types;
868
592
                }
869
593
 
870
 
                private UnencodeResult unencodeQuotedPrintable( ByteBuffer in )
 
594
                private UnencodeResult unencodeQuotedPrintable( String str, String charset )
871
595
                {
872
596
                        boolean another = false;
873
597
 
874
 
                        // unencode quoted-printable encoding, as per RFC1521 section 5.1
875
 
                        byte[] out = new byte[ in.limit() - in.position() ];
 
598
                        // default encoding scheme
 
599
                        if( charset == null ) charset = "UTF-8";
 
600
 
 
601
                        // unencode quoted-pritable encoding, as per RFC1521 section 5.1
 
602
                        byte[] bytes = new byte[ str.length() ];
876
603
                        int j = 0;
877
 
                        for( int i = in.position(); i < in.limit(); i++ )
 
604
                        for( int i = 0; i < str.length(); i++ )
878
605
                        {
879
606
                                // get next char and process...
880
 
                                byte ch = in.array()[ i ];
881
 
                                if( ch == '=' && i < in.limit() - 2 )
 
607
                                char ch = str.charAt( i );
 
608
                                if( ch == '=' && i < str.length() - 2 )
882
609
                                {
883
610
                                        // we found a =XX format byte, add it
884
 
                                        out[ j ] = (byte)(
885
 
                                                        Character.digit( in.array()[ i + 1 ], 16 ) * 16 +
886
 
                                                        Character.digit( in.array()[ i + 2 ], 16 ) );
 
611
                                        bytes[ j ] = (byte)(
 
612
                                                        Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
 
613
                                                        Character.digit( str.charAt( i + 2 ), 16 ) );
887
614
                                        i += 2;
888
615
                                }
889
 
                                else if( ch == '=' && i == in.limit() - 1 )
 
616
                                else if( ch == '=' && i == str.length() - 1 )
890
617
                                {
891
618
                                        // we found a '=' at the end of a line signifying a multi-
892
619
                                        // line string, so we don't add it.
895
622
                                }
896
623
                                else
897
624
                                        // just a normal char...
898
 
                                        out[ j ] = (byte)ch;
 
625
                                        bytes[ j ] = (byte)ch;
899
626
                                j++;
900
627
                        }
901
628
 
902
 
                        return new UnencodeResult( another, ByteBuffer.wrap( out, 0, j ) );
903
 
                }
904
 
 
905
 
                private ByteBuffer transcodeAsciiToUtf8( ByteBuffer in )
906
 
                {
907
 
                        // transcode
908
 
                        byte[] out = new byte[ ( in.limit() - in.position() ) * 2 ];
909
 
                        int j = 0;
910
 
                        for( int a = in.position(); a < in.limit(); a++ )
911
 
                        {
912
 
                                // if char is < 127, keep it as-is
913
 
                                if( in.array()[ a ] >= 0 )
914
 
                                        out[ j++ ] = in.array()[ a ];
915
 
 
916
 
                                // else, convert it to UTF-8
917
 
                                else {
918
 
                                        int b = 0xff & (int)in.array()[ a ];
919
 
                                        out[ j++ ] = (byte)( 0xc0 | ( b >> 6 ) );
920
 
                                        out[ j++ ] = (byte)( 0x80 | ( b & 0x3f ) );
921
 
                                }
922
 
                        }
923
 
 
924
 
                        return ByteBuffer.wrap( out, 0, j );
 
629
                        return new UnencodeResult( another, bytes, j );
925
630
                }
926
631
        }
927
632
}