Skip to content

Commit

Permalink
Merge pull request #119 from oss-slu/116-Location
Browse files Browse the repository at this point in the history
116 location grabbing
  • Loading branch information
yashb196 authored Feb 12, 2024
2 parents 4319866 + a551ebd commit 69b9e47
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 10 deletions.
34 changes: 32 additions & 2 deletions __tests__/AddNoteScreen.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import PhotoScroller from "../lib/components/photoScroller";
import { Media } from '../lib/models/media_class';
import moxios from 'moxios';
import AudioContainer from '../lib/components/audio';
import * as Location from 'expo-location';

beforeAll(() => {
jest.spyOn(console, 'log').mockImplementation(() => {});
Expand All @@ -31,6 +32,11 @@ jest.mock('../lib/components/ThemeProvider', () => ({
}),
}));

jest.mock('expo-location', () => ({
getForegroundPermissionsAsync: jest.fn(),
requestForegroundPermissionsAsync: jest.fn(),
}));

describe("AddNoteScreen", () => {
let wrapper;
let setNoteContentMock;
Expand Down Expand Up @@ -64,10 +70,35 @@ describe("AddNoteScreen", () => {


});
});

/*describe("AddNoteScreen's checkLocationPermission method", () => {
it('Should show an alert when location permission is denied', async () => {
const wrapper = shallow(<AddNoteScreen />);
const button = wrapper.find('[testID="checklocationpermission"]');
});
// Mocking getForegroundPermissionsAsync to return denied status
const mockGetForegroundPermissionsAsync = jest.spyOn(Location, 'getForegroundPermissionsAsync');
mockGetForegroundPermissionsAsync.mockResolvedValueOnce({ status: 'denied' });
// Mocking requestForegroundPermissionsAsync to return granted status after a subsequent request
const mockRequestForegroundPermissionsAsync = jest.spyOn(Location, 'requestForegroundPermissionsAsync');
mockRequestForegroundPermissionsAsync.mockResolvedValueOnce({ status: 'granted' });
// Spy on Alert.alert to check if it's called with the correct arguments
const mockAlert = jest.spyOn(Alert, 'alert');
// Simulate onPress event of TouchableOpacity
button.props().onPress();
wrapper.find(TouchableOpacity).prop('onPress')();
// Expect Alert.alert to have been called with the correct arguments
expect(mockAlert).toHaveBeenCalledWith(
'Location permission denied',
'Please grant location permission to save the note or remove the title to not save.'
);
});
}); */

describe('PhotoScroller\'s handleNewMedia method', () => {
it('Show an alert when pressed with Take a photo or Choose a photo from camera roll', () => {
Expand All @@ -76,7 +107,6 @@ describe('PhotoScroller\'s handleNewMedia method', () => {
throw new Error('Function not implemented.');
}} active={true} />);
const button = wrapper.find('[testID="photoScrollerButton"]');

const mockAlert = jest.spyOn(Alert, 'alert');
button.props().onPress();

Expand Down
3 changes: 2 additions & 1 deletion app.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@
},
"updates": {
"url": "https://u.expo.dev/801029ef-db83-4668-a97a-5adcc4c333e2"

},
"extra": {

}
}
}
69 changes: 62 additions & 7 deletions lib/screens/AddNoteScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
KeyboardAvoidingView,
Platform
} from "react-native";
import * as Location from 'expo-location';
import { Note, AddNoteScreenProps } from "../../types";
import ToastMessage from 'react-native-toast-message';
import PhotoScroller from "../components/photoScroller";
Expand Down Expand Up @@ -50,6 +51,7 @@ const AddNoteScreen: React.FC<AddNoteScreenProps> = ({ navigation, route }) => {
const [keyboardHeight, setKeyboardHeight] = useState(0);
const scrollViewRef = useRef<ScrollView | null>(null);
const [initialLoad, setInitialLoad] = useState(true);
const [promptedMissingTitle, setPromptedMissingTitle] = useState(false);
const [location, setLocation] = useState<{
latitude: number;
longitude: number;
Expand Down Expand Up @@ -144,22 +146,75 @@ const AddNoteScreen: React.FC<AddNoteScreenProps> = ({ navigation, route }) => {
});
};

const checkLocationPermission = async () => {
try {
let { status } = await Location.getForegroundPermissionsAsync();

if (status !== 'granted') {
// Location permission not granted, request it
const requestResult = await Location.requestForegroundPermissionsAsync();

if (requestResult.status === 'denied') {
// Location permission denied after requesting, request again
const requestAgainResult = await Location.requestForegroundPermissionsAsync();
status = requestAgainResult.status;
}

if (status !== 'granted') {
// Location permission still not granted
Alert.alert("Location permission denied", "Please grant location permission to save the note or remove the title to not save.");
return false;
}
}

// Location permission already granted or granted after request
return true;
} catch (error) {
console.error("Error checking location permission:", error);
return false;
}
};

const saveNote = async () => {
const locationPermissionGranted = await checkLocationPermission();
if (titleText === "") {
navigation.goBack();
} else if (bodyText !== "" && titleText === "") {
Alert.alert("A title is necessary to save");
} else {
if (!promptedMissingTitle) {
setPromptedMissingTitle(true);
Alert.alert(
"Title is empty",
"Please enter a title to save the note, or press back again to confirm not saving the note.",
);
return;
} else {
navigation.goBack();
return;
}
}
if (!locationPermissionGranted) {
return; // Stop saving the note if location permission is not granted
}
else {
try {
const userLocation = await Location.getCurrentPositionAsync({});
const userID = await user.getId();
let latitude, longitude;

if (Platform.OS === 'ios') {
latitude = location?.latitude.toString();
longitude = location?.longitude.toString();
} else if (Platform.OS === 'android') {
latitude = userLocation.coords.latitude.toString();
longitude = userLocation.coords.longitude.toString();
}

const newNote = {
title: titleText,
text: bodyText,
media: newMedia,
audio: newAudio,
creator: userID,
latitude: location?.latitude.toString() || "",
longitude: location?.longitude.toString() || "",
latitude: latitude,
longitude: longitude,
published: isPublished,
tags: tags,
time: time,
Expand All @@ -182,7 +237,7 @@ const AddNoteScreen: React.FC<AddNoteScreenProps> = ({ navigation, route }) => {
<View style={NotePageStyles().topContainer}>

<View style={NotePageStyles().topButtonsContainer}>
<TouchableOpacity style={NotePageStyles().topButtons} onPress={saveNote}>
<TouchableOpacity style={NotePageStyles().topButtons} onPress={saveNote} testID="checklocationpermission">
<Ionicons name="arrow-back-outline" size={30} color={NotePageStyles().saveText.color} />
</TouchableOpacity>
<TextInput
Expand Down

0 comments on commit 69b9e47

Please sign in to comment.