/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

25
25
 
26
26
import java.io.BufferedReader;
27
27
import java.io.File;
 
28
import java.io.FileInputStream;
28
29
import java.io.FileNotFoundException;
29
30
import java.io.FileReader;
30
31
import java.io.FilenameFilter;
31
32
import java.io.IOException;
32
33
import java.io.UnsupportedEncodingException;
 
34
import java.nio.ByteBuffer;
33
35
import java.util.Arrays;
34
36
import java.util.HashSet;
 
37
import java.util.Iterator;
35
38
import java.util.List;
36
39
import java.util.Set;
37
40
import java.util.Vector;
38
41
import java.util.regex.Matcher;
39
42
import java.util.regex.Pattern;
 
43
import java.util.NoSuchElementException;
 
44
import java.lang.UnsupportedOperationException;
40
45
 
41
46
import android.content.SharedPreferences;
42
47
import android.provider.Contacts;
118
123
                {
119
124
                        // open file
120
125
                        BufferedReader reader = new BufferedReader(
121
 
                                        new FileReader( file ) );
 
126
                                new FileReader( file ) );
122
127
 
123
128
                        // read
124
129
                        String line;
127
132
                        {
128
133
                                if( !inVCard ) {
129
134
                                        // look for vcard beginning
130
 
                                        if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
 
135
                                        if( line.matches( "^BEGIN:VCARD" ) ) {
131
136
                                                inVCard = true;
132
137
                                                _vCardCount++;
133
138
                                        }
134
139
                                }
135
 
                                else if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
 
140
                                else if( line.matches( "^END:VCARD" ) )
136
141
                                        inVCard = false;
137
142
                        }
138
143
 
148
153
 
149
154
        private void importVCardFile( File file ) throws AbortImportException
150
155
        {
 
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
 
151
164
                try
152
165
                {
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() );
 
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() );
164
173
                }
165
174
                catch( FileNotFoundException e ) {
166
175
                        showError( getText( R.string.error_filenotfound ) +
171
180
                }
172
181
        }
173
182
 
174
 
        private void importVCardFileContent( String content, String fileName )
175
 
                        throws AbortImportException
 
183
        private void importVCardFileContent( byte[] content, String fileName )
 
184
                throws AbortImportException
176
185
        {
177
 
                // get lines and parse them
178
 
                String[] lines = content.split( "\n" );
 
186
                // go through lines
179
187
                VCard vCard = null;
180
 
                for( int i = 0; i < lines.length; i++ )
 
188
                ContentLineIterator cli = new ContentLineIterator( content );
 
189
                while( cli.hasNext() )
181
190
                {
182
 
                        String line = lines[ i ];
 
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
                        }
183
203
 
184
204
                        if( vCard == null ) {
185
205
                                // look for vcard beginning
186
 
                                if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
 
206
                                if( line.matches( "^BEGIN:VCARD" ) ) {
187
207
                                        setProgress( ++_progress );
188
208
                                        vCard = new VCard();
189
209
                                }
190
210
                        }
191
211
                        else {
192
212
                                // look for vcard content or ending
193
 
                                if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
 
213
                                if( line.matches( "^END:VCARD" ) )
194
214
                                {
195
215
                                        // store vcard and do away with it
196
216
                                        try {
200
220
                                        catch( VCard.ParseException e ) {
201
221
                                                skipContact();
202
222
                                                if( !showContinue(
203
 
                                                                getText( R.string.error_vcf_parse ).toString()
204
 
                                                                + fileName + "\n" + e.getMessage() ) )
 
223
                                                        getText( R.string.error_vcf_parse ).toString()
 
224
                                                        + fileName + "\n" + e.getMessage() ) )
 
225
                                                {
205
226
                                                        finish( ACTION_ABORT );
 
227
                                                }
206
228
                                        }
207
229
                                        catch( VCard.SkipContactException e ) {
208
230
                                                skipContact();
214
236
                                {
215
237
                                        // try giving the line to the vcard
216
238
                                        try {
217
 
                                                vCard.parseLine( line );
 
239
                                                vCard.parseLine( buffer, line,
 
240
                                                        cli.doesNextLineLookFolded() );
218
241
                                        }
219
242
                                        catch( VCard.ParseException e ) {
220
243
                                                skipContact();
221
244
                                                if( !showContinue(
222
 
                                                                getText( R.string.error_vcf_parse ).toString()
223
 
                                                                + fileName + "\n" + e.getMessage() ) )
 
245
                                                        getText( R.string.error_vcf_parse ).toString()
 
246
                                                        + fileName + "\n" + e.getMessage() ) )
 
247
                                                {
224
248
                                                        finish( ACTION_ABORT );
 
249
                                                }
225
250
 
226
251
                                                // although we're continuing, we still need to abort
227
252
                                                // this vCard. Further lines will be ignored until we
239
264
                }
240
265
        }
241
266
 
 
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
 
242
330
        private class VCard extends ContactData
243
331
        {
244
332
                private final static int NAMELEVEL_NONE = 0;
247
335
                private final static int NAMELEVEL_N = 3;
248
336
 
249
337
                private String _version = null;
250
 
                private Vector< String > _lines = null;
 
338
                private Vector< ByteBuffer > _buffers = null;
251
339
                private int _name_level = NAMELEVEL_NONE;
252
 
                private boolean _parser_in_multiline = false;
 
340
                private boolean _parser_in_encoded_multiline = false;
 
341
                private boolean _parser_in_folded_multiline = false;
253
342
                private String _parser_current_name_and_params = null;
254
343
                private String _parser_buffered_value_so_far = "";
255
344
 
256
345
                protected class UnencodeResult
257
346
                {
258
347
                        private boolean _another_line_required;
259
 
                        private byte[] _bytes;
260
 
                        private int _num_bytes;
 
348
                        private ByteBuffer _buffer;
261
349
 
262
 
                        public UnencodeResult( boolean another_line_required, byte[] bytes,
263
 
                                int num_bytes )
 
350
                        public UnencodeResult( boolean another_line_required,
 
351
                                ByteBuffer buffer )
264
352
                        {
265
353
                                _another_line_required = another_line_required;
266
 
                                _bytes = bytes;
267
 
                                _num_bytes = num_bytes;
 
354
                                _buffer = buffer;
268
355
                        }
269
356
 
270
357
                        public boolean isAnotherLineRequired()
272
359
                                return _another_line_required;
273
360
                        }
274
361
 
275
 
                        public byte[] getBytes()
276
 
                        {
277
 
                                return _bytes;
278
 
                        }
279
 
 
280
 
                        public int getNumBytes()
281
 
                        {
282
 
                                return _num_bytes;
 
362
                        public ByteBuffer getBuffer()
 
363
                        {
 
364
                                return _buffer;
283
365
                        }
284
366
                }
285
367
 
301
383
                @SuppressWarnings("serial")
302
384
                protected class SkipContactException extends Exception { }
303
385
 
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!
 
386
                private String extractCollonPartFromLine( ByteBuffer buffer,
 
387
                        String line, boolean former )
 
388
                {
 
389
                        String ret = null;
 
390
 
 
391
                        // get a US-ASCII version of the line for processing, unless we were
 
392
                        // supplied with one
 
393
                        if( line == null ) {
 
394
                                try {
 
395
                                        line = new String( buffer.array(), buffer.position(),
 
396
                                                buffer.limit() - buffer.position(), "US-ASCII" );
 
397
                                }
 
398
                                catch( UnsupportedEncodingException e ) {
 
399
                                        // we know US-ASCII is supported, so appease the compiler...
 
400
                                        line = "";
 
401
                                }
 
402
                        }
 
403
 
 
404
                        // split line into name and value parts and check to make sure we
 
405
                        // only got 2 parts and that the first part is not zero in length
 
406
                        String[] parts = line.split( ":", 2 );
 
407
                        if( parts.length == 2 && parts[ 0 ].length() > 0 )
 
408
                                ret = parts[ former? 0 : 1 ];
 
409
 
 
410
                        return ret;
 
411
                }
 
412
 
 
413
                private String extractNameAndParamsFromLine( ByteBuffer buffer,
 
414
                        String line )
 
415
                {
 
416
                        return extractCollonPartFromLine( buffer, line, true );
 
417
                }
 
418
 
 
419
                private String extractValueFromLine( ByteBuffer buffer, String line )
 
420
                {
 
421
                        return extractCollonPartFromLine( buffer, line, false );
 
422
                }
 
423
 
 
424
                public void parseLine( ByteBuffer buffer, String line,
 
425
                        boolean next_line_looks_folded )
 
426
                        throws ParseException, SkipContactException,
 
427
                        AbortImportException
 
428
                {
 
429
                        // do we have a version yet?
320
430
                        if( _version == null )
321
431
                        {
322
 
                                // is this a version?
323
 
                                if( props.length == 2 && props[ 0 ].equals( "VERSION" ) )
 
432
                                // tentatively get name and params from line
 
433
                                String name_and_params =
 
434
                                        extractNameAndParamsFromLine( buffer, line );
 
435
 
 
436
                                // is it a version line?
 
437
                                if( name_and_params != null &&
 
438
                                        name_and_params.equals( "VERSION" ) )
324
439
                                {
325
 
                                        // yes, check/store it
326
 
                                        if( !props[ 1 ].equals( "2.1" ) &&
327
 
                                                        !props[ 1 ].equals( "3.0" ) )
 
440
                                        // yes, get it!
 
441
                                        String value = extractValueFromLine( buffer, line );
 
442
                                        if( !value.equals( "2.1" ) && !value.equals( "3.0" ) )
328
443
                                                throw new ParseException( R.string.error_vcf_version );
329
 
                                        _version = props[ 1 ];
 
444
                                        _version = value;
330
445
 
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;
 
446
                                        // parse any buffers we've been accumulating while we waited
 
447
                                        // for a version
 
448
                                        if( _buffers != null )
 
449
                                                for( int i = 0; i < _buffers.size(); i++ )
 
450
                                                        parseLine( _buffers.get( i ), null,
 
451
                                                                i + 1 < _buffers.size() &&
 
452
                                                                _buffers.get( i + 1 ).hasRemaining() &&
 
453
                                                                _buffers.get( i + 1 ).get(
 
454
                                                                        _buffers.get( i + 1 ).position() ) == ' ' );
 
455
                                        _buffers = null;
336
456
                                }
337
457
                                else
338
458
                                {
339
 
                                        // no, so stash this line till we have a version
340
 
                                        if( _lines == null )
341
 
                                                _lines = new Vector< String >();
342
 
                                        _lines.add( line );
 
459
                                        // no, so stash this line till we get a version
 
460
                                        if( _buffers == null )
 
461
                                                _buffers = new Vector< ByteBuffer >();
 
462
                                        _buffers.add( buffer );
343
463
                                }
344
464
                        }
345
465
                        else
346
466
                        {
347
 
                                if( _parser_in_multiline )
 
467
                                // name and params and the position in the buffer where the
 
468
                                // "value" part of the line start
 
469
                                String name_and_params;
 
470
                                int pos;
 
471
 
 
472
                                if( _parser_in_encoded_multiline ||
 
473
                                        _parser_in_folded_multiline )
348
474
                                {
349
475
                                        // if we're currently in a multi-line value, use the stored
350
476
                                        // property name and parameters
351
 
                                        props = new String[ 2 ];
352
 
                                        props[ 0 ] = _parser_current_name_and_params;
353
 
                                        props[ 1 ] = line.trim();
 
477
                                        name_and_params = _parser_current_name_and_params;
 
478
 
 
479
                                        pos = buffer.position();
 
480
 
 
481
                                        // for folded multi-lines, skip the single space at the
 
482
                                        // start of the next line
 
483
                                        if( _parser_in_folded_multiline )
 
484
                                                pos++;
 
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
 
489
                                                while( pos < buffer.limit() && (
 
490
                                                        buffer.get( pos ) == ' ' ||
 
491
                                                        buffer.get( pos ) == '\t' ) )
 
492
                                                {
 
493
                                                        pos++;
 
494
                                                }
354
495
                                }
355
496
                                else
356
497
                                {
357
 
                                        // for normal lines, check the property name/value bits
358
 
                                        if( props.length < 2 || props[ 0 ].length() == 0 )
 
498
                                        // get name and params from line, and since we're not
 
499
                                        // parsing a subsequent line in a multi-line, this should
 
500
                                        // not fail, or it's an error
 
501
                                        name_and_params =
 
502
                                                extractNameAndParamsFromLine( buffer, line );
 
503
                                        if( name_and_params == null )
359
504
                                                throw new ParseException(
360
505
                                                        R.string.error_vcf_malformed );
361
506
 
362
 
                                        // ignore empty properties
363
 
                                        if( props[ 1 ].length() < 1 )
364
 
                                                return;
 
507
                                        // calculate how many chars to skip from beginning of line
 
508
                                        // so we skip the property "name:" part
 
509
                                        pos = buffer.position() + name_and_params.length() + 1;
365
510
 
366
511
                                        // reset the saved multi-line state
367
 
                                        _parser_current_name_and_params = props[ 0 ];
 
512
                                        _parser_current_name_and_params = name_and_params;
368
513
                                        _parser_buffered_value_so_far = "";
369
514
                                }
370
515
 
 
516
                                // get value from buffer, as raw bytes
 
517
                                ByteBuffer value;
 
518
                                value = ByteBuffer.wrap( buffer.array(), pos,
 
519
                                        buffer.limit() - pos );
 
520
 
371
521
                                // get parameter parts
372
 
                                String[] params = props[ 0 ].split( ";" );
373
 
                                for( int i = 0; i < params.length; i++ )
374
 
                                        params[ i ] = params[ i ].trim();
 
522
                                String[] name_param_parts = name_and_params.split( ";", -1 );
 
523
                                for( int i = 0; i < name_param_parts.length; i++ )
 
524
                                        name_param_parts[ i ] = name_param_parts[ i ].trim();
375
525
 
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" ) )
 
526
                                // parse encoding parameter
 
527
                                String encoding = checkParam( name_param_parts, "ENCODING" );
 
528
                                if( encoding != null ) encoding = encoding.toUpperCase();
 
529
                                if( encoding != null && !encoding.equals( "8BIT" ) &&
 
530
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
386
531
                                        //&& !encoding.equals( "BASE64" ) )
387
532
                                {
388
533
                                        throw new ParseException( R.string.error_vcf_encoding );
389
534
                                }
390
535
 
 
536
                                // parse charset parameter
 
537
                                String charset = checkParam( name_param_parts, "CHARSET" );
 
538
                                if( charset != null ) charset = charset.toUpperCase();
 
539
                                if( charset != null && !charset.equals( "US-ASCII" ) &&
 
540
                                        !charset.equals( "ASCII" ) &&
 
541
                                        !charset.equals( "UTF-8" ) )
 
542
                                {
 
543
                                        throw new ParseException( R.string.error_vcf_charset );
 
544
                                }
 
545
 
391
546
                                // do unencoding (or default to a fake unencoding result with
392
547
                                // the raw string)
393
 
                                UnencodeResult result;
 
548
                                UnencodeResult unencoding_result = null;
394
549
                                if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
395
 
                                        result = unencodeQuotedPrintable( props[ 1 ], charset );
 
550
                                        unencoding_result = unencodeQuotedPrintable( value );
396
551
//                              else if( encoding != null && encoding.equals( "BASE64" ) )
397
 
//                                      result = unencodeBase64( props[ 1 ], charset );
398
 
                                else
399
 
                                        result = new UnencodeResult( false, props[ 1 ].getBytes(),
400
 
                                                props[ 1 ].getBytes().length );
 
552
//                                      unencoding_result = unencodeBase64( props[ 1 ], charset );
 
553
                                if( unencoding_result != null ) {
 
554
                                        value = unencoding_result.getBuffer();
 
555
                                        _parser_in_encoded_multiline =
 
556
                                                unencoding_result.isAnotherLineRequired();
 
557
                                }
 
558
 
 
559
                                // convert 8-bit ASCII charset to US-ASCII
 
560
                                if( charset == null || charset.equals( "ASCII" ) ) {
 
561
                                        value = transcodeAsciiToUtf8( value );
 
562
                                        charset = "UTF-8";
 
563
                                }
401
564
 
402
565
                                // process charset
 
566
                                String string_value;
403
567
                                try {
404
 
                                        props[ 1 ] = new String( result.getBytes(), 0,
405
 
                                                result.getNumBytes(),
406
 
                                                charset == null? "UTF-8" : charset );
 
568
                                        string_value = new String( value.array(), value.position(),
 
569
                                                value.limit() - value.position(), charset );
407
570
                                } catch( UnsupportedEncodingException e ) {
408
571
                                        throw new ParseException( R.string.error_vcf_charset );
409
572
                                }
410
573
 
 
574
                                // now we know whether we're in an encoding multi-line,
 
575
                                // determine if we're in a v3 folded multi-line or not
 
576
                                _parser_in_folded_multiline = !_parser_in_encoded_multiline &&
 
577
                                        _version.equals( "3.0" ) && next_line_looks_folded;
 
578
 
411
579
                                // handle multi-line requests
412
 
                                _parser_in_multiline = result.isAnotherLineRequired();
413
 
                                if( _parser_in_multiline ) {
414
 
                                        _parser_buffered_value_so_far += props[ 1 ];
 
580
                                if( _parser_in_encoded_multiline ||
 
581
                                        _parser_in_folded_multiline )
 
582
                                {
 
583
                                        _parser_buffered_value_so_far += string_value;
415
584
                                        return;
416
585
                                }
417
586
 
418
587
                                // add on buffered multi-line content
419
 
                                String value = _parser_buffered_value_so_far + props[ 1 ];
 
588
                                String complete_value =
 
589
                                        _parser_buffered_value_so_far + string_value;
 
590
 
 
591
                                // ignore empty values
 
592
                                if( complete_value.length() < 1 ) return;
420
593
 
421
594
                                // parse some properties
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 );
 
595
                                if( name_param_parts[ 0 ].equals( "N" ) )
 
596
                                        parseN( name_param_parts, complete_value );
 
597
                                else if( name_param_parts[ 0 ].equals( "FN" ) )
 
598
                                        parseFN( name_param_parts, complete_value );
 
599
                                else if( name_param_parts[ 0 ].equals( "ORG" ) )
 
600
                                        parseORG( name_param_parts, complete_value );
 
601
                                else if( name_param_parts[ 0 ].equals( "TEL" ) )
 
602
                                        parseTEL( name_param_parts, complete_value );
 
603
                                else if( name_param_parts[ 0 ].equals( "EMAIL" ) )
 
604
                                        parseEMAIL( name_param_parts, complete_value );
432
605
                        }
433
606
                }
434
607
 
435
608
                private void parseN( String[] params, String value )
436
 
                                throws ParseException, SkipContactException,
437
 
                                AbortImportException
 
609
                        throws ParseException, SkipContactException,
 
610
                        AbortImportException
438
611
                {
439
612
                        // already got a better name?
440
613
                        if( _name_level >= NAMELEVEL_N ) return;
441
614
 
442
615
                        // get name parts
443
 
                        String[] nameparts = value.split( ";" );
444
 
                        for( int i = 0; i < nameparts.length; i++ )
445
 
                                nameparts[ i ] = nameparts[ i ].trim();
 
616
                        String[] name_parts = value.split( ";" );
 
617
                        for( int i = 0; i < name_parts.length; i++ )
 
618
                                name_parts[ i ] = name_parts[ i ].trim();
446
619
 
447
620
                        // build name
448
621
                        value = "";
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 ];
 
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 ];
453
626
 
454
627
                        // set name
455
628
                        setName( value );
462
635
                }
463
636
 
464
637
                private void parseFN( String[] params, String value )
465
 
                                throws ParseException, SkipContactException
 
638
                        throws ParseException, SkipContactException
466
639
                {
467
640
                        // already got a better name?
468
641
                        if( _name_level >= NAMELEVEL_FN ) return;
473
646
                }
474
647
 
475
648
                private void parseORG( String[] params, String value )
476
 
                                throws ParseException, SkipContactException
 
649
                        throws ParseException, SkipContactException
477
650
                {
478
651
                        // already got a better name?
479
652
                        if( _name_level >= NAMELEVEL_ORG ) return;
480
653
 
481
654
                        // get org parts
482
 
                        String[] orgparts = value.split( ";" );
483
 
                        for( int i = 0; i < orgparts.length; i++ )
484
 
                                orgparts[ i ] = orgparts[ i ].trim();
 
655
                        String[] org_parts = value.split( ";" );
 
656
                        for( int i = 0; i < org_parts.length; i++ )
 
657
                                org_parts[ i ] = org_parts[ i ].trim();
485
658
 
486
659
                        // build name
487
 
                        if( orgparts[ 0 ].length() == 0 && orgparts.length > 1 )
488
 
                                value = orgparts[ 1 ];
 
660
                        if( org_parts.length > 1 && org_parts[ 0 ].length() == 0 )
 
661
                                value = org_parts[ 1 ];
489
662
                        else
490
 
                                value = orgparts[ 0 ];
 
663
                                value = org_parts[ 0 ];
491
664
 
492
665
                        // set name
493
666
                        setName( value );
495
668
                }
496
669
 
497
670
                private void parseTEL( String[] params, String value )
498
 
                                throws ParseException
 
671
                        throws ParseException
499
672
                {
500
673
                        if( value.length() == 0 ) return;
501
674
 
502
675
                        Set< String > types = extractTypes( params, Arrays.asList(
503
 
                                        "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
504
 
                                        "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
 
676
                                "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
 
677
                                "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
505
678
 
506
679
                        // here's the logic...
507
680
                        boolean preferred = types.contains( "PREF" );
 
681
                        int type = PhonesColumns.TYPE_MOBILE;
508
682
                        if( types.contains( "VOICE" ) )
509
683
                                if( types.contains( "WORK" ) )
510
 
                                        addPhone( value, PhonesColumns.TYPE_WORK, preferred );
 
684
                                        type = PhonesColumns.TYPE_WORK;
511
685
                                else
512
 
                                        addPhone( value, PhonesColumns.TYPE_HOME, preferred );
 
686
                                        type = PhonesColumns.TYPE_HOME;
513
687
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
514
 
                                addPhone( value, PhonesColumns.TYPE_MOBILE, preferred );
 
688
                                type = PhonesColumns.TYPE_MOBILE;
515
689
                        if( types.contains( "FAX" ) )
516
690
                                if( types.contains( "HOME" ) )
517
 
                                        addPhone( value, PhonesColumns.TYPE_FAX_HOME, preferred );
 
691
                                        type = PhonesColumns.TYPE_FAX_HOME;
518
692
                                else
519
 
                                        addPhone( value, PhonesColumns.TYPE_FAX_WORK, preferred );
 
693
                                        type = PhonesColumns.TYPE_FAX_WORK;
520
694
                        if( types.contains( "PAGER" ) )
521
 
                                addPhone( value, PhonesColumns.TYPE_PAGER, preferred );
 
695
                                type = PhonesColumns.TYPE_PAGER;
 
696
 
 
697
                        // add phone number
 
698
                        addPhone( value, type, preferred );
522
699
                }
523
700
 
524
701
                public void parseEMAIL( String[] params, String value )
525
 
                                throws ParseException
 
702
                        throws ParseException
526
703
                {
527
704
                        if( value.length() == 0 ) return;
528
705
 
529
706
                        Set< String > types = extractTypes( params, Arrays.asList(
530
 
                                        "PREF", "WORK", "HOME", "INTERNET" ) );
 
707
                                "PREF", "WORK", "HOME", "INTERNET" ) );
531
708
 
532
709
                        // here's the logic...
533
710
                        boolean preferred = types.contains( "PREF" );
538
715
                }
539
716
 
540
717
                public void finaliseParsing()
541
 
                                throws ParseException, SkipContactException,
542
 
                                AbortImportException
 
718
                        throws ParseException, SkipContactException,
 
719
                        AbortImportException
543
720
                {
544
721
                        // missing version (and data is present)
545
 
                        if( _version == null && _lines != null )
 
722
                        if( _version == null && _buffers != null )
546
723
                                throw new ParseException( R.string.error_vcf_malformed );
547
724
 
548
725
                        //  missing name properties?
558
735
 
559
736
                private String checkParam( String[] params, String name )
560
737
                {
561
 
                        Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
 
738
                        Pattern p = Pattern.compile(
 
739
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$" );
562
740
                        for( int i = 0; i < params.length; i++ ) {
563
741
                                Matcher m = p.matcher( params[ i ] );
564
742
                                if( m.matches() )
565
 
                                        return m.group( 1 );
 
743
                                        return m.group( 2 );
566
744
                        }
567
745
                        return null;
568
746
                }
569
747
 
570
748
                private Set< String > extractTypes( String[] params,
571
 
                                List< String > validTypes )
 
749
                        List< String > valid_types )
572
750
                {
573
751
                        HashSet< String > types = new HashSet< String >();
574
752
 
575
753
                        // get 3.0-style TYPE= param
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 ] );
 
754
                        String type_param;
 
755
                        if( ( type_param = checkParam( params, "TYPE" ) ) != null ) {
 
756
                                String[] parts = type_param.split( "," );
 
757
                                for( int i = 0; i < parts.length; i++ )
 
758
                                        if( valid_types.contains( parts[ i ] ) )
 
759
                                                types.add( parts[ i ] );
582
760
                        }
583
761
 
584
762
                        // get 2.1-style type param
585
763
                        if( _version.equals( "2.1" ) ) {
586
764
                                for( int i = 1; i < params.length; i++ )
587
 
                                        if( validTypes.contains( params[ i ] ) )
 
765
                                        if( valid_types.contains( params[ i ] ) )
588
766
                                                types.add( params[ i ] );
589
767
                        }
590
768
 
591
769
                        return types;
592
770
                }
593
771
 
594
 
                private UnencodeResult unencodeQuotedPrintable( String str, String charset )
 
772
                private UnencodeResult unencodeQuotedPrintable( ByteBuffer in )
595
773
                {
596
774
                        boolean another = false;
597
775
 
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() ];
 
776
                        // unencode quoted-printable encoding, as per RFC1521 section 5.1
 
777
                        byte[] out = new byte[ in.limit() - in.position() ];
603
778
                        int j = 0;
604
 
                        for( int i = 0; i < str.length(); i++ )
 
779
                        for( int i = in.position(); i < in.limit(); i++ )
605
780
                        {
606
781
                                // get next char and process...
607
 
                                char ch = str.charAt( i );
608
 
                                if( ch == '=' && i < str.length() - 2 )
 
782
                                byte ch = in.array()[ i ];
 
783
                                if( ch == '=' && i < in.limit() - 2 )
609
784
                                {
610
785
                                        // we found a =XX format byte, add it
611
 
                                        bytes[ j ] = (byte)(
612
 
                                                        Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
613
 
                                                        Character.digit( str.charAt( i + 2 ), 16 ) );
 
786
                                        out[ j ] = (byte)(
 
787
                                                        Character.digit( in.array()[ i + 1 ], 16 ) * 16 +
 
788
                                                        Character.digit( in.array()[ i + 2 ], 16 ) );
614
789
                                        i += 2;
615
790
                                }
616
 
                                else if( ch == '=' && i == str.length() - 1 )
 
791
                                else if( ch == '=' && i == in.limit() - 1 )
617
792
                                {
618
793
                                        // we found a '=' at the end of a line signifying a multi-
619
794
                                        // line string, so we don't add it.
622
797
                                }
623
798
                                else
624
799
                                        // just a normal char...
625
 
                                        bytes[ j ] = (byte)ch;
 
800
                                        out[ j ] = (byte)ch;
626
801
                                j++;
627
802
                        }
628
803
 
629
 
                        return new UnencodeResult( another, bytes, j );
 
804
                        return new UnencodeResult( another, ByteBuffer.wrap( out, 0, j ) );
 
805
                }
 
806
 
 
807
                private ByteBuffer transcodeAsciiToUtf8( ByteBuffer in )
 
808
                {
 
809
                        // transcode
 
810
                        byte[] out = new byte[ ( in.limit() - in.position() ) * 2 ];
 
811
                        int j = 0;
 
812
                        for( int a = in.position(); a < in.limit(); a++ )
 
813
                        {
 
814
                                // if char is < 127, keep it as-is
 
815
                                if( in.array()[ a ] >= 0 )
 
816
                                        out[ j++ ] = in.array()[ a ];
 
817
 
 
818
                                // else, convert it to UTF-8
 
819
                                else {
 
820
                                        int b = 0xff & (int)in.array()[ a ];
 
821
                                        out[ j++ ] = (byte)( 0xc0 | ( b >> 6 ) );
 
822
                                        out[ j++ ] = (byte)( 0x80 | ( b & 0x3f ) );
 
823
                                }
 
824
                        }
 
825
 
 
826
                        return ByteBuffer.wrap( out, 0, j );
630
827
                }
631
828
        }
632
829
}