/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
/*
 * Exporter.java
 *
 * Copyright (C) 2011 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;
import android.provider.Contacts;

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

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

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

		// create output filename
		String filename = prefs.getString( "filename", "android-contacts.vcf" );
		File file = new File( "/sdcard" + prefs.getString( "location", "/" ) +
			filename );

		// check if the output file already exists
		if( file.exists() && file.length() > 0 )
			if( !showContinue( R.string.error_vcf_exists ) )
				finish( ACTION_ABORT );

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

	/**
	 * 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();
	}


	@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 header
		out.append( "BEGIN:VCARD\n" );
		out.append( "VERSION:3.0\n" );

		// append formatted name
		String name = contact.getName();
		if( name == null ) name = "";
		out.append( fold( "FN:" + escape( name ) ) + "\n" );

		// append 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 Contacts.Phones.TYPE_HOME:
					types.add( "VOICE" ); types.add( "HOME" ); break;
				case Contacts.Phones.TYPE_WORK:
					types.add( "VOICE" ); types.add( "WORK" ); break;
				case Contacts.Phones.TYPE_FAX_HOME:
					types.add( "FAX" ); types.add( "HOME" ); break;
				case Contacts.Phones.TYPE_FAX_WORK:
					types.add( "FAX" ); types.add( "WORK" ); break;
				case Contacts.Phones.TYPE_PAGER:
					types.add( "PAGER" ); break;
				case Contacts.Phones.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 Contacts.ContactMethods.TYPE_HOME:
					types.add( "HOME" ); break;
				case Contacts.ContactMethods.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 Contacts.ContactMethods.TYPE_HOME:
					types.add( "HOME" ); break;
				case Contacts.ContactMethods.TYPE_WORK:
					types.add( "WORK" ); break;
				}
				out.append( fold( "LABEL" +
					( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
					":" + escape( addresses.get( a ).getAddress() ) ) + "\n" );
			}
		}

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

		// write to file
		try {
			_ostream.write( out.toString().getBytes() );
			_ostream.flush();
		}
		catch( IOException e ) {
			showError( R.string.error_ioerror );
		}

		return true;
	}

}