4
* Copyright (C) 2011 to 2013 Tim Marston <tim@ed.am>
6
* This file is part of the Export Contacts program (hereafter referred
7
* to as "this program"). For more information, see
8
* http://ed.am/dev/android/export-contacts
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.
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.
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/>.
24
package am.ed.exportcontacts;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.util.AbstractCollection;
31
import java.util.ArrayList;
32
import java.util.Iterator;
34
import android.content.SharedPreferences;
36
public class VcardExporter extends Exporter
38
protected FileOutputStream _ostream = null;
39
protected boolean _first_contact = true;
41
public VcardExporter( Doit doit )
47
protected void preExport() throws AbortExportException
49
SharedPreferences prefs = getSharedPreferences();
51
// create output filename
52
File file = new File( ConfigureVCF.getSdCardPathPrefix() +
53
prefs.getString( "path", "/" ) +
54
prefs.getString( "filename", "android-contacts.vcf" ) );
56
// check if the output file already exists
57
if( file.exists() && file.length() > 0 )
58
showContinueOrAbort( R.string.error_vcf_exists );
62
_ostream = new FileOutputStream( file );
64
catch( FileNotFoundException e ) {
65
showError( getText( R.string.error_filenotfound ) +
71
* Do line folding at 75 chars
73
* @return folded string
75
private String fold( String line )
77
StringBuilder ret = new StringBuilder( line.length() );
79
// keep pulling off the first line's worth of chars, while the string is
80
// still longer than a line should be
81
while( line.length() > 75 )
83
// length of the line we'll be pulling off
86
// if splitting at this length would break apart a codepoint, use
88
if( Character.isHighSurrogate( line.charAt( len - 1 ) ) )
91
// count how many backslashes would be at the end of the line we're
94
for( int a = len - 1; a >= 0; a-- )
95
if( line.charAt( a ) == '\\' )
100
// if there would be an odd number of slashes at the end of the line
101
// then pull off one fewer characters so that we don't break apart
106
// pull off the line and add it to the output, folded
107
ret.append( line.substring( 0, len ) + "\n " );
108
line = line.substring( len );
111
// add any remaining data
114
return ret.toString();
118
* Do unsafe character escaping
120
* @return escaped string
122
private String escape( String str )
124
StringBuilder ret = new StringBuilder( str.length() );
125
for( int a = 0; a < str.length(); a++ )
127
int c = str.codePointAt( a );
131
// append escaped newline
137
// append return character
142
ret.append( Character.toChars( c ) );
146
return ret.toString();
152
@SuppressWarnings( "rawtypes" )
153
public static String join( AbstractCollection s, String delimiter)
155
StringBuffer buffer = new StringBuffer();
156
Iterator iter = s.iterator();
157
if( iter.hasNext() ) {
158
buffer.append( iter.next() );
159
while( iter.hasNext() ) {
160
buffer.append( delimiter );
161
buffer.append( iter.next() );
164
return buffer.toString();
168
* Is the provided value a valid date-and-or-time, as per the spec?
170
* @param value the value
171
* @return true if it is
173
protected boolean isValidDateAndOrTime( String value )
175
// ISO 8601:2004 4.1.2 date with 4.1.2.3 a) and b) reduced accuracy
177
"[0-9]{4}(?:-?[0-9]{2}(?:-?[0-9]{2})?)?";
179
// ISO 8601:2000 5.2.1.3 d), e) and f) truncated date representation
181
"--(?:[0-9]{2}(?:-?[0-9]{2})?|-[0-9]{2})";
183
// ISO 8601:2004 4.2.2 time with 4.2.2.3 reduced accuracy, 4.2.4 UTC and
184
// 4.2.5 zone offset, no 4.2.2.4 decimal fraction and no 4.2.3 24:00
187
"(?:[0-1][0-9]|2[0-3])(?::?[0-5][0-9](?::?(?:60|[0-5][0-9]))?)?" +
188
"(?:Z|[-+](?:[0-1][0-9]|2[0-3])(?::?[0-5][0-9])?)?";
190
// ISO 8601:2000 5.3.1.4 a), b) and c) truncated time representation
192
"-(?:[0-5][0-9](?::?(?:60|[0-5][0-9]))?|-(?:60|[0-5][0-9]))";
194
// RFC6350 (vCard 3.0) date-and-or-time with mandatory time designator
195
String date_and_or_time =
196
"(?:" + date + "|" + date_trunc + ")?" +
197
"(?:T(?:" + time + "|" + time_trunc + "))?";
199
return value.matches( date_and_or_time );
202
protected void writeToFile( byte data[], String identifier )
203
throws AbortExportException
207
_ostream.write( data );
210
catch( IOException e ) {
211
showError( R.string.error_ioerror );
216
protected boolean exportContact( ContactData contact )
217
throws AbortExportException
219
StringBuilder out = new StringBuilder();
221
// skip if the contact has no identifiable features
222
if( contact.getPrimaryIdentifier() == null )
227
_first_contact = false;
232
out.append( "BEGIN:VCARD\n" );
233
out.append( "VERSION:3.0\n" );
235
// append formatted name
236
String identifier = contact.getPrimaryIdentifier();
237
if( identifier != null ) identifier = identifier.trim();
238
if( identifier == null || identifier.length() == 0 ) {
239
showContinueOrAbort( R.string.error_vcf_noname );
242
out.append( fold( "FN:" + escape( identifier ) ) + "\n" );
245
String name = contact.getName();
246
if( name == null ) name = "";
247
String[] bits = name.split( " +" );
248
StringBuilder tmp = new StringBuilder();
249
for( int a = 1; a < bits.length - 1; a++ ) {
250
if( a > 1 ) tmp.append( " " );
251
tmp.append( escape( bits[ a ] ) );
253
String value = escape( bits[ bits.length - 1 ] ) + ";" +
254
( bits.length > 1? escape( bits[ 0 ] ) : "" ) + ";" +
255
tmp.toString() + ";;";
256
out.append( fold( "N:" + value ) + "\n" );
258
// append organisations and titles
259
ArrayList< Exporter.ContactData.OrganisationDetail > organisations =
260
contact.getOrganisations();
261
if( organisations != null ) {
262
for( int a = 0; a < organisations.size(); a++ ) {
263
if( organisations.get( a ).getOrganisation() != null )
264
out.append( fold( "ORG:" + escape(
265
organisations.get( a ).getOrganisation() ) ) + "\n" );
266
if( organisations.get( a ).getTitle() != null )
267
out.append( fold( "TITLE:" + escape(
268
organisations.get( a ).getTitle() ) ) + "\n" );
272
// append phone numbers
273
ArrayList< Exporter.ContactData.NumberDetail > numbers =
274
contact.getNumbers();
275
if( numbers != null ) {
276
for( int a = 0; a < numbers.size(); a++ ) {
277
ArrayList< String > types = new ArrayList< String >();
278
switch( numbers.get( a ).getType() ) {
279
case ContactData.TYPE_HOME:
280
types.add( "VOICE" ); types.add( "HOME" ); break;
281
case ContactData.TYPE_WORK:
282
types.add( "VOICE" ); types.add( "WORK" ); break;
283
case ContactData.TYPE_FAX_HOME:
284
types.add( "FAX" ); types.add( "HOME" ); break;
285
case ContactData.TYPE_FAX_WORK:
286
types.add( "FAX" ); types.add( "WORK" ); break;
287
case ContactData.TYPE_PAGER:
288
types.add( "PAGER" ); break;
289
case ContactData.TYPE_MOBILE:
290
types.add( "VOICE" ); types.add( "CELL" ); break;
292
if( a == 0 ) types.add( "PREF" );
293
out.append( fold( "TEL" +
294
( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
295
":" + escape( numbers.get( a ).getNumber() ) ) + "\n" );
299
// append email addresses
300
ArrayList< Exporter.ContactData.EmailDetail > emails =
302
if( emails != null ) {
303
for( int a = 0; a < emails.size(); a++ ) {
304
ArrayList< String > types = new ArrayList< String >();
305
types.add( "INTERNET" );
306
switch( emails.get( a ).getType() ) {
307
case ContactData.TYPE_HOME:
308
types.add( "HOME" ); break;
309
case ContactData.TYPE_WORK:
310
types.add( "WORK" ); break;
312
out.append( fold( "EMAIL" +
313
( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
314
":" + escape( emails.get( a ).getEmail() ) ) + "\n" );
319
ArrayList< Exporter.ContactData.AddressDetail > addresses =
320
contact.getAddresses();
321
if( addresses != null ) {
322
for( int a = 0; a < addresses.size(); a++ ) {
323
ArrayList< String > types = new ArrayList< String >();
324
types.add( "POSTAL" );
325
switch( addresses.get( a ).getType() ) {
326
case ContactData.TYPE_HOME:
327
types.add( "HOME" ); break;
328
case ContactData.TYPE_WORK:
329
types.add( "WORK" ); break;
331
// we use LABEL because is accepts formatted text (whereas ADR
332
// expects semicolon-delimited fields with specific purposes)
333
out.append( fold( "LABEL" +
334
( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
335
":" + escape( addresses.get( a ).getAddress() ) ) + "\n" );
340
ArrayList< String > notes = contact.getNotes();
342
for( int a = 0; a < notes.size(); a++ )
343
out.append( fold( "NOTE:" + escape( notes.get( a ) ) ) + "\n" );
346
String birthday = contact.getBirthday();
347
if( birthday != null ) {
349
if( isValidDateAndOrTime( birthday ) )
350
out.append( fold( "BDAY:" + escape( birthday ) ) + "\n" );
353
fold( "BDAY;VALUE=text:" + escape( birthday ) ) + "\n" );
357
out.append( "END:VCARD\n" );
359
// replace '\n' with "\r\n" (spec requires CRLF)
362
pos = out.indexOf( "\n", pos );
363
if( pos == -1 ) break;
364
out.replace( pos, pos + 1, "\r\n" );
366
// skip our inserted string
371
writeToFile( out.toString().getBytes(), identifier );