index.android.js 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. const ReactNative = require('react-native')
  3. const RNPermissions = ReactNative.PermissionsAndroid;
  4. const AsyncStorage = ReactNative.AsyncStorage
  5. const RNPTypes = {
  6. location: RNPermissions.PERMISSIONS.ACCESS_FINE_LOCATION,
  7. camera: RNPermissions.PERMISSIONS.CAMERA,
  8. microphone: RNPermissions.PERMISSIONS.RECORD_AUDIO,
  9. contacts: RNPermissions.PERMISSIONS.READ_CONTACTS,
  10. event: RNPermissions.PERMISSIONS.READ_CALENDAR,
  11. storage: RNPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,
  12. photo: RNPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,
  13. }
  14. const RESULTS = {
  15. [ RNPermissions.RESULTS.GRANTED ]: 'authorized',
  16. [ RNPermissions.RESULTS.DENIED ]: 'denied',
  17. [ RNPermissions.RESULTS.NEVER_ASK_AGAIN ]: 'restricted',
  18. }
  19. const STORAGE_KEY = '@RNPermissions:didAskPermission:'
  20. const setDidAskOnce = p => AsyncStorage.setItem(STORAGE_KEY + p, 'true')
  21. const getDidAskOnce = p => AsyncStorage.getItem(STORAGE_KEY + p).then(res => !!res)
  22. class ReactNativePermissions {
  23. canOpenSettings() {
  24. return false
  25. }
  26. openSettings() {
  27. return Promise.reject('\'openSettings\' is Depricated on android')
  28. }
  29. getTypes() {
  30. return Object.keys(RNPTypes);
  31. }
  32. check(permission) {
  33. const androidPermission = RNPTypes[permission]
  34. if (!androidPermission) return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on Android`);
  35. const shouldShowRationale = ReactNative.NativeModules.PermissionsAndroid.shouldShowRequestPermissionRationale;
  36. return RNPermissions.check(androidPermission)
  37. .then(isAuthorized => {
  38. if (isAuthorized) return 'authorized'
  39. return getDidAskOnce(permission)
  40. .then(didAsk => {
  41. if (didAsk) {
  42. return shouldShowRationale(androidPermission)
  43. .then(shouldShow => shouldShow ? 'denied' : 'restricted')
  44. }
  45. return 'undetermined'
  46. })
  47. })
  48. }
  49. request(permission) {
  50. const androidPermission = RNPTypes[permission]
  51. if (!androidPermission) return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on Android`);
  52. return RNPermissions.request(androidPermission)
  53. .then(res => {
  54. return setDidAskOnce(permission)
  55. .then(() => RESULTS[res])
  56. });
  57. }
  58. checkMultiple(permissions) {
  59. return Promise.all(permissions.map(this.check.bind(this)))
  60. .then(res => res.reduce((pre, cur, i) => {
  61. var name = permissions[i]
  62. pre[name] = cur
  63. return pre
  64. }, {}))
  65. }
  66. }
  67. module.exports = new ReactNativePermissions()