/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/importcontacts/VCFImporter.java

  • Committer: edam
  • Date: 2009-01-11 13:00:10 UTC
  • Revision ID: edam@waxworlds.org-20090111130010-rf7ahtdf01mcnkdg
- updated todo list

Show diffs side-by-side

added added

removed removed

1
 
/*
2
 
 * VCFImporter.java
3
 
 *
4
 
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
5
 
 *
6
 
 * This file is part of the Import Contacts program (hereafter referred
7
 
 * to as "this program"). For more information, see
8
 
 * http://www.waxworlds.org/edam/software/android/import-contacts
9
 
 *
10
 
 * This program is free software: you can redistribute it and/or modify
11
 
 * it under the terms of the GNU General Public License as published by
12
 
 * the Free Software Foundation, either version 3 of the License, or
13
 
 * (at your option) any later version.
14
 
 *
15
 
 * This program is distributed in the hope that it will be useful,
16
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 
 * GNU General Public License for more details.
19
 
 *
20
 
 * You should have received a copy of the GNU General Public License
21
 
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 
 */
23
 
 
24
 
package org.waxworlds.edam.importcontacts;
 
1
package org.waxworlds.importcontacts;
25
2
 
26
3
import java.io.BufferedReader;
27
4
import java.io.File;
38
15
import java.util.regex.Matcher;
39
16
import java.util.regex.Pattern;
40
17
 
 
18
import org.waxworlds.importcontacts.Importer.AbortImportException;
 
19
 
41
20
import android.content.SharedPreferences;
42
21
import android.provider.Contacts;
43
22
import android.provider.Contacts.PhonesColumns;
65
44
                try
66
45
                {
67
46
                        // open directory
68
 
                        String path = "/sdcard" + prefs.getString( "location", "/" );
69
 
                        File file = new File( path );
70
 
                        if( !file.exists() )
 
47
                        String location = prefs.getString( "location", "" );
 
48
                        File dir = new File( location );
 
49
                        if( !dir.exists() || !dir.isDirectory() )
71
50
                                showError( R.string.error_locationnotfound );
72
51
 
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
 
                                        }
81
 
                                }
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
 
                        }
 
52
                        // get files
 
53
                        class VCardFilter implements FilenameFilter {
 
54
                            public boolean accept( File dir, String name ) {
 
55
                                return name.toLowerCase().endsWith( ".vcf" );
 
56
                            }
 
57
                        }
 
58
                        files = dir.listFiles( new VCardFilter() );
90
59
                }
91
60
                catch( SecurityException e ) {
92
61
                        showError( R.string.error_locationpermissions );
138
107
 
139
108
                }
140
109
                catch( FileNotFoundException e ) {
141
 
                        showError( getText( R.string.error_filenotfound ) +
142
 
                                file.getName() );
 
110
                        showError( getText( R.string.error_filenotfound ) + file.getName() );
143
111
                }
144
112
                catch( IOException e ) {
145
113
                        showError( getText( R.string.error_ioerror ) + file.getName() );
163
131
                        importVCardFileContent( content.toString(), file.getName() );
164
132
                }
165
133
                catch( FileNotFoundException e ) {
166
 
                        showError( getText( R.string.error_filenotfound ) +
167
 
                                file.getName() );
 
134
                        showError( getText( R.string.error_filenotfound ) + file.getName() );
168
135
                }
169
136
                catch( IOException e ) {
170
137
                        showError( getText( R.string.error_ioerror ) + file.getName() );
174
141
        private void importVCardFileContent( String content, String fileName )
175
142
                        throws AbortImportException
176
143
        {
 
144
                // unfold RFC2425 section 5.8.1 folded lines, except that we must also
 
145
                // handle embedded Quoted-Printable encodings that have a trailing '='.
 
146
                // So we remove these first before doing RFC2425 unfolding.
 
147
                content = content.replaceAll( "=\n[ \\t]", "" )
 
148
                                .replaceAll( "\n[ \\t]", "" );
 
149
 
177
150
                // get lines and parse them
178
151
                String[] lines = content.split( "\n" );
179
152
                VCard vCard = null;
248
221
 
249
222
                private String _version = null;
250
223
                private Vector< String > _lines = null;
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")
 
224
                private int _nameLevel = NAMELEVEL_NONE;
 
225
 
287
226
                protected class ParseException extends Exception
288
227
                {
289
 
                        @SuppressWarnings("unused")
290
228
                        public ParseException( String error )
291
229
                        {
292
230
                                super( error );
298
236
                        }
299
237
                }
300
238
 
301
 
                @SuppressWarnings("serial")
302
239
                protected class SkipContactException extends Exception { }
303
240
 
304
241
                public void parseLine( String line )
305
242
                                throws ParseException, SkipContactException,
306
243
                                AbortImportException
307
244
                {
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 );
 
245
                        // get property halves
 
246
                        String[] props = line.split( ":" );
316
247
                        for( int i = 0; i < props.length; i++ )
317
248
                                props[ i ] = props[ i ].trim();
 
249
                        if( props.length < 2 ||
 
250
                                        props[ 0 ].length() < 1 || props[ 1 ].length() < 1 )
 
251
                                throw new ParseException( R.string.error_vcf_malformed );
318
252
 
319
 
                        // if we haven't yet got a version, we won't be paring anything!
320
253
                        if( _version == null )
321
254
                        {
322
 
                                // is this a version?
323
 
                                if( props.length == 2 && props[ 0 ].equals( "VERSION" ) )
 
255
                                if( props[ 0 ].equals( "VERSION" ) )
324
256
                                {
325
 
                                        // yes, check/store it
 
257
                                        // get version
326
258
                                        if( !props[ 1 ].equals( "2.1" ) &&
327
259
                                                        !props[ 1 ].equals( "3.0" ) )
328
260
                                                throw new ParseException( R.string.error_vcf_version );
336
268
                                }
337
269
                                else
338
270
                                {
339
 
                                        // no, so stash this line till we have a version
 
271
                                        // stash this line till we have a version
340
272
                                        if( _lines == null )
341
273
                                                _lines = new Vector< String >();
342
274
                                        _lines.add( line );
344
276
                        }
345
277
                        else
346
278
                        {
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
 
 
371
279
                                // get parameter parts
372
280
                                String[] params = props[ 0 ].split( ";" );
373
281
                                for( int i = 0; i < params.length; i++ )
374
282
                                        params[ i ] = params[ i ].trim();
375
283
 
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
 
 
421
284
                                // parse some properties
422
285
                                if( params[ 0 ].equals( "N" ) )
423
 
                                        parseN( params, value );
 
286
                                        parseN( params, props[ 1 ] );
424
287
                                else if( params[ 0 ].equals( "FN" ) )
425
 
                                        parseFN( params, value );
 
288
                                        parseFN( params, props[ 1 ] );
426
289
                                else if( params[ 0 ].equals( "ORG" ) )
427
 
                                        parseORG( params, value );
 
290
                                        parseORG( params, props[ 1 ] );
428
291
                                else if( params[ 0 ].equals( "TEL" ) )
429
 
                                        parseTEL( params, value );
 
292
                                        parseTEL( params, props[ 1 ] );
430
293
                                else if( params[ 0 ].equals( "EMAIL" ) )
431
 
                                        parseEMAIL( params, value );
 
294
                                        parseEMAIL( params, props[ 1 ] );
432
295
                        }
433
296
                }
434
297
 
437
300
                                AbortImportException
438
301
                {
439
302
                        // already got a better name?
440
 
                        if( _name_level >= NAMELEVEL_N ) return;
 
303
                        if( _nameLevel >= NAMELEVEL_N ) return;
441
304
 
442
305
                        // get name parts
443
306
                        String[] nameparts = value.split( ";" );
452
315
                                value += ( value.length() == 0? "" : " " ) + nameparts[ 0 ];
453
316
 
454
317
                        // set name
455
 
                        setName( value );
456
 
                        _name_level = NAMELEVEL_N;
 
318
                        setName( undoCharsetAndEncoding( params, value ) );
 
319
                        _nameLevel = NAMELEVEL_N;
457
320
 
458
321
                        // check now to see if we need to import this contact (to avoid
459
322
                        // parsing the rest of the vCard unnecessarily)
465
328
                                throws ParseException, SkipContactException
466
329
                {
467
330
                        // already got a better name?
468
 
                        if( _name_level >= NAMELEVEL_FN ) return;
 
331
                        if( _nameLevel >= NAMELEVEL_FN ) return;
469
332
 
470
333
                        // set name
471
 
                        setName( value );
472
 
                        _name_level = NAMELEVEL_FN;
 
334
                        setName( undoCharsetAndEncoding( params, value ) );
 
335
                        _nameLevel = NAMELEVEL_FN;
473
336
                }
474
337
 
475
338
                private void parseORG( String[] params, String value )
476
339
                                throws ParseException, SkipContactException
477
340
                {
478
341
                        // already got a better name?
479
 
                        if( _name_level >= NAMELEVEL_ORG ) return;
 
342
                        if( _nameLevel >= NAMELEVEL_ORG ) return;
480
343
 
481
344
                        // get org parts
482
345
                        String[] orgparts = value.split( ";" );
490
353
                                value = orgparts[ 0 ];
491
354
 
492
355
                        // set name
493
 
                        setName( value );
494
 
                        _name_level = NAMELEVEL_ORG;
 
356
                        setName( undoCharsetAndEncoding( params, value ) );
 
357
                        _nameLevel = NAMELEVEL_ORG;
495
358
                }
496
359
 
497
360
                private void parseTEL( String[] params, String value )
522
385
                }
523
386
 
524
387
                public void parseEMAIL( String[] params, String value )
525
 
                                throws ParseException
526
388
                {
527
389
                        if( value.length() == 0 ) return;
528
390
 
546
408
                                throw new ParseException( R.string.error_vcf_malformed );
547
409
 
548
410
                        //  missing name properties?
549
 
                        if( _name_level == NAMELEVEL_NONE )
 
411
                        if( _nameLevel == NAMELEVEL_NONE )
550
412
                                throw new ParseException( R.string.error_vcf_noname );
551
413
 
552
414
                        // check if we should import this one? If we've already got an 'N'-
553
415
                        // type name, this will already have been done by parseN() so we
554
416
                        // mustn't do this here (or it could prompt twice!)
555
 
                        if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
 
417
                        if( _nameLevel < NAMELEVEL_N && !isImportRequired( getName() ) )
556
418
                                throw new SkipContactException();
557
419
                }
558
420
 
 
421
                private String undoCharsetAndEncoding( String[] params, String value )
 
422
                                throws ParseException
 
423
                {
 
424
                        // check encoding/charset
 
425
                        String charset, encoding;
 
426
                        if( ( charset = checkParam( params, "CHARSET" ) ) != null &&
 
427
                                        !charset.equals( "UTF-8" ) && !charset.equals( "UTF-16" ) )
 
428
                                throw new ParseException( R.string.error_vcf_charset );
 
429
                        if( ( encoding = checkParam( params, "ENCODING" ) ) != null &&
 
430
                                        !encoding.equals( "QUOTED-PRINTABLE" ) )
 
431
                                throw new ParseException( R.string.error_vcf_encoding );
 
432
 
 
433
                        // do decoding?
 
434
                        if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
 
435
                                return unencodeQuotedPrintable( value, charset );
 
436
 
 
437
                        // nothing to do!
 
438
                        return value;
 
439
                }
 
440
 
559
441
                private String checkParam( String[] params, String name )
560
442
                {
561
443
                        Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
591
473
                        return types;
592
474
                }
593
475
 
594
 
                private UnencodeResult unencodeQuotedPrintable( String str, String charset )
 
476
                private String unencodeQuotedPrintable( String str, String charset )
595
477
                {
596
 
                        boolean another = false;
597
 
 
598
478
                        // default encoding scheme
599
479
                        if( charset == null ) charset = "UTF-8";
600
480
 
601
481
                        // unencode quoted-pritable encoding, as per RFC1521 section 5.1
602
482
                        byte[] bytes = new byte[ str.length() ];
603
483
                        int j = 0;
604
 
                        for( int i = 0; i < str.length(); i++ )
605
 
                        {
606
 
                                // get next char and process...
 
484
                        for( int i = 0; i < str.length(); i++, j++ ) {
607
485
                                char ch = str.charAt( i );
608
 
                                if( ch == '=' && i < str.length() - 2 )
609
 
                                {
610
 
                                        // we found a =XX format byte, add it
 
486
                                if( ch == '=' && i < str.length() - 2 ) {
611
487
                                        bytes[ j ] = (byte)(
612
488
                                                        Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
613
489
                                                        Character.digit( str.charAt( i + 2 ), 16 ) );
614
490
                                        i += 2;
615
491
                                }
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
 
                                }
623
492
                                else
624
 
                                        // just a normal char...
625
493
                                        bytes[ j ] = (byte)ch;
626
 
                                j++;
627
494
                        }
628
 
 
629
 
                        return new UnencodeResult( another, bytes, j );
 
495
                        try {
 
496
                                return new String( bytes, 0, j, charset );
 
497
                        } catch( UnsupportedEncodingException e ) { }
 
498
                        return null;
630
499
                }
631
500
        }
632
501
}