wavelength_app/components/chat/mediaUtils.ts

66 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

2024-10-15 16:58:01 -05:00
import { Alert } from 'react-native';
import * as Linking from 'expo-linking';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import * as ImagePicker from 'expo-image-picker';
export const getPermissionAsync = async (
permission: Permissions.PermissionType) => {
const {status} = await Permissions.askAsync(permission);
if (status !== 'granted') {
const permissionName = permission.toLowerCase().replace('_', ' ');
Alert.alert(
`Cannot access ${permissionName}`,
`If you would like to use this feature, you will need to enable ` +
`the ${permissionName} permission in your phone's settings.`,
[
{
text: 'Let\'s go!',
onPress: () => Linking.openURL('app-settings:'),
},
{
text: 'Nevermind',
onPress: () => {},
style: 'cancel'
},
],
{ cancelable: true }
);
return false;
}
return true;
};
export const getLocationAsync = async (
onSend: (locations: { location: Location.LocationObjectCoords }[]) => void) => {
const response = await Location.requestForegroundPermissionsAsync();
if (!response.granted) return;
const location = await Location.getCurrentPositionAsync();
if (!location) return;
onSend([{ location: location.coords }]);
};
export const pickImageAsync = async (onSend: (images: {image: string}[]) => void) => {
const response = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (!response.granted) return;
const result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
if (result.canceled) return;
const images = result.assets.map(({ uri: image }) => ({ image }));
onSend(images);
};
export const takePictureAsync = async (onSend: (images: {image: string}[]) => void) => {
const response = await ImagePicker.requestCameraPermissionsAsync();
if (!response.granted) return;
const result = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});
if (result.canceled) return;
const images = result.assets.map(({ uri: image }) => ({ image }));
onSend(images);
};