updated getEmail and getScannedEmail endpoints. Added Polling and Rescan Inbox feature for EmailScreen.tsx

This commit is contained in:
2024-08-04 22:17:40 +08:00
parent 32a8f5d30f
commit 20cb565f2f
2 changed files with 162 additions and 99 deletions

View File

@@ -16,9 +16,9 @@ const API_URL_SET_BOOKMARK = "/v1/user/setBookmark";
const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark"; const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark";
const API_URL_GET_SCANNED_GMAILS = "/v1/gmail/getEmails"; const API_URL_GET_EMAILS = "/v1/gmail/getEmails";
const API_URL_GET_USER = "/v1/user/getUser"; // New endpoint const API_URL_GET_SCANNED_EMAILS = "/v1/gmail/getScannedEmails";
const API_URL_GET_USER = "/v1/user/getUser";
// Create an Axios instance // Create an Axios instance
@@ -103,37 +103,6 @@ export const getQRCodeDetails = async (qrCodeId: string) => {
}); });
}; };
// Function to get scanned Gmail emails
export const getEmails = async (accessToken: string) => {
console.log("getEmails function called");
try {
console.log("Making API request to get scanned emails with accessToken:", accessToken);
const response = await apiRequest({
method: 'get',
url: `${API_BASE_URL}${API_URL_GET_SCANNED_GMAILS}`,
headers: {
'accessToken': accessToken,
},
});
console.log("API Response:", response);
return response;
} catch (error) {
console.error("Error during getEmails API call:", error);
if (error.response) {
console.error("Response error data:", error.response.data);
} else if (error.request) {
console.error("Request error, no response received:", error.request);
} else {
console.error("Error message:", error.message);
}
throw error;
}
};
//----------- //-----------
// GET User's Scanned Histories // GET User's Scanned Histories
@@ -187,14 +156,67 @@ export const deleteAllScannedHistories = async () => {
}); });
}; };
// GET Scan user's GMAILS // GET already scanned emails from DB
export const getScannedGmails = async () => { export const getScannedEmails = async () => {
return apiRequest({ console.log("getScannedEmails function called");
try {
console.log("Making API request to get already scanned emails from the database");
const response = await apiRequest({
method: 'get', method: 'get',
url: `${API_BASE_URL}${API_URL_GET_SCANNED_GMAILS}` url: `${API_BASE_URL}${API_URL_GET_SCANNED_EMAILS}`
}); });
console.log("API Response:", response);
return response;
} catch (error) {
console.error("Error during getScannedEmails API call:", error);
if (error.response) {
console.error("Response error data:", error.response.data);
} else if (error.request) {
console.error("Request error, no response received:", error.request);
} else {
console.error("Error message:", error.message);
}
throw error;
}
}; };
// Function to get start the scanning of inbox in server
export const getEmails = async (accessToken: string, refreshToken: string) => {
console.log("getEmails function called");
try {
console.log("Making API request to get Gmail emails with accessToken and refreshToken");
const response = await apiRequest({
method: 'get',
url: `${API_BASE_URL}${API_URL_GET_EMAILS}`,
headers: {
accessToken,
refreshToken,
},
});
console.log("API Response:", response);
return response;
} catch (error) {
console.error("Error during getEmails API call:", error);
if (error.response) {
console.error("Response error data:", error.response.data);
} else if (error.request) {
console.error("Request error, no response received:", error.request);
} else {
console.error("Error message:", error.message);
}
throw error;
}
};
// Get user information // Get user information
export const getUserInfo = async () => { export const getUserInfo = async () => {
return apiRequest({ return apiRequest({

View File

@@ -1,55 +1,83 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, FlatList, StyleSheet, ActivityIndicator, Alert } from 'react-native'; import { View, Text, TouchableOpacity, FlatList, StyleSheet, ActivityIndicator, Alert } from 'react-native';
import { getEmails } from '../api/qrCodeAPI'; import { getEmails, getScannedEmails } from '../api/qrCodeAPI';
const EmailScreen: React.FC = () => { const EmailScreen: React.FC = () => {
const [selectedMessage, setSelectedMessage] = useState(null); const [selectedMessage, setSelectedMessage] = useState(null);
const [emailData, setEmailData] = useState(null); const [emailData, setEmailData] = useState(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [rescanLoading, setRescanLoading] = useState(false);
const [error, setError] = useState(null); const [error, setError] = useState(null);
useEffect(() => { useEffect(() => {
const fetchEmails = async () => { startPollingForScannedEmails();
}, []);
// Function to initiate the email fetching process
const initiateEmailFetch = async () => {
setRescanLoading(true);
try { try {
const emails = await getEmails('access Token here!!!'); // Replace with actual token retrieval // Call to start email fetching process
setEmailData(emails); const response = await getEmails(
'Access Token here',
'Refresh Token here'
);
setRescanLoading(false);
} catch (error) { } catch (error) {
setError('Error fetching emails.'); console.error('Error initiating email fetch:', error);
} finally { setError('Error rescanning inbox.');
setLoading(false); setRescanLoading(false);
} }
}; };
fetchEmails(); // Function to poll for scanned emails
}, []); const startPollingForScannedEmails = () => {
const pollingInterval = setInterval(async () => {
try {
const scannedEmails = await getScannedEmails();
if (scannedEmails) {
setEmailData(scannedEmails);
clearInterval(pollingInterval);
setLoading(false);
}
} catch (error) {
console.error('Error fetching scanned emails:', error);
setError('Error fetching emails.');
clearInterval(pollingInterval);
setLoading(false);
}
}, 3000); // Poll every 3 seconds
};
const handleSelectMessage = (message) => { const handleSelectMessage = (message) => {
setSelectedMessage(selectedMessage === message ? null : message); setSelectedMessage(selectedMessage === message ? null : message);
}; };
if (loading) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#ff69b4" />
<Text >Fetching emails...</Text>
</View>
);
}
if (error) {
return (
<View style={styles.errorContainer}>
<Text>{error}</Text>
</View>
);
}
return ( return (
<View style={styles.container}> <View style={styles.container}>
{loading && (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#ff69b4" />
<Text style={{ color: '#ff69b4' }}>Fetching emails...</Text>
</View>
)}
{error && (
<View style={styles.errorContainer}>
<Text style={{ color: '#ff69b4' }}>{error}</Text>
</View>
)}
{emailData && ( {emailData && (
<> <>
<Text style={styles.header}>{emailData.emailAddress}</Text> <View style={styles.buttonContainer}>
<TouchableOpacity onPress={initiateEmailFetch} style={styles.button}>
<Text style={styles.buttonText}>Rescan Inbox</Text>
</TouchableOpacity>
</View>
{rescanLoading && (
<View style={styles.rescanIndicator}>
<Text style={{ color: '#ff69b4' }}>Rescanning inbox...</Text>
</View>
)}
<FlatList <FlatList
data={emailData.messages} data={emailData.messages}
keyExtractor={(item) => item.messageId} keyExtractor={(item) => item.messageId}
@@ -86,7 +114,7 @@ const EmailScreen: React.FC = () => {
</View> </View>
))} ))}
</View> </View>
)} )}
</View> </View>
)} )}
</TouchableOpacity> </TouchableOpacity>
@@ -115,11 +143,24 @@ const styles = StyleSheet.create({
backgroundColor: '#f8f0fc', backgroundColor: '#f8f0fc',
padding: 10, padding: 10,
}, },
loadingText: { buttonContainer: {
fontSize: 18, justifyContent: 'center',
color: '#ff69b4', alignItems: 'center',
marginBottom: 10, marginVertical: 20,
textAlign: 'center', },
button: {
backgroundColor: '#ff69b4',
padding: 10,
borderRadius: 5,
},
buttonText: {
color: '#fff',
fontWeight: 'bold',
},
rescanIndicator: {
justifyContent: 'center',
alignItems: 'center',
marginVertical: 10,
}, },
emailListContainer: { emailListContainer: {
flex: 1, flex: 1,