/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

21
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
22
 */
23
23
 
24
 
package org.waxworlds.importcontacts;
 
24
package org.waxworlds.edam.importcontacts;
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;
40
 
 
41
 
import org.waxworlds.importcontacts.Importer.AbortImportException;
 
43
import java.util.NoSuchElementException;
 
44
import java.lang.UnsupportedOperationException;
42
45
 
43
46
import android.content.SharedPreferences;
44
47
import android.provider.Contacts;
67
70
                try
68
71
                {
69
72
                        // open directory
70
 
                        String location = prefs.getString( "location", "" );
71
 
                        File dir = new File( location );
72
 
                        if( !dir.exists() || !dir.isDirectory() )
 
73
                        String path = "/sdcard" + prefs.getString( "location", "/" );
 
74
                        File file = new File( path );
 
75
                        if( !file.exists() )
73
76
                                showError( R.string.error_locationnotfound );
74
77
 
75
 
                        // get files
76
 
                        class VCardFilter implements FilenameFilter {
77
 
                            public boolean accept( File dir, String name ) {
78
 
                                return name.toLowerCase().endsWith( ".vcf" );
79
 
                            }
80
 
                        }
81
 
                        files = dir.listFiles( new VCardFilter() );
 
78
                        // directory, or file?
 
79
                        if( file.isDirectory() )
 
80
                        {
 
81
                                // get files
 
82
                                class VCardFilter implements FilenameFilter {
 
83
                                        public boolean accept( File dir, String name ) {
 
84
                                                return name.toLowerCase().endsWith( ".vcf" );
 
85
                                        }
 
86
                                }
 
87
                                files = file.listFiles( new VCardFilter() );
 
88
                        }
 
89
                        else
 
90
                        {
 
91
                                // use just this file
 
92
                                files = new File[ 1 ];
 
93
                                files[ 0 ] = file;
 
94
                        }
82
95
                }
83
96
                catch( SecurityException e ) {
84
97
                        showError( R.string.error_locationpermissions );
110
123
                {
111
124
                        // open file
112
125
                        BufferedReader reader = new BufferedReader(
113
 
                                        new FileReader( file ) );
 
126
                                new FileReader( file ) );
114
127
 
115
128
                        // read
116
129
                        String line;
119
132
                        {
120
133
                                if( !inVCard ) {
121
134
                                        // look for vcard beginning
122
 
                                        if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
 
135
                                        if( line.matches( "^BEGIN:VCARD" ) ) {
123
136
                                                inVCard = true;
124
137
                                                _vCardCount++;
125
138
                                        }
126
139
                                }
127
 
                                else if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
 
140
                                else if( line.matches( "^END:VCARD" ) )
128
141
                                        inVCard = false;
129
142
                        }
130
143
 
131
144
                }
132
145
                catch( FileNotFoundException e ) {
133
 
                        showError( getText( R.string.error_filenotfound ) + file.getName() );
 
146
                        showError( getText( R.string.error_filenotfound ) +
 
147
                                file.getName() );
134
148
                }
135
149
                catch( IOException e ) {
136
150
                        showError( getText( R.string.error_ioerror ) + file.getName() );
139
153
 
140
154
        private void importVCardFile( File file ) throws AbortImportException
141
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
 
142
164
                try
143
165
                {
144
 
                        // open file
145
 
                        BufferedReader reader = new BufferedReader(
146
 
                                        new FileReader( file ) );
147
 
 
148
 
                        // read
149
 
                        StringBuffer content = new StringBuffer();
150
 
                        String line;
151
 
                        while( ( line = reader.readLine() ) != null )
152
 
                                content.append( line ).append( "\n" );
153
 
 
154
 
                        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() );
155
173
                }
156
174
                catch( FileNotFoundException e ) {
157
 
                        showError( getText( R.string.error_filenotfound ) + file.getName() );
 
175
                        showError( getText( R.string.error_filenotfound ) +
 
176
                                file.getName() );
158
177
                }
159
178
                catch( IOException e ) {
160
179
                        showError( getText( R.string.error_ioerror ) + file.getName() );
161
180
                }
162
181
        }
163
182
 
164
 
        private void importVCardFileContent( String content, String fileName )
165
 
                        throws AbortImportException
 
183
        private void importVCardFileContent( byte[] content, String fileName )
 
184
                throws AbortImportException
166
185
        {
167
 
                // unfold RFC2425 section 5.8.1 folded lines, except that we must also
168
 
                // handle embedded Quoted-Printable encodings that have a trailing '='.
169
 
                // So we remove these first before doing RFC2425 unfolding.
170
 
                content = content.replaceAll( "=\n[ \\t]", "" )
171
 
                                .replaceAll( "\n[ \\t]", "" );
172
 
 
173
 
                // get lines and parse them
174
 
                String[] lines = content.split( "\n" );
 
186
                // go through lines
175
187
                VCard vCard = null;
176
 
                for( int i = 0; i < lines.length; i++ )
 
188
                ContentLineIterator cli = new ContentLineIterator( content );
 
189
                while( cli.hasNext() )
177
190
                {
178
 
                        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
                        }
179
203
 
180
204
                        if( vCard == null ) {
181
205
                                // look for vcard beginning
182
 
                                if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
 
206
                                if( line.matches( "^BEGIN:VCARD" ) ) {
183
207
                                        setProgress( ++_progress );
184
208
                                        vCard = new VCard();
185
209
                                }
186
210
                        }
187
211
                        else {
188
212
                                // look for vcard content or ending
189
 
                                if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
 
213
                                if( line.matches( "^END:VCARD" ) )
190
214
                                {
191
215
                                        // store vcard and do away with it
192
216
                                        try {
196
220
                                        catch( VCard.ParseException e ) {
197
221
                                                skipContact();
198
222
                                                if( !showContinue(
199
 
                                                                getText( R.string.error_vcf_parse ).toString()
200
 
                                                                + fileName + "\n" + e.getMessage() ) )
 
223
                                                        getText( R.string.error_vcf_parse ).toString()
 
224
                                                        + fileName + "\n" + e.getMessage() ) )
 
225
                                                {
201
226
                                                        finish( ACTION_ABORT );
 
227
                                                }
202
228
                                        }
203
229
                                        catch( VCard.SkipContactException e ) {
204
230
                                                skipContact();
210
236
                                {
211
237
                                        // try giving the line to the vcard
212
238
                                        try {
213
 
                                                vCard.parseLine( line );
 
239
                                                vCard.parseLine( buffer, line,
 
240
                                                        cli.doesNextLineLookFolded() );
214
241
                                        }
215
242
                                        catch( VCard.ParseException e ) {
216
243
                                                skipContact();
217
244
                                                if( !showContinue(
218
 
                                                                getText( R.string.error_vcf_parse ).toString()
219
 
                                                                + fileName + "\n" + e.getMessage() ) )
 
245
                                                        getText( R.string.error_vcf_parse ).toString()
 
246
                                                        + fileName + "\n" + e.getMessage() ) )
 
247
                                                {
220
248
                                                        finish( ACTION_ABORT );
 
249
                                                }
221
250
 
222
251
                                                // although we're continuing, we still need to abort
223
252
                                                // this vCard. Further lines will be ignored until we
235
264
                }
236
265
        }
237
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
 
238
330
        private class VCard extends ContactData
239
331
        {
240
332
                private final static int NAMELEVEL_NONE = 0;
243
335
                private final static int NAMELEVEL_N = 3;
244
336
 
245
337
                private String _version = null;
246
 
                private Vector< String > _lines = null;
247
 
                private int _nameLevel = NAMELEVEL_NONE;
248
 
 
 
338
                private Vector< ByteBuffer > _buffers = null;
 
339
                private int _name_level = NAMELEVEL_NONE;
 
340
                private boolean _parser_in_encoded_multiline = false;
 
341
                private boolean _parser_in_folded_multiline = false;
 
342
                private String _parser_current_name_and_params = null;
 
343
                private String _parser_buffered_value_so_far = "";
 
344
 
 
345
                protected class UnencodeResult
 
346
                {
 
347
                        private boolean _another_line_required;
 
348
                        private ByteBuffer _buffer;
 
349
 
 
350
                        public UnencodeResult( boolean another_line_required,
 
351
                                ByteBuffer buffer )
 
352
                        {
 
353
                                _another_line_required = another_line_required;
 
354
                                _buffer = buffer;
 
355
                        }
 
356
 
 
357
                        public boolean isAnotherLineRequired()
 
358
                        {
 
359
                                return _another_line_required;
 
360
                        }
 
361
 
 
362
                        public ByteBuffer getBuffer()
 
363
                        {
 
364
                                return _buffer;
 
365
                        }
 
366
                }
 
367
 
 
368
                @SuppressWarnings("serial")
249
369
                protected class ParseException extends Exception
250
370
                {
 
371
                        @SuppressWarnings("unused")
251
372
                        public ParseException( String error )
252
373
                        {
253
374
                                super( error );
259
380
                        }
260
381
                }
261
382
 
 
383
                @SuppressWarnings("serial")
262
384
                protected class SkipContactException extends Exception { }
263
385
 
264
 
                public void parseLine( String line )
265
 
                                throws ParseException, SkipContactException,
266
 
                                AbortImportException
267
 
                {
268
 
                        // get property halves
269
 
                        String[] props = line.split( ":" );
270
 
                        for( int i = 0; i < props.length; i++ )
271
 
                                props[ i ] = props[ i ].trim();
272
 
                        if( props.length < 2 ||
273
 
                                        props[ 0 ].length() < 1 || props[ 1 ].length() < 1 )
274
 
                                throw new ParseException( R.string.error_vcf_malformed );
275
 
 
 
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?
276
430
                        if( _version == null )
277
431
                        {
278
 
                                if( 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" ) )
279
439
                                {
280
 
                                        // get version
281
 
                                        if( !props[ 1 ].equals( "2.1" ) &&
282
 
                                                        !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" ) )
283
443
                                                throw new ParseException( R.string.error_vcf_version );
284
 
                                        _version = props[ 1 ];
 
444
                                        _version = value;
285
445
 
286
 
                                        // parse any other lines we've accumulated so far
287
 
                                        if( _lines != null )
288
 
                                                for( int i = 0; i < _lines.size(); i++ )
289
 
                                                        parseLine( _lines.get( i ) );
290
 
                                        _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;
291
456
                                }
292
457
                                else
293
458
                                {
294
 
                                        // stash this line till we have a version
295
 
                                        if( _lines == null )
296
 
                                                _lines = new Vector< String >();
297
 
                                        _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 );
298
463
                                }
299
464
                        }
300
465
                        else
301
466
                        {
 
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 )
 
474
                                {
 
475
                                        // if we're currently in a multi-line value, use the stored
 
476
                                        // property name and parameters
 
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
                                                }
 
495
                                }
 
496
                                else
 
497
                                {
 
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 )
 
504
                                                throw new ParseException(
 
505
                                                        R.string.error_vcf_malformed );
 
506
 
 
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;
 
510
 
 
511
                                        // reset the saved multi-line state
 
512
                                        _parser_current_name_and_params = name_and_params;
 
513
                                        _parser_buffered_value_so_far = "";
 
514
                                }
 
515
 
 
516
                                // get value from buffer, as raw bytes
 
517
                                ByteBuffer value;
 
518
                                value = ByteBuffer.wrap( buffer.array(), pos,
 
519
                                        buffer.limit() - pos );
 
520
 
302
521
                                // get parameter parts
303
 
                                String[] params = props[ 0 ].split( ";" );
304
 
                                for( int i = 0; i < params.length; i++ )
305
 
                                        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();
 
525
 
 
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" ) )
 
531
                                        //&& !encoding.equals( "BASE64" ) )
 
532
                                {
 
533
                                        throw new ParseException( R.string.error_vcf_encoding );
 
534
                                }
 
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
 
 
546
                                // do unencoding (or default to a fake unencoding result with
 
547
                                // the raw string)
 
548
                                UnencodeResult unencoding_result = null;
 
549
                                if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
 
550
                                        unencoding_result = unencodeQuotedPrintable( value );
 
551
//                              else if( encoding != null && encoding.equals( "BASE64" ) )
 
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
                                }
 
564
 
 
565
                                // process charset
 
566
                                String string_value;
 
567
                                try {
 
568
                                        string_value = new String( value.array(), value.position(),
 
569
                                                value.limit() - value.position(), charset );
 
570
                                } catch( UnsupportedEncodingException e ) {
 
571
                                        throw new ParseException( R.string.error_vcf_charset );
 
572
                                }
 
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
 
 
579
                                // handle multi-line requests
 
580
                                if( _parser_in_encoded_multiline ||
 
581
                                        _parser_in_folded_multiline )
 
582
                                {
 
583
                                        _parser_buffered_value_so_far += string_value;
 
584
                                        return;
 
585
                                }
 
586
 
 
587
                                // add on buffered multi-line content
 
588
                                String complete_value =
 
589
                                        _parser_buffered_value_so_far + string_value;
 
590
 
 
591
                                // ignore empty values
 
592
                                if( complete_value.length() < 1 ) return;
306
593
 
307
594
                                // parse some properties
308
 
                                if( params[ 0 ].equals( "N" ) )
309
 
                                        parseN( params, props[ 1 ] );
310
 
                                else if( params[ 0 ].equals( "FN" ) )
311
 
                                        parseFN( params, props[ 1 ] );
312
 
                                else if( params[ 0 ].equals( "ORG" ) )
313
 
                                        parseORG( params, props[ 1 ] );
314
 
                                else if( params[ 0 ].equals( "TEL" ) )
315
 
                                        parseTEL( params, props[ 1 ] );
316
 
                                else if( params[ 0 ].equals( "EMAIL" ) )
317
 
                                        parseEMAIL( params, props[ 1 ] );
 
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 );
318
605
                        }
319
606
                }
320
607
 
321
608
                private void parseN( String[] params, String value )
322
 
                                throws ParseException, SkipContactException,
323
 
                                AbortImportException
 
609
                        throws ParseException, SkipContactException,
 
610
                        AbortImportException
324
611
                {
325
612
                        // already got a better name?
326
 
                        if( _nameLevel >= NAMELEVEL_N ) return;
 
613
                        if( _name_level >= NAMELEVEL_N ) return;
327
614
 
328
615
                        // get name parts
329
 
                        String[] nameparts = value.split( ";" );
330
 
                        for( int i = 0; i < nameparts.length; i++ )
331
 
                                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();
332
619
 
333
620
                        // build name
334
621
                        value = "";
335
 
                        if( nameparts.length > 1 && nameparts[ 1 ].length() > 0 )
336
 
                                value += nameparts[ 1 ];
337
 
                        if( nameparts[ 0 ].length() > 0 )
338
 
                                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 ];
339
626
 
340
627
                        // set name
341
 
                        setName( undoCharsetAndEncoding( params, value ) );
342
 
                        _nameLevel = NAMELEVEL_N;
 
628
                        setName( value );
 
629
                        _name_level = NAMELEVEL_N;
343
630
 
344
631
                        // check now to see if we need to import this contact (to avoid
345
632
                        // parsing the rest of the vCard unnecessarily)
348
635
                }
349
636
 
350
637
                private void parseFN( String[] params, String value )
351
 
                                throws ParseException, SkipContactException
 
638
                        throws ParseException, SkipContactException
352
639
                {
353
640
                        // already got a better name?
354
 
                        if( _nameLevel >= NAMELEVEL_FN ) return;
 
641
                        if( _name_level >= NAMELEVEL_FN ) return;
355
642
 
356
643
                        // set name
357
 
                        setName( undoCharsetAndEncoding( params, value ) );
358
 
                        _nameLevel = NAMELEVEL_FN;
 
644
                        setName( value );
 
645
                        _name_level = NAMELEVEL_FN;
359
646
                }
360
647
 
361
648
                private void parseORG( String[] params, String value )
362
 
                                throws ParseException, SkipContactException
 
649
                        throws ParseException, SkipContactException
363
650
                {
364
651
                        // already got a better name?
365
 
                        if( _nameLevel >= NAMELEVEL_ORG ) return;
 
652
                        if( _name_level >= NAMELEVEL_ORG ) return;
366
653
 
367
654
                        // get org parts
368
 
                        String[] orgparts = value.split( ";" );
369
 
                        for( int i = 0; i < orgparts.length; i++ )
370
 
                                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();
371
658
 
372
659
                        // build name
373
 
                        if( orgparts[ 0 ].length() == 0 && orgparts.length > 1 )
374
 
                                value = orgparts[ 1 ];
 
660
                        if( org_parts.length > 1 && org_parts[ 0 ].length() == 0 )
 
661
                                value = org_parts[ 1 ];
375
662
                        else
376
 
                                value = orgparts[ 0 ];
 
663
                                value = org_parts[ 0 ];
377
664
 
378
665
                        // set name
379
 
                        setName( undoCharsetAndEncoding( params, value ) );
380
 
                        _nameLevel = NAMELEVEL_ORG;
 
666
                        setName( value );
 
667
                        _name_level = NAMELEVEL_ORG;
381
668
                }
382
669
 
383
670
                private void parseTEL( String[] params, String value )
384
 
                                throws ParseException
 
671
                        throws ParseException
385
672
                {
386
673
                        if( value.length() == 0 ) return;
387
674
 
388
675
                        Set< String > types = extractTypes( params, Arrays.asList(
389
 
                                        "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
390
 
                                        "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
 
676
                                "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
 
677
                                "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
391
678
 
392
679
                        // here's the logic...
393
680
                        boolean preferred = types.contains( "PREF" );
 
681
                        int type = PhonesColumns.TYPE_MOBILE;
394
682
                        if( types.contains( "VOICE" ) )
395
683
                                if( types.contains( "WORK" ) )
396
 
                                        addPhone( value, PhonesColumns.TYPE_WORK, preferred );
 
684
                                        type = PhonesColumns.TYPE_WORK;
397
685
                                else
398
 
                                        addPhone( value, PhonesColumns.TYPE_HOME, preferred );
 
686
                                        type = PhonesColumns.TYPE_HOME;
399
687
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
400
 
                                addPhone( value, PhonesColumns.TYPE_MOBILE, preferred );
 
688
                                type = PhonesColumns.TYPE_MOBILE;
401
689
                        if( types.contains( "FAX" ) )
402
690
                                if( types.contains( "HOME" ) )
403
 
                                        addPhone( value, PhonesColumns.TYPE_FAX_HOME, preferred );
 
691
                                        type = PhonesColumns.TYPE_FAX_HOME;
404
692
                                else
405
 
                                        addPhone( value, PhonesColumns.TYPE_FAX_WORK, preferred );
 
693
                                        type = PhonesColumns.TYPE_FAX_WORK;
406
694
                        if( types.contains( "PAGER" ) )
407
 
                                addPhone( value, PhonesColumns.TYPE_PAGER, preferred );
 
695
                                type = PhonesColumns.TYPE_PAGER;
 
696
 
 
697
                        // add phone number
 
698
                        addPhone( value, type, preferred );
408
699
                }
409
700
 
410
701
                public void parseEMAIL( String[] params, String value )
 
702
                        throws ParseException
411
703
                {
412
704
                        if( value.length() == 0 ) return;
413
705
 
414
706
                        Set< String > types = extractTypes( params, Arrays.asList(
415
 
                                        "PREF", "WORK", "HOME", "INTERNET" ) );
 
707
                                "PREF", "WORK", "HOME", "INTERNET" ) );
416
708
 
417
709
                        // here's the logic...
418
710
                        boolean preferred = types.contains( "PREF" );
423
715
                }
424
716
 
425
717
                public void finaliseParsing()
426
 
                                throws ParseException, SkipContactException,
427
 
                                AbortImportException
 
718
                        throws ParseException, SkipContactException,
 
719
                        AbortImportException
428
720
                {
429
721
                        // missing version (and data is present)
430
 
                        if( _version == null && _lines != null )
 
722
                        if( _version == null && _buffers != null )
431
723
                                throw new ParseException( R.string.error_vcf_malformed );
432
724
 
433
725
                        //  missing name properties?
434
 
                        if( _nameLevel == NAMELEVEL_NONE )
 
726
                        if( _name_level == NAMELEVEL_NONE )
435
727
                                throw new ParseException( R.string.error_vcf_noname );
436
728
 
437
729
                        // check if we should import this one? If we've already got an 'N'-
438
730
                        // type name, this will already have been done by parseN() so we
439
731
                        // mustn't do this here (or it could prompt twice!)
440
 
                        if( _nameLevel < NAMELEVEL_N && !isImportRequired( getName() ) )
 
732
                        if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
441
733
                                throw new SkipContactException();
442
734
                }
443
735
 
444
 
                private String undoCharsetAndEncoding( String[] params, String value )
445
 
                                throws ParseException
446
 
                {
447
 
                        // check encoding/charset
448
 
                        String charset, encoding;
449
 
                        if( ( charset = checkParam( params, "CHARSET" ) ) != null &&
450
 
                                        !charset.equals( "UTF-8" ) && !charset.equals( "UTF-16" ) )
451
 
                                throw new ParseException( R.string.error_vcf_charset );
452
 
                        if( ( encoding = checkParam( params, "ENCODING" ) ) != null &&
453
 
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
454
 
                                throw new ParseException( R.string.error_vcf_encoding );
455
 
 
456
 
                        // do decoding?
457
 
                        if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
458
 
                                return unencodeQuotedPrintable( value, charset );
459
 
 
460
 
                        // nothing to do!
461
 
                        return value;
462
 
                }
463
 
 
464
736
                private String checkParam( String[] params, String name )
465
737
                {
466
 
                        Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
 
738
                        Pattern p = Pattern.compile(
 
739
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$" );
467
740
                        for( int i = 0; i < params.length; i++ ) {
468
741
                                Matcher m = p.matcher( params[ i ] );
469
742
                                if( m.matches() )
470
 
                                        return m.group( 1 );
 
743
                                        return m.group( 2 );
471
744
                        }
472
745
                        return null;
473
746
                }
474
747
 
475
748
                private Set< String > extractTypes( String[] params,
476
 
                                List< String > validTypes )
 
749
                        List< String > valid_types )
477
750
                {
478
751
                        HashSet< String > types = new HashSet< String >();
479
752
 
480
753
                        // get 3.0-style TYPE= param
481
 
                        String typeParam;
482
 
                        if( ( typeParam = checkParam( params, "TYPE" ) ) != null ) {
483
 
                                String[] bits = typeParam.split( "," );
484
 
                                for( int i = 0; i < bits.length; i++ )
485
 
                                        if( validTypes.contains( bits[ i ] ) )
486
 
                                                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 ] );
487
760
                        }
488
761
 
489
762
                        // get 2.1-style type param
490
763
                        if( _version.equals( "2.1" ) ) {
491
764
                                for( int i = 1; i < params.length; i++ )
492
 
                                        if( validTypes.contains( params[ i ] ) )
 
765
                                        if( valid_types.contains( params[ i ] ) )
493
766
                                                types.add( params[ i ] );
494
767
                        }
495
768
 
496
769
                        return types;
497
770
                }
498
771
 
499
 
                private String unencodeQuotedPrintable( String str, String charset )
 
772
                private UnencodeResult unencodeQuotedPrintable( ByteBuffer in )
500
773
                {
501
 
                        // default encoding scheme
502
 
                        if( charset == null ) charset = "UTF-8";
 
774
                        boolean another = false;
503
775
 
504
 
                        // unencode quoted-pritable encoding, as per RFC1521 section 5.1
505
 
                        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() ];
506
778
                        int j = 0;
507
 
                        for( int i = 0; i < str.length(); i++, j++ ) {
508
 
                                char ch = str.charAt( i );
509
 
                                if( ch == '=' && i < str.length() - 2 ) {
510
 
                                        bytes[ j ] = (byte)(
511
 
                                                        Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
512
 
                                                        Character.digit( str.charAt( i + 2 ), 16 ) );
 
779
                        for( int i = in.position(); i < in.limit(); i++ )
 
780
                        {
 
781
                                // get next char and process...
 
782
                                byte ch = in.array()[ i ];
 
783
                                if( ch == '=' && i < in.limit() - 2 )
 
784
                                {
 
785
                                        // we found a =XX format byte, add it
 
786
                                        out[ j ] = (byte)(
 
787
                                                        Character.digit( in.array()[ i + 1 ], 16 ) * 16 +
 
788
                                                        Character.digit( in.array()[ i + 2 ], 16 ) );
513
789
                                        i += 2;
514
790
                                }
 
791
                                else if( ch == '=' && i == in.limit() - 1 )
 
792
                                {
 
793
                                        // we found a '=' at the end of a line signifying a multi-
 
794
                                        // line string, so we don't add it.
 
795
                                        another = true;
 
796
                                        continue;
 
797
                                }
515
798
                                else
516
 
                                        bytes[ j ] = (byte)ch;
517
 
                        }
518
 
                        try {
519
 
                                return new String( bytes, 0, j, charset );
520
 
                        } catch( UnsupportedEncodingException e ) { }
521
 
                        return null;
 
799
                                        // just a normal char...
 
800
                                        out[ j ] = (byte)ch;
 
801
                                j++;
 
802
                        }
 
803
 
 
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 );
522
827
                }
523
828
        }
524
829
}