/android/export-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/export-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
/*
 * Exporter.java
 *
 * Copyright (C) 2011 to 2013 Tim Marston <tim@ed.am>
 *
 * This file is part of the Export Contacts program (hereafter referred
 * to as "this program").  For more information, see
 * http://ed.am/dev/android/export-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 am.ed.exportcontacts;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Iterator;

import android.content.SharedPreferences;

public class VcardExporter extends Exporter
{
	protected FileOutputStream _ostream = null;
	protected boolean _first_contact = true;

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

	@Override
	protected void preExport() throws AbortExportException
	{
		SharedPreferences prefs = getSharedPreferences();

		// create output filename
		File file = new File( ConfigureVCF.getSdCardPathPrefix() +
			prefs.getString( "path", "/" ) +
			prefs.getString( "filename", "android-contacts.vcf" ) );

		// check if the output file already exists
		if( file.exists() && file.length() > 0 )
			showContinueOrAbort( R.string.error_vcf_exists );

		// open file
		try {
			_ostream = new FileOutputStream( file );
		}
		catch( FileNotFoundException e ) {
			showError( getText( R.string.error_filenotfound ) +
				file.getPath() );
		}
	}

	/**
	 * Do line folding at 75 chars
	 * @param raw string
	 * @return folded string
	 */
	private String fold( String line )
	{
		StringBuilder ret = new StringBuilder( line.length() );

		// keep pulling off the first line's worth of chars, while the string is
		// still longer than a line should be
		while( line.length() > 75 )
		{
			// length of the line we'll be pulling off
			int len = 75;

			// if splitting at this length would break apart a codepoint, use
			// one less char
			if( Character.isHighSurrogate( line.charAt( len - 1 ) ) )
				len--;

			// count how many backslashes would be at the end of the line we're
			// pulling off
			int count = 0;
			for( int a = len - 1; a >= 0; a-- )
				if( line.charAt( a ) == '\\' )
					count++;
				else
					break;

			// if there would be an odd number of slashes at the end of the line
			// then pull off one fewer characters so that we don't break apart
			// escape sequences
			if( count % 2 == 1 )
				len--;

			// pull off the line and add it to the output, folded
			ret.append( line.substring( 0, len ) + "\n " );
			line = line.substring( len );
		}

		// add any remaining data
		ret.append( line );

		return ret.toString();
	}

	/**
	 * Do unsafe character escaping
	 * @param raw string
	 * @return escaped string
	 */
	private String escape( String str )
	{
		StringBuilder ret = new StringBuilder( str.length() );
		for( int a = 0; a < str.length(); a++ )
		{
			int c = str.codePointAt( a );
			switch( c )
			{
			case '\n':
				// append escaped newline
				ret.append( "\\n" );
				break;
			case ',':
			case ';':
			case '\\':
				// append return character
				ret.append( '\\' );
				// fall through
			default:
				// append character
				ret.append( Character.toChars( c ) );
			}
		}

		return ret.toString();
	}

	/**
	 * join
	 */
	@SuppressWarnings( "rawtypes" )
	public static String join( AbstractCollection s, String delimiter)
	{
		StringBuffer buffer = new StringBuffer();
		Iterator iter = s.iterator();
		if( iter.hasNext() ) {
			buffer.append( iter.next() );
			while( iter.hasNext() ) {
				buffer.append( delimiter );
				buffer.append( iter.next() );
			}
		}
		return buffer.toString();
	}

	/**
	 * Is the provided value a valid date-and-or-time, as per the spec?
	 *
	 * @param value the value
	 * @return true if it is
	 */
	protected boolean isValidDateAndOrTime( String value )
	{
		// ISO 8601:2004 4.1.2 date with 4.1.2.3 a) and b) reduced accuracy
		String date =
			"[0-9]{4}(?:-?[0-9]{2}(?:-?[0-9]{2})?)?";

		// ISO 8601:2000 5.2.1.3 d), e) and f) truncated date representation
		String date_trunc =
			"--(?:[0-9]{2}(?:-?[0-9]{2})?|-[0-9]{2})";

		// ISO 8601:2004 4.2.2 time with 4.2.2.3 reduced accuracy, 4.2.4 UTC and
		// 4.2.5 zone offset, no 4.2.2.4 decimal fraction and no 4.2.3 24:00
		// midnight
		String time =
			"(?:[0-1][0-9]|2[0-3])(?::?[0-5][0-9](?::?(?:60|[0-5][0-9]))?)?" +
			"(?:Z|[-+](?:[0-1][0-9]|2[0-3])(?::?[0-5][0-9])?)?";

		// ISO 8601:2000 5.3.1.4 a), b) and c) truncated time representation
		String time_trunc =
			"-(?:[0-5][0-9](?::?(?:60|[0-5][0-9]))?|-(?:60|[0-5][0-9]))";

		// RFC6350 (vCard 3.0) date-and-or-time with mandatory time designator
		String date_and_or_time =
			"(?:" + date + "|" + date_trunc + ")?" +
			"(?:T(?:" + time + "|" + time_trunc + "))?";

		return value.matches( date_and_or_time );
	}

	protected void writeToFile( byte data[], String identifier )
		throws AbortExportException
	{
		// write to file
		try {
			_ostream.write( data );
			_ostream.flush();
		}
		catch( IOException e ) {
			showError( R.string.error_ioerror );
		}
	}

	@Override
	protected boolean exportContact( ContactData contact )
		throws AbortExportException
	{
		StringBuilder out = new StringBuilder();

		// skip if the contact has no identifiable features
		if( contact.getPrimaryIdentifier() == null )
			return false;

		// append newline
		if( _first_contact )
			_first_contact = false;
		else
			out.append( "\n" );

		// append header
		out.append( "BEGIN:VCARD\n" );
		out.append( "VERSION:3.0\n" );

		// append formatted name
		String identifier = contact.getPrimaryIdentifier();
		if( identifier != null ) identifier = identifier.trim();
		if( identifier == null || identifier.length() == 0 ) {
			showContinueOrAbort( R.string.error_vcf_noname );
			return false;
		}
		out.append( fold( "FN:" + escape( identifier ) ) + "\n" );

		// append name
		String name = contact.getName();
		if( name == null ) name = "";
		String[] bits = name.split( " +" );
		StringBuilder tmp = new StringBuilder();
		for( int a = 1; a < bits.length - 1; a++ ) {
			if( a > 1 ) tmp.append( " " );
			tmp.append( escape( bits[ a ] ) );
		}
		String value = escape( bits[ bits.length - 1 ] ) + ";" +
			( bits.length > 1? escape( bits[ 0 ] ) : "" ) + ";" +
			tmp.toString() + ";;";
		out.append( fold( "N:" + value ) + "\n" );

		// append organisations and titles
		ArrayList< Exporter.ContactData.OrganisationDetail > organisations =
			contact.getOrganisations();
		if( organisations != null ) {
			for( int a = 0; a < organisations.size(); a++ ) {
				if( organisations.get( a ).getOrganisation() != null )
					out.append( fold( "ORG:" + escape(
						organisations.get( a ).getOrganisation() ) ) + "\n" );
				if( organisations.get( a ).getTitle() != null )
					out.append( fold( "TITLE:" + escape(
						organisations.get( a ).getTitle() ) ) + "\n" );
			}
		}

		// append phone numbers
		ArrayList< Exporter.ContactData.NumberDetail > numbers =
			contact.getNumbers();
		if( numbers != null ) {
			for( int a = 0; a < numbers.size(); a++ ) {
				ArrayList< String > types = new ArrayList< String >();
				switch( numbers.get( a ).getType() ) {
				case ContactData.TYPE_HOME:
					types.add( "VOICE" ); types.add( "HOME" ); break;
				case ContactData.TYPE_WORK:
					types.add( "VOICE" ); types.add( "WORK" ); break;
				case ContactData.TYPE_FAX_HOME:
					types.add( "FAX" ); types.add( "HOME" ); break;
				case ContactData.TYPE_FAX_WORK:
					types.add( "FAX" ); types.add( "WORK" ); break;
				case ContactData.TYPE_PAGER:
					types.add( "PAGER" ); break;
				case ContactData.TYPE_MOBILE:
					types.add( "VOICE" ); types.add( "CELL" ); break;
				}
				if( a == 0 ) types.add( "PREF" );
				out.append( fold( "TEL" +
					( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
					":" + escape( numbers.get( a ).getNumber() ) ) + "\n" );
			}
		}

		// append email addresses
		ArrayList< Exporter.ContactData.EmailDetail > emails =
			contact.getEmails();
		if( emails != null ) {
			for( int a = 0; a < emails.size(); a++ ) {
				ArrayList< String > types = new ArrayList< String >();
				types.add( "INTERNET" );
				switch( emails.get( a ).getType() ) {
				case ContactData.TYPE_HOME:
					types.add( "HOME" ); break;
				case ContactData.TYPE_WORK:
					types.add( "WORK" ); break;
				}
				out.append( fold( "EMAIL" +
					( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
					":" + escape( emails.get( a ).getEmail() ) ) + "\n" );
			}
		}

		// append addresses
		ArrayList< Exporter.ContactData.AddressDetail > addresses =
			contact.getAddresses();
		if( addresses != null ) {
			for( int a = 0; a < addresses.size(); a++ ) {
				ArrayList< String > types = new ArrayList< String >();
				types.add( "POSTAL" );
				switch( addresses.get( a ).getType() ) {
				case ContactData.TYPE_HOME:
					types.add( "HOME" ); break;
				case ContactData.TYPE_WORK:
					types.add( "WORK" ); break;
				}
				// we use LABEL because is accepts formatted text (whereas ADR
				// expects semicolon-delimited fields with specific purposes)
				out.append( fold( "LABEL" +
					( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
					":" + escape( addresses.get( a ).getAddress() ) ) + "\n" );
			}
		}

		// append notes
		ArrayList< String > notes = contact.getNotes();
		if( notes != null )
			for( int a = 0; a < notes.size(); a++ )
				out.append( fold( "NOTE:" + escape( notes.get( a ) ) ) + "\n" );

		// append birthday
		String birthday = contact.getBirthday();
		if( birthday != null ) {
			birthday.trim();
			if( isValidDateAndOrTime( birthday ) )
				out.append( fold( "BDAY:" + escape( birthday ) ) + "\n" );
			else
				out.append(
					fold( "BDAY;VALUE=text:" + escape( birthday ) ) + "\n" );
		}

		// append footer
		out.append( "END:VCARD\n" );

		// replace '\n' with "\r\n" (spec requires CRLF)
		int pos = 0;
		while( true ) {
			pos = out.indexOf( "\n", pos );
			if( pos == -1 ) break;
			out.replace( pos, pos + 1, "\r\n" );

			// skip our inserted string
			pos += 2;
		}

		// write to file
		writeToFile( out.toString().getBytes(), identifier );

		return true;
	}

}