aboutsummaryrefslogtreecommitdiffstats
path: root/OpenPGP-Keychain/src/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java
blob: cb186ba16573b21e82621a5b909106834ec2a6f1 (plain)
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
/*
 * Copyright (C) 2012 Dominik Schürmann <dominik@dominikschuermann.de>
 * Copyright (C) 2011 Senecaso
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sufficientlysecure.keychain.ui;

import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround;
import org.sufficientlysecure.keychain.helper.OtherHelper;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
import org.sufficientlysecure.keychain.ui.dialog.DeleteFileDialogFragment;
import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.R;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;


import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

public class ImportKeysActivity extends SherlockFragmentActivity {
    public static final String ACTION_IMPORT = Constants.INTENT_PREFIX + "IMPORT";
    public static final String ACTION_IMPORT_FROM_FILE = Constants.INTENT_PREFIX
            + "IMPORT_FROM_FILE";
    public static final String ACTION_IMPORT_FROM_QR_CODE = Constants.INTENT_PREFIX
            + "IMPORT_FROM_QR_CODE";
    public static final String ACTION_IMPORT_FROM_NFC = Constants.INTENT_PREFIX + "IMPORT_FROM_NFC";

    // only used by IMPORT
    public static final String EXTRA_TEXT = "text";
    public static final String EXTRA_KEYRING_BYTES = "keyringBytes";

    // public static final String EXTRA_KEY_ID = "keyId";

    protected String mImportFilename;
    protected byte[] mImportData;

    protected boolean mDeleteAfterImport = false;

    FileDialogFragment mFileDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.import_keys);

        // set actionbar without home button if called from another app
        OtherHelper.setActionBarBackButton(this);

        handleActions(getIntent());
    }

    /**
     * ActionBar menu is created based on class variables to change it at runtime
     * 
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, Id.menu.option.import_from_file, 0, R.string.menu_importFromFile)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.add(1, Id.menu.option.import_from_qr_code, 1, R.string.menu_importFromQrCode)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.add(1, Id.menu.option.import_from_nfc, 2, R.string.menu_importFromNfc)
                .setShowAsAction(
                        MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case android.R.id.home:
            // app icon in Action Bar clicked; go home
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;

        case Id.menu.option.import_from_file:
            showImportFromFileDialog();
            return true;

        case Id.menu.option.import_from_qr_code:
            importFromQrCode();
            return true;

        case Id.menu.option.import_from_nfc:
            importFromNfc();
            return true;

        default:
            return super.onOptionsItemSelected(item);

        }
    }

    protected void handleActions(Intent intent) {
        String action = intent.getAction();
        Bundle extras = intent.getExtras();

        if (extras == null) {
            extras = new Bundle();
        }

        /**
         * Android Standard Actions
         */
        if (Intent.ACTION_VIEW.equals(action)) {
            // Android's Action when opening file associated to APG (see AndroidManifest.xml)
            // override action to delegate it to APGs ACTION_IMPORT
            action = ACTION_IMPORT;
        }

        /**
         * APG's own Actions
         */
        if (ACTION_IMPORT.equals(action)) {
            if ("file".equals(intent.getScheme()) && intent.getDataString() != null) {
                mImportFilename = intent.getData().getPath();
                mImportData = null;
            } else if (extras.containsKey(EXTRA_TEXT)) {
                mImportData = intent.getStringExtra(EXTRA_TEXT).getBytes();
                mImportFilename = null;
            } else if (extras.containsKey(EXTRA_KEYRING_BYTES)) {
                mImportData = intent.getByteArrayExtra(EXTRA_KEYRING_BYTES);
                mImportFilename = null;
            }
            loadKeyListFragment();
        } else if (ACTION_IMPORT_FROM_FILE.equals(action)) {
            if ("file".equals(intent.getScheme()) && intent.getDataString() != null) {
                mImportFilename = intent.getData().getPath();
                mImportData = null;
            }
            showImportFromFileDialog();
        } else if (ACTION_IMPORT_FROM_QR_CODE.equals(action)) {
            importFromQrCode();
        } else if (ACTION_IMPORT_FROM_NFC.equals(action)) {
            importFromNfc();
        }
    }

    public void loadKeyListFragment() {
        if (mImportData != null || mImportFilename != null) {
            // generate list of keyrings
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            ImportKeysListFragment listFragment = new ImportKeysListFragment();
            Bundle args = new Bundle();
            args.putByteArray(ImportKeysListFragment.ARG_KEYRING_BYTES, mImportData);
            args.putString(ImportKeysListFragment.ARG_IMPORT_FILENAME, mImportFilename);
            listFragment.setArguments(args);
            // replace container in view with fragment
            fragmentTransaction.replace(R.id.import_keys_list_container, listFragment);
            fragmentTransaction.commit();
        }
    }

    private void importFromQrCode() {
        new IntentIntegrator(this).initiateScan();
    }

    private void importFromNfc() {
        // show nfc help
        Intent intent = new Intent(this, HelpActivity.class);
        intent.putExtra(HelpActivity.EXTRA_SELECTED_TAB, 1);
        startActivityForResult(intent, 0);
    }

    /**
     * Show to dialog from where to import keys
     */
    public void showImportFromFileDialog() {
        // Message is received after file is selected
        Handler returnHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                if (message.what == FileDialogFragment.MESSAGE_OKAY) {
                    Bundle data = message.getData();
                    mImportFilename = data.getString(FileDialogFragment.MESSAGE_DATA_FILENAME);
                    mDeleteAfterImport = data.getBoolean(FileDialogFragment.MESSAGE_DATA_CHECKED);
                    
                    Log.d(Constants.TAG, "mImportFilename: " + mImportFilename);
                    Log.d(Constants.TAG, "mDeleteAfterImport: " + mDeleteAfterImport);

                    loadKeyListFragment();
                }
            }
        };

        // Create a new Messenger for the communication back
        final Messenger messenger = new Messenger(returnHandler);

        DialogFragmentWorkaround.INTERFACE.runnableRunDelayed(new Runnable() {
            public void run() {
                mFileDialog = FileDialogFragment.newInstance(messenger,
                        getString(R.string.title_importKeys),
                        getString(R.string.specifyFileToImportFrom), Constants.path.APP_DIR + "/",
                        null, Id.request.filename);

                mFileDialog.show(getSupportFragmentManager(), "fileDialog");
            }
        });
    }

    // private void importAndSignOld(final long keyId, final String expectedFingerprint) {
    // if (expectedFingerprint != null && expectedFingerprint.length() > 0) {
    //
    // Thread t = new Thread() {
    // @Override
    // public void run() {
    // try {
    // // TODO: display some sort of spinner here while the user waits
    //
    // // TODO: there should be only 1
    // HkpKeyServer server = new HkpKeyServer(mPreferences.getKeyServers()[0]);
    // String encodedKey = server.get(keyId);
    //
    // PGPKeyRing keyring = PGPHelper.decodeKeyRing(new ByteArrayInputStream(
    // encodedKey.getBytes()));
    // if (keyring != null && keyring instanceof PGPPublicKeyRing) {
    // PGPPublicKeyRing publicKeyRing = (PGPPublicKeyRing) keyring;
    //
    // // make sure the fingerprints match before we cache this thing
    // String actualFingerprint = PGPHelper.convertFingerprintToHex(publicKeyRing
    // .getPublicKey().getFingerprint());
    // if (expectedFingerprint.equals(actualFingerprint)) {
    // // store the signed key in our local cache
    // int retval = PGPMain.storeKeyRingInCache(publicKeyRing);
    // if (retval != Id.return_value.ok
    // && retval != Id.return_value.updated) {
    // status.putString(EXTRA_ERROR,
    // "Failed to store signed key in local cache");
    // } else {
    // Intent intent = new Intent(ImportFromQRCodeActivity.this,
    // SignKeyActivity.class);
    // intent.putExtra(EXTRA_KEY_ID, keyId);
    // startActivityForResult(intent, Id.request.sign_key);
    // }
    // } else {
    // status.putString(
    // EXTRA_ERROR,
    // "Scanned fingerprint does NOT match the fingerprint of the received key.  You shouldnt trust this key.");
    // }
    // }
    // } catch (QueryException e) {
    // Log.e(TAG, "Failed to query KeyServer", e);
    // status.putString(EXTRA_ERROR, "Failed to query KeyServer");
    // status.putInt(Constants.extras.STATUS, Id.message.done);
    // } catch (IOException e) {
    // Log.e(TAG, "Failed to query KeyServer", e);
    // status.putString(EXTRA_ERROR, "Failed to query KeyServer");
    // status.putInt(Constants.extras.STATUS, Id.message.done);
    // }
    // }
    // };
    //
    // t.setName("KeyExchange Download Thread");
    // t.setDaemon(true);
    // t.start();
    // }
    // }

    public void scanAgainOnClick(View view) {
        new IntentIntegrator(this).initiateScan();
    }

    public void finishOnClick(View view) {
        finish();
    }

    public void importOnClick(View view) {
        Log.d(Constants.TAG, "Import key button clicked!");

        importKeys();
    }

    /**
     * Import keys with mImportData
     */
    public void importKeys() {
        if (mImportData != null || mImportFilename != null) {
            Log.d(Constants.TAG, "importKeys started");

            // Send all information needed to service to import key in other thread
            Intent intent = new Intent(this, KeychainIntentService.class);

            intent.setAction(KeychainIntentService.ACTION_IMPORT_KEYRING);

            // fill values for this action
            Bundle data = new Bundle();

            // TODO: check for key type?
            // data.putInt(ApgIntentService.IMPORT_KEY_TYPE, Id.type.secret_key);

            if (mImportData != null) {
                data.putInt(KeychainIntentService.TARGET, KeychainIntentService.TARGET_BYTES);
                data.putByteArray(KeychainIntentService.IMPORT_BYTES, mImportData);
            } else {
                data.putInt(KeychainIntentService.TARGET, KeychainIntentService.TARGET_FILE);
                data.putString(KeychainIntentService.IMPORT_FILENAME, mImportFilename);
            }

            intent.putExtra(KeychainIntentService.EXTRA_DATA, data);

            // Message is received after importing is done in ApgService
            KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this,
                    R.string.progress_importing, ProgressDialog.STYLE_HORIZONTAL) {
                public void handleMessage(Message message) {
                    // handle messages by standard ApgHandler first
                    super.handleMessage(message);

                    if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) {
                        // get returned data bundle
                        Bundle returnData = message.getData();

                        int added = returnData.getInt(KeychainIntentService.RESULT_IMPORT_ADDED);
                        int updated = returnData.getInt(KeychainIntentService.RESULT_IMPORT_UPDATED);
                        int bad = returnData.getInt(KeychainIntentService.RESULT_IMPORT_BAD);
                        String toastMessage;
                        if (added > 0 && updated > 0) {
                            toastMessage = getString(R.string.keysAddedAndUpdated, added, updated);
                        } else if (added > 0) {
                            toastMessage = getString(R.string.keysAdded, added);
                        } else if (updated > 0) {
                            toastMessage = getString(R.string.keysUpdated, updated);
                        } else {
                            toastMessage = getString(R.string.noKeysAddedOrUpdated);
                        }
                        Toast.makeText(ImportKeysActivity.this, toastMessage, Toast.LENGTH_SHORT)
                                .show();
                        if (bad > 0) {
                            AlertDialog.Builder alert = new AlertDialog.Builder(
                                    ImportKeysActivity.this);

                            alert.setIcon(android.R.drawable.ic_dialog_alert);
                            alert.setTitle(R.string.warning);
                            alert.setMessage(ImportKeysActivity.this.getString(
                                    R.string.badKeysEncountered, bad));

                            alert.setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {
                                            dialog.cancel();
                                        }
                                    });
                            alert.setCancelable(true);
                            alert.create().show();
                        } else if (mDeleteAfterImport) {
                            // everything went well, so now delete, if that was turned on
                            DeleteFileDialogFragment deleteFileDialog = DeleteFileDialogFragment
                                    .newInstance(mImportFilename);
                            deleteFileDialog.show(getSupportFragmentManager(), "deleteDialog");
                        }
                    }
                };
            };

            // Create a new Messenger for the communication back
            Messenger messenger = new Messenger(saveHandler);
            intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger);

            // show progress dialog
            saveHandler.showProgressDialog(this);

            // start service with intent
            startService(intent);
        } else {
            Toast.makeText(this, R.string.error_nothingImport, Toast.LENGTH_LONG).show();
        }
    }

    public void signAndUploadOnClick(View view) {
        // first, import!
        importOnClick(view);

        // TODO: implement sign and upload!
        Toast.makeText(ImportKeysActivity.this, "Not implemented right now!", Toast.LENGTH_SHORT)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case Id.request.filename: {
            if (resultCode == RESULT_OK && data != null) {
                try {
                    String path = data.getData().getPath();
                    Log.d(Constants.TAG, "path=" + path);

                    // set filename used in export/import dialogs
                    mFileDialog.setFilename(path);
                } catch (NullPointerException e) {
                    Log.e(Constants.TAG, "Nullpointer while retrieving path!", e);
                }
            }
            return;
        }
        case IntentIntegrator.REQUEST_CODE: {
            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode,
                    data);
            if (scanResult != null && scanResult.getFormatName() != null) {

                // mScannedContent = scanResult.getContents();

                mImportData = scanResult.getContents().getBytes();
                mImportFilename = null;

                // mContentView.setText(mScannedContent);
                // String[] bits = scanResult.getContents().split(",");
                // if (bits.length != 2) {
                // return; // dont know how to handle this. Not a valid code
                // }
                //
                // long keyId = Long.parseLong(bits[0]);
                // String expectedFingerprint = bits[1];

                // importAndSign(keyId, expectedFingerprint);
            }

            break;
        }

        default: {
            super.onActivityResult(requestCode, resultCode, data);
        }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        loadKeyListFragment();
    }

}