Search in sources :

Example 1 with PluginResult

use of org.apache.cordova.PluginResult in project cordova-plugin-local-notifications by katzer.

the class LocalNotification method isPresent.

/**
     * If a notification with an ID is present.
     *
     * @param id
     *      Notification ID
     * @param command
     *      The callback context used when calling back into JavaScript.
     */
private void isPresent(int id, CallbackContext command) {
    boolean exist = getNotificationMgr().exist(id);
    PluginResult result = new PluginResult(PluginResult.Status.OK, exist);
    command.sendPluginResult(result);
}
Also used : PluginResult(org.apache.cordova.PluginResult)

Example 2 with PluginResult

use of org.apache.cordova.PluginResult in project cordova-plugin-local-notifications by katzer.

the class LocalNotification method isTriggered.

/**
     * If a notification with an ID is triggered.
     *
     * @param id
     *      Notification ID
     * @param command
     *      The callback context used when calling back into JavaScript.
     */
private void isTriggered(int id, CallbackContext command) {
    boolean exist = getNotificationMgr().exist(id, Notification.Type.TRIGGERED);
    PluginResult result = new PluginResult(PluginResult.Status.OK, exist);
    command.sendPluginResult(result);
}
Also used : PluginResult(org.apache.cordova.PluginResult)

Example 3 with PluginResult

use of org.apache.cordova.PluginResult in project cordova-plugin-zeroconf by becvert.

the class ZeroConf method execute.

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
    if (ACTION_GET_HOSTNAME.equals(action)) {
        if (hostname != null) {
            Log.d(TAG, "Hostname: " + hostname);
            callbackContext.success(hostname);
        } else {
            callbackContext.error("Error: undefined hostname");
            return false;
        }
    } else if (ACTION_REGISTER.equals(action)) {
        final String type = args.optString(0);
        final String domain = args.optString(1);
        final String name = args.optString(2);
        final int port = args.optInt(3);
        final JSONObject props = args.optJSONObject(4);
        final String addressFamily = args.optString(5);
        Log.d(TAG, "Register " + type + domain);
        cordova.getThreadPool().execute(new Runnable() {

            @Override
            public void run() {
                try {
                    if (registrationManager == null) {
                        List<InetAddress> selectedAddresses = addresses;
                        if ("ipv6".equalsIgnoreCase(addressFamily)) {
                            selectedAddresses = ipv6Addresses;
                        } else if ("ipv4".equalsIgnoreCase(addressFamily)) {
                            selectedAddresses = ipv4Addresses;
                        }
                        registrationManager = new RegistrationManager(selectedAddresses, hostname);
                    }
                    ServiceInfo service = registrationManager.register(type, domain, name, port, props);
                    if (service == null) {
                        callbackContext.error("Failed to register");
                        return;
                    }
                    JSONObject status = new JSONObject();
                    status.put("action", "registered");
                    status.put("service", jsonifyService(service));
                    Log.d(TAG, "Sending result: " + status.toString());
                    PluginResult result = new PluginResult(PluginResult.Status.OK, status);
                    callbackContext.sendPluginResult(result);
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage(), e);
                    callbackContext.error("Error: " + e.getMessage());
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                    callbackContext.error("Error: " + e.getMessage());
                } catch (RuntimeException e) {
                    Log.e(TAG, e.getMessage(), e);
                    callbackContext.error("Error: " + e.getMessage());
                }
            }
        });
    } else if (ACTION_UNREGISTER.equals(action)) {
        final String type = args.optString(0);
        final String domain = args.optString(1);
        final String name = args.optString(2);
        Log.d(TAG, "Unregister " + type + domain);
        if (registrationManager != null) {
            final RegistrationManager rm = registrationManager;
            cordova.getThreadPool().execute(new Runnable() {

                @Override
                public void run() {
                    rm.unregister(type, domain, name);
                    callbackContext.success();
                }
            });
        } else {
            callbackContext.success();
        }
    } else if (ACTION_STOP.equals(action)) {
        Log.d(TAG, "Stop");
        if (registrationManager != null) {
            final RegistrationManager rm = registrationManager;
            registrationManager = null;
            cordova.getThreadPool().execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        rm.stop();
                        callbackContext.success();
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                        callbackContext.error("Error: " + e.getMessage());
                    }
                }
            });
        } else {
            callbackContext.success();
        }
    } else if (ACTION_WATCH.equals(action)) {
        final String type = args.optString(0);
        final String domain = args.optString(1);
        final String addressFamily = args.optString(2);
        Log.d(TAG, "Watch " + type + domain);
        cordova.getThreadPool().execute(new Runnable() {

            @Override
            public void run() {
                try {
                    if (browserManager == null) {
                        List<InetAddress> selectedAddresses = addresses;
                        if ("ipv6".equalsIgnoreCase(addressFamily)) {
                            selectedAddresses = ipv6Addresses;
                        } else if ("ipv4".equalsIgnoreCase(addressFamily)) {
                            selectedAddresses = ipv4Addresses;
                        }
                        browserManager = new BrowserManager(selectedAddresses, hostname);
                    }
                    browserManager.watch(type, domain, callbackContext);
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                    callbackContext.error("Error: " + e.getMessage());
                } catch (RuntimeException e) {
                    Log.e(TAG, e.getMessage(), e);
                    callbackContext.error("Error: " + e.getMessage());
                }
            }
        });
        PluginResult result = new PluginResult(Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
    } else if (ACTION_UNWATCH.equals(action)) {
        final String type = args.optString(0);
        final String domain = args.optString(1);
        Log.d(TAG, "Unwatch " + type + domain);
        if (browserManager != null) {
            final BrowserManager bm = browserManager;
            cordova.getThreadPool().execute(new Runnable() {

                @Override
                public void run() {
                    bm.unwatch(type, domain);
                    callbackContext.success();
                }
            });
        } else {
            callbackContext.success();
        }
    } else if (ACTION_CLOSE.equals(action)) {
        Log.d(TAG, "Close");
        if (browserManager != null) {
            final BrowserManager bm = browserManager;
            browserManager = null;
            cordova.getThreadPool().execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        bm.close();
                        callbackContext.success();
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                        callbackContext.error("Error: " + e.getMessage());
                    }
                }
            });
        } else {
            callbackContext.success();
        }
    } else if (ACTION_REINIT.equals(action)) {
        Log.e(TAG, "Re-Initializing");
        cordova.getThreadPool().execute(new Runnable() {

            @Override
            public void run() {
                onDestroy();
                initialize(cordova, webView);
                callbackContext.success();
                Log.e(TAG, "Re-Initialization complete");
            }
        });
    } else {
        Log.e(TAG, "Invalid action: " + action);
        callbackContext.error("Invalid action: " + action);
        return false;
    }
    return true;
}
Also used : PluginResult(org.apache.cordova.PluginResult) JSONException(org.json.JSONException) IOException(java.io.IOException) ServiceInfo(javax.jmdns.ServiceInfo) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) InetAddress(java.net.InetAddress)

Example 4 with PluginResult

use of org.apache.cordova.PluginResult in project cordova-plugin-android-fingerprint-auth by mjwheatley.

the class FingerprintAuth method setPluginResultError.

public static boolean setPluginResultError(String errorMessage) {
    mCallbackContext.error(errorMessage);
    mPluginResult = new PluginResult(PluginResult.Status.ERROR);
    return false;
}
Also used : PluginResult(org.apache.cordova.PluginResult)

Example 5 with PluginResult

use of org.apache.cordova.PluginResult in project cordova-plugin-android-fingerprint-auth by mjwheatley.

the class FingerprintAuth method execute.

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            JSONArray of arguments for the plugin.
 * @param callbackContext The callback id used when calling back into JavaScript.
 * @return A PluginResult object with a status and message.
 */
public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    mCallbackContext = callbackContext;
    if (android.os.Build.VERSION.SDK_INT < 23) {
        Log.e(TAG, "minimum SDK version 23 required");
        mPluginResult = new PluginResult(PluginResult.Status.ERROR);
        mCallbackContext.error(PluginError.MINIMUM_SDK.name());
        mCallbackContext.sendPluginResult(mPluginResult);
        return true;
    }
    Log.v(TAG, "FingerprintAuth action: " + action);
    if (action.equals("availability")) {
        mAction = PluginAction.AVAILABILITY;
    } else if (action.equals("encrypt")) {
        mAction = PluginAction.ENCRYPT;
        mCipherModeCrypt = true;
    } else if (action.equals("decrypt")) {
        mAction = PluginAction.DECRYPT;
        mCipherModeCrypt = false;
    } else if (action.equals("delete")) {
        mAction = PluginAction.DELETE;
    }
    if (mAction != null) {
        final JSONObject arg_object = args.getJSONObject(0);
        JSONObject resultJson = new JSONObject();
        if (mAction != PluginAction.AVAILABILITY) {
            if (!arg_object.has("clientId")) {
                Log.e(TAG, "Missing required parameters.");
                mPluginResult = new PluginResult(PluginResult.Status.ERROR);
                mCallbackContext.error(PluginError.MISSING_PARAMETERS.name());
                mCallbackContext.sendPluginResult(mPluginResult);
                return true;
            }
            mClientId = arg_object.getString("clientId");
            if (arg_object.has("username")) {
                mUsername = arg_object.getString("username");
            }
        }
        switch(mAction) {
            case AVAILABILITY:
                if (!cordova.hasPermission(Manifest.permission.USE_FINGERPRINT)) {
                    cordova.requestPermission(this, PERMISSIONS_REQUEST_FINGERPRINT, Manifest.permission.USE_FINGERPRINT);
                } else {
                    sendAvailabilityResult();
                }
                return true;
            case ENCRYPT:
            case DECRYPT:
                boolean missingParam = false;
                mEncryptNoAuth = false;
                switch(mAction) {
                    case ENCRYPT:
                        String password = "";
                        if (arg_object.has("password")) {
                            password = arg_object.getString("password");
                        }
                        mClientSecret = mClientId + mUsername + CREDENTIAL_DELIMITER + password;
                        if (arg_object.has("encryptNoAuth")) {
                            mEncryptNoAuth = arg_object.getBoolean("encryptNoAuth");
                        }
                        break;
                    case DECRYPT:
                        if (arg_object.has("token")) {
                            mClientSecret = arg_object.getString("token");
                        } else {
                            missingParam = true;
                        }
                        break;
                }
                if (missingParam) {
                    Log.e(TAG, "Missing required parameters for specified action.");
                    mPluginResult = new PluginResult(PluginResult.Status.ERROR);
                    mCallbackContext.error(PluginError.MISSING_ACTION_PARAMETERS.name());
                    mCallbackContext.sendPluginResult(mPluginResult);
                    return true;
                }
                if (arg_object.has("disableBackup")) {
                    mDisableBackup = arg_object.getBoolean("disableBackup");
                }
                if (arg_object.has("locale")) {
                    mLangCode = arg_object.getString("locale");
                    Log.d(TAG, "Change language to locale: " + mLangCode);
                }
                if (arg_object.has("maxAttempts")) {
                    int maxAttempts = arg_object.getInt("maxAttempts");
                    if (maxAttempts < 5) {
                        mMaxAttempts = maxAttempts;
                    }
                }
                if (arg_object.has("userAuthRequired")) {
                    mUserAuthRequired = arg_object.getBoolean("userAuthRequired");
                }
                if (arg_object.has("dialogTitle")) {
                    mDialogTitle = arg_object.getString("dialogTitle");
                }
                if (arg_object.has("dialogMessage")) {
                    mDialogMessage = arg_object.getString("dialogMessage");
                }
                if (arg_object.has("dialogHint")) {
                    mDialogHint = arg_object.getString("dialogHint");
                }
                // Set language
                Resources res = cordova.getActivity().getResources();
                // Change locale settings in the app.
                DisplayMetrics dm = res.getDisplayMetrics();
                Configuration conf = res.getConfiguration();
                // The two argument Locale constructor signature must be used in that case.
                if (mLangCode.length() == 5) {
                    conf.locale = new Locale(mLangCode.substring(0, 2).toLowerCase(), mLangCode.substring(mLangCode.length() - 2).toUpperCase());
                } else {
                    conf.locale = new Locale(mLangCode.toLowerCase());
                }
                res.updateConfiguration(conf, dm);
                SecretKey key = getSecretKey();
                if (key == null) {
                    if (createKey()) {
                        key = getSecretKey();
                    }
                }
                if (key == null) {
                    mCallbackContext.sendPluginResult(mPluginResult);
                } else {
                    if (mEncryptNoAuth) {
                        onAuthenticated(false, null);
                    } else {
                        if (isFingerprintAuthAvailable()) {
                            cordova.getActivity().runOnUiThread(new Runnable() {

                                public void run() {
                                    // Set up the crypto object for later. The object will be authenticated by use
                                    // of the fingerprint.
                                    mFragment = new FingerprintAuthenticationDialogFragment();
                                    if (initCipher()) {
                                        mFragment.setCancelable(false);
                                        // Show the fingerprint dialog. The user has the option to use the fingerprint with
                                        // crypto, or you can fall back to using a server-side verified password.
                                        mFragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                                        FragmentTransaction transaction = cordova.getActivity().getFragmentManager().beginTransaction();
                                        transaction.add(mFragment, DIALOG_FRAGMENT_TAG);
                                        transaction.commitAllowingStateLoss();
                                    } else {
                                        if (!mDisableBackup) {
                                            // This happens if the lock screen has been disabled or or a fingerprint got
                                            // enrolled. Thus show the dialog to authenticate with their password
                                            mFragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                                            mFragment.setStage(FingerprintAuthenticationDialogFragment.Stage.NEW_FINGERPRINT_ENROLLED);
                                            FragmentTransaction transaction = cordova.getActivity().getFragmentManager().beginTransaction();
                                            transaction.add(mFragment, DIALOG_FRAGMENT_TAG);
                                            transaction.commitAllowingStateLoss();
                                        } else {
                                            Log.e(TAG, "Failed to init Cipher and backup disabled.");
                                            mCallbackContext.error(PluginError.INIT_CIPHER_FAILED.name());
                                            mPluginResult = new PluginResult(PluginResult.Status.ERROR);
                                            mCallbackContext.sendPluginResult(mPluginResult);
                                        }
                                    }
                                }
                            });
                            mPluginResult.setKeepCallback(true);
                        } else {
                            /**
                             *                                 Use backup
                             */
                            Log.v(TAG, "In backup");
                            if (useBackupLockScreen() == true) {
                                Log.v(TAG, "useBackupLockScreen: true");
                            } else {
                                Log.v(TAG, "useBackupLockScreen: false");
                            }
                            if (useBackupLockScreen()) {
                                showAuthenticationScreen();
                            } else {
                                Log.e(TAG, "Fingerprint authentication not available");
                                mPluginResult = new PluginResult(PluginResult.Status.ERROR);
                                mCallbackContext.error(PluginError.FINGERPRINT_NOT_AVAILABLE.name());
                                mCallbackContext.sendPluginResult(mPluginResult);
                            }
                        }
                    }
                }
                return true;
            case DELETE:
                boolean ivDeleted = false;
                boolean secretKeyDeleted = false;
                try {
                    mKeyStore.load(null);
                    mKeyStore.deleteEntry(mClientId);
                    secretKeyDeleted = true;
                    ivDeleted = deleteIV();
                } catch (KeyStoreException e) {
                    Log.e(TAG, "Error while deleting SecretKey.", e);
                } catch (CertificateException e) {
                    Log.e(TAG, "Error while deleting SecretKey.", e);
                } catch (NoSuchAlgorithmException e) {
                    Log.e(TAG, "Error while deleting SecretKey.", e);
                } catch (IOException e) {
                    Log.e(TAG, "Error while deleting SecretKey.", e);
                }
                if (ivDeleted && secretKeyDeleted) {
                    mPluginResult = new PluginResult(PluginResult.Status.OK);
                    mCallbackContext.success();
                } else {
                    Log.e(TAG, "Error while deleting Fingerprint data.");
                    mPluginResult = new PluginResult(PluginResult.Status.ERROR);
                    mCallbackContext.error(PluginError.FINGERPRINT_DATA_NOT_DELETED.name());
                }
                mCallbackContext.sendPluginResult(mPluginResult);
                return true;
        }
    }
    return false;
}
Also used : Locale(java.util.Locale) PluginResult(org.apache.cordova.PluginResult) Configuration(android.content.res.Configuration) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) DisplayMetrics(android.util.DisplayMetrics) SecretKey(javax.crypto.SecretKey) FragmentTransaction(android.app.FragmentTransaction) JSONObject(org.json.JSONObject) Resources(android.content.res.Resources)

Aggregations

PluginResult (org.apache.cordova.PluginResult)68 JSONException (org.json.JSONException)23 JSONObject (org.json.JSONObject)21 JSONArray (org.json.JSONArray)14 IOException (java.io.IOException)8 NativeToJsMessageQueue (org.apache.cordova.NativeToJsMessageQueue)6 Test (org.junit.Test)6 Uri (android.net.Uri)4 FileNotFoundException (java.io.FileNotFoundException)4 AlertDialog (android.app.AlertDialog)3 DialogInterface (android.content.DialogInterface)3 Intent (android.content.Intent)3 TextView (android.widget.TextView)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 OutputStream (java.io.OutputStream)3 ArrayList (java.util.ArrayList)3 CallbackContext (org.apache.cordova.CallbackContext)3 CordovaResourceApi (org.apache.cordova.CordovaResourceApi)3 SharedPreferences (android.content.SharedPreferences)2