@capgo/capacitor-permissions 0.0.0-stage → 8.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,263 @@
1
+ package app.capgo.permissions
2
+
3
+ import android.Manifest
4
+ import android.content.Context
5
+ import android.content.SharedPreferences
6
+ import android.content.pm.PackageManager
7
+ import android.os.Build
8
+ import androidx.core.app.ActivityCompat
9
+ import androidx.core.content.ContextCompat
10
+ import com.getcapacitor.Logger
11
+
12
+ class Permissions(private val context: Context) {
13
+ companion object {
14
+ const val GRANTED = "granted"
15
+ const val DENIED = "denied"
16
+ const val BLOCKED = "blocked"
17
+ const val LIMITED = "limited"
18
+ const val UNAVAILABLE = "unavailable"
19
+ private const val PREFS = "capgo_permissions_asked"
20
+ }
21
+
22
+ private val prefs: SharedPreferences
23
+ get() = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
24
+
25
+ fun getPluginVersion(): String = "native"
26
+
27
+ fun markAsked(permission: String) {
28
+ prefs.edit().putBoolean(permission, true).apply()
29
+ }
30
+
31
+ fun wasAsked(permission: String): Boolean = prefs.getBoolean(permission, false)
32
+
33
+ fun androidPermissionsFor(name: String): Array<String>? = permissionsFor(name, forRequest = false)
34
+
35
+ fun androidPermissionsToRequest(name: String): Array<String>? = permissionsFor(name, forRequest = true)
36
+
37
+ private fun permissionsFor(name: String, forRequest: Boolean): Array<String>? {
38
+ return when (name) {
39
+ "camera" -> arrayOf(Manifest.permission.CAMERA)
40
+ "microphone", "speechRecognition" -> arrayOf(Manifest.permission.RECORD_AUDIO)
41
+ "photoLibrary", "mediaImages" -> mediaImagePermissions(forRequest)
42
+ "photoLibraryAddOnly" -> writeStoragePermissions()
43
+ "contacts" -> arrayOf(Manifest.permission.READ_CONTACTS)
44
+ "calendar" -> arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
45
+ "locationWhenInUse" -> arrayOf(
46
+ Manifest.permission.ACCESS_COARSE_LOCATION,
47
+ Manifest.permission.ACCESS_FINE_LOCATION,
48
+ )
49
+ "locationAlways" -> locationAlwaysPermissions(forRequest)
50
+ "bluetooth" -> bluetoothPermissions()
51
+ "motion", "activityRecognition" -> activityRecognitionPermissions()
52
+ "notifications" -> notificationPermissions()
53
+ "phone" -> arrayOf(Manifest.permission.READ_PHONE_STATE)
54
+ "sms" -> arrayOf(Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS)
55
+ "mediaAudio" -> mediaAudioPermissions()
56
+ "mediaVideo" -> mediaVideoPermissions()
57
+ "reminders", "appTrackingTransparency" -> null
58
+ else -> null
59
+ }
60
+ }
61
+
62
+ fun checkStatus(name: String, activity: android.app.Activity?): String {
63
+ val declarePerms =
64
+ if (name == "locationAlways") {
65
+ androidPermissionsFor(name)
66
+ } else {
67
+ androidPermissionsToRequest(name)
68
+ } ?: return UNAVAILABLE
69
+ if (declarePerms.isEmpty()) {
70
+ return GRANTED
71
+ }
72
+ try {
73
+ if (!allDeclared(declarePerms)) {
74
+ return UNAVAILABLE
75
+ }
76
+ if (name == "photoLibrary" || name == "mediaImages") {
77
+ return checkPhotoLibraryStatus(activity)
78
+ }
79
+ val checkPerms = androidPermissionsFor(name) ?: return UNAVAILABLE
80
+ val allGranted = checkPerms.all { isGranted(it) }
81
+ if (allGranted) {
82
+ return GRANTED
83
+ }
84
+ // locationAlways: fine/coarse may be granted while background is not
85
+ if (name == "locationAlways" && partialLocationAlwaysGranted()) {
86
+ return DENIED
87
+ }
88
+ return deniedOrBlocked(name, checkPerms, activity)
89
+ } catch (e: SecurityException) {
90
+ Logger.error("Permissions", "SecurityException checking $name", e)
91
+ return UNAVAILABLE
92
+ }
93
+ }
94
+
95
+ fun shouldShowRationale(name: String, activity: android.app.Activity?): Boolean {
96
+ val perms = androidPermissionsFor(name) ?: return false
97
+ if (activity == null || perms.isEmpty()) {
98
+ return false
99
+ }
100
+ return perms.any { ActivityCompat.shouldShowRequestPermissionRationale(activity, it) }
101
+ }
102
+
103
+ private fun checkPhotoLibraryStatus(activity: android.app.Activity?): String {
104
+ if (Build.VERSION.SDK_INT >= 33) {
105
+ val full = isGranted(Manifest.permission.READ_MEDIA_IMAGES)
106
+ if (full) {
107
+ return GRANTED
108
+ }
109
+ if (Build.VERSION.SDK_INT >= 34 &&
110
+ isGranted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED)
111
+ ) {
112
+ return LIMITED
113
+ }
114
+ return deniedOrBlocked(
115
+ "photoLibrary",
116
+ arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
117
+ activity,
118
+ )
119
+ }
120
+ val storage = Manifest.permission.READ_EXTERNAL_STORAGE
121
+ if (isGranted(storage)) {
122
+ return GRANTED
123
+ }
124
+ return deniedOrBlocked("photoLibrary", arrayOf(storage), activity)
125
+ }
126
+
127
+ private fun deniedOrBlocked(
128
+ name: String,
129
+ perms: Array<String>,
130
+ activity: android.app.Activity?,
131
+ ): String {
132
+ if (activity != null &&
133
+ perms.any { ActivityCompat.shouldShowRequestPermissionRationale(activity, it) }
134
+ ) {
135
+ return DENIED
136
+ }
137
+ if (!wasAsked(name)) {
138
+ return DENIED
139
+ }
140
+ return BLOCKED
141
+ }
142
+
143
+ private fun partialLocationAlwaysGranted(): Boolean {
144
+ val foreground =
145
+ isGranted(Manifest.permission.ACCESS_FINE_LOCATION) ||
146
+ isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)
147
+ if (!foreground) {
148
+ return false
149
+ }
150
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
151
+ return !isGranted(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
152
+ }
153
+ return false
154
+ }
155
+
156
+ private fun isGranted(permission: String): Boolean {
157
+ return ContextCompat.checkSelfPermission(context, permission) ==
158
+ PackageManager.PERMISSION_GRANTED
159
+ }
160
+
161
+ private fun allDeclared(perms: Array<String>): Boolean {
162
+ val requested = declaredPermissions()
163
+ return perms.all { requested.contains(it) }
164
+ }
165
+
166
+ private fun declaredPermissions(): Set<String> {
167
+ return try {
168
+ val flags = PackageManager.GET_PERMISSIONS
169
+ val info = context.packageManager.getPackageInfo(context.packageName, flags)
170
+ info.requestedPermissions?.toSet() ?: emptySet()
171
+ } catch (_: Exception) {
172
+ emptySet()
173
+ }
174
+ }
175
+
176
+ private fun mediaImagePermissions(forRequest: Boolean): Array<String> {
177
+ return if (Build.VERSION.SDK_INT >= 33) {
178
+ if (!forRequest && Build.VERSION.SDK_INT >= 34) {
179
+ arrayOf(
180
+ Manifest.permission.READ_MEDIA_IMAGES,
181
+ Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED,
182
+ )
183
+ } else {
184
+ arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
185
+ }
186
+ } else {
187
+ arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
188
+ }
189
+ }
190
+
191
+ private fun mediaAudioPermissions(): Array<String> {
192
+ return if (Build.VERSION.SDK_INT >= 33) {
193
+ arrayOf(Manifest.permission.READ_MEDIA_AUDIO)
194
+ } else {
195
+ arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
196
+ }
197
+ }
198
+
199
+ private fun mediaVideoPermissions(): Array<String> {
200
+ return if (Build.VERSION.SDK_INT >= 33) {
201
+ arrayOf(Manifest.permission.READ_MEDIA_VIDEO)
202
+ } else {
203
+ arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
204
+ }
205
+ }
206
+
207
+ private fun writeStoragePermissions(): Array<String> {
208
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
209
+ emptyArray()
210
+ } else {
211
+ arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
212
+ }
213
+ }
214
+
215
+ private fun locationAlwaysPermissions(forRequest: Boolean): Array<String> {
216
+ val foreground =
217
+ arrayOf(
218
+ Manifest.permission.ACCESS_COARSE_LOCATION,
219
+ Manifest.permission.ACCESS_FINE_LOCATION,
220
+ )
221
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
222
+ return foreground
223
+ }
224
+ if (!forRequest) {
225
+ return foreground + Manifest.permission.ACCESS_BACKGROUND_LOCATION
226
+ }
227
+ val hasForeground =
228
+ isGranted(Manifest.permission.ACCESS_FINE_LOCATION) ||
229
+ isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)
230
+ return if (hasForeground) {
231
+ arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
232
+ } else {
233
+ foreground
234
+ }
235
+ }
236
+
237
+ private fun bluetoothPermissions(): Array<String> {
238
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
239
+ arrayOf(
240
+ Manifest.permission.BLUETOOTH_CONNECT,
241
+ Manifest.permission.BLUETOOTH_SCAN,
242
+ )
243
+ } else {
244
+ emptyArray()
245
+ }
246
+ }
247
+
248
+ private fun activityRecognitionPermissions(): Array<String> {
249
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
250
+ arrayOf(Manifest.permission.ACTIVITY_RECOGNITION)
251
+ } else {
252
+ emptyArray()
253
+ }
254
+ }
255
+
256
+ private fun notificationPermissions(): Array<String> {
257
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
258
+ arrayOf(Manifest.permission.POST_NOTIFICATIONS)
259
+ } else {
260
+ emptyArray()
261
+ }
262
+ }
263
+ }
@@ -0,0 +1,273 @@
1
+ package app.capgo.permissions
2
+
3
+ import android.Manifest
4
+ import android.content.Intent
5
+ import android.net.Uri
6
+ import android.os.Build
7
+ import android.provider.Settings
8
+ import androidx.activity.result.ActivityResultLauncher
9
+ import androidx.activity.result.contract.ActivityResultContracts
10
+ import androidx.core.app.ActivityCompat
11
+ import com.getcapacitor.JSObject
12
+ import com.getcapacitor.Plugin
13
+ import com.getcapacitor.PluginCall
14
+ import com.getcapacitor.PluginMethod
15
+ import com.getcapacitor.annotation.CapacitorPlugin
16
+ import org.json.JSONArray
17
+
18
+ @CapacitorPlugin(name = "Permissions")
19
+ class PermissionsPlugin : Plugin() {
20
+
21
+ private lateinit var implementation: Permissions
22
+ private var permissionLauncher: ActivityResultLauncher<Array<String>>? = null
23
+ private var pendingCall: PluginCall? = null
24
+ private var pendingName: String? = null
25
+ private var pendingQueue: MutableList<String> = mutableListOf()
26
+ private var pendingStatuses: JSObject? = null
27
+ private var pendingIsMultiple: Boolean = false
28
+
29
+ override fun load() {
30
+ implementation = Permissions(context)
31
+ permissionLauncher =
32
+ bridge.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->
33
+ finishPermissionRequest()
34
+ }
35
+ }
36
+
37
+ @PluginMethod
38
+ fun check(call: PluginCall) {
39
+ val name = call.getString("permission")
40
+ if (name.isNullOrBlank()) {
41
+ call.reject("permission is required")
42
+ return
43
+ }
44
+ call.resolve(statusResult(implementation.checkStatus(name, activity)))
45
+ }
46
+
47
+ @PluginMethod
48
+ fun request(call: PluginCall) {
49
+ val name = call.getString("permission")
50
+ if (name.isNullOrBlank()) {
51
+ call.reject("permission is required")
52
+ return
53
+ }
54
+ startRequest(call, listOf(name), multiple = false)
55
+ }
56
+
57
+ @PluginMethod
58
+ fun checkMultiple(call: PluginCall) {
59
+ val names = readPermissionList(call) ?: return
60
+ val statuses = JSObject()
61
+ for (name in names) {
62
+ statuses.put(name, implementation.checkStatus(name, activity))
63
+ }
64
+ val ret = JSObject()
65
+ ret.put("statuses", statuses)
66
+ call.resolve(ret)
67
+ }
68
+
69
+ @PluginMethod
70
+ fun requestMultiple(call: PluginCall) {
71
+ val names = readPermissionList(call) ?: return
72
+ startRequest(call, names, multiple = true)
73
+ }
74
+
75
+ @PluginMethod
76
+ fun shouldShowRationale(call: PluginCall) {
77
+ val name = call.getString("permission")
78
+ if (name.isNullOrBlank()) {
79
+ call.reject("permission is required")
80
+ return
81
+ }
82
+ val ret = JSObject()
83
+ ret.put("shouldShow", implementation.shouldShowRationale(name, activity))
84
+ call.resolve(ret)
85
+ }
86
+
87
+ @PluginMethod
88
+ fun openSettings(call: PluginCall) {
89
+ val type = call.getString("type") ?: "application"
90
+ val intent =
91
+ if (type == "notifications") {
92
+ Intent().apply {
93
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
94
+ action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
95
+ putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
96
+ } else {
97
+ action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
98
+ data = Uri.fromParts("package", context.packageName, null)
99
+ }
100
+ }
101
+ } else {
102
+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
103
+ data = Uri.fromParts("package", context.packageName, null)
104
+ }
105
+ }
106
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
107
+ context.startActivity(intent)
108
+ call.resolve()
109
+ }
110
+
111
+ @PluginMethod
112
+ fun requestPreciseLocation(call: PluginCall) {
113
+ startRequest(call, listOf("locationWhenInUse"), multiple = false)
114
+ }
115
+
116
+ @PluginMethod
117
+ fun getPluginVersion(call: PluginCall) {
118
+ call.resolve(JSObject().put("version", implementation.getPluginVersion()))
119
+ }
120
+
121
+ private fun startRequest(call: PluginCall, names: List<String>, multiple: Boolean) {
122
+ if (pendingCall != null) {
123
+ call.reject("Another permission request is in progress")
124
+ return
125
+ }
126
+ pendingCall = call
127
+ pendingIsMultiple = multiple
128
+ pendingStatuses = JSObject()
129
+ pendingQueue = names.toMutableList()
130
+ requestNext()
131
+ }
132
+
133
+ private fun requestNext() {
134
+ val call = pendingCall ?: return
135
+ if (pendingQueue.isEmpty()) {
136
+ finishAll(call)
137
+ return
138
+ }
139
+ val name = pendingQueue.removeAt(0)
140
+ pendingName = name
141
+ val perms =
142
+ try {
143
+ implementation.androidPermissionsToRequest(name)
144
+ } catch (e: SecurityException) {
145
+ pendingStatuses?.put(name, Permissions.UNAVAILABLE)
146
+ requestNext()
147
+ return
148
+ }
149
+ if (perms == null) {
150
+ pendingStatuses?.put(name, Permissions.UNAVAILABLE)
151
+ requestNext()
152
+ return
153
+ }
154
+ if (perms.isEmpty()) {
155
+ implementation.markAsked(name)
156
+ pendingStatuses?.put(name, Permissions.GRANTED)
157
+ requestNext()
158
+ return
159
+ }
160
+ val status = implementation.checkStatus(name, activity)
161
+ if (status == Permissions.GRANTED || status == Permissions.LIMITED) {
162
+ pendingStatuses?.put(name, status)
163
+ requestNext()
164
+ return
165
+ }
166
+ if (status == Permissions.UNAVAILABLE) {
167
+ pendingStatuses?.put(name, Permissions.UNAVAILABLE)
168
+ requestNext()
169
+ return
170
+ }
171
+ val launcher = permissionLauncher
172
+ if (launcher == null) {
173
+ // Fallback to ActivityCompat if launcher is missing
174
+ try {
175
+ ActivityCompat.requestPermissions(activity, perms, 29101)
176
+ } catch (e: SecurityException) {
177
+ pendingStatuses?.put(name, Permissions.UNAVAILABLE)
178
+ requestNext()
179
+ return
180
+ }
181
+ // Without launcher callback we resolve after marking asked via check
182
+ implementation.markAsked(name)
183
+ pendingStatuses?.put(name, implementation.checkStatus(name, activity))
184
+ requestNext()
185
+ return
186
+ }
187
+ try {
188
+ launcher.launch(perms)
189
+ } catch (e: SecurityException) {
190
+ pendingStatuses?.put(name, Permissions.UNAVAILABLE)
191
+ requestNext()
192
+ }
193
+ }
194
+
195
+ private fun finishPermissionRequest() {
196
+ val name = pendingName ?: return
197
+ implementation.markAsked(name)
198
+ val status = implementation.checkStatus(name, activity)
199
+ // locationAlways on Q+ needs a second prompt for background after foreground.
200
+ if (name == "locationAlways" &&
201
+ status != Permissions.GRANTED &&
202
+ status != Permissions.UNAVAILABLE &&
203
+ status != Permissions.BLOCKED
204
+ ) {
205
+ val nextPerms = implementation.androidPermissionsToRequest(name)
206
+ if (nextPerms != null &&
207
+ nextPerms.size == 1 &&
208
+ nextPerms[0] == Manifest.permission.ACCESS_BACKGROUND_LOCATION
209
+ ) {
210
+ val launcher = permissionLauncher
211
+ if (launcher != null) {
212
+ try {
213
+ launcher.launch(nextPerms)
214
+ return
215
+ } catch (_: SecurityException) {
216
+ pendingStatuses?.put(name, Permissions.UNAVAILABLE)
217
+ requestNext()
218
+ return
219
+ }
220
+ }
221
+ }
222
+ }
223
+ pendingStatuses?.put(name, implementation.checkStatus(name, activity))
224
+ requestNext()
225
+ }
226
+
227
+ private fun finishAll(call: PluginCall) {
228
+ val statuses = pendingStatuses ?: JSObject()
229
+ pendingCall = null
230
+ pendingName = null
231
+ pendingStatuses = null
232
+ pendingQueue = mutableListOf()
233
+ if (pendingIsMultiple) {
234
+ val ret = JSObject()
235
+ ret.put("statuses", statuses)
236
+ call.resolve(ret)
237
+ } else {
238
+ val keys = statuses.keys()
239
+ val first = if (keys.hasNext()) keys.next() else null
240
+ val status =
241
+ if (first != null) {
242
+ statuses.getString(first) ?: Permissions.UNAVAILABLE
243
+ } else {
244
+ Permissions.UNAVAILABLE
245
+ }
246
+ call.resolve(statusResult(status))
247
+ }
248
+ }
249
+
250
+ private fun statusResult(status: String): JSObject {
251
+ return JSObject().put("status", status)
252
+ }
253
+
254
+ private fun readPermissionList(call: PluginCall): List<String>? {
255
+ val arr: JSONArray? = call.getArray("permissions")
256
+ if (arr == null || arr.length() == 0) {
257
+ call.reject("permissions is required")
258
+ return null
259
+ }
260
+ val list = mutableListOf<String>()
261
+ for (i in 0 until arr.length()) {
262
+ val value = arr.optString(i, "")
263
+ if (value.isNotBlank()) {
264
+ list.add(value)
265
+ }
266
+ }
267
+ if (list.isEmpty()) {
268
+ call.reject("permissions is required")
269
+ return null
270
+ }
271
+ return list
272
+ }
273
+ }
File without changes