/android/import-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/import-contacts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
 * VCFImporter.java
 *
 * Copyright (C) 2009 Tim Marston <edam@waxworlds.org>
 *
 * This file is part of the Import Contacts program (hereafter referred
 * to as "this program"). For more information, see
 * http://www.waxworlds.org/edam/software/android/import-contacts
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.waxworlds.edam.importcontacts;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.SharedPreferences;
import android.provider.Contacts;
import android.provider.Contacts.PhonesColumns;

public class VCFImporter extends Importer
{
	private int _vCardCount = 0;
	private int _progress = 0;

	public VCFImporter( Doit doit )
	{
		super( doit );
	}

	@Override
	protected void onImport() throws AbortImportException
	{
		SharedPreferences prefs = getSharedPreferences();

		// update UI
		setProgressMessage( R.string.doit_scanning );

		// get a list of vcf files
		File[] files = null;
		try
		{
			// open directory
			String path = "/sdcard" + prefs.getString( "location", "/" );
			File file = new File( path );
			if( !file.exists() )
				showError( R.string.error_locationnotfound );

			// directory, or file?
			if( file.isDirectory() )
			{
				// get files
				class VCardFilter implements FilenameFilter {
					public boolean accept( File dir, String name ) {
						return name.toLowerCase().endsWith( ".vcf" );
					}
				}
				files = file.listFiles( new VCardFilter() );
			}
			else
			{
				// use just this file
				files = new File[ 1 ];
				files[ 0 ] = file;
			}
		}
		catch( SecurityException e ) {
			showError( R.string.error_locationpermissions );
		}

		// check num files and set progress max
		if( files != null && files.length > 0 )
			setProgressMax( files.length );
		else
			showError( R.string.error_locationnofiles );

		// scan through the files
		setTmpProgress( 0 );
		for( int i = 0; i < files.length; i++ ) {
			countVCardFile( files[ i ] );
			setTmpProgress( i );
		}
		setProgressMax( _vCardCount );	// will also update tmp progress

		// import them
		setProgress( 0 );
		for( int i = 0; i < files.length; i++ )
			importVCardFile( files[ i ] );
	}

	private void countVCardFile( File file ) throws AbortImportException
	{
		try
		{
			// open file
			BufferedReader reader = new BufferedReader(
					new FileReader( file ) );

			// read
			String line;
			boolean inVCard = false;
			while( ( line = reader.readLine() ) != null )
			{
				if( !inVCard ) {
					// look for vcard beginning
					if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
						inVCard = true;
						_vCardCount++;
					}
				}
				else if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
					inVCard = false;
			}

		}
		catch( FileNotFoundException e ) {
			showError( getText( R.string.error_filenotfound ) +
				file.getName() );
		}
		catch( IOException e ) {
			showError( getText( R.string.error_ioerror ) + file.getName() );
		}
	}

	private void importVCardFile( File file ) throws AbortImportException
	{
		try
		{
			// open file
			BufferedReader reader = new BufferedReader(
					new FileReader( file ) );

			// read
			StringBuffer content = new StringBuffer();
			String line;
			while( ( line = reader.readLine() ) != null )
				content.append( line ).append( "\n" );

			importVCardFileContent( content.toString(), file.getName() );
		}
		catch( FileNotFoundException e ) {
			showError( getText( R.string.error_filenotfound ) +
				file.getName() );
		}
		catch( IOException e ) {
			showError( getText( R.string.error_ioerror ) + file.getName() );
		}
	}

	private void importVCardFileContent( String content, String fileName )
			throws AbortImportException
	{
		// get lines and parse them
		String[] lines = content.split( "\n" );
		VCard vCard = null;
		for( int i = 0; i < lines.length; i++ )
		{
			String line = lines[ i ];

			if( vCard == null ) {
				// look for vcard beginning
				if( line.matches( "^BEGIN[ \\t]*:[ \\t]*VCARD" ) ) {
					setProgress( ++_progress );
					vCard = new VCard();
				}
			}
			else {
				// look for vcard content or ending
				if( line.matches( "^END[ \\t]*:[ \\t]*VCARD" ) )
				{
					// store vcard and do away with it
					try {
						vCard.finaliseParsing();
						importContact( vCard );
					}
					catch( VCard.ParseException e ) {
						skipContact();
						if( !showContinue(
								getText( R.string.error_vcf_parse ).toString()
								+ fileName + "\n" + e.getMessage() ) )
							finish( ACTION_ABORT );
					}
					catch( VCard.SkipContactException e ) {
						skipContact();
						// do nothing
					}
					vCard = null;
				}
				else
				{
					// try giving the line to the vcard
					try {
						vCard.parseLine( line );
					}
					catch( VCard.ParseException e ) {
						skipContact();
						if( !showContinue(
								getText( R.string.error_vcf_parse ).toString()
								+ fileName + "\n" + e.getMessage() ) )
							finish( ACTION_ABORT );

						// although we're continuing, we still need to abort
						// this vCard. Further lines will be ignored until we
						// get to another BEGIN:VCARD line.
						vCard = null;
					}
					catch( VCard.SkipContactException e ) {
						skipContact();
						// abort this vCard. Further lines will be ignored until
						// we get to another BEGIN:VCARD line.
						vCard = null;
					}
				}
			}
		}
	}

	private class VCard extends ContactData
	{
		private final static int NAMELEVEL_NONE = 0;
		private final static int NAMELEVEL_ORG = 1;
		private final static int NAMELEVEL_FN = 2;
		private final static int NAMELEVEL_N = 3;

		private String _version = null;
		private Vector< String > _lines = null;
		private int _name_level = NAMELEVEL_NONE;
		private boolean _parser_in_multiline = false;
		private String _parser_current_name_and_params = null;
		private String _parser_buffered_value_so_far = "";

		protected class UnencodeResult
		{
			private boolean _another_line_required;
			private byte[] _bytes;
			private int _num_bytes;

			public UnencodeResult( boolean another_line_required, byte[] bytes,
				int num_bytes )
			{
				_another_line_required = another_line_required;
				_bytes = bytes;
				_num_bytes = num_bytes;
			}

			public boolean isAnotherLineRequired()
			{
				return _another_line_required;
			}

			public byte[] getBytes()
			{
				return _bytes;
			}

			public int getNumBytes()
			{
				return _num_bytes;
			}
		}

		@SuppressWarnings("serial")
		protected class ParseException extends Exception
		{
			@SuppressWarnings("unused")
			public ParseException( String error )
			{
				super( error );
			}

			public ParseException( int res )
			{
				super( VCFImporter.this.getText( res ).toString() );
			}
		}

		@SuppressWarnings("serial")
		protected class SkipContactException extends Exception { }

		public void parseLine( String line )
				throws ParseException, SkipContactException,
				AbortImportException
		{
			// ignore empty lines
			if( line.trim() == "" ) return;

			// split line into name and value parts (this may turn out to be
			// unwanted if the line is a subsequent line in a multi-line
			// value, but we have to do this now to check for and handle VCF
			// versions first)
			String[] props = line.split(  ":", 2 );
			for( int i = 0; i < props.length; i++ )
				props[ i ] = props[ i ].trim();

			// if we haven't yet got a version, we won't be paring anything!
			if( _version == null )
			{
				// is this a version?
				if( props.length == 2 && props[ 0 ].equals( "VERSION" ) )
				{
					// yes, check/store it
					if( !props[ 1 ].equals( "2.1" ) &&
							!props[ 1 ].equals( "3.0" ) )
						throw new ParseException( R.string.error_vcf_version );
					_version = props[ 1 ];

					// parse any other lines we've accumulated so far
					if( _lines != null )
						for( int i = 0; i < _lines.size(); i++ )
							parseLine( _lines.get( i ) );
					_lines = null;
				}
				else
				{
					// no, so stash this line till we have a version
					if( _lines == null )
						_lines = new Vector< String >();
					_lines.add( line );
				}
			}
			else
			{
				if( _parser_in_multiline )
				{
					// if we're currently in a multi-line value, use the stored
					// property name and parameters
					props = new String[ 2 ];
					props[ 0 ] = _parser_current_name_and_params;
					props[ 1 ] = line.trim();
				}
				else
				{
					// for normal lines, check the property name/value bits
					if( props.length < 2 || props[ 0 ].length() == 0 )
						throw new ParseException(
							R.string.error_vcf_malformed );

					// ignore empty properties
					if( props[ 1 ].length() < 1 )
						return;

					// reset the saved multi-line state
					_parser_current_name_and_params = props[ 0 ];
					_parser_buffered_value_so_far = "";
				}

				// get parameter parts
				String[] params = props[ 0 ].split( ";" );
				for( int i = 0; i < params.length; i++ )
					params[ i ] = params[ i ].trim();

				// parse charset and encoding parameters
				String charset, encoding;
				if( ( charset = checkParam( params, "CHARSET" ) ) != null &&
					!charset.equals( "UTF-8" ) && !charset.equals( "UTF-16" ) )
				{
					throw new ParseException( R.string.error_vcf_charset );
				}
				if( ( encoding = checkParam( params, "ENCODING" ) ) != null &&
					!encoding.equals( "QUOTED-PRINTABLE" ) &&
					!encoding.equals( "8BIT" ) )
					//&& !encoding.equals( "BASE64" ) )
				{
					throw new ParseException( R.string.error_vcf_encoding );
				}

				// do unencoding (or default to a fake unencoding result with
				// the raw string)
				UnencodeResult result;
				if( encoding != null && encoding.equals( "QUOTED-PRINTABLE" ) )
					result = unencodeQuotedPrintable( props[ 1 ], charset );
//				else if( encoding != null && encoding.equals( "BASE64" ) )
//					result = unencodeBase64( props[ 1 ], charset );
				else
					result = new UnencodeResult( false, props[ 1 ].getBytes(),
						props[ 1 ].getBytes().length );

				// process charset
				try {
					props[ 1 ] = new String( result.getBytes(), 0,
						result.getNumBytes(),
						charset == null? "UTF-8" : charset );
				} catch( UnsupportedEncodingException e ) {
					throw new ParseException( R.string.error_vcf_charset );
				}

				// handle multi-line requests
				_parser_in_multiline = result.isAnotherLineRequired();
				if( _parser_in_multiline ) {
					_parser_buffered_value_so_far += props[ 1 ];
					return;
				}

				// add on buffered multi-line content
				String value = _parser_buffered_value_so_far + props[ 1 ];

				// parse some properties
				if( params[ 0 ].equals( "N" ) )
					parseN( params, value );
				else if( params[ 0 ].equals( "FN" ) )
					parseFN( params, value );
				else if( params[ 0 ].equals( "ORG" ) )
					parseORG( params, value );
				else if( params[ 0 ].equals( "TEL" ) )
					parseTEL( params, value );
				else if( params[ 0 ].equals( "EMAIL" ) )
					parseEMAIL( params, value );
			}
		}

		private void parseN( String[] params, String value )
				throws ParseException, SkipContactException,
				AbortImportException
		{
			// already got a better name?
			if( _name_level >= NAMELEVEL_N ) return;

			// get name parts
			String[] nameparts = value.split( ";" );
			for( int i = 0; i < nameparts.length; i++ )
				nameparts[ i ] = nameparts[ i ].trim();

			// build name
			value = "";
			if( nameparts.length > 1 && nameparts[ 1 ].length() > 0 )
				value += nameparts[ 1 ];
			if( nameparts[ 0 ].length() > 0 )
				value += ( value.length() == 0? "" : " " ) + nameparts[ 0 ];

			// set name
			setName( value );
			_name_level = NAMELEVEL_N;

			// check now to see if we need to import this contact (to avoid
			// parsing the rest of the vCard unnecessarily)
			if( !isImportRequired( getName() ) )
				throw new SkipContactException();
		}

		private void parseFN( String[] params, String value )
				throws ParseException, SkipContactException
		{
			// already got a better name?
			if( _name_level >= NAMELEVEL_FN ) return;

			// set name
			setName( value );
			_name_level = NAMELEVEL_FN;
		}

		private void parseORG( String[] params, String value )
				throws ParseException, SkipContactException
		{
			// already got a better name?
			if( _name_level >= NAMELEVEL_ORG ) return;

			// get org parts
			String[] orgparts = value.split( ";" );
			for( int i = 0; i < orgparts.length; i++ )
				orgparts[ i ] = orgparts[ i ].trim();

			// build name
			if( orgparts[ 0 ].length() == 0 && orgparts.length > 1 )
				value = orgparts[ 1 ];
			else
				value = orgparts[ 0 ];

			// set name
			setName( value );
			_name_level = NAMELEVEL_ORG;
		}

		private void parseTEL( String[] params, String value )
				throws ParseException
		{
			if( value.length() == 0 ) return;

			Set< String > types = extractTypes( params, Arrays.asList(
					"PREF", "HOME", "WORK", "VOICE", "FAX", "MSG", "CELL",
					"PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO" ) );

			// here's the logic...
			boolean preferred = types.contains( "PREF" );
			if( types.contains( "VOICE" ) )
				if( types.contains( "WORK" ) )
					addPhone( value, PhonesColumns.TYPE_WORK, preferred );
				else
					addPhone( value, PhonesColumns.TYPE_HOME, preferred );
			else if( types.contains( "CELL" ) || types.contains( "VIDEO" ) )
				addPhone( value, PhonesColumns.TYPE_MOBILE, preferred );
			if( types.contains( "FAX" ) )
				if( types.contains( "HOME" ) )
					addPhone( value, PhonesColumns.TYPE_FAX_HOME, preferred );
				else
					addPhone( value, PhonesColumns.TYPE_FAX_WORK, preferred );
			if( types.contains( "PAGER" ) )
				addPhone( value, PhonesColumns.TYPE_PAGER, preferred );
		}

		public void parseEMAIL( String[] params, String value )
				throws ParseException
		{
			if( value.length() == 0 ) return;

			Set< String > types = extractTypes( params, Arrays.asList(
					"PREF", "WORK", "HOME", "INTERNET" ) );

			// here's the logic...
			boolean preferred = types.contains( "PREF" );
			if( types.contains( "WORK" ) )
				addEmail( value, Contacts.ContactMethods.TYPE_WORK, preferred );
			else
				addEmail( value, Contacts.ContactMethods.TYPE_HOME, preferred );
		}

		public void finaliseParsing()
				throws ParseException, SkipContactException,
				AbortImportException
		{
			// missing version (and data is present)
			if( _version == null && _lines != null )
				throw new ParseException( R.string.error_vcf_malformed );

			//  missing name properties?
			if( _name_level == NAMELEVEL_NONE )
				throw new ParseException( R.string.error_vcf_noname );

			// check if we should import this one? If we've already got an 'N'-
			// type name, this will already have been done by parseN() so we
			// mustn't do this here (or it could prompt twice!)
			if( _name_level < NAMELEVEL_N && !isImportRequired( getName() ) )
				throw new SkipContactException();
		}

		private String checkParam( String[] params, String name )
		{
			Pattern p = Pattern.compile( "^" + name + "[ \\t]*=[ \\t]*(.*)$" );
			for( int i = 0; i < params.length; i++ ) {
				Matcher m = p.matcher( params[ i ] );
				if( m.matches() )
					return m.group( 1 );
			}
			return null;
		}

		private Set< String > extractTypes( String[] params,
				List< String > validTypes )
		{
			HashSet< String > types = new HashSet< String >();

			// get 3.0-style TYPE= param
			String typeParam;
			if( ( typeParam = checkParam( params, "TYPE" ) ) != null ) {
				String[] bits = typeParam.split( "," );
				for( int i = 0; i < bits.length; i++ )
					if( validTypes.contains( bits[ i ] ) )
						types.add( bits[ i ] );
			}

			// get 2.1-style type param
			if( _version.equals( "2.1" ) ) {
				for( int i = 1; i < params.length; i++ )
					if( validTypes.contains( params[ i ] ) )
						types.add( params[ i ] );
			}

			return types;
		}

		private UnencodeResult unencodeQuotedPrintable( String str, String charset )
		{
			boolean another = false;

			// default encoding scheme
			if( charset == null ) charset = "UTF-8";

			// unencode quoted-pritable encoding, as per RFC1521 section 5.1
			byte[] bytes = new byte[ str.length() ];
			int j = 0;
			for( int i = 0; i < str.length(); i++ )
			{
				// get next char and process...
				char ch = str.charAt( i );
				if( ch == '=' && i < str.length() - 2 )
				{
					// we found a =XX format byte, add it
					bytes[ j ] = (byte)(
							Character.digit( str.charAt( i + 1 ), 16 ) * 16 +
							Character.digit( str.charAt( i + 2 ), 16 ) );
					i += 2;
				}
				else if( ch == '=' && i == str.length() - 1 )
				{
					// we found a '=' at the end of a line signifying a multi-
					// line string, so we don't add it.
					another = true;
					continue;
				}
				else
					// just a normal char...
					bytes[ j ] = (byte)ch;
				j++;
			}

			return new UnencodeResult( another, bytes, j );
		}
	}
}