Search in sources :

Example 1 with Permission

use of com.getcapacitor.annotation.Permission in project capacitor by ionic-team.

the class Bridge method getPermissionStates.

/**
 * Helper to check all permissions and see the current states of each permission.
 *
 * @since 3.0.0
 * @return A mapping of permission aliases to the associated granted status.
 */
protected Map<String, PermissionState> getPermissionStates(Plugin plugin) {
    Map<String, PermissionState> permissionsResults = new HashMap<>();
    CapacitorPlugin annotation = plugin.getPluginHandle().getPluginAnnotation();
    for (Permission perm : annotation.permissions()) {
        // Otherwise, get its true state.
        if (perm.strings().length == 0 || (perm.strings().length == 1 && perm.strings()[0].isEmpty())) {
            String key = perm.alias();
            if (!key.isEmpty()) {
                PermissionState existingResult = permissionsResults.get(key);
                // auto set permission state to GRANTED if the alias is empty.
                if (existingResult == null) {
                    permissionsResults.put(key, PermissionState.GRANTED);
                }
            }
        } else {
            for (String permString : perm.strings()) {
                String key = perm.alias().isEmpty() ? permString : perm.alias();
                PermissionState permissionStatus;
                if (ActivityCompat.checkSelfPermission(this.getContext(), permString) == PackageManager.PERMISSION_GRANTED) {
                    permissionStatus = PermissionState.GRANTED;
                } else {
                    permissionStatus = PermissionState.PROMPT;
                    // Check if there is a cached permission state for the "Never ask again" state
                    SharedPreferences prefs = getContext().getSharedPreferences(PERMISSION_PREFS_NAME, Activity.MODE_PRIVATE);
                    String state = prefs.getString(permString, null);
                    if (state != null) {
                        permissionStatus = PermissionState.byState(state);
                    }
                }
                PermissionState existingResult = permissionsResults.get(key);
                // multiple permissions with the same alias must all be true, otherwise all false.
                if (existingResult == null || existingResult == PermissionState.GRANTED) {
                    permissionsResults.put(key, permissionStatus);
                }
            }
        }
    }
    return permissionsResults;
}
Also used : HashMap(java.util.HashMap) CapacitorPlugin(com.getcapacitor.annotation.CapacitorPlugin) SharedPreferences(android.content.SharedPreferences) Permission(com.getcapacitor.annotation.Permission)

Example 2 with Permission

use of com.getcapacitor.annotation.Permission in project capacitor by ionic-team.

the class Plugin method requestPermissions.

/**
 * Exported plugin call to request all permissions for this plugin.
 * To manually request permissions within a plugin use:
 * {@link #requestAllPermissions(PluginCall, String)}, or
 * {@link #requestPermissionForAlias(String, PluginCall, String)}, or
 * {@link #requestPermissionForAliases(String[], PluginCall, String)}
 *
 * @param call the plugin call
 */
@PluginMethod
public void requestPermissions(PluginCall call) {
    CapacitorPlugin annotation = handle.getPluginAnnotation();
    if (annotation == null) {
        // handle permission requests for plugins defined with @NativePlugin (prior to 3.0.0)
        NativePlugin legacyAnnotation = this.handle.getLegacyPluginAnnotation();
        String[] perms = legacyAnnotation.permissions();
        if (perms.length > 0) {
            saveCall(call);
            pluginRequestPermissions(perms, legacyAnnotation.permissionRequestCode());
        } else {
            call.resolve();
        }
    } else {
        // handle permission requests for plugins defined with @CapacitorPlugin (since 3.0.0)
        String[] permAliases = null;
        Set<String> autoGrantPerms = new HashSet<>();
        // If call was made with a list of specific permission aliases to request, save them
        // to be requested
        JSArray providedPerms = call.getArray("permissions");
        List<String> providedPermsList = null;
        try {
            providedPermsList = providedPerms.toList();
        } catch (JSONException ignore) {
        // do nothing
        }
        // If call was made without any custom permissions, request all from plugin annotation
        Set<String> aliasSet = new HashSet<>();
        if (providedPermsList == null || providedPermsList.isEmpty()) {
            for (Permission perm : annotation.permissions()) {
                // Otherwise, the alias is added to the list to be requested.
                if (perm.strings().length == 0 || (perm.strings().length == 1 && perm.strings()[0].isEmpty())) {
                    if (!perm.alias().isEmpty()) {
                        autoGrantPerms.add(perm.alias());
                    }
                } else {
                    aliasSet.add(perm.alias());
                }
            }
            permAliases = aliasSet.toArray(new String[0]);
        } else {
            for (Permission perm : annotation.permissions()) {
                if (providedPermsList.contains(perm.alias())) {
                    aliasSet.add(perm.alias());
                }
            }
            if (aliasSet.isEmpty()) {
                call.reject("No valid permission alias was requested of this plugin.");
            } else {
                permAliases = aliasSet.toArray(new String[0]);
            }
        }
        if (permAliases != null && permAliases.length > 0) {
            // request permissions using provided aliases or all defined on the plugin
            requestPermissionForAliases(permAliases, call, "checkPermissions");
        } else if (!autoGrantPerms.isEmpty()) {
            // if the plugin only has auto-grant permissions, return all as GRANTED
            JSObject permissionsResults = new JSObject();
            for (String perm : autoGrantPerms) {
                permissionsResults.put(perm, PermissionState.GRANTED.toString());
            }
            call.resolve(permissionsResults);
        } else {
            // no permissions are defined on the plugin, resolve undefined
            call.resolve();
        }
    }
}
Also used : CapacitorPlugin(com.getcapacitor.annotation.CapacitorPlugin) Permission(com.getcapacitor.annotation.Permission) JSONException(org.json.JSONException) HashSet(java.util.HashSet)

Example 3 with Permission

use of com.getcapacitor.annotation.Permission in project capacitor by ionic-team.

the class Plugin method getPermissionStringsForAliases.

/**
 * Gets the Android permission strings defined on the {@link CapacitorPlugin} annotation with
 * the provided aliases.
 *
 * @param aliases aliases for permissions defined on the plugin
 * @return Android permission strings associated with the provided aliases, if exists
 */
private String[] getPermissionStringsForAliases(@NonNull String[] aliases) {
    CapacitorPlugin annotation = handle.getPluginAnnotation();
    HashSet<String> perms = new HashSet<>();
    for (Permission perm : annotation.permissions()) {
        if (Arrays.asList(aliases).contains(perm.alias())) {
            perms.addAll(Arrays.asList(perm.strings()));
        }
    }
    return perms.toArray(new String[0]);
}
Also used : CapacitorPlugin(com.getcapacitor.annotation.CapacitorPlugin) Permission(com.getcapacitor.annotation.Permission) HashSet(java.util.HashSet)

Example 4 with Permission

use of com.getcapacitor.annotation.Permission in project capacitor by ionic-team.

the class Plugin method requestAllPermissions.

/**
 * Request all of the specified permissions in the CapacitorPlugin annotation (if any)
 *
 * If there is no registered permission callback for the PluginCall passed in, the call will
 * be rejected. Make sure a valid permission callback method is registered using the
 * {@link PermissionCallback} annotation.
 *
 * @since 3.0.0
 * @param call the plugin call
 * @param callbackName the name of the callback to run when the permission request is complete
 */
protected void requestAllPermissions(@NonNull PluginCall call, @NonNull String callbackName) {
    CapacitorPlugin annotation = handle.getPluginAnnotation();
    if (annotation != null) {
        HashSet<String> perms = new HashSet<>();
        for (Permission perm : annotation.permissions()) {
            perms.addAll(Arrays.asList(perm.strings()));
        }
        permissionActivityResult(call, perms.toArray(new String[0]), callbackName);
    }
}
Also used : CapacitorPlugin(com.getcapacitor.annotation.CapacitorPlugin) Permission(com.getcapacitor.annotation.Permission) HashSet(java.util.HashSet)

Example 5 with Permission

use of com.getcapacitor.annotation.Permission in project capacitor by ionic-team.

the class Plugin method initializeActivityLaunchers.

/**
 * Registers activity result launchers defined on plugins, used for permission requests and
 * activities started for result.
 */
void initializeActivityLaunchers() {
    List<Method> pluginClassMethods = new ArrayList<>();
    for (Class<?> pluginCursor = getClass(); !pluginCursor.getName().equals(Object.class.getName()); pluginCursor = pluginCursor.getSuperclass()) {
        pluginClassMethods.addAll(Arrays.asList(pluginCursor.getDeclaredMethods()));
    }
    for (final Method method : pluginClassMethods) {
        if (method.isAnnotationPresent(ActivityCallback.class)) {
            // register callbacks annotated with ActivityCallback for activity results
            ActivityResultLauncher<Intent> launcher = bridge.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> triggerActivityCallback(method, result));
            activityLaunchers.put(method.getName(), launcher);
        } else if (method.isAnnotationPresent(PermissionCallback.class)) {
            // register callbacks annotated with PermissionCallback for permission results
            ActivityResultLauncher<String[]> launcher = bridge.registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> triggerPermissionCallback(method, permissions));
            permissionLaunchers.put(method.getName(), launcher);
        }
    }
}
Also used : Context(android.content.Context) Arrays(java.util.Arrays) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) Intent(android.content.Intent) HashMap(java.util.HashMap) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ActivityCallback(com.getcapacitor.annotation.ActivityCallback) JSONException(org.json.JSONException) Locale(java.util.Locale) Map(java.util.Map) Method(java.lang.reflect.Method) PermissionHelper(com.getcapacitor.util.PermissionHelper) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) ActivityCompat(androidx.core.app.ActivityCompat) CapacitorPlugin(com.getcapacitor.annotation.CapacitorPlugin) Set(java.util.Set) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) Nullable(androidx.annotation.Nullable) PermissionCallback(com.getcapacitor.annotation.PermissionCallback) Configuration(android.content.res.Configuration) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) Activity(android.app.Activity) Permission(com.getcapacitor.annotation.Permission) ActivityResult(androidx.activity.result.ActivityResult) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Intent(android.content.Intent) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) Method(java.lang.reflect.Method) PermissionCallback(com.getcapacitor.annotation.PermissionCallback) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher)

Aggregations

CapacitorPlugin (com.getcapacitor.annotation.CapacitorPlugin)6 Permission (com.getcapacitor.annotation.Permission)6 HashSet (java.util.HashSet)4 HashMap (java.util.HashMap)2 JSONException (org.json.JSONException)2 Activity (android.app.Activity)1 Context (android.content.Context)1 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 PackageManager (android.content.pm.PackageManager)1 Configuration (android.content.res.Configuration)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1 ActivityResult (androidx.activity.result.ActivityResult)1 ActivityResultLauncher (androidx.activity.result.ActivityResultLauncher)1 ActivityResultContracts (androidx.activity.result.contract.ActivityResultContracts)1 NonNull (androidx.annotation.NonNull)1 Nullable (androidx.annotation.Nullable)1 AppCompatActivity (androidx.appcompat.app.AppCompatActivity)1 ActivityCompat (androidx.core.app.ActivityCompat)1