/android/export-contacts

To get this branch, use:
bzr branch http://bzr.ed.am/android/export-contacts

« back to all changes in this revision

Viewing changes to src/am/ed/exportcontacts/VcardExporter.java

  • Committer: Tim Marston
  • Date: 2013-07-16 16:24:59 UTC
  • Revision ID: tim@ed.am-20130716162459-u5z1iogael46ukp3
separate vcards with a newline

Show diffs side-by-side

added added

removed removed

 
1
/*
 
2
 * Exporter.java
 
3
 *
 
4
 * Copyright (C) 2011 to 2013 Tim Marston <tim@ed.am>
 
5
 *
 
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
 
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 am.ed.exportcontacts;
 
25
 
 
26
import java.io.File;
 
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;
 
33
 
 
34
import android.content.SharedPreferences;
 
35
 
 
36
public class VcardExporter extends Exporter
 
37
{
 
38
        protected FileOutputStream _ostream = null;
 
39
        protected boolean _first_contact = true;
 
40
 
 
41
        public VcardExporter( Doit doit )
 
42
        {
 
43
                super( doit );
 
44
        }
 
45
 
 
46
        @Override
 
47
        protected void preExport() throws AbortExportException
 
48
        {
 
49
                SharedPreferences prefs = getSharedPreferences();
 
50
 
 
51
                // create output filename
 
52
                String filename = prefs.getString( "filename", "android-contacts.vcf" );
 
53
                File file = new File( "/sdcard" + prefs.getString( "location", "/" ) +
 
54
                        filename );
 
55
 
 
56
                // check if the output file already exists
 
57
                if( file.exists() && file.length() > 0 )
 
58
                        if( !showContinue( R.string.error_vcf_exists ) )
 
59
                                finish( ACTION_ABORT );
 
60
 
 
61
                // open file
 
62
                try {
 
63
                        _ostream = new FileOutputStream( file );
 
64
                }
 
65
                catch( FileNotFoundException e ) {
 
66
                        showError( R.string.error_filenotfound );
 
67
                }
 
68
        }
 
69
 
 
70
        /**
 
71
         * Do line folding at 75 chars
 
72
         * @param raw string
 
73
         * @return folded string
 
74
         */
 
75
        private String fold( String line )
 
76
        {
 
77
                StringBuilder ret = new StringBuilder( line.length() );
 
78
 
 
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 )
 
82
                {
 
83
                        // length of the line we'll be pulling off
 
84
                        int len = 75;
 
85
 
 
86
                        // if splitting at this length would break apart a codepoint, use
 
87
                        // one less char
 
88
                        if( Character.isHighSurrogate( line.charAt( len - 1 ) ) )
 
89
                                len--;
 
90
 
 
91
                        // count how many backslashes would be at the end of the line we're
 
92
                        // pulling off
 
93
                        int count = 0;
 
94
                        for( int a = len - 1; a >= 0; a-- )
 
95
                                if( line.charAt( a ) == '\\' )
 
96
                                        count++;
 
97
                                else
 
98
                                        break;
 
99
 
 
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
 
102
                        // escape sequences
 
103
                        if( count % 2 == 1 )
 
104
                                len--;
 
105
 
 
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 );
 
109
                }
 
110
 
 
111
                // add any remaining data
 
112
                ret.append( line );
 
113
 
 
114
                return ret.toString();
 
115
        }
 
116
 
 
117
        /**
 
118
         * Do unsafe character escaping
 
119
         * @param raw string
 
120
         * @return escaped string
 
121
         */
 
122
        private String escape( String str )
 
123
        {
 
124
                StringBuilder ret = new StringBuilder( str.length() );
 
125
                for( int a = 0; a < str.length(); a++ )
 
126
                {
 
127
                        int c = str.codePointAt( a );
 
128
                        switch( c )
 
129
                        {
 
130
                        case '\n':
 
131
                                // append escaped newline
 
132
                                ret.append( "\\n" );
 
133
                                break;
 
134
                        case ',':
 
135
                        case ';':
 
136
                        case '\\':
 
137
                                // append return character
 
138
                                ret.append( '\\' );
 
139
                                // fall through
 
140
                        default:
 
141
                                // append character
 
142
                                ret.append( Character.toChars( c ) );
 
143
                        }
 
144
                }
 
145
 
 
146
                return ret.toString();
 
147
        }
 
148
 
 
149
        /**
 
150
         * join
 
151
         */
 
152
        @SuppressWarnings( "rawtypes" )
 
153
        public static String join( AbstractCollection s, String delimiter)
 
154
        {
 
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() );
 
162
                        }
 
163
                }
 
164
                return buffer.toString();
 
165
        }
 
166
 
 
167
        @Override
 
168
        protected boolean exportContact( ContactData contact )
 
169
                throws AbortExportException
 
170
        {
 
171
                StringBuilder out = new StringBuilder();
 
172
 
 
173
                // skip if the contact has no identifiable features
 
174
                if( contact.getPrimaryIdentifier() == null )
 
175
                        return false;
 
176
 
 
177
                // append newline
 
178
                if( _first_contact )
 
179
                        _first_contact = false;
 
180
                else
 
181
                        out.append( "\n" );
 
182
 
 
183
                // append header
 
184
                out.append( "BEGIN:VCARD\n" );
 
185
                out.append( "VERSION:3.0\n" );
 
186
 
 
187
                // append formatted name
 
188
                String name = contact.getName();
 
189
                if( name == null ) name = "";
 
190
                out.append( fold( "FN:" + escape( name ) ) + "\n" );
 
191
 
 
192
                // append name
 
193
                String[] bits = name.split( " +" );
 
194
                StringBuilder tmp = new StringBuilder();
 
195
                for( int a = 1; a < bits.length - 1; a++ ) {
 
196
                        if( a > 1 ) tmp.append( " " );
 
197
                        tmp.append( escape( bits[ a ] ) );
 
198
                }
 
199
                String value = escape( bits[ bits.length - 1 ] ) + ";" +
 
200
                        ( bits.length > 1? escape( bits[ 0 ] ) : "" ) + ";" +
 
201
                        tmp.toString() + ";;";
 
202
                out.append( fold( "N:" + value ) + "\n" );
 
203
 
 
204
                // append organisations and titles
 
205
                ArrayList< Exporter.ContactData.OrganisationDetail > organisations =
 
206
                        contact.getOrganisations();
 
207
                if( organisations != null ) {
 
208
                        for( int a = 0; a < organisations.size(); a++ ) {
 
209
                                if( organisations.get( a ).getOrganisation() != null )
 
210
                                        out.append( fold( "ORG:" + escape(
 
211
                                                organisations.get( a ).getOrganisation() ) ) + "\n" );
 
212
                                if( organisations.get( a ).getTitle() != null )
 
213
                                        out.append( fold( "TITLE:" + escape(
 
214
                                                organisations.get( a ).getTitle() ) ) + "\n" );
 
215
                        }
 
216
                }
 
217
 
 
218
                // append phone numbers
 
219
                ArrayList< Exporter.ContactData.NumberDetail > numbers =
 
220
                        contact.getNumbers();
 
221
                if( numbers != null ) {
 
222
                        for( int a = 0; a < numbers.size(); a++ ) {
 
223
                                ArrayList< String > types = new ArrayList< String >();
 
224
                                switch( numbers.get( a ).getType() ) {
 
225
                                case ContactData.TYPE_HOME:
 
226
                                        types.add( "VOICE" ); types.add( "HOME" ); break;
 
227
                                case ContactData.TYPE_WORK:
 
228
                                        types.add( "VOICE" ); types.add( "WORK" ); break;
 
229
                                case ContactData.TYPE_FAX_HOME:
 
230
                                        types.add( "FAX" ); types.add( "HOME" ); break;
 
231
                                case ContactData.TYPE_FAX_WORK:
 
232
                                        types.add( "FAX" ); types.add( "WORK" ); break;
 
233
                                case ContactData.TYPE_PAGER:
 
234
                                        types.add( "PAGER" ); break;
 
235
                                case ContactData.TYPE_MOBILE:
 
236
                                        types.add( "VOICE" ); types.add( "CELL" ); break;
 
237
                                }
 
238
                                if( a == 0 ) types.add( "PREF" );
 
239
                                out.append( fold( "TEL" +
 
240
                                        ( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
 
241
                                        ":" + escape( numbers.get( a ).getNumber() ) ) + "\n" );
 
242
                        }
 
243
                }
 
244
 
 
245
                // append email addresses
 
246
                ArrayList< Exporter.ContactData.EmailDetail > emails =
 
247
                        contact.getEmails();
 
248
                if( emails != null ) {
 
249
                        for( int a = 0; a < emails.size(); a++ ) {
 
250
                                ArrayList< String > types = new ArrayList< String >();
 
251
                                types.add( "INTERNET" );
 
252
                                switch( emails.get( a ).getType() ) {
 
253
                                case ContactData.TYPE_HOME:
 
254
                                        types.add( "HOME" ); break;
 
255
                                case ContactData.TYPE_WORK:
 
256
                                        types.add( "WORK" ); break;
 
257
                                }
 
258
                                out.append( fold( "EMAIL" +
 
259
                                        ( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
 
260
                                        ":" + escape( emails.get( a ).getEmail() ) ) + "\n" );
 
261
                        }
 
262
                }
 
263
 
 
264
                // append addresses
 
265
                ArrayList< Exporter.ContactData.AddressDetail > addresses =
 
266
                        contact.getAddresses();
 
267
                if( addresses != null ) {
 
268
                        for( int a = 0; a < addresses.size(); a++ ) {
 
269
                                ArrayList< String > types = new ArrayList< String >();
 
270
                                types.add( "POSTAL" );
 
271
                                switch( addresses.get( a ).getType() ) {
 
272
                                case ContactData.TYPE_HOME:
 
273
                                        types.add( "HOME" ); break;
 
274
                                case ContactData.TYPE_WORK:
 
275
                                        types.add( "WORK" ); break;
 
276
                                }
 
277
                                // we use LABEL because is accepts formatted text (whereas ADR
 
278
                                // expects semicolon-delimited fields with specific purposes)
 
279
                                out.append( fold( "LABEL" +
 
280
                                        ( types.size() > 0? ";TYPE=" + join( types, "," ) : "" ) +
 
281
                                        ":" + escape( addresses.get( a ).getAddress() ) ) + "\n" );
 
282
                        }
 
283
                }
 
284
 
 
285
                // append notes
 
286
                ArrayList< String > notes = contact.getNotes();
 
287
                if( notes != null )
 
288
                        for( int a = 0; a < notes.size(); a++ )
 
289
                                out.append( fold( "NOTE:" + escape( notes.get( a ) ) ) + "\n" );
 
290
 
 
291
                // append footer
 
292
                out.append( "END:VCARD\n" );
 
293
 
 
294
                // replace '\n' with "\r\n" (spec requires CRLF)
 
295
                int pos = 0;
 
296
                while( true ) {
 
297
                        pos = out.indexOf( "\n", pos );
 
298
                        if( pos == -1 ) break;
 
299
                        out.replace( pos, pos + 1, "\r\n" );
 
300
 
 
301
                        // skip our inserted string
 
302
                        pos += 2;
 
303
                }
 
304
 
 
305
                // write to file
 
306
                try {
 
307
                        _ostream.write( out.toString().getBytes() );
 
308
                        _ostream.flush();
 
309
                }
 
310
                catch( IOException e ) {
 
311
                        showError( R.string.error_ioerror );
 
312
                }
 
313
 
 
314
                return true;
 
315
        }
 
316
 
 
317
}