index.android.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. call_phone: RNPermissions.PERMISSIONS.CALL_PHONE,
  14. }
  15. const RESULTS = {
  16. [ RNPermissions.RESULTS.GRANTED ]: 'authorized',
  17. [ RNPermissions.RESULTS.DENIED ]: 'denied',
  18. [ RNPermissions.RESULTS.NEVER_ASK_AGAIN ]: 'restricted',
  19. }
  20. const STORAGE_KEY = '@RNPermissions:didAskPermission:'
  21. const setDidAskOnce = p => AsyncStorage.setItem(STORAGE_KEY + p, 'true')
  22. const getDidAskOnce = p => AsyncStorage.getItem(STORAGE_KEY + p).then(res => !!res)
  23. class ReactNativePermissions {
  24. canOpenSettings() {
  25. return false
  26. }
  27. openSettings() {
  28. return Promise.reject('\'openSettings\' is Depricated on android')
  29. }
  30. getTypes() {
  31. return Object.keys(RNPTypes);
  32. }
  33. check(permission) {
  34. const androidPermission = RNPTypes[permission]
  35. if (!androidPermission) return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on Android`);
  36. const shouldShowRationale = ReactNative.NativeModules.PermissionsAndroid.shouldShowRequestPermissionRationale;
  37. return RNPermissions.check(androidPermission)
  38. .then(isAuthorized => {
  39. if (isAuthorized) return 'authorized'
  40. return getDidAskOnce(permission)
  41. .then(didAsk => {
  42. if (didAsk) {
  43. return shouldShowRationale(androidPermission)
  44. .then(shouldShow => shouldShow ? 'denied' : 'restricted')
  45. }
  46. return 'undetermined'
  47. })
  48. })
  49. }
  50. request(permission) {
  51. const androidPermission = RNPTypes[permission]
  52. if (!androidPermission) return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on Android`);
  53. return RNPermissions.request(androidPermission)
  54. .then(res => {
  55. return setDidAskOnce(permission)
  56. .then(() => RESULTS[res])
  57. });
  58. }
  59. checkMultiple(permissions) {
  60. return Promise.all(permissions.map(this.check.bind(this)))
  61. .then(res => res.reduce((pre, cur, i) => {
  62. var name = permissions[i]
  63. pre[name] = cur
  64. return pre
  65. }, {}))
  66. }
  67. }
  68. module.exports = new ReactNativePermissions()