/android/import-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/import-contacts

« back to all changes in this revision

Viewing changes to src/org/waxworlds/edam/importcontacts/VCFImporter.java

  • Committer: edam
  • Date: 2010-10-28 15:49:21 UTC
  • Revision ID: edam@waxworlds.org-20101028154921-98svlxlpno3cpzb8
- added file chooser
- changed file/dir entry box for a button that opens the file chooser
- added dialog to ask if you want to select a dir to scan or a file
- fixed bug where you could abort as dialog opened and the dialog wasn't cancelled
- fixed crash where you could abort as the merge prompt opened and it would try to use the just-destroyed importer
- fixed bug where closing the application at the end would show "aborted!" erroniously

Show diffs side-by-side

added added

removed removed

1
1
/*
2
2
 * VCFImporter.java
3
3
 *
4
 
 * Copyright (C) 2009 to 2011 Tim Marston <tim@ed.am>
 
4
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
5
5
 *
6
6
 * This file is part of the Import Contacts program (hereafter referred
7
7
 * to as "this program"). For more information, see
8
 
 * http://ed.am/dev/android/import-contacts
 
8
 * http://www.waxworlds.org/edam/software/android/import-contacts
9
9
 *
10
10
 * This program is free software: you can redistribute it and/or modify
11
11
 * it under the terms of the GNU General Public License as published by
21
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
22
 */
23
23
 
24
 
package am.ed.importcontacts;
 
24
package org.waxworlds.edam.importcontacts;
25
25
 
26
26
import java.io.BufferedReader;
27
27
import java.io.File;
28
 
import java.io.FileInputStream;
29
28
import java.io.FileNotFoundException;
30
29
import java.io.FileReader;
31
30
import java.io.FilenameFilter;
32
31
import java.io.IOException;
33
32
import java.io.UnsupportedEncodingException;
34
 
import java.nio.ByteBuffer;
35
 
import java.util.ArrayList;
36
33
import java.util.Arrays;
37
 
import java.util.HashMap;
38
34
import java.util.HashSet;
39
 
import java.util.Iterator;
40
35
import java.util.List;
41
 
import java.util.Locale;
42
 
import java.util.NoSuchElementException;
43
36
import java.util.Set;
44
37
import java.util.Vector;
45
38
import java.util.regex.Matcher;
46
39
import java.util.regex.Pattern;
47
40
 
48
 
import android.annotation.SuppressLint;
49
41
import android.content.SharedPreferences;
 
42
import android.provider.Contacts;
 
43
import android.provider.Contacts.PhonesColumns;
50
44
 
51
 
public class VcardImporter extends Importer
 
45
public class VCFImporter extends Importer
52
46
{
53
 
        private int _vcard_count = 0;
 
47
        private int _vCardCount = 0;
54
48
        private int _progress = 0;
55
49
 
56
 
        public VcardImporter( Doit doit )
 
50
        public VCFImporter( Doit doit )
57
51
        {
58
52
                super( doit );
59
53
        }
60
54
 
61
 
        @SuppressLint( "SdCardPath" )
62
55
        @Override
63
56
        protected void onImport() throws AbortImportException
64
57
        {
83
76
                                // get files
84
77
                                class VCardFilter implements FilenameFilter {
85
78
                                        public boolean accept( File dir, String name ) {
86
 
                                                return name.toLowerCase( Locale.US ).endsWith( ".vcf" );
 
79
                                                return name.toLowerCase().endsWith( ".vcf" );
87
80
                                        }
88
81
                                }
89
82
                                files = file.listFiles( new VCardFilter() );
111
104
                        countVCardFile( files[ i ] );
112
105
                        setTmpProgress( i );
113
106
                }
114
 
                setProgressMax( _vcard_count ); // will also update tmp progress
 
107
                setProgressMax( _vCardCount );  // will also update tmp progress
115
108
 
116
109
                // import them
117
110
                setProgress( 0 );
118
111
                for( int i = 0; i < files.length; i++ )
119
112
                        importVCardFile( files[ i ] );
120
 
                setProgress( _vcard_count );
121
113
        }
122
114
 
123
115
        private void countVCardFile( File file ) throws AbortImportException
126
118
                {
127
119
                        // open file
128
120
                        BufferedReader reader = new BufferedReader(
129
 
                                new FileReader( file ) );
 
121
                                        new FileReader( file ) );
130
122
 
131
123
                        // read
132
124
                        String line;
133
 
                        boolean in_vcard = false;
 
125
                        boolean inVCard = false;
134
126
                        while( ( line = reader.readLine() ) != null )
135
127
                        {
136
 
                                if( !in_vcard ) {
 
128
                                if( !inVCard ) {
137
129
                                        // look for vcard beginning
138
 
                                        if( line.matches( "^BEGIN:VCARD" ) ) {
139
 
                                                in_vcard = true;
140
 
                                                _vcard_count++;
 
130
                                        if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
 
131
                                                inVCard = true;
 
132
                                                _vCardCount++;
141
133
                                        }
142
134
                                }
143
 
                                else if( line.matches( "^END:VCARD" ) )
144
 
                                        in_vcard = false;
 
135
                                else if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
 
136
                                        inVCard = false;
145
137
                        }
146
138
 
147
139
                }
156
148
 
157
149
        private void importVCardFile( File file ) throws AbortImportException
158
150
        {
159
 
                // check file is good
160
 
                if( !file.exists() )
161
 
                        showError( getText( R.string.error_filenotfound ) +
162
 
                                file.getName() );
163
 
                if( file.length() == 0 )
164
 
                        showError( getText( R.string.error_fileisempty ) +
165
 
                                file.getName() );
166
 
 
167
151
                try
168
152
                {
169
 
                        // open/read file
170
 
                        FileInputStream istream = new FileInputStream( file );
171
 
                        byte[] content = new byte[ (int)file.length() ];
172
 
                        istream.read( content );
173
 
                        istream = null;
174
 
 
175
 
                        // import
176
 
                        importVCardFileContent( content, file.getName() );
 
153
                        // open file
 
154
                        BufferedReader reader = new BufferedReader(
 
155
                                        new FileReader( file ) );
 
156
 
 
157
                        // read
 
158
                        StringBuffer content = new StringBuffer();
 
159
                        String line;
 
160
                        while( ( line = reader.readLine() ) != null )
 
161
                                content.append( line ).append( "\n" );
 
162
 
 
163
                        importVCardFileContent( content.toString(), file.getName() );
177
164
                }
178
165
                catch( FileNotFoundException e ) {
179
166
                        showError( getText( R.string.error_filenotfound ) +
184
171
                }
185
172
        }
186
173
 
187
 
        private void importVCardFileContent( byte[] content, String fileName )
188
 
                throws AbortImportException
 
174
        private void importVCardFileContent( String content, String fileName )
 
175
                        throws AbortImportException
189
176
        {
190
 
                // go through lines
191
 
                Vcard vcard = null;
192
 
                int vcard_start_line = 0;
193
 
                ContentLineIterator cli = new ContentLineIterator( content );
194
 
                while( cli.hasNext() )
 
177
                // get lines and parse them
 
178
                String[] lines = content.split( "\n" );
 
179
                VCard vCard = null;
 
180
                for( int i = 0; i < lines.length; i++ )
195
181
                {
196
 
                        ByteBuffer buffer = cli.next();
197
 
 
198
 
                        // get a US-ASCII version of the line for processing
199
 
                        String line;
200
 
                        try {
201
 
                                line = new String( buffer.array(), buffer.position(),
202
 
                                        buffer.limit() - buffer.position(), "US-ASCII" );
203
 
                        }
204
 
                        catch( UnsupportedEncodingException e ) {
205
 
                                // we know US-ASCII is supported, so appease the compiler...
206
 
                                line = "";
207
 
                        }
208
 
 
209
 
                        if( vcard == null ) {
 
182
                        String line = lines[ i ];
 
183
 
 
184
                        if( vCard == null ) {
210
185
                                // look for vcard beginning
211
 
                                if( line.matches( "^BEGIN[ \t]*:[ \t]*VCARD" ) ) {
212
 
                                        setProgress( _progress++ );
213
 
                                        vcard = new Vcard();
214
 
                                        vcard_start_line = cli.getLineNumber();
 
186
                                if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
 
187
                                        setProgress( ++_progress );
 
188
                                        vCard = new VCard();
215
189
                                }
216
190
                        }
217
191
                        else {
218
192
                                // look for vcard content or ending
219
 
                                if( line.matches( "^END[ \t]*:[ \t]*VCARD" ) )
 
193
                                if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
220
194
                                {
221
 
                                        // finalise the vcard/contact
 
195
                                        // store vcard and do away with it
222
196
                                        try {
223
 
                                                vcard.finaliseVcard();
224
 
 
225
 
                                                // pass the finalised contact to the importer
226
 
                                                importContact( vcard );
227
 
                                        }
228
 
                                        catch( Vcard.ParseException e ) {
229
 
                                                if( !showContinue(
230
 
                                                        getText( R.string.error_vcf_parse ).toString()
231
 
                                                        + fileName +
232
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
233
 
                                                        + cli.getLineNumber() + ":\n" + e.getMessage() ) )
234
 
                                                {
235
 
                                                        finish( ACTION_ABORT );
236
 
                                                }
237
 
                                                else
238
 
                                                        skipContact();
239
 
                                        }
240
 
                                        catch( ContactData.ContactNotIdentifiableException e ) {
241
 
                                                if( !showContinue(
242
 
                                                        getText( R.string.error_vcf_parse ).toString()
243
 
                                                        + fileName +
244
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
245
 
                                                        + vcard_start_line + ":\n" + getText(
246
 
                                                                R.string.error_vcf_notenoughinfo ).toString()
247
 
                                                ) )
248
 
                                                {
249
 
                                                        finish( ACTION_ABORT );
250
 
                                                }
251
 
                                                else
252
 
                                                        skipContact();
253
 
                                        }
254
 
 
255
 
                                        // discard this vcard
256
 
                                        vcard = null;
 
197
                                                vCard.finaliseParsing();
 
198
                                                importContact( vCard );
 
199
                                        }
 
200
                                        catch( VCard.ParseException e ) {
 
201
                                                skipContact();
 
202
                                                if( !showContinue(
 
203
                                                                getText( R.string.error_vcf_parse ).toString()
 
204
                                                                + fileName + "\n" + e.getMessage() ) )
 
205
                                                        finish( ACTION_ABORT );
 
206
                                        }
 
207
                                        catch( VCard.SkipContactException e ) {
 
208
                                                skipContact();
 
209
                                                // do nothing
 
210
                                        }
 
211
                                        vCard = null;
257
212
                                }
258
213
                                else
259
214
                                {
260
215
                                        // try giving the line to the vcard
261
216
                                        try {
262
 
                                                vcard.parseLine( buffer, line,
263
 
                                                        cli.doesNextLineLookFolded() );
 
217
                                                vCard.parseLine( line );
264
218
                                        }
265
 
                                        catch( Vcard.ParseException e ) {
 
219
                                        catch( VCard.ParseException e ) {
266
220
                                                skipContact();
267
221
                                                if( !showContinue(
268
 
                                                        getText( R.string.error_vcf_parse ).toString()
269
 
                                                        + fileName +
270
 
                                                        getText( R.string.error_vcf_parse_line ).toString()
271
 
                                                        + cli.getLineNumber() + "\n" + e.getMessage() ) )
272
 
                                                {
 
222
                                                                getText( R.string.error_vcf_parse ).toString()
 
223
                                                                + fileName + "\n" + e.getMessage() ) )
273
224
                                                        finish( ACTION_ABORT );
274
 
                                                }
275
225
 
276
226
                                                // although we're continuing, we still need to abort
277
227
                                                // this vCard. Further lines will be ignored until we
278
228
                                                // get to another BEGIN:VCARD line.
279
 
                                                vcard = null;
 
229
                                                vCard = null;
280
230
                                        }
281
 
                                        catch( Vcard.SkipImportException e ) {
 
231
                                        catch( VCard.SkipContactException e ) {
282
232
                                                skipContact();
283
233
                                                // abort this vCard. Further lines will be ignored until
284
234
                                                // we get to another BEGIN:VCARD line.
285
 
                                                vcard = null;
 
235
                                                vCard = null;
286
236
                                        }
287
237
                                }
288
238
                        }
289
239
                }
290
240
        }
291
241
 
292
 
        class ContentLineIterator implements Iterator< ByteBuffer >
293
 
        {
294
 
                protected byte[] _content = null;
295
 
                protected int _pos = 0;
296
 
                protected int _line = 0;
297
 
 
298
 
                public ContentLineIterator( byte[] content )
299
 
                {
300
 
                        _content = content;
301
 
                }
302
 
 
303
 
                @Override
304
 
                public boolean hasNext()
305
 
                {
306
 
                        return _pos < _content.length;
307
 
                }
308
 
 
309
 
                @Override
310
 
                public ByteBuffer next()
311
 
                {
312
 
                        int initial_pos = _pos;
313
 
 
314
 
                        // find newline
315
 
                        for( ; _pos < _content.length; _pos++ )
316
 
                                if( _content[ _pos ] == '\n' )
317
 
                                {
318
 
                                        // adjust for a \r preceding the \n
319
 
                                        int to = ( _pos > 0 && _content[ _pos - 1 ] == '\r' &&
320
 
                                                _pos > initial_pos )? _pos - 1 : _pos;
321
 
                                        _pos++;
322
 
                                        _line++;
323
 
                                        return ByteBuffer.wrap( _content, initial_pos,
324
 
                                                to - initial_pos );
325
 
                                }
326
 
 
327
 
                        // we didn't find one, but were there bytes left?
328
 
                        if( _pos != initial_pos ) {
329
 
                                int to = _pos;
330
 
                                _pos++;
331
 
                                _line++;
332
 
                                return ByteBuffer.wrap( _content, initial_pos,
333
 
                                        to - initial_pos );
334
 
                        }
335
 
 
336
 
                        // no bytes left
337
 
                        throw new NoSuchElementException();
338
 
                }
339
 
 
340
 
                @Override
341
 
                public void remove()
342
 
                {
343
 
                        throw new UnsupportedOperationException();
344
 
                }
345
 
 
346
 
                /**
347
 
                 * Does the next line, if there is one, look like it should be folded
348
 
                 * onto the end of this one?
349
 
                 * @return
350
 
                 */
351
 
                public boolean doesNextLineLookFolded()
352
 
                {
353
 
                        return _pos > 0 && _pos < _content.length &&
354
 
                                _content[ _pos - 1 ] == '\n' &&
355
 
                                ( _content[ _pos ] == ' ' || _content[ _pos ] == '\t' );
356
 
                }
357
 
 
358
 
                public int getLineNumber()
359
 
                {
360
 
                        return _line;
361
 
                }
362
 
        }
363
 
 
364
 
        private class Vcard extends ContactData
 
242
        private class VCard extends ContactData
365
243
        {
366
244
                private final static int NAMELEVEL_NONE = 0;
367
 
                private final static int NAMELEVEL_N = 1;
 
245
                private final static int NAMELEVEL_ORG = 1;
368
246
                private final static int NAMELEVEL_FN = 2;
369
 
 
370
 
                private final static int MULTILINE_NONE = 0;
371
 
                private final static int MULTILINE_ENCODED = 1; // v2.1 quoted-printable
372
 
                private final static int MULTILINE_ESCAPED = 2; // v2.1 \\CRLF
373
 
                private final static int MULTILINE_FOLDED = 3;  // MIME-DIR folding
 
247
                private final static int NAMELEVEL_N = 3;
374
248
 
375
249
                private String _version = null;
376
 
                private Vector< ByteBuffer > _buffers = null;
 
250
                private Vector< String > _lines = null;
377
251
                private int _name_level = NAMELEVEL_NONE;
378
 
                private int _parser_multiline_state = MULTILINE_NONE;
 
252
                private boolean _parser_in_multiline = false;
379
253
                private String _parser_current_name_and_params = null;
380
254
                private String _parser_buffered_value_so_far = "";
381
 
                private String _cached_organisation = null;
382
 
                private String _cached_title = null;
383
255
 
384
256
                protected class UnencodeResult
385
257
                {
386
258
                        private boolean _another_line_required;
387
 
                        private ByteBuffer _buffer;
 
259
                        private byte[] _bytes;
 
260
                        private int _num_bytes;
388
261
 
389
 
                        public UnencodeResult( boolean another_line_required,
390
 
                                ByteBuffer buffer )
 
262
                        public UnencodeResult( boolean another_line_required, byte[] bytes,
 
263
                                int num_bytes )
391
264
                        {
392
265
                                _another_line_required = another_line_required;
393
 
                                _buffer = buffer;
 
266
                                _bytes = bytes;
 
267
                                _num_bytes = num_bytes;
394
268
                        }
395
269
 
396
270
                        public boolean isAnotherLineRequired()
398
272
                                return _another_line_required;
399
273
                        }
400
274
 
401
 
                        public ByteBuffer getBuffer()
402
 
                        {
403
 
                                return _buffer;
 
275
                        public byte[] getBytes()
 
276
                        {
 
277
                                return _bytes;
 
278
                        }
 
279
 
 
280
                        public int getNumBytes()
 
281
                        {
 
282
                                return _num_bytes;
404
283
                        }
405
284
                }
406
285
 
415
294
 
416
295
                        public ParseException( int res )
417
296
                        {
418
 
                                super( VcardImporter.this.getText( res ).toString() );
 
297
                                super( VCFImporter.this.getText( res ).toString() );
419
298
                        }
420
299
                }
421
300
 
422
301
                @SuppressWarnings("serial")
423
 
                protected class SkipImportException extends Exception { }
424
 
 
425
 
                private String extractCollonPartFromLine( ByteBuffer buffer,
426
 
                        String line, boolean former )
427
 
                {
428
 
                        String ret = null;
429
 
 
430
 
                        // get a US-ASCII version of the line for processing, unless we were
431
 
                        // supplied with one
432
 
                        if( line == null ) {
433
 
                                try {
434
 
                                        line = new String( buffer.array(), buffer.position(),
435
 
                                                buffer.limit() - buffer.position(), "US-ASCII" );
436
 
                                }
437
 
                                catch( UnsupportedEncodingException e ) {
438
 
                                        // we know US-ASCII is supported, so appease the compiler...
439
 
                                        line = "";
440
 
                                }
441
 
                        }
442
 
 
443
 
                        // split line into name and value parts and check to make sure we
444
 
                        // only got 2 parts and that the first part is not zero in length
445
 
                        String[] parts = line.split( ":", 2 );
446
 
                        if( parts.length == 2 && parts[ 0 ].length() > 0 )
447
 
                                ret = parts[ former? 0 : 1 ];
448
 
 
449
 
                        return ret;
450
 
                }
451
 
 
452
 
                private String extractNameAndParamsFromLine( ByteBuffer buffer,
453
 
                        String line )
454
 
                {
455
 
                        return extractCollonPartFromLine( buffer, line, true );
456
 
                }
457
 
 
458
 
                private String extractValueFromLine( ByteBuffer buffer, String line )
459
 
                {
460
 
                        return extractCollonPartFromLine( buffer, line, false );
461
 
                }
462
 
 
463
 
                public void parseLine( ByteBuffer buffer, String line,
464
 
                        boolean next_line_looks_folded )
465
 
                        throws ParseException, SkipImportException,
466
 
                        AbortImportException
467
 
                {
468
 
                        // do we have a version yet?
 
302
                protected class SkipContactException extends Exception { }
 
303
 
 
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!
469
320
                        if( _version == null )
470
321
                        {
471
 
                                // tentatively get name and params from line
472
 
                                String name_and_params =
473
 
                                        extractNameAndParamsFromLine( buffer, line );
474
 
 
475
 
                                // is it a version line?
476
 
                                if( name_and_params != null &&
477
 
                                        name_and_params.equalsIgnoreCase( "VERSION" ) )
 
322
                                // is this a version?
 
323
                                if( props.length == 2 && props[ 0 ].equals( "VERSION" ) )
478
324
                                {
479
 
                                        // yes, get it!
480
 
                                        String value = extractValueFromLine( buffer, line );
481
 
                                        if( !value.equals( "2.1" ) && !value.equals( "3.0" ) )
 
325
                                        // yes, check/store it
 
326
                                        if( !props[ 1 ].equals( "2.1" ) &&
 
327
                                                        !props[ 1 ].equals( "3.0" ) )
482
328
                                                throw new ParseException( R.string.error_vcf_version );
483
 
                                        _version = value;
 
329
                                        _version = props[ 1 ];
484
330
 
485
 
                                        // parse any buffers we've been accumulating while we waited
486
 
                                        // for a version
487
 
                                        if( _buffers != null )
488
 
                                                for( int i = 0; i < _buffers.size(); i++ )
489
 
                                                        parseLine( _buffers.get( i ), null,
490
 
                                                                i + 1 < _buffers.size() &&
491
 
                                                                _buffers.get( i + 1 ).hasRemaining() &&
492
 
                                                                _buffers.get( i + 1 ).get(
493
 
                                                                        _buffers.get( i + 1 ).position() ) == ' ' );
494
 
                                        _buffers = null;
 
331
                                        // parse any other lines we've accumulated so far
 
332
                                        if( _lines != null )
 
333
                                                for( int i = 0; i < _lines.size(); i++ )
 
334
                                                        parseLine( _lines.get( i ) );
 
335
                                        _lines = null;
495
336
                                }
496
337
                                else
497
338
                                {
498
 
                                        // no, so stash this line till we get a version
499
 
                                        if( _buffers == null )
500
 
                                                _buffers = new Vector< ByteBuffer >();
501
 
                                        _buffers.add( buffer );
 
339
                                        // no, so stash this line till we have a version
 
340
                                        if( _lines == null )
 
341
                                                _lines = new Vector< String >();
 
342
                                        _lines.add( line );
502
343
                                }
503
344
                        }
504
345
                        else
505
346
                        {
506
 
                                // name and params and the position in the buffer where the
507
 
                                // "value" part of the line start
508
 
                                String name_and_params;
509
 
                                int pos;
510
 
 
511
 
                                if( _parser_multiline_state != MULTILINE_NONE )
 
347
                                if( _parser_in_multiline )
512
348
                                {
513
349
                                        // if we're currently in a multi-line value, use the stored
514
350
                                        // property name and parameters
515
 
                                        name_and_params = _parser_current_name_and_params;
516
 
 
517
 
                                        // skip some initial line characters, depending on the type
518
 
                                        // of multi-line we're handling
519
 
                                        pos = buffer.position();
520
 
                                        switch( _parser_multiline_state )
521
 
                                        {
522
 
                                        case MULTILINE_FOLDED:
523
 
                                                pos++;
524
 
                                                break;
525
 
                                        case MULTILINE_ENCODED:
526
 
                                                while( pos < buffer.limit() && (
527
 
                                                        buffer.get( pos ) == ' ' ||
528
 
                                                        buffer.get( pos ) == '\t' ) )
529
 
                                                {
530
 
                                                        pos++;
531
 
                                                }
532
 
                                                break;
533
 
                                        default:
534
 
                                                // do nothing
535
 
                                        }
536
 
 
537
 
                                        // take us out of multi-line so that we can re-detect that
538
 
                                        // this line is a multi-line or not
539
 
                                        _parser_multiline_state = MULTILINE_NONE;
 
351
                                        props = new String[ 2 ];
 
352
                                        props[ 0 ] = _parser_current_name_and_params;
 
353
                                        props[ 1 ] = line.trim();
540
354
                                }
541
355
                                else
542
356
                                {
543
 
                                        // get name and params from line, and since we're not
544
 
                                        // parsing a subsequent line in a multi-line, this should
545
 
                                        // not fail, or it's an error
546
 
                                        name_and_params =
547
 
                                                extractNameAndParamsFromLine( buffer, line );
548
 
                                        if( name_and_params == null )
 
357
                                        // for normal lines, check the property name/value bits
 
358
                                        if( props.length < 2 || props[ 0 ].length() == 0 )
549
359
                                                throw new ParseException(
550
360
                                                        R.string.error_vcf_malformed );
551
361
 
552
 
                                        // calculate how many chars to skip from beginning of line
553
 
                                        // so we skip the property "name:" part
554
 
                                        pos = buffer.position() + name_and_params.length() + 1;
 
362
                                        // ignore empty properties
 
363
                                        if( props[ 1 ].length() < 1 )
 
364
                                                return;
555
365
 
556
366
                                        // reset the saved multi-line state
557
 
                                        _parser_current_name_and_params = name_and_params;
 
367
                                        _parser_current_name_and_params = props[ 0 ];
558
368
                                        _parser_buffered_value_so_far = "";
559
369
                                }
560
370
 
561
 
                                // get value from buffer, as raw bytes
562
 
                                ByteBuffer value;
563
 
                                value = ByteBuffer.wrap( buffer.array(), pos,
564
 
                                        buffer.limit() - pos );
565
 
 
566
371
                                // get parameter parts
567
 
                                String[] name_param_parts = name_and_params.split( ";", -1 );
568
 
                                for( int i = 0; i < name_param_parts.length; i++ )
569
 
                                        name_param_parts[ i ] = name_param_parts[ i ].trim();
570
 
 
571
 
                                // determine whether we care about this entry
572
 
                                final HashSet< String > interesting_fields =
573
 
                                        new HashSet< String >( Arrays.asList( new String[] { "N",
574
 
                                                "FN", "ORG", "TITLE", "TEL", "EMAIL", "ADR", "LABEL" }
575
 
                                ) );
576
 
                                boolean is_interesting_field =
577
 
                                        interesting_fields.contains( name_param_parts[ 0 ] );
578
 
 
579
 
                                // parse encoding parameter
580
 
                                String encoding = checkParam( name_param_parts, "ENCODING" );
581
 
                                if( encoding != null )
582
 
                                        encoding = encoding.toUpperCase( Locale.US );
583
 
                                if( is_interesting_field && encoding != null &&
584
 
                                        !encoding.equalsIgnoreCase( "8BIT" ) &&
585
 
                                        !encoding.equalsIgnoreCase( "QUOTED-PRINTABLE" ) )
586
 
                                        //&& !encoding.equalsIgnoreCase( "BASE64" ) )
 
372
                                String[] params = props[ 0 ].split( ";" );
 
373
                                for( int i = 0; i < params.length; i++ )
 
374
                                        params[ i ] = params[ i ].trim();
 
375
 
 
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" ) )
 
386
                                        //&& !encoding.equals( "BASE64" ) )
587
387
                                {
588
388
                                        throw new ParseException( R.string.error_vcf_encoding );
589
389
                                }
590
390
 
591
 
                                // parse charset parameter
592
 
                                String charset = checkParam( name_param_parts, "CHARSET" );
593
 
                                if( charset != null )
594
 
                                        charset = charset.toUpperCase( Locale.US );
595
 
                                if( charset != null &&
596
 
                                        !charset.equalsIgnoreCase( "US-ASCII" ) &&
597
 
                                        !charset.equalsIgnoreCase( "ASCII" ) &&
598
 
                                        !charset.equalsIgnoreCase( "UTF-8" ) )
599
 
                                {
600
 
                                        throw new ParseException( R.string.error_vcf_charset );
601
 
                                }
602
 
 
603
391
                                // do unencoding (or default to a fake unencoding result with
604
392
                                // the raw string)
605
 
                                UnencodeResult unencoding_result = null;
606
 
                                if( encoding != null &&
607
 
                                        encoding.equalsIgnoreCase( "QUOTED-PRINTABLE" ) )
608
 
                                {
609
 
                                        unencoding_result = unencodeQuotedPrintable( value );
610
 
                                }
611
 
//                              else if( encoding != null &&
612
 
//                                      encoding.equalsIgnoreCase( "BASE64" ) )
613
 
//                              {
614
 
//                                      unencoding_result = unencodeBase64( props[ 1 ], charset );
615
 
//                              }
616
 
                                if( unencoding_result != null ) {
617
 
                                        value = unencoding_result.getBuffer();
618
 
                                        if( unencoding_result.isAnotherLineRequired() )
619
 
                                                _parser_multiline_state = MULTILINE_ENCODED;
620
 
                                }
621
 
 
622
 
                                // convert 8-bit US-ASCII charset to UTF-8 (where no charset is
623
 
                                // specified for a v2.1 vcard entry, we assume it's US-ASCII)
624
 
                                if( ( charset == null && _version.equals( "2.1" ) ) ||
625
 
                                        ( charset != null && (
626
 
                                                charset.equalsIgnoreCase( "ASCII" ) ||
627
 
                                                charset.equalsIgnoreCase( "US-ASCII" ) ) ) )
628
 
                                {
629
 
                                        value = transcodeAsciiToUtf8( value );
630
 
                                }
631
 
 
632
 
                                // process charset (value is now in UTF-8)
633
 
                                String string_value;
 
393
                                UnencodeResult result;
 
394
                                if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
 
395
                                        result = unencodeQuotedPrintable( props[ 1 ], charset );
 
396
//                              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 );
 
401
 
 
402
                                // process charset
634
403
                                try {
635
 
                                        string_value = new String( value.array(), value.position(),
636
 
                                                value.limit() - value.position(), "UTF-8" );
 
404
                                        props[ 1 ] = new String( result.getBytes(), 0,
 
405
                                                result.getNumBytes(),
 
406
                                                charset == null? "UTF-8" : charset );
637
407
                                } catch( UnsupportedEncodingException e ) {
638
408
                                        throw new ParseException( R.string.error_vcf_charset );
639
409
                                }
640
410
 
641
 
                                // for some entries that have semicolon-separated value parts,
642
 
                                // check to see if the value ends in an escape character, which
643
 
                                // indicates that we have a multi-line value
644
 
                                if( ( name_param_parts[ 0 ].equalsIgnoreCase( "N" ) ||
645
 
                                        name_param_parts[ 0 ].equalsIgnoreCase( "ORG" ) ||
646
 
                                        name_param_parts[ 0 ].equalsIgnoreCase( "ADR" ) ) &&
647
 
                                        doesStringEndInAnEscapeChar( string_value ) )
648
 
                                {
649
 
                                        _parser_multiline_state = MULTILINE_ESCAPED;
650
 
                                        string_value = string_value.substring( 0,
651
 
                                                string_value.length() - 1 );
652
 
                                }
653
 
 
654
 
                                // if we know we're not in an encoding-based multi-line, check
655
 
                                // to see if we're in a folded multi-line
656
 
                                if( _parser_multiline_state == MULTILINE_NONE &&
657
 
                                        next_line_looks_folded )
658
 
                                {
659
 
                                        _parser_multiline_state = MULTILINE_FOLDED;
660
 
                                }
661
 
 
662
 
                                // handle multi-lines by buffering them and parsing them when we
663
 
                                // are processing the last line in a multi-line sequence
664
 
                                if( _parser_multiline_state != MULTILINE_NONE ) {
665
 
                                        _parser_buffered_value_so_far += string_value;
 
411
                                // handle multi-line requests
 
412
                                _parser_in_multiline = result.isAnotherLineRequired();
 
413
                                if( _parser_in_multiline ) {
 
414
                                        _parser_buffered_value_so_far += props[ 1 ];
666
415
                                        return;
667
416
                                }
668
 
                                String complete_value =
669
 
                                        ( _parser_buffered_value_so_far + string_value ).trim();
670
417
 
671
 
                                // ignore empty values
672
 
                                if( complete_value.length() < 1 ) return;
 
418
                                // add on buffered multi-line content
 
419
                                String value = _parser_buffered_value_so_far + props[ 1 ];
673
420
 
674
421
                                // parse some properties
675
 
                                if( name_param_parts[ 0 ].equalsIgnoreCase( "N" ) )
676
 
                                        parseN( name_param_parts, complete_value );
677
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "FN" ) )
678
 
                                        parseFN( name_param_parts, complete_value );
679
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "ORG" ) )
680
 
                                        parseORG( name_param_parts, complete_value );
681
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "TITLE" ) )
682
 
                                        parseTITLE( name_param_parts, complete_value );
683
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "TEL" ) )
684
 
                                        parseTEL( name_param_parts, complete_value );
685
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "EMAIL" ) )
686
 
                                        parseEMAIL( name_param_parts, complete_value );
687
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "ADR" ) )
688
 
                                        parseADR( name_param_parts, complete_value );
689
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "LABEL" ) )
690
 
                                        parseLABEL( name_param_parts, complete_value );
691
 
                                else if( name_param_parts[ 0 ].equalsIgnoreCase( "NOTE" ) )
692
 
                                        parseNOTE( name_param_parts, complete_value );
693
 
                        }
694
 
                }
695
 
 
696
 
                private boolean doesStringEndInAnEscapeChar( String string )
697
 
                {
698
 
                        // count the number of backslashes at the end of the string
699
 
                        int count = 0;
700
 
                        for( int a = string.length() - 1; a >= 0; a-- )
701
 
                                if( string.charAt( a ) == '\\' )
702
 
                                        count++;
703
 
                                else
704
 
                                        break;
705
 
 
706
 
                        // if there are an even number of backslashes then the final one
707
 
                        // doesn't count
708
 
                        return ( count & 1 ) == 1;
709
 
                }
710
 
 
711
 
                private String[] splitValueByCharacter( String value, char character )
712
 
                {
713
 
                        // split string in to parts by specified character
714
 
                        ArrayList< String > parts = new ArrayList< String >(
715
 
                                Arrays.asList( value.split( "" + character ) ) );
716
 
 
717
 
                        // go through parts
718
 
                        for( int a = 0; a < parts.size(); a++ )
719
 
                        {
720
 
                                String str = parts.get( a );
721
 
 
722
 
                                // look for parts that end in an escape character, but ignore
723
 
                                // the final part. We've already detected escape chars at the
724
 
                                // end of the final part in parseLine() and handled multi-lines
725
 
                                // accordingly.
726
 
                                if( a < parts.size() - 1 &&
727
 
                                        doesStringEndInAnEscapeChar( str ) )
728
 
                                {
729
 
                                        // append the escaped character, join the next part to this
730
 
                                        // part and remove the next part
731
 
                                        parts.set( a, str.substring( 0, str.length() - 1 ) +
732
 
                                                character + parts.get( a + 1 ) );
733
 
                                        parts.remove( a + 1 );
734
 
 
735
 
                                        // re-visit this part
736
 
                                        a--;
737
 
                                        continue;
738
 
                                }
739
 
 
740
 
                                // trim and replace string
741
 
                                str = str.trim();
742
 
                                parts.set( a, str );
743
 
                        }
744
 
 
745
 
                        String[] ret = new String[ parts.size() ];
746
 
                        return parts.toArray( ret );
747
 
                }
748
 
 
749
 
                private String unescapeValue( String value )
750
 
                {
751
 
                        StringBuilder ret = new StringBuilder( value.length() );
752
 
                        boolean in_escape = false;
753
 
                        for( int a = 0; a < value.length(); a++ )
754
 
                        {
755
 
                                int c = value.codePointAt( a );
756
 
 
757
 
                                // process a normal character
758
 
                                if( !in_escape ) {
759
 
                                        if( c == '\\' )
760
 
                                                in_escape = true;
761
 
                                        else
762
 
                                                ret.append( Character.toChars( c ) );
763
 
                                        continue;
764
 
                                }
765
 
 
766
 
                                // process an escape sequence
767
 
                                in_escape = false;
768
 
                                switch( c )
769
 
                                {
770
 
                                case 'T':
771
 
                                case 't':
772
 
                                        // add tab (invalid/non-standard, but accepted)
773
 
                                        ret.append( '\t' );
774
 
                                        break;
775
 
                                case 'N':
776
 
                                case 'n':
777
 
                                        // add newline
778
 
                                        ret.append( '\n' );
779
 
                                        break;
780
 
                                case '\\':
781
 
                                case ',':
782
 
                                case ';':
783
 
                                        // add escaped character
784
 
                                        ret.append( Character.toChars( c ) );
785
 
                                        break;
786
 
                                default:
787
 
                                        // unknown escape sequence, so add it unescaped
788
 
                                        // (invalid/non-standard, but accepted)
789
 
                                        ret.append( "\\" );
790
 
                                        ret.append( Character.toChars( c ) );
791
 
                                        break;
792
 
                                }
793
 
                        }
794
 
 
795
 
                        return ret.toString();
 
422
                                if( params[ 0 ].equals( "N" ) )
 
423
                                        parseN( params, value );
 
424
                                else if( params[ 0 ].equals( "FN" ) )
 
425
                                        parseFN( params, value );
 
426
                                else if( params[ 0 ].equals( "ORG" ) )
 
427
                                        parseORG( params, value );
 
428
                                else if( params[ 0 ].equals( "TEL" ) )
 
429
                                        parseTEL( params, value );
 
430
                                else if( params[ 0 ].equals( "EMAIL" ) )
 
431
                                        parseEMAIL( params, value );
 
432
                        }
796
433
                }
797
434
 
798
435
                private void parseN( String[] params, String value )
 
436
                                throws ParseException, SkipContactException,
 
437
                                AbortImportException
799
438
                {
800
439
                        // already got a better name?
801
440
                        if( _name_level >= NAMELEVEL_N ) return;
802
441
 
803
442
                        // get name parts
804
 
                        String[] name_parts = splitValueByCharacter( value, ';' );
 
443
                        String[] nameparts = value.split( ";" );
 
444
                        for( int i = 0; i < nameparts.length; i++ )
 
445
                                nameparts[ i ] = nameparts[ i ].trim();
805
446
 
806
447
                        // build name
807
448
                        value = "";
808
 
                        final int[] part_order = { 3, 1, 2, 0, 4 };
809
 
                        for( int a = 0; a < part_order.length; a++ )
810
 
                                if( name_parts.length > part_order[ a ] &&
811
 
                                        name_parts[ part_order[ a ] ].length() > 0 )
812
 
                                {
813
 
                                        // split this part in to it's comma-separated bits
814
 
                                        String[] name_part_parts = splitValueByCharacter(
815
 
                                                name_parts[ part_order[ a ] ], ',' );
816
 
                                        for( int b = 0; b < name_part_parts.length; b++ )
817
 
                                                if( name_part_parts[ b ].length() > 0 )
818
 
                                                {
819
 
                                                        if( value.length() == 0 ) value += " ";
820
 
                                                        value += name_part_parts[ b ];
821
 
                                                }
822
 
                                }
 
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 ];
823
453
 
824
454
                        // set name
825
 
                        setName( unescapeValue( value ) );
 
455
                        setName( value );
826
456
                        _name_level = NAMELEVEL_N;
 
457
 
 
458
                        // check now to see if we need to import this contact (to avoid
 
459
                        // parsing the rest of the vCard unnecessarily)
 
460
                        if( !isImportRequired( getName() ) )
 
461
                                throw new SkipContactException();
827
462
                }
828
463
 
829
464
                private void parseFN( String[] params, String value )
 
465
                                throws ParseException, SkipContactException
830
466
                {
831
467
                        // already got a better name?
832
468
                        if( _name_level >= NAMELEVEL_FN ) return;
833
469
 
834
470
                        // set name
835
 
                        setName( unescapeValue( value ) );
 
471
                        setName( value );
836
472
                        _name_level = NAMELEVEL_FN;
837
473
                }
838
474
 
839
475
                private void parseORG( String[] params, String value )
 
476
                                throws ParseException, SkipContactException
840
477
                {
 
478
                        // already got a better name?
 
479
                        if( _name_level >= NAMELEVEL_ORG ) return;
 
480
 
841
481
                        // get org parts
842
 
                        String[] org_parts = splitValueByCharacter( value, ';' );
843
 
                        if( org_parts == null || org_parts.length < 1 ) return;
844
 
 
845
 
                        // build organisation name
846
 
                        StringBuilder builder = new StringBuilder(
847
 
                                String.valueOf( org_parts[ 0 ] ) );
848
 
                        for( int a = 1; a < org_parts.length; a++ )
849
 
                                builder.append( ", " ).append( org_parts[ a ] );
850
 
                        String organisation = unescapeValue( builder.toString() );
851
 
 
852
 
                        // set organisation name (using a title we've previously found)
853
 
                        addOrganisation( organisation, _cached_title, true );
854
 
 
855
 
                        // if we've not previously found a title, store this organisation
856
 
                        // name (we'll need it when we find a title to update the
857
 
                        // organisation, by name), else if we *have* previously found a
858
 
                        // title, clear it (since we just used it)
859
 
                        if( _cached_title == null )
860
 
                                _cached_organisation = organisation;
861
 
                        else
862
 
                                _cached_title = null;
863
 
                }
864
 
 
865
 
                private void parseTITLE( String[] params, String value )
866
 
                {
867
 
                        value = unescapeValue( value );
868
 
 
869
 
                        // if we previously had an organisation, look it up and append this
870
 
                        // title to it
871
 
                        if( _cached_organisation != null && hasOrganisations() ) {
872
 
                                HashMap< String, ExtraDetail > datas = getOrganisations();
873
 
                                ExtraDetail detail = datas.get( _cached_organisation );
874
 
                                if( detail != null )
875
 
                                        detail.setExtra( value );
876
 
                        }
877
 
 
878
 
                        // same as when handling organisation, if we've not previously found
879
 
                        // an organisation we store this title, else we clear it (since we
880
 
                        // just appended this title to it)
881
 
                        if( _cached_organisation == null )
882
 
                                _cached_title = value;
883
 
                        else
884
 
                                _cached_organisation = null;
 
482
                        String[] orgparts = value.split( ";" );
 
483
                        for( int i = 0; i < orgparts.length; i++ )
 
484
                                orgparts[ i ] = orgparts[ i ].trim();
 
485
 
 
486
                        // build name
 
487
                        if( orgparts[ 0 ].length() == 0 && orgparts.length > 1 )
 
488
                                value = orgparts[ 1 ];
 
489
                        else
 
490
                                value = orgparts[ 0 ];
 
491
 
 
492
                        // set name
 
493
                        setName( value );
 
494
                        _name_level = NAMELEVEL_ORG;
885
495
                }
886
496
 
887
497
                private void parseTEL( String[] params, String value )
 
498
                                throws ParseException
888
499
                {
889
500
                        if( value.length() == 0 ) return;
890
501
 
891
502
                        Set< String > types = extractTypes( params, Arrays.asList(
892
 
                                "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
893
 
                                "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
 
503
                                        "PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
 
504
                                        "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );
894
505
 
895
506
                        // here's the logic...
896
 
                        boolean is_preferred = types.contains( "PREF" );
897
 
                        int type;
 
507
                        boolean preferred = types.contains( "PREF" );
 
508
                        if( types.contains( "VOICE" ) )
 
509
                                if( types.contains( "WORK" ) )
 
510
                                        addPhone( value, PhonesColumns.TYPE_WORK, preferred );
 
511
                                else
 
512
                                        addPhone( value, PhonesColumns.TYPE_HOME, preferred );
 
513
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
 
514
                                addPhone( value, PhonesColumns.TYPE_MOBILE, preferred );
898
515
                        if( types.contains( "FAX" ) )
899
516
                                if( types.contains( "HOME" ) )
900
 
                                        type = TYPE_FAX_HOME;
 
517
                                        addPhone( value, PhonesColumns.TYPE_FAX_HOME, preferred );
901
518
                                else
902
 
                                        type = TYPE_FAX_WORK;
903
 
                        else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
904
 
                                type = TYPE_MOBILE;
905
 
                        else if( types.contains( "PAGER" ) )
906
 
                                type = TYPE_PAGER;
907
 
                        else if( types.contains( "WORK" ) )
908
 
                                type = TYPE_WORK;
909
 
                        else
910
 
                                type = TYPE_HOME;
911
 
 
912
 
                        // add phone number
913
 
                        addNumber( value, type, is_preferred );
 
519
                                        addPhone( value, PhonesColumns.TYPE_FAX_WORK, preferred );
 
520
                        if( types.contains( "PAGER" ) )
 
521
                                addPhone( value, PhonesColumns.TYPE_PAGER, preferred );
914
522
                }
915
523
 
916
524
                public void parseEMAIL( String[] params, String value )
 
525
                                throws ParseException
917
526
                {
918
527
                        if( value.length() == 0 ) return;
919
528
 
920
529
                        Set< String > types = extractTypes( params, Arrays.asList(
921
 
                                "PREF", "WORK", "HOME", "INTERNET" ) );
922
 
 
923
 
                        // add email address
924
 
                        boolean is_preferred = types.contains( "PREF" );
925
 
                        int type;
926
 
                        if( types.contains( "WORK" ) )
927
 
                                type = TYPE_WORK;
928
 
                        else
929
 
                                type = TYPE_HOME;
930
 
 
931
 
                        addEmail( unescapeValue( value ), type, is_preferred );
932
 
                }
933
 
 
934
 
                private void parseADR( String[] params, String value )
935
 
                {
936
 
                        // get address parts
937
 
                        String[] adr_parts = splitValueByCharacter( value, ';' );
938
 
 
939
 
                        // build address
940
 
                        value = "";
941
 
                        for( int a = 0; a < adr_parts.length; a++ )
942
 
                                if( adr_parts[ a ].length() > 0 )
943
 
                                {
944
 
                                        // version 3.0 vCards allow further splitting by comma
945
 
                                        if( _version.equals( "3.0" ) )
946
 
                                        {
947
 
                                                // split this part in to it's comma-separated bits and
948
 
                                                // add them on individual lines
949
 
                                                String[] adr_part_parts =
950
 
                                                        splitValueByCharacter( adr_parts[ a ], ',' );
951
 
                                                for( int b = 0; b < adr_part_parts.length; b++ )
952
 
                                                        if( adr_part_parts[ b ].length() > 0 )
953
 
                                                        {
954
 
                                                                if( value.length() > 0 ) value += "\n";
955
 
                                                                value += adr_part_parts[ b ];
956
 
                                                        }
957
 
                                        }
958
 
                                        else
959
 
                                        {
960
 
                                                // add this part on an individual line
961
 
                                                if( value.length() > 0 ) value += "\n";
962
 
                                                value += adr_parts[ a ];
963
 
                                        }
964
 
                                }
965
 
 
966
 
                        Set< String > types = extractTypes( params, Arrays.asList(
967
 
                                "PREF", "WORK", "HOME" ) );
968
 
 
969
 
                        // add address
970
 
                        int type;
971
 
                        if( types.contains( "WORK" ) )
972
 
                                type = TYPE_WORK;
973
 
                        else
974
 
                                type = TYPE_HOME;
975
 
 
976
 
                        addAddress( unescapeValue( value ), type );
977
 
                }
978
 
 
979
 
                private void parseLABEL( String[] params, String value )
980
 
                {
981
 
                        Set< String > types = extractTypes( params, Arrays.asList(
982
 
                                "PREF", "WORK", "HOME" ) );
983
 
 
984
 
                        // add address
985
 
                        int type;
986
 
                        if( types.contains( "WORK" ) )
987
 
                                type = TYPE_WORK;
988
 
                        else
989
 
                                type = TYPE_HOME;
990
 
 
991
 
                        addAddress( unescapeValue( value ), type );
992
 
                }
993
 
 
994
 
                private void parseNOTE( String[] params, String value )
995
 
                {
996
 
                        addNote( unescapeValue( value ) );
997
 
                }
998
 
 
999
 
                public void finaliseVcard()
1000
 
                        throws ParseException, ContactNotIdentifiableException
 
530
                                        "PREF", "WORK", "HOME", "INTERNET" ) );
 
531
 
 
532
                        // here's the logic...
 
533
                        boolean preferred = types.contains( "PREF" );
 
534
                        if( types.contains( "WORK" ) )
 
535
                                addEmail( value, Contacts.ContactMethods.TYPE_WORK, preferred );
 
536
                        else
 
537
                                addEmail( value, Contacts.ContactMethods.TYPE_HOME, preferred );
 
538
                }
 
539
 
 
540
                public void finaliseParsing()
 
541
                                throws ParseException, SkipContactException,
 
542
                                AbortImportException
1001
543
                {
1002
544
                        // missing version (and data is present)
1003
 
                        if( _version == null && _buffers != null )
 
545
                        if( _version == null && _lines != null )
1004
546
                                throw new ParseException( R.string.error_vcf_malformed );
1005
547
 
1006
 
                        // finalise the parent class
1007
 
                        finalise();
 
548
                        //  missing name properties?
 
549
                        if( _name_level == NAMELEVEL_NONE )
 
550
                                throw new ParseException( R.string.error_vcf_noname );
 
551
 
 
552
                        // check if we should import this one? If we've already got an 'N'-
 
553
                        // type name, this will already have been done by parseN() so we
 
554
                        // mustn't do this here (or it could prompt twice!)
 
555
                        if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
 
556
                                throw new SkipContactException();
1008
557
                }
1009
558
 
1010
 
                /**
1011
 
                 * Amongst the params, find the value of the first, only, of any with
1012
 
                 * the specified name
1013
 
                 * @param params
1014
 
                 * @param name
1015
 
                 * @return a value, or null
1016
 
                 */
1017
559
                private String checkParam( String[] params, String name )
1018
560
                {
1019
 
                        String[] res = checkParams( params, name );
1020
 
                        return res.length > 0? res[ 0 ] : null;
1021
 
                }
1022
 
 
1023
 
                /**
1024
 
                 * Amongst the params, find the values of any with the specified name
1025
 
                 * @param params
1026
 
                 * @param name
1027
 
                 * @return an array of values, or null
1028
 
                 */
1029
 
                private String[] checkParams( String[] params, String name )
1030
 
                {
1031
 
                        HashSet< String > ret = new HashSet< String >();
1032
 
 
1033
 
                        Pattern p = Pattern.compile(
1034
 
                                "^" + name + "[ \\t]*=[ \\t]*(\"?)(.*)\\1$",
1035
 
                                Pattern.CASE_INSENSITIVE );
 
561
                        Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
1036
562
                        for( int i = 0; i < params.length; i++ ) {
1037
563
                                Matcher m = p.matcher( params[ i ] );
1038
564
                                if( m.matches() )
1039
 
                                        ret.add( m.group( 2 ) );
 
565
                                        return m.group( 1 );
1040
566
                        }
1041
 
 
1042
 
                        return (String[]) ret.toArray( new String[ ret.size() ] );
 
567
                        return null;
1043
568
                }
1044
569
 
1045
 
                /**
1046
 
                 * Amongst the params, return any type values present. For v2.1 vCards,
1047
 
                 * those types are just parameters. For v3.0, they are prefixed with
1048
 
                 * "TYPE=". There may also be multiple type parameters.
1049
 
                 * @param params an array of params to look for types in
1050
 
                 * @param valid_types an list of upper-case type values to look for
1051
 
                 * @return a set of present type values
1052
 
                 */
1053
570
                private Set< String > extractTypes( String[] params,
1054
 
                        List< String > valid_types )
 
571
                                List< String > validTypes )
1055
572
                {
1056
573
                        HashSet< String > types = new HashSet< String >();
1057
574
 
1058
575
                        // get 3.0-style TYPE= param
1059
 
                        String type_params[] = checkParams( params, "TYPE" );
1060
 
                        for( int a = 0; a < type_params.length; a++ )
1061
 
                        {
1062
 
                                // check for a comma-separated list of types (why? this isn't in
1063
 
                                // the specs!)
1064
 
                                String[] parts = type_params[ a ].split( "," );
1065
 
                                for( int i = 0; i < parts.length; i++ )
1066
 
                                        parts[ i ] = parts[ i ].toUpperCase( Locale.US );
1067
 
                                for( int i = 0; i < parts.length; i++ )
1068
 
                                        if( valid_types.contains( parts[ i ] ) )
1069
 
                                                types.add( parts[ i ] );
 
576
                        String typeParam;
 
577
                        if( ( typeParam = checkParam( params, "TYPE" ) ) != null ) {
 
578
                                String[] bits = typeParam.split( "," );
 
579
                                for( int i = 0; i < bits.length; i++ )
 
580
                                        if( validTypes.contains( bits[ i ] ) )
 
581
                                                types.add( bits[ i ] );
1070
582
                        }
1071
583
 
1072
584
                        // get 2.1-style type param
1073
585
                        if( _version.equals( "2.1" ) ) {
1074
586
                                for( int i = 1; i < params.length; i++ )
1075
 
                                        if( valid_types.contains( params[ i ] ) )
 
587
                                        if( validTypes.contains( params[ i ] ) )
1076
588
                                                types.add( params[ i ] );
1077
589
                        }
1078
590
 
1079
591
                        return types;
1080
592
                }
1081
593
 
1082
 
                private UnencodeResult unencodeQuotedPrintable( ByteBuffer in )
 
594
                private UnencodeResult unencodeQuotedPrintable( String str, String charset )
1083
595
                {
1084
596
                        boolean another = false;
1085
597
 
1086
 
                        // unencode quoted-printable encoding, as per RFC1521 section 5.1
1087
 
                        byte[] out = new byte[ in.limit() - in.position() ];
 
598
                        // default encoding scheme
 
599
                        if( charset == null ) charset = "UTF-8";
 
600
 
 
601
                        // unencode quoted-pritable encoding, as per RFC1521 section 5.1
 
602
                        byte[] bytes = new byte[ str.length() ];
1088
603
                        int j = 0;
1089
 
                        for( int i = in.position(); i < in.limit(); i++ )
 
604
                        for( int i = 0; i < str.length(); i++ )
1090
605
                        {
1091
606
                                // get next char and process...
1092
 
                                byte ch = in.array()[ i ];
1093
 
                                if( ch == '=' && i < in.limit() - 2 )
 
607
                                char ch = str.charAt( i );
 
608
                                if( ch == '=' && i < str.length() - 2 )
1094
609
                                {
1095
610
                                        // we found a =XX format byte, add it
1096
 
                                        out[ j ] = (byte)(
1097
 
                                                        Character.digit( in.array()[ i + 1 ], 16 ) * 16 +
1098
 
                                                        Character.digit( in.array()[ i + 2 ], 16 ) );
 
611
                                        bytes[ j ] = (byte)(
 
612
                                                        Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
 
613
                                                        Character.digit( str.charAt( i + 2 ), 16 ) );
1099
614
                                        i += 2;
1100
615
                                }
1101
 
                                else if( ch == '=' && i == in.limit() - 1 )
 
616
                                else if( ch == '=' && i == str.length() - 1 )
1102
617
                                {
1103
618
                                        // we found a '=' at the end of a line signifying a multi-
1104
619
                                        // line string, so we don't add it.
1107
622
                                }
1108
623
                                else
1109
624
                                        // just a normal char...
1110
 
                                        out[ j ] = (byte)ch;
 
625
                                        bytes[ j ] = (byte)ch;
1111
626
                                j++;
1112
627
                        }
1113
628
 
1114
 
                        return new UnencodeResult( another, ByteBuffer.wrap( out, 0, j ) );
1115
 
                }
1116
 
 
1117
 
                private ByteBuffer transcodeAsciiToUtf8( ByteBuffer in )
1118
 
                {
1119
 
                        // transcode
1120
 
                        byte[] out = new byte[ ( in.limit() - in.position() ) * 2 ];
1121
 
                        int j = 0;
1122
 
                        for( int a = in.position(); a < in.limit(); a++ )
1123
 
                        {
1124
 
                                // if char is < 127, keep it as-is
1125
 
                                if( in.array()[ a ] >= 0 )
1126
 
                                        out[ j++ ] = in.array()[ a ];
1127
 
 
1128
 
                                // else, convert it to UTF-8
1129
 
                                else {
1130
 
                                        int b = 0xff & (int)in.array()[ a ];
1131
 
                                        out[ j++ ] = (byte)( 0xc0 | ( b >> 6 ) );
1132
 
                                        out[ j++ ] = (byte)( 0x80 | ( b & 0x3f ) );
1133
 
                                }
1134
 
                        }
1135
 
 
1136
 
                        return ByteBuffer.wrap( out, 0, j );
 
629
                        return new UnencodeResult( another, bytes, j );
1137
630
                }
1138
631
        }
1139
632
}