react-native#PermissionsAndroid JavaScript Examples

The following examples show how to use react-native#PermissionsAndroid. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js    From react-native-audio-video-tools with MIT License 7 votes vote down vote up
askPermission = async (permission, title, message) => {
    return await PermissionsAndroid.request(
        permission,
        {
            title: title,
            message: message,
            buttonNegative: "Deny",
            buttonPositive: "Allow"
        }
    );
}
Example #2
Source File: Result.js    From react-native-audio-video-tools with MIT License 6 votes vote down vote up
isFilePermissionGranted = async () => {
    try {
        const readPermission = await askPermission(
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
            "RNAudioVideoTools App Read Permission",
            "In order to save your media, We need permission to access your phone folder"
        );
        const writePermission = await askPermission(
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
            "RNAudioVideoTools App Write Permission",
            "In order to save your media, We need permission to access your phone folder"
        );
        return readPermission === PermissionsAndroid.RESULTS.GRANTED
            && writePermission === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
        return null;
    }
}
Example #3
Source File: ImageUtil.js    From RRWallet with MIT License 6 votes vote down vote up
async function saveToCameraRoll(uri) {
  if (!_.isString(uri) || uri.length <= 0) {
    throw new Error(ERROR_MESSAGE_SAVE_IMAGE);
  }
  if (Platform.OS === "android") {
    try {
      const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
      if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
        throw new Error(ERROR_MESSAGE_SAVE_IMAGE);
      }
    } catch (err) {
      throw new Error(ERROR_MESSAGE_SAVE_IMAGE);
    }
  }
  try {
    await CameraRoll.saveToCameraRoll(uri);
  } catch (error) {
    throw new Error(ERROR_MESSAGE_SAVE_IMAGE);
  }
}
Example #4
Source File: permissions.js    From duofolio with GNU General Public License v3.0 6 votes vote down vote up
getStoragePermission = async () => {
	let permissions = await PermissionsAndroid.requestMultiple(
		[
			PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
			PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
		],
		{
			title: 'Duofolio Storage Permission',
			message: 'Duofolio needs to access your storage'
		}
	);

	if (permissions['android.permission.READ_EXTERNAL_STORAGE'] === 'granted') {
		return;
	} else {
		Alert.alert(
			'Permission required',
			'Allow Duofolio to access your storage',
			[{ text: 'OK', onPress: async () => await getStoragePermission() }],
			{ cancelable: false }
		);
	}
}
Example #5
Source File: permissions.js    From lx-music-mobile with Apache License 2.0 6 votes vote down vote up
requestStoragePermission = async() => {
  const isGranted = await checkStoragePermissions()
  if (isGranted) return isGranted

  try {
    const granted = await PermissionsAndroid.requestMultiple(
      [
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
      ],
      // {
      //   title: '存储读写权限申请',
      //   message:
      //     '洛雪音乐助手需要使用存储读写权限才能下载歌曲.',
      //   buttonNeutral: '一会再问我',
      //   buttonNegative: '取消',
      //   buttonPositive: '确定',
      // },
    )
    // console.log(granted)
    // console.log(Object.values(granted).every(r => r === PermissionsAndroid.RESULTS.GRANTED))
    // console.log(PermissionsAndroid.RESULTS)
    const granteds = Object.values(granted)
    return granteds.every(r => r === PermissionsAndroid.RESULTS.GRANTED)
      ? true
      : granteds.includes(PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN)
        ? null
        : false
    // if (granted === PermissionsAndroid.RESULTS.GRANTED) {
    //   console.log('You can use the storage')
    // } else {
    //   console.log('Storage permission denied')
    // }
  } catch (err) {
    console.warn(err)
    return err.message
  }
}
Example #6
Source File: App.js    From BLEServiceDiscovery with GNU General Public License v3.0 6 votes vote down vote up
App: () => React$Node = () => {


  if (Platform.OS === 'android') {
    // Calling the permission function
    const granted = PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      {
        title: 'Bluetooth Permissions',
        message: 'We need access to bluetooth permissions',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      // Permission Granted
      console.log('granted');
    }
  }
  return (
    <>
      <Provider store={store}>
        <NavigationContainer>
          <Stack.Navigator>
            <Stack.Screen name="BLEDevices" component={BLEList} />
            <Stack.Screen name="BLEServices" component={BLEservices} />
            <Stack.Screen
              name="BLECharacteristics"
              component={BLEservicecharacteristics}
            />
            <Stack.Screen
              name="BLECharacteristic"
              component={BLECharacteristic}
            />
          </Stack.Navigator>
        </NavigationContainer>
      </Provider>
    </>
  );
}
Example #7
Source File: index.js    From BLEServiceDiscovery with GNU General Public License v3.0 6 votes vote down vote up
requestLocationPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      {
        title: 'Location permission for bluetooth scanning',
        message: 'wahtever',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('Location permission for bluetooth scanning granted');
      return true;
    } else {
      console.log('Location permission for bluetooth scanning revoked');
      return false;
    }
  } catch (err) {
    console.warn(err);
    return false;
  }
}
Example #8
Source File: HomeHeadDivision.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
async requestLocationPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: 'Location Permission',
            message:
              'Please enable your location ' +
              'so you can clock in later!',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Location permission accept');
          this.findCoordinates();
        } else {
          console.log('Location permission denied');
        }
      } catch (err) {
        console.warn('Error: Get Location Permission');
      }
    }
Example #9
Source File: LoggedIn.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
async requestLocationPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: 'Location Permission',
            message:
              'Please enable your location ' +
              'so you can clock in later!',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Location permission accept');
          this.findCoordinates();
        } else {
          console.log('Location permission denied');
        }
      } catch (err) {
        console.warn('Error: Get Location Permission');
      }
    }
Example #10
Source File: fitness.js    From intentional-walk with MIT License 6 votes vote down vote up
async function requestPermissions() {
  // on Android, we now need to separately ask for permission to read from the phone's activity sensors
  // SEPARATELY from asking for permissions to use Google Fit APIs below...
  if (Platform.OS === 'android') {
    const result = await PermissionsAndroid.requestMultiple([
      'android.permission.ACTIVITY_RECOGNITION',
      'com.google.android.gms.permission.ACTIVITY_RECOGNITION',
    ]);
    if (
      result['android.permission.ACTIVITY_RECOGNITION'] !==
        PermissionsAndroid.RESULTS.GRANTED &&
      result['com.google.android.gms.permission.ACTIVITY_RECOGNITION'] !==
        PermissionsAndroid.RESULTS.GRANTED
    ) {
      return false;
    }
  }
  let permitted = await Fitness.requestPermissions(permissions);
  if (permitted && Platform.OS === 'android') {
    permitted = await Fitness.subscribeToSteps();
  }
  return permitted;
}
Example #11
Source File: permissions.js    From duofolio with GNU General Public License v3.0 5 votes vote down vote up
checkStoragePermissions = async () => {
	let granted = await PermissionsAndroid.check(
		PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
	);
	return granted;
}
Example #12
Source File: permissions.js    From lx-music-mobile with Apache License 2.0 5 votes vote down vote up
checkStoragePermissions = () => PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE)
Example #13
Source File: Layout.js    From react-native-audio-video-tools with MIT License 4 votes vote down vote up
Layout = ({navigation, viewContent, controlPanel, headerText, onUploadPressed, type}) => {
    const [remoteUrl, setRemoteUrl] = useState('');
    const [isSelectModalVisible, setIsSelectModalVisible] = useState(false);
    const [isUrlInputModalVisible, setIsUrlInputModalVisible] = useState(false);

    // Get default remote media url to use
    const defaultRemoteMediaUrl = type === 'audio'
        ? DEFAULT_REMOTE_AUDIO_URL
        : DEFAULT_REMOTE_VIDEO_URL;

    /**
     * Display url modal
     */
    const getFileFromUrl = () => {
        setIsUrlInputModalVisible(true);
        setIsSelectModalVisible(false);
    };

    /**
     * Handle remote url button press action
     * @param action
     */
    const onRemoteUrlBtnAction = (action) => {
        if (action === 'Ok') {
            if (isValidUrl(remoteUrl)) {
                onUploadPressed(remoteUrl);
                setIsUrlInputModalVisible(false);
                setRemoteUrl('');
            }
            else toast.error("Please enter a valid url");
        } else {
            setIsSelectModalVisible(true);
            setIsUrlInputModalVisible(false);
        }
    };

    /**
     * Ask permission to perform operation on file file
     * @returns {Promise<null|boolean>}
     */
    const isFilePermissionGranted = async () => {
        try {
            const readPermission = await askPermission(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                "RNAudioVideoTools App Read Permission",
                "In order to save your media, We need permission to access your phone folder"
            );
            const writePermission = await askPermission(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                "RNAudioVideoTools App Write Permission",
                "In order to save your media, We need permission to access your phone folder"
            );
            return readPermission === PermissionsAndroid.RESULTS.GRANTED
                && writePermission === PermissionsAndroid.RESULTS.GRANTED;
        } catch (err) {
            return null;
        }
    };

    /**
     * Select a file from picker and return its full path
     * @returns {Promise<void>}
     */
    const getFileFromPicker = async () => {
        try {

            // Ask permission to access file
            const _isFilePermissionGranted = await isFilePermissionGranted();

            // The following line is NOT a mistake
            if (_isFilePermissionGranted === false) {
                toast.error("You need to grant permission in order to continue");
                return;
            } else if (_isFilePermissionGranted === null) {
                toast.error("An error occur asking permission. Please try again later");
                return;
            }

            // Pick a single file
            const res = await DocumentPicker.pick({
                type: [DocumentPicker.types[type]],
            });

            // Get information about file in order to have its full path
            const result = await FS.stat(res.uri);

            // Remove ending "/" if present
            const path = result.path[result.path.length - 1] === '/'
                ? result.path.substring(0, result.path.length - 1) : result.path;

            // Prepend file protocol in order to be compatible with RNAudioVideoTools
            const destinationFileFullPath = 'file://' + path;

            // Return the response path
            onUploadPressed(destinationFileFullPath);
            setIsSelectModalVisible(false);
        } catch (err) {}
    };

    /**
     * Left component on header
     * @returns {*}
     */
    const renderLeftComponent = () => {
        return (
            <TouchableOpacity
                onPress={() => navigation.toggleDrawer()}
                hitSlop={{top: 20, left: 20, bottom: 20, right: 20}}
            >
                <Icon
                    name='menu'
                    color={COLORS.White}
                />
            </TouchableOpacity>
        );
    };

    /**
     * Right component on header
     * @returns {*}
     */
    const renderRightComponent = () => {
        return (
            <Button
                iconRight
                title="Select"
                icon={
                    <Icon
                        name="video-library"
                        type="material"
                        size={15}
                        color={COLORS.White}
                        style={{marginLeft: 5}}
                    />
                }
                onPress={() => setIsSelectModalVisible(true)}
            />
        );
    };

    return (
        <>
            <Header
                leftComponent={renderLeftComponent()}
                centerComponent={{ text: headerText, style: { color: COLORS.White, fontSize: 18 } }}
                rightComponent={renderRightComponent()}
            />
            <View style={styles.container}>
                <View style={styles.viewContent}>
                    {viewContent}
                </View>
                <View style={styles.middleContent} />
                <View style={styles.controlPanel}>
                    {controlPanel}
                </View>
            </View>
            <CustomModal
                title={"Choose a file"}
                isVisible={isSelectModalVisible}
                leftText={"From phone"}
                rightText={"From url"}
                onLeftClick={() => getFileFromPicker()}
                onRightClick={() => getFileFromUrl()}
                onCloseClick={() => setIsSelectModalVisible(false)}
                content={(
                    <Text style={{textAlign: 'center'}}>{`Please select ${type === 'audio' ? 'an audio' : 'a video'} file...`}</Text>
                )}
            />
            <CustomModal
                title={"Url"}
                isVisible={isUrlInputModalVisible}
                leftText={"Back"}
                rightText={"Ok"}
                onLeftClick={() => onRemoteUrlBtnAction('Cancel')}
                onRightClick={() => onRemoteUrlBtnAction('Ok')}
                onCloseClick={() => onRemoteUrlBtnAction('Cancel')}
                content={(
                    <View>
                        <Text>Please enter a remote url.</Text>
                        <Text>Example:
                            <Text
                                style={{color: PRIMARY_COLOR}}
                                onPress={() => setRemoteUrl(defaultRemoteMediaUrl)}
                            >
                                {' ' + defaultRemoteMediaUrl}
                            </Text>
                        </Text>
                        <Input
                            value={remoteUrl}
                            placeholder='url...'
                            onChangeText={setRemoteUrl}
                            containerStyle={{marginTop: 5}}
                        />
                    </View>
                )}
            />
        </>
    );
}
Example #14
Source File: user.js    From guardioes-app with Apache License 2.0 4 votes vote down vote up
UserProvider = ({ children }) => {
    const [credentials, setCredentials] = useState({})
    const [token, setToken] = useState('')
    const [user, setUser] = useState({})
    const [avatar, setAvatar] = useState('')
    const [households, setHouseholds] = useState([])
    const [householdAvatars, setHouseholdAvatars] = useState({})
    const [selected, setSelected] = useState({})
    const [surveys, setSurveys] = useState([])
    const [location, setLocation] = useState({})
    const [group, setGroup] = useState({})
    const [app, setApp] = useState({})
    const [appTips, setAppTips] = useState({ loading: true })
    const [score, setScore] = useState(0)
    const [lastReport, setLastReport] = useState('')
    const [lastForm, setLastForm] = useState('')

    const [isLoading, setIsLoading] = useState(true)
    const [isLoggedIn, setIsLoggedIn] = useState(true)
    const [isOffline, setIsOffline] = useState(false)
    const [needSignIn, setNeedSignIn] = useState(true)

    useEffect(() => {
        loadStoredData()

        const internetInfo = NetInfo.addEventListener((state) => {
            verifyInternetState(state)
        })

        return () => {
            internetInfo()
        }
    }, [])

    const loadStoredData = useCallback(async () => {
        // Loads only essencial data stored
        let email = ''
        let password = ''
        let token = ''

        await RNSecureStorage.get('userEmail')
            .then((data) => {
                email = data
            })
            .catch((err) => {
                console.log(err)
            })

        await RNSecureStorage.get('userPwd')
            .then((data) => {
                password = data
            })
            .catch((err) => {
                console.log(err)
            })

        await RNSecureStorage.get('userToken')
            .then((data) => {
                token = data
            })
            .catch((err) => {
                console.log(err)
            })

        const userData = JSON.parse(await AsyncStorage.getItem('userData'))
        const selectedData = JSON.parse(
            await AsyncStorage.getItem('selectedData')
        )

        if (email !== '' && password !== '') {
            setCredentials({
                email,
                password,
            })
        } else {
            await signOut()
        }
        if (token !== '') {
            setToken(token)
        }
        if (userData) {
            setUser(userData)
        }
        if (selectedData) {
            setSelected(selectedData)
        }

        SplashScreen.hide()
        setIsLoading(false)
    }, [])

    const loadSecondaryData = async () => {
        // Loads secondary data and verify user credentials
        const avatar = await AsyncStorage.getItem('userAvatar')
        const score = parseInt(await AsyncStorage.getItem('score'), 10)
        const appTips = JSON.parse(await AsyncStorage.getItem('appTips'))
        const lastReport = await AsyncStorage.getItem('lastReport')
        const lastForm = await AsyncStorage.getItem('lastForm')
        const householdsData = JSON.parse(
            await AsyncStorage.getItem('householdsData')
        )
        const householdAvatars = JSON.parse(
            await AsyncStorage.getItem('householdAvatars')
        )

        if (avatar) {
            setAvatar(avatar)
        }
        if (score) {
            setScore(score)
        }
        if (appTips) {
            setAppTips(appTips)
        } else {
            setAppTips({})
        }
        if (lastReport) {
            setLastReport(lastReport)
        }
        if (lastForm) {
            setLastForm(lastForm)
        }
        if (householdsData) {
            setHouseholds(householdsData)
        }
        if (householdAvatars) {
            setHouseholdAvatars(householdAvatars)
        }
        if (needSignIn) {
            await signIn(credentials)
        }
    }

    const verifyInternetState = (state) => {
        if (!state.isConnected) {
            setIsOffline(true)
        } else if (
            state.isInternetReachable === null ||
            state.isInternetReachable
        ) {
            setIsOffline(false)
        } else {
            setIsOffline(true)
        }
    }

    const storeUser = async (user, token = null, credentials = null) => {
        const { households } = user
        const { app } = user

        if (households) {
            storeHouseholds(households)
            user.households = undefined
        }
        if (app) {
            setApp(app)
            user.app = undefined
        }

        setUser(user)
        await AsyncStorage.setItem('userData', JSON.stringify(user))

        if (token) {
            setToken(token)

            await RNSecureStorage.set('userToken', token, {
                accessible: ACCESSIBLE,
            })
        }
        if (credentials) {
            await RNSecureStorage.set('userEmail', credentials.email, {
                accessible: ACCESSIBLE,
            })

            await RNSecureStorage.set('userPwd', credentials.password, {
                accessible: ACCESSIBLE,
            })
        }
    }

    const sendUserTagsToOneSignal = (user) => {
        const userGroup = user.group ? user.group.split('/')[3] : null

        OneSignal.setExternalUserId(user.id.toString())
        OneSignal.sendTags({
            city: user.city,
            group: userGroup,
            doses: user.doses,
        })
    }

    const signIn = async ({ email, password }) => {
        const response = await authUser({ user: { email, password } })

        if (response.status === 200) {
            storeUser(response.data.user, response.headers.authorization)
            sendUserTagsToOneSignal(response.data.user)
            setNeedSignIn(false)
        } else if (response.status === 401) {
            signOut()
        }
    }

    const removeUserTagsfromOneSignal = () => {
        OneSignal.removeExternalUserId()
        OneSignal.deleteTag('city')
        OneSignal.deleteTag('group')
        OneSignal.deleteTag('score')
        OneSignal.deleteTag('doses')
    }

    const signOut = async () => {
        // Delete user credentials and cache data stored
        await AsyncStorage.multiRemove([
            'userData',
            'userAvatar',
            'householdsData',
            'householdAvatars',
            'selectedData',
            'score',
            'appTips',
            'lastReport',
            'surveysData',
            'contentsData',
        ])

        RNSecureStorage.exists('userEmail').then((exists) =>
            exists ? RNSecureStorage.remove('userEmail') : null
        )

        RNSecureStorage.exists('userPwd').then((exists) =>
            exists ? RNSecureStorage.remove('userPwd') : null
        )

        RNSecureStorage.exists('userToken').then((exists) =>
            exists ? RNSecureStorage.remove('userToken') : null
        )

        removeUserTagsfromOneSignal()
        setIsLoggedIn(false)
    }

    const selectUser = async (person) => {
        if (person.description) {
            // Is a household
            person.user = undefined

            setSelected(person)
            await AsyncStorage.setItem('selectedData', JSON.stringify(person))
        } else {
            setSelected({})
            await AsyncStorage.removeItem('selectedData')
        }
    }

    const getCurrentUserInfo = () => {
        if (selected.description) {
            // Is a household
            return {
                ...selected,
                is_household: true,
                name: selected.description ? selected.description : '',
                description: undefined,
                avatar: householdAvatars[selected.id],
            }
        }
        return {
            ...user,
            is_household: false,
            name: user.user_name ? user.user_name : '',
            user_name: undefined,
            avatar,
        }
    }

    const updateUserAvatar = async (source) => {
        if (source) {
            setAvatar(source)
            await AsyncStorage.setItem('userAvatar', source)
        } else {
            setAvatar('')
            await AsyncStorage.removeItem('userAvatar')
        }
    }

    const storeHouseholds = async (households) => {
        households.sort(
            (a, b) =>
                new Date(b.created_at).getTime() -
                new Date(a.created_at).getTime()
        )
        setHouseholds(households)

        await AsyncStorage.setItem('householdsData', JSON.stringify(households))
    }

    const updateHouseholdAvatars = async (id, source) => {
        const newAvatars = { ...householdAvatars, [id]: source }
        setHouseholdAvatars(newAvatars)

        await AsyncStorage.setItem(
            'householdAvatars',
            JSON.stringify(newAvatars)
        )
    }

    const storeSurveys = (surveys) => {
        setSurveys(surveys)
        AsyncStorage.setItem('surveysData', JSON.stringify(surveys))
    }

    const getCurrentLocation = async () => {
        try {
            if (Platform.OS === 'android') {
                await PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                    {
                        title: translate('locationRequest.permissionTitle'),
                        message:
                            translate('locationRequest.permissionMessage') +
                            translate('locationRequest.permissionMessage2'),
                        buttonNegative: translate('locationRequest.cancelText'),
                        buttonPositive: translate('locationRequest.okText'),
                    }
                )
            }
        } catch (err) {
            console.warn(err)
        }

        return new Promise((resolve) =>
            Geolocation.getCurrentPosition(
                (position) => {
                    const local = {
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                        latitudeDelta: 0.06,
                        longitudeDelta: 0.06,
                        error: 0,
                    }
                    setLocation(local)
                    resolve(local)
                },
                (error) => {
                    Alert.alert(
                        translate('locationRequest.errorTitle'),
                        translate('locationRequest.errorMessage')
                    )
                    const local = {
                        latitude: 0,
                        longitude: 0,
                        latitudeDelta: 0.06,
                        longitudeDelta: 0.06,
                        error: error.code,
                    }
                    setLocation(local)
                    resolve(local)
                },
                {
                    enableHighAccuracy: true,
                    timeout: 30000,
                }
            )
        )
    }

    const getAppTip = (tip) => {
        if (appTips.loading) {
            return false
        }
        return !appTips[tip]
    }

    const hideAppTip = async (tip) => {
        const newTips = { ...appTips, [tip]: true }
        setAppTips(newTips)

        await AsyncStorage.setItem('appTips', JSON.stringify(newTips))
    }

    const updateUserScore = async () => {
        const lastReportDate = new Date(lastReport)
        const todayDate = new Date()

        lastReportDate.setHours(0, 0, 0, 0)
        let newScore = 0

        const daysDiff = Math.floor(
            (todayDate.getTime() - lastReportDate.getTime()) /
                (1000 * 60 * 60 * 24)
        )

        switch (daysDiff) {
            case 0:
                newScore = score
                console.warn('Already reported today')
                break
            case 1:
                newScore = score + 1
                setScore(newScore)
                setLastReport(todayDate.toString())
                console.warn('Reported the day before')
                break
            default:
                setScore(newScore)
                setLastReport(todayDate.toString())
                console.warn('Did not report the day before')
        }

        await AsyncStorage.setItem('score', newScore.toString())
        await AsyncStorage.setItem('lastReport', todayDate.toISOString())

        OneSignal.sendTags({ score: newScore })
        console.warn(`User score: ${newScore}`)
    }

    const storeLastForm = async (lastFormDate) => {
        const newLastForm = lastFormDate.toISOString()
        setLastForm(newLastForm)
        AsyncStorage.setItem('lastForm', newLastForm)
    }

    const storeCacheData = async (key, data) => {
        // Keep in mind that AsyncStorage space is only 6 MB on Android
        if (typeof data === 'string') {
            await AsyncStorage.setItem(key, data)
        } else {
            await AsyncStorage.setItem(key, JSON.stringify(data))
        }
    }

    const getCacheData = async (key, string = true) => {
        // This could be slow depending on size of data stored
        if (string) {
            return AsyncStorage.getItem(key)
        }
        return JSON.parse(await AsyncStorage.getItem(key))
    }

    return (
        <UserContext.Provider
            value={{
                token,
                user,
                loadSecondaryData,
                storeUser,
                selectUser,
                signOut,
                getCurrentUserInfo,
                avatar,
                updateUserAvatar,
                households,
                storeHouseholds,
                householdAvatars,
                updateHouseholdAvatars,
                surveys,
                storeSurveys,
                location,
                getCurrentLocation,
                group,
                setGroup,
                app,
                getAppTip,
                hideAppTip,
                score,
                updateUserScore,
                lastReport,
                lastForm,
                storeLastForm,
                storeCacheData,
                getCacheData,
                isLoading,
                isLoggedIn,
                setIsLoggedIn,
                isOffline,
                needSignIn,
                setNeedSignIn,
            }}
        >
            {children}
        </UserContext.Provider>
    )
}
Example #15
Source File: Controls.js    From app with GNU General Public License v3.0 4 votes vote down vote up
Controls = ({
	selectedSong,
	liked,
	onPressLike,
	paused,
	shuffleOn,
	repeatOn,
	onPressPlay,
	onPressPause,
	onBack,
	onForward,
	onPressShuffle,
	onPressRepeat,
	backwardDisabled,
	forwardDisabled,
	navig
}) => {
	const [chatModalVisible, setChatModalVisible] = useState(false);
	const [recommendModalVisible, setRecommendModalVisible] = useState(false);

  	const REMOTE_IMAGE_PATH = selectedSong.track_url
  	
	const checkPermission = async () => {

		if (Platform.OS === 'ios') {
			downloadImage();
		} else {
			try {
				const granted = await PermissionsAndroid.request(
					PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
					{
						title: 'Storage Permission Required',
						message:
						'App needs access to your storage to download Photos',
					}
				);

				if (granted === PermissionsAndroid.RESULTS.GRANTED) {
					console.log('Storage Permission Granted.');
					downloadImage();
				}
				else {
					ToastAndroid.show("Storage Permission Not Granted", ToastAndroid.SHORT);
				}
			}
			catch (err) {
				console.warn(err);
			}
		}
	};

 	const downloadImage = () => {

    	let media_URL = REMOTE_IMAGE_PATH;    
    
    	let ext = getExtention(media_URL);
    	
		ext = '.' + ext[0];
    
		const { config, fs } = RNFetchBlob;
		
		let PictureDir = fs.dirs.PictureDir;

		let options = {
			fileCache: true,
			addAndroidDownloads: {
				useDownloadManager: true,
				notification: true,
				path:
				PictureDir +
				'/song_' + 
				selectedSong.track_name +
				ext,
				description: 'Media',
			},
		};

		config(options)
			.fetch('GET', media_URL)
			.then(res => {
			console.log('res -> ', JSON.stringify(res));
			ToastAndroid.show("Downloaded Successfully", ToastAndroid.SHORT);
		});
  	};

  	const getExtention = filename => {
    	return /[.]/.exec(filename) ?
             /[^.]+$/.exec(filename) : undefined;
  	};

	return (
		<View style={styles.container}>
			<View>
				<ChatModal
					selectedSong={selectedSong}
					toggleVisibility={setChatModalVisible}
					modalVisible={chatModalVisible}
				/>
				<Recommend
					navig={navig}
					toggleVisibility={setRecommendModalVisible}
					modalVisible={recommendModalVisible}
				/>
				<View
					style={{
						width: '100%',
						bottom: '10%',
						flexDirection: 'row',
						justifyContent: 'space-around',
					}}>
					<TouchableOpacity
						activeOpacity={0}
						onPress={checkPermission}>
						<Icon
							size={30}
							name="download-outline"
							style={[
								{color: defaultString.darkColor}
							]}
						/>
					</TouchableOpacity>

					<TouchableOpacity
						onPress={onPressLike}>
						{liked ? (
							<Icon
								size={30}
								name="heart"
								style={[
									{
										color: defaultString.darkColor,
									},
								]}
							/>
						) : (
							<Icon
								size={30}
								name="heart-outline"
								style={[
									{
										color: defaultString.darkColor,
									},
								]}
							/>
						)}
					</TouchableOpacity>

					<TouchableOpacity
						onPress={() => {
							setRecommendModalVisible(true);
						}}>
						<OctIcon
							size={30}
							name="versions"
							style={[{color: defaultString.darkColor}]}
						/>
					</TouchableOpacity>
					<TouchableOpacity
						onPress={() => {
							console.log('sending to the moon');
							setChatModalVisible(true);
						}}>
						<Icon
							size={30}
							name="rocket-outline"
							style={[{color: defaultString.darkColor}]}
						/>
					</TouchableOpacity>
					<TouchableOpacity
						activeOpacity={0.0}
						onPress={onPressRepeat}>
						<Icon
							size={30}
							name="repeat-outline"
							style={[
								{color: defaultString.darkColor},
								repeatOn ? [] : styles.off,
							]}
						/>
					</TouchableOpacity>
				</View>
				<View
					style={{
						marginLeft: '20%',
						top: '5%',
						width: '60%',
						flexDirection: 'row',
						justifyContent: 'space-around',
					}}>
					<TouchableOpacity
						onPress={onBack}
						disabled={backwardDisabled}>
						<Icon
							size={40}
							name="play-skip-back-circle-outline"
							style={[
								{
									color: defaultString.darkColor,
								},
								backwardDisabled && {opacity: 0.3},
							]}
						/>
					</TouchableOpacity>
					{!paused ? (
						<TouchableOpacity onPress={onPressPause}>
							<View style={styles.playButton}>
								<Icon
									size={40}
									name="pause-outline"
									style={{
										color: defaultString.darkColor,
									}}
								/>
							</View>
						</TouchableOpacity>
					) : (
						<TouchableOpacity onPress={onPressPlay}>
							<View style={styles.playButton}>
								<Icon
									size={40}
									name="play-outline"
									style={{
										color: defaultString.darkColor,
										marginLeft: 5,
									}}
								/>
							</View>
						</TouchableOpacity>
					)}
					<TouchableOpacity
						onPress={onForward}
						disabled={forwardDisabled}>
						<Icon
							size={40}
							name="play-skip-forward-circle-outline"
							style={[
								forwardDisabled && {opacity: 0.3},
								{color: defaultString.darkColor},
							]}
						/>
					</TouchableOpacity>
				</View>
			</View>
		</View>
	);
}
Example #16
Source File: ContactsView.js    From WhatsApp-Clone with MIT License 4 votes vote down vote up
ContactsView = ({navigation, route}) => {
  const [contacts, setContacts] = useState([]);

  useEffect(() => {
    getRegisteredUsers();
  }, []);

  const getRegisteredUsers = () => {
    getLoggedInUserList()
      .then(async res => {
        console.log('User List Response => ', res.data);
        if (res.data.success) {
          var userList = res.data.data;
          var ownerID = await getLocalData(constants.USER_ID);

          for (let index = 0; index < userList.length; index++) {
            const user = userList[index];
            if (user.userId === ownerID) {
              userList.splice(index, 1);
            }
          }
          setContacts(userList);
        }
      })
      .catch(err => {
        console.log('User List Error => ', err);
      });
  };

  const getAllContacts = () => {
    if (Platform.OS === 'android') {
      console.log('PLATFORM => ', Platform.OS);
      PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS,
        {
          title: 'Contacts',
          message: 'This app would like to view your contacts.',
          buttonPositive: 'Accept',
        },
      )
        .then(flag => {
          console.log('WRITE_CONTACTS Permission Granted => ', flag);

          if (flag === 'granted') {
            PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
              {
                title: 'Contacts',
                message: 'This app would like to view your contacts.',
                buttonPositive: 'Accept',
              },
            )
              .then(flag => {
                console.log('READ_CONTACTS Permission Granted => ', flag);
                if (flag === 'granted') {
                  fectchContacts();
                }
              })
              .catch(() => {
                console.log('READ_CONTACTS Permission Denied');
              });
          }
        })
        .catch(() => {
          console.log('WRITE_CONTACTS Permission Denied');
        });
    } else {
      fectchContacts();
    }
  };

  const fectchContacts = () => {
    Contacts.getAll((err, contacts) => {
      if (err === 'denied') {
        // error
        console.log('fectchContacts Error');
      } else {
        // contacts returned in Array
        // console.log(JSON.stringify(contacts));

        setContacts(contacts);
      }
    });
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <Container>
        <ContactsHeaderView
          item={contacts ? contacts.length : 0}
          navigation={navigation}
        />
        {contacts.length <= 0 && <EmptyComponent message={'No User Found'} />}
        <FlatList
          // contentContainerStyle={DEFAULT_STYLES.container}
          data={contacts}
          keyExtractor={(item, index) => index.toString()}
          ItemSeparatorComponent={() => {
            return <_Divider />;
          }}
          renderItem={({item}) => {
            return (
              <ContactsItem
                item={item}
                navigation={navigation}
                userChatList={route.params.chatList}
              />
            );
          }}
        />
      </Container>
    </SafeAreaView>
  );
}