/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

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;
38
38
import java.util.regex.Matcher;
39
39
import java.util.regex.Pattern;
40
40
 
41
 
import org.waxworlds.importcontacts.Importer.AbortImportException;
42
 
 
43
41
import android.content.SharedPreferences;
44
42
import android.provider.Contacts;
45
43
import android.provider.Contacts.PhonesColumns;
67
65
                try
68
66
                {
69
67
                        // open directory
70
 
                        String location = prefs.getString( "location", "" );
71
 
                        File dir = new File( location );
72
 
                        if( !dir.exists() || !dir.isDirectory() )
 
68
                        String path = "/sdcard" + prefs.getString( "location", "/" );
 
69
                        File file = new File( path );
 
70
                        if( !file.exists() )
73
71
                                showError( R.string.error_locationnotfound );
74
72
 
75
 
                        // get files
76
 
                        class VCardFilter implements FilenameFilter {
77
 
                                public boolean accept( File dir, String name ) {
78
 
                                        return name.toLowerCase().endsWith( ".vcf" );
 
73
                        // directory, or file?
 
74
                        if( file.isDirectory() )
 
75
                        {
 
76
                                // get files
 
77
                                class VCardFilter implements FilenameFilter {
 
78
                                        public boolean accept( File dir, String name ) {
 
79
                                                return name.toLowerCase().endsWith( ".vcf" );
 
80
                                        }
79
81
                                }
80
 
                        }
81
 
                        files = dir.listFiles( new VCardFilter() );
 
82
                                files = file.listFiles( new VCardFilter() );
 
83
                        }
 
84
                        else
 
85
                        {
 
86
                                // use just this file
 
87
                                files = new File[ 1 ];
 
88
                                files[ 0 ] = file;
 
89
                        }
82
90
                }
83
91
                catch( SecurityException e ) {
84
92
                        showError( R.string.error_locationpermissions );
130
138
 
131
139
                }
132
140
                catch( FileNotFoundException e ) {
133
 
                        showError( getText( R.string.error_filenotfound ) + file.getName() );
 
141
                        showError( getText( R.string.error_filenotfound ) +
 
142
                                file.getName() );
134
143
                }
135
144
                catch( IOException e ) {
136
145
                        showError( getText( R.string.error_ioerror ) + file.getName() );
154
163
                        importVCardFileContent( content.toString(), file.getName() );
155
164
                }
156
165
                catch( FileNotFoundException e ) {
157
 
                        showError( getText( R.string.error_filenotfound ) + file.getName() );
 
166
                        showError( getText( R.string.error_filenotfound ) +
 
167
                                file.getName() );
158
168
                }
159
169
                catch( IOException e ) {
160
170
                        showError( getText( R.string.error_ioerror ) + file.getName() );
164
174
        private void importVCardFileContent( String content, String fileName )
165
175
                        throws AbortImportException
166
176
        {
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
177
                // get lines and parse them
174
178
                String[] lines = content.split( "\n" );
175
179
                VCard vCard = null;
244
248
 
245
249
                private String _version = null;
246
250
                private Vector< String > _lines = null;
247
 
                private int _nameLevel = NAMELEVEL_NONE;
248
 
 
 
251
                private int _name_level = NAMELEVEL_NONE;
 
252
                private boolean _parser_in_multiline = false;
 
253
                private String _parser_current_name_and_params = null;
 
254
                private String _parser_buffered_value_so_far = "";
 
255
 
 
256
                protected class UnencodeResult
 
257
                {
 
258
                        private boolean _another_line_required;
 
259
                        private byte[] _bytes;
 
260
                        private int _num_bytes;
 
261
 
 
262
                        public UnencodeResult( boolean another_line_required, byte[] bytes,
 
263
                                int num_bytes )
 
264
                        {
 
265
                                _another_line_required = another_line_required;
 
266
                                _bytes = bytes;
 
267
                                _num_bytes = num_bytes;
 
268
                        }
 
269
 
 
270
                        public boolean isAnotherLineRequired()
 
271
                        {
 
272
                                return _another_line_required;
 
273
                        }
 
274
 
 
275
                        public byte[] getBytes()
 
276
                        {
 
277
                                return _bytes;
 
278
                        }
 
279
 
 
280
                        public int getNumBytes()
 
281
                        {
 
282
                                return _num_bytes;
 
283
                        }
 
284
                }
 
285
 
 
286
                @SuppressWarnings("serial")
249
287
                protected class ParseException extends Exception
250
288
                {
 
289
                        @SuppressWarnings("unused")
251
290
                        public ParseException( String error )
252
291
                        {
253
292
                                super( error );
259
298
                        }
260
299
                }
261
300
 
 
301
                @SuppressWarnings("serial")
262
302
                protected class SkipContactException extends Exception { }
263
303
 
264
304
                public void parseLine( String line )
265
305
                                throws ParseException, SkipContactException,
266
306
                                AbortImportException
267
307
                {
268
 
                        // get property halves
269
 
                        String[] props = line.split( ":" );
 
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 );
270
316
                        for( int i = 0; i < props.length; i++ )
271
317
                                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
318
 
 
319
                        // if we haven't yet got a version, we won't be paring anything!
276
320
                        if( _version == null )
277
321
                        {
278
 
                                if( props[ 0 ].equals( "VERSION" ) )
 
322
                                // is this a version?
 
323
                                if( props.length == 2 && props[ 0 ].equals( "VERSION" ) )
279
324
                                {
280
 
                                        // get version
 
325
                                        // yes, check/store it
281
326
                                        if( !props[ 1 ].equals( "2.1" ) &&
282
327
                                                        !props[ 1 ].equals( "3.0" ) )
283
328
                                                throw new ParseException( R.string.error_vcf_version );
291
336
                                }
292
337
                                else
293
338
                                {
294
 
                                        // stash this line till we have a version
 
339
                                        // no, so stash this line till we have a version
295
340
                                        if( _lines == null )
296
341
                                                _lines = new Vector< String >();
297
342
                                        _lines.add( line );
299
344
                        }
300
345
                        else
301
346
                        {
 
347
                                if( _parser_in_multiline )
 
348
                                {
 
349
                                        // if we're currently in a multi-line value, use the stored
 
350
                                        // property name and parameters
 
351
                                        props = new String[ 2 ];
 
352
                                        props[ 0 ] = _parser_current_name_and_params;
 
353
                                        props[ 1 ] = line.trim();
 
354
                                }
 
355
                                else
 
356
                                {
 
357
                                        // for normal lines, check the property name/value bits
 
358
                                        if( props.length < 2 || props[ 0 ].length() == 0 )
 
359
                                                throw new ParseException(
 
360
                                                        R.string.error_vcf_malformed );
 
361
 
 
362
                                        // ignore empty properties
 
363
                                        if( props[ 1 ].length() < 1 )
 
364
                                                return;
 
365
 
 
366
                                        // reset the saved multi-line state
 
367
                                        _parser_current_name_and_params = props[ 0 ];
 
368
                                        _parser_buffered_value_so_far = "";
 
369
                                }
 
370
 
302
371
                                // get parameter parts
303
372
                                String[] params = props[ 0 ].split( ";" );
304
373
                                for( int i = 0; i < params.length; i++ )
305
374
                                        params[ i ] = params[ i ].trim();
306
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" ) )
 
387
                                {
 
388
                                        throw new ParseException( R.string.error_vcf_encoding );
 
389
                                }
 
390
 
 
391
                                // do unencoding (or default to a fake unencoding result with
 
392
                                // the raw string)
 
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
 
403
                                try {
 
404
                                        props[ 1 ] = new String( result.getBytes(), 0,
 
405
                                                result.getNumBytes(),
 
406
                                                charset == null? "UTF-8" : charset );
 
407
                                } catch( UnsupportedEncodingException e ) {
 
408
                                        throw new ParseException( R.string.error_vcf_charset );
 
409
                                }
 
410
 
 
411
                                // handle multi-line requests
 
412
                                _parser_in_multiline = result.isAnotherLineRequired();
 
413
                                if( _parser_in_multiline ) {
 
414
                                        _parser_buffered_value_so_far += props[ 1 ];
 
415
                                        return;
 
416
                                }
 
417
 
 
418
                                // add on buffered multi-line content
 
419
                                String value = _parser_buffered_value_so_far + props[ 1 ];
 
420
 
307
421
                                // parse some properties
308
422
                                if( params[ 0 ].equals( "N" ) )
309
 
                                        parseN( params, props[ 1 ] );
 
423
                                        parseN( params, value );
310
424
                                else if( params[ 0 ].equals( "FN" ) )
311
 
                                        parseFN( params, props[ 1 ] );
 
425
                                        parseFN( params, value );
312
426
                                else if( params[ 0 ].equals( "ORG" ) )
313
 
                                        parseORG( params, props[ 1 ] );
 
427
                                        parseORG( params, value );
314
428
                                else if( params[ 0 ].equals( "TEL" ) )
315
 
                                        parseTEL( params, props[ 1 ] );
 
429
                                        parseTEL( params, value );
316
430
                                else if( params[ 0 ].equals( "EMAIL" ) )
317
 
                                        parseEMAIL( params, props[ 1 ] );
 
431
                                        parseEMAIL( params, value );
318
432
                        }
319
433
                }
320
434
 
323
437
                                AbortImportException
324
438
                {
325
439
                        // already got a better name?
326
 
                        if( _nameLevel >= NAMELEVEL_N ) return;
 
440
                        if( _name_level >= NAMELEVEL_N ) return;
327
441
 
328
442
                        // get name parts
329
443
                        String[] nameparts = value.split( ";" );
338
452
                                value += ( value.length() == 0? "" : " " ) + nameparts[ 0 ];
339
453
 
340
454
                        // set name
341
 
                        setName( undoCharsetAndEncoding( params, value ) );
342
 
                        _nameLevel = NAMELEVEL_N;
 
455
                        setName( value );
 
456
                        _name_level = NAMELEVEL_N;
343
457
 
344
458
                        // check now to see if we need to import this contact (to avoid
345
459
                        // parsing the rest of the vCard unnecessarily)
351
465
                                throws ParseException, SkipContactException
352
466
                {
353
467
                        // already got a better name?
354
 
                        if( _nameLevel >= NAMELEVEL_FN ) return;
 
468
                        if( _name_level >= NAMELEVEL_FN ) return;
355
469
 
356
470
                        // set name
357
 
                        setName( undoCharsetAndEncoding( params, value ) );
358
 
                        _nameLevel = NAMELEVEL_FN;
 
471
                        setName( value );
 
472
                        _name_level = NAMELEVEL_FN;
359
473
                }
360
474
 
361
475
                private void parseORG( String[] params, String value )
362
476
                                throws ParseException, SkipContactException
363
477
                {
364
478
                        // already got a better name?
365
 
                        if( _nameLevel >= NAMELEVEL_ORG ) return;
 
479
                        if( _name_level >= NAMELEVEL_ORG ) return;
366
480
 
367
481
                        // get org parts
368
482
                        String[] orgparts = value.split( ";" );
376
490
                                value = orgparts[ 0 ];
377
491
 
378
492
                        // set name
379
 
                        setName( undoCharsetAndEncoding( params, value ) );
380
 
                        _nameLevel = NAMELEVEL_ORG;
 
493
                        setName( value );
 
494
                        _name_level = NAMELEVEL_ORG;
381
495
                }
382
496
 
383
497
                private void parseTEL( String[] params, String value )
408
522
                }
409
523
 
410
524
                public void parseEMAIL( String[] params, String value )
 
525
                                throws ParseException
411
526
                {
412
527
                        if( value.length() == 0 ) return;
413
528
 
431
546
                                throw new ParseException( R.string.error_vcf_malformed );
432
547
 
433
548
                        //  missing name properties?
434
 
                        if( _nameLevel == NAMELEVEL_NONE )
 
549
                        if( _name_level == NAMELEVEL_NONE )
435
550
                                throw new ParseException( R.string.error_vcf_noname );
436
551
 
437
552
                        // check if we should import this one? If we've already got an 'N'-
438
553
                        // type name, this will already have been done by parseN() so we
439
554
                        // mustn't do this here (or it could prompt twice!)
440
 
                        if( _nameLevel < NAMELEVEL_N && !isImportRequired( getName() ) )
 
555
                        if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
441
556
                                throw new SkipContactException();
442
557
                }
443
558
 
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
559
                private String checkParam( String[] params, String name )
465
560
                {
466
561
                        Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
496
591
                        return types;
497
592
                }
498
593
 
499
 
                private String unencodeQuotedPrintable( String str, String charset )
 
594
                private UnencodeResult unencodeQuotedPrintable( String str, String charset )
500
595
                {
 
596
                        boolean another = false;
 
597
 
501
598
                        // default encoding scheme
502
599
                        if( charset == null ) charset = "UTF-8";
503
600
 
504
601
                        // unencode quoted-pritable encoding, as per RFC1521 section 5.1
505
602
                        byte[] bytes = new byte[ str.length() ];
506
603
                        int j = 0;
507
 
                        for( int i = 0; i < str.length(); i++, j++ ) {
 
604
                        for( int i = 0; i < str.length(); i++ )
 
605
                        {
 
606
                                // get next char and process...
508
607
                                char ch = str.charAt( i );
509
 
                                if( ch == '=' && i < str.length() - 2 ) {
 
608
                                if( ch == '=' && i < str.length() - 2 )
 
609
                                {
 
610
                                        // we found a =XX format byte, add it
510
611
                                        bytes[ j ] = (byte)(
511
612
                                                        Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
512
613
                                                        Character.digit( str.charAt( i + 2 ), 16 ) );
513
614
                                        i += 2;
514
615
                                }
 
616
                                else if( ch == '=' && i == str.length() - 1 )
 
617
                                {
 
618
                                        // we found a '=' at the end of a line signifying a multi-
 
619
                                        // line string, so we don't add it.
 
620
                                        another = true;
 
621
                                        continue;
 
622
                                }
515
623
                                else
 
624
                                        // just a normal char...
516
625
                                        bytes[ j ] = (byte)ch;
 
626
                                j++;
517
627
                        }
518
 
                        try {
519
 
                                return new String( bytes, 0, j, charset );
520
 
                        } catch( UnsupportedEncodingException e ) { }
521
 
                        return null;
 
628
 
 
629
                        return new UnencodeResult( another, bytes, j );
522
630
                }
523
631
        }
524
632
}