Recommit, without build falire (native_modules.gradle' line: 401, finished with non-zero exit value 1)

This commit is contained in:
2024-08-03 23:07:41 +08:00
parent 804eb6f024
commit 7f7f686ef8
6 changed files with 404 additions and 337 deletions

View File

@@ -1,2 +1,2 @@
NODE_ENV=development
BASE_URL=http://192.168.1.30:8080
BASE_URL=http://192.168.10.247:8080

View File

@@ -2,18 +2,22 @@ import axios from 'axios';
import Constants from 'expo-constants';
const { API_BASE_URL, ENVIRONMENT } = Constants.expoConfig.extra;
import { fetchAuthSession, getCurrentUser } from 'aws-amplify/auth';
//const API_BASE_URL = 'https://localhost:8443';
const API_URL_DETECT = "/v1/qrcodetypes/detect";
const API_URL_VERIFY_URL = "/v1/qrcodetypes/verifyURL"
const API_URL_VIRUS_TOTAL_CHECK = "/v1/qrcodetypes/virusTotalCheck"
const API_URL_CHECK_REDIRECTS = "/v1/qrcodetypes/checkRedirects"
const API_URL_GET_HISTORIES = "/v1/user/getScannedHistories"
const API_URL_DELETE_SCANNED_HISTORY = "/v1/user/deleteScannedHistories"
const API_URL_GET_BOOKMARKS = "/v1/user/getBookmarks"
const API_URL_SET_BOOKMARK = "/v1/user/setBookmark"
const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark"
const API_URL_GET_SCANNED_GMAILS = "/v1/gmail/getEmails"
const API_URL_SCAN = "/v1/qrcodetypes/scan";
const API_URL_GET_QR_DETAILS = "/v1/qrcodetypes/getQRDetails";
const API_URL_GET_HISTORIES = "/v1/user/getScannedHistories";
const API_URL_DELETE_SCANNED_HISTORY = "/v1/user/deleteScannedHistories";
const API_URL_DELETE_ALL_HISTORIES = "/v1/user/deleteAllScannedHistories";
const API_URL_GET_BOOKMARKS = "/v1/user/getBookmarks";
const API_URL_SET_BOOKMARK = "/v1/user/setBookmark";
const API_URL_DELETE_BOOKMARK = "/v1/user/deleteBookmark";
const API_URL_GET_SCANNED_GMAILS = "/v1/gmail/getEmails";
const API_URL_GET_USER = "/v1/user/getUser"; // New endpoint
// Create an Axios instance
const apiClient = axios.create({
@@ -36,6 +40,9 @@ apiClient.interceptors.request.use(
}
}
// Log the X-USER-ID header
console.log('X-USER-ID:', config.headers['X-USER-ID']);
return config;
},
(error) => {
@@ -47,22 +54,17 @@ apiClient.interceptors.request.use(
export const apiRequest = async (config) => {
try {
console.log("ENVIRONMENT:", ENVIRONMENT);
console.log(`API Call - ${config.method.toUpperCase()}:`, config.url, config.data || '');
console.log(config);
const response = await apiClient(config);
console.log('API Response:', response.data);
return response.data;
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code that falls out of the range of 2xx
console.error('API Error - Response:', error.response.data);
} else if (error.request) {
// The request was made but no response was received
console.error('API Error - No Response:', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.error('API Error - General:', error.message);
}
throw error;
@@ -81,37 +83,29 @@ const fetchUserId = async () => {
return currentUser.userId;
};
export const detectQRCodeType = async (data) => {
// Function to handle /scan request
export const scanQRCode = async (data) => {
return apiRequest({
method: 'post',
url: `${API_BASE_URL}${API_URL_DETECT}`,
url: `${API_BASE_URL}${API_URL_SCAN}`,
data: { data }
});
};
export const verifyURL = async (data) => {
// Function to get QR code details
export const getQRCodeDetails = async (qrCodeId: string) => {
return apiRequest({
method: 'post',
url: `${API_BASE_URL}${API_URL_VERIFY_URL}`,
data: { data }
method: 'get',
url: `${API_BASE_URL}${API_URL_GET_QR_DETAILS}`,
headers: { 'QR-ID': qrCodeId },
});
};
export const virusTotalCheck = async (data) => {
return apiRequest({
method: 'post',
url: `${API_BASE_URL}${API_URL_VIRUS_TOTAL_CHECK}`,
data: { data }
});
};
export const checkRedirects = async (data) => {
return apiRequest({
method: 'post',
url: `${API_BASE_URL}${API_URL_CHECK_REDIRECTS}`,
data: { data }
});
};
//-----------
// GET User's Scanned Histories
export const getScannedHistories = async () => {
return apiRequest({
@@ -119,7 +113,8 @@ export const getScannedHistories = async () => {
url: `${API_BASE_URL}${API_URL_GET_HISTORIES}`
});
};
// GET All User's Bookmark
// GET All User's Bookmarks
export const getAllUserBookmarks = async () => {
return apiRequest({
method: 'get',
@@ -132,7 +127,7 @@ export const setBookmark = async (qrCodeId: string) => {
return apiRequest({
method: 'post',
url: `${API_BASE_URL}${API_URL_SET_BOOKMARK}`,
data: { "qrCodeId": qrCodeId }
data: { qrCodeId }
});
};
@@ -141,7 +136,7 @@ export const deleteBookmark = async (qrCodeId: string) => {
return apiRequest({
method: 'put',
url: `${API_BASE_URL}${API_URL_DELETE_BOOKMARK}`,
data: { "qrCodeId": qrCodeId }
data: { qrCodeId }
});
};
@@ -150,7 +145,15 @@ export const deleteScannedHistory = async (qrCodeId: string) => {
return apiRequest({
method: 'put',
url: `${API_BASE_URL}${API_URL_DELETE_SCANNED_HISTORY}`,
data: { "qrCodeId": qrCodeId }
data: { qrCodeId }
});
};
// Function to delete all scanned histories
export const deleteAllScannedHistories = async () => {
return apiRequest({
method: 'put',
url: `${API_BASE_URL}${API_URL_DELETE_ALL_HISTORIES}`,
});
};
@@ -161,3 +164,11 @@ export const getScannedGmails = async () => {
url: `${API_BASE_URL}${API_URL_GET_SCANNED_GMAILS}`
});
};
// Get user information
export const getUserInfo = async () => {
return apiRequest({
method: 'get',
url: `${API_BASE_URL}${API_URL_GET_USER}`,
});
};

View File

@@ -1,40 +1,78 @@
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, Modal } from 'react-native';
import { View, Text, StyleSheet, Image, TouchableOpacity, Modal, ActivityIndicator, Alert } from 'react-native';
import QRCode from 'react-native-qrcode-svg';
import { Ionicons } from '@expo/vector-icons';
import * as Sharing from 'expo-sharing';
import { WebView } from 'react-native-webview';
//import * as Sharing from 'expo-sharing';
//import * as Clipboard from 'expo-clipboard'; // >.<
import { getQRCodeDetails } from '../api/qrCodeAPI';
import SecureWebView from '../components/SecureWebView'; // Import the SecureWebView component
// Define Props for ScannedDataBox component
interface ScannedDataBoxProps {
data: string;
dataType: string;
qrCodeId: string;
clearScanData: () => void;
scanResult: {
secureConnection: boolean;
virusTotalCheck: boolean;
redirects: number;
};
}
const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearScanData, scanResult }) => {
const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ qrCodeId, clearScanData }) => {
const [isModalVisible, setIsModalVisible] = useState(false);
const [qrDetails, setQrDetails] = useState<any>(null);
const [isWebViewVisible, setIsWebViewVisible] = useState(false);
console.log("ScannedDataBox -> Data", data);
console.log("DataType", dataType);
const [webViewUrl, setWebViewUrl] = useState('');
useEffect(() => {
console.log("Scan result set:", scanResult);
}, [data]);
const fetchQRDetails = async () => {
try {
const details = await getQRCodeDetails(qrCodeId);
setQrDetails(details.qrcode);
console.log('details for scannedDataBOX:', details);
} catch (error) {
console.error('Error fetching QR details:', error);
}
};
if (qrCodeId) {
fetchQRDetails();
}
}, [qrCodeId]);
if (!qrDetails) {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#ff69b4" />
</View>
);
}
// Clipboard Button KIV...cause it broke everything......
/* const copyToClipboard = async () => {
try {
const contents = qrDetails.data?.contents || 'Undefined';
await Clipboard.setStringAsync(contents);
Alert.alert('Copied to Clipboard', 'The QR code content has been copied to your clipboard.');
} catch (error) {
console.error('Error copying to clipboard:', error);
}
};
*/
// Handle cases where data might be undefined
const data = qrDetails.data || {};
const details = qrDetails.details || {};
const type = data.info?.type || 'Undefined';
const contents = data.contents || 'Undefined';
const secureConnection = details.hstsHeader?.includes('HSTS Header') ? '✔️' : '✘';
const redirects = details.redirect || 0;
const securityHeaders = details.hstsHeader || ['No Headers'];
const redirectChain = details.redirectChain || ['No Redirects'];
// Determine the result text based on scan result
const getResultText = () => {
if (!scanResult.secureConnection && !scanResult.virusTotalCheck) {
if (secureConnection === '✘' || redirects > 0) {
return 'DANGEROUS';
} else if (scanResult.redirects > 0) {
return 'WARNING';
} else {
} else if (secureConnection === '✔️' && redirects === 0) {
return 'SAFE';
} else {
return 'WARNING';
}
};
@@ -52,15 +90,9 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
}
};
const shareQRCodeData = async () => {
try {
await Sharing.shareAsync(data);
} catch (error) {
console.error('Error sharing QR code data:', error);
}
};
const openWebView = () => {
// Open the WebView for the URL
const openWebView = (url: string) => {
setWebViewUrl(url);
setIsWebViewVisible(true);
};
@@ -74,12 +106,12 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
{/* Display scanned data */}
<View style={styles.row}>
<Image source={require('../assets/ScanIcon3.png')} style={styles.scan_icon} />
<Text style={styles.payload}>{data}</Text>
<Text style={styles.payload}>{contents}</Text>
</View>
<View style={styles.divider} />
<Text style={styles.timestampText}>{new Date().toLocaleString()}</Text>
<Text style={styles.timestampText}>{data.createdAt ? new Date(data.createdAt).toLocaleString() : 'Invalid Date'}</Text>
<View style={styles.qrContainer}>
<QRCode value={data || 'No Data'} size={75} backgroundColor="transparent" />
<QRCode value={contents || 'No Data'} size={75} backgroundColor="transparent" />
<Text style={[styles.resultText, { color: getResultColor() }]}>
Result: {getResultText()}
</Text>
@@ -87,25 +119,46 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
<View style={styles.divider} />
{/* Display data type */}
<Text style={styles.typeText}>Type: {dataType}</Text>
<Text style={styles.typeText}>Type: {type}</Text>
<Text style={styles.blankLine}>{'\n'}</Text>
{/* Display scan checks */}
{type === 'URL' && (
<>
<Text style={styles.checksText}>Checks</Text>
<Text style={styles.checksText}>Secure Connection: {scanResult.secureConnection ? '✔️' : '✘'}</Text>
<Text style={styles.checksText}>Virus Total Check: {scanResult.virusTotalCheck ? '✔️' : '✘'}</Text>
<Text style={styles.checksText}>Redirects: {scanResult.redirects}</Text>
<Text style={styles.checksText}>Secure Connection: {secureConnection}</Text>
<Text style={styles.checksText}>Redirects: {redirects}</Text>
<TouchableOpacity style={styles.showAllButton} onPress={() => Alert.alert('Redirect Chain', redirectChain.join('\n'))}>
<Text style={styles.showAllButtonText}>Show all redirects</Text>
</TouchableOpacity>
</>
)}
{type === 'SMS' && (
<>
<Text style={styles.checksText}>Recipient Phone Number: {details.phone || 'Undefined'}</Text>
<Text style={styles.checksText}>Message Content: {details.message || 'Undefined'}</Text>
</>
)}
{type === 'TEXT' && (
<>
<Text style={styles.checksText}>Content: {contents}</Text>
</>
)}
{/* Action buttons */}
<View style={styles.iconContainer}>
<TouchableOpacity style={styles.iconButton} onPress={shareQRCodeData}>
<Ionicons name="share-social" size={18} color="#2196F3" />
<Text style={styles.iconText}>Share</Text>
<TouchableOpacity style={styles.iconButton} /*onPress={copyToClipboard}*/>
<Ionicons name="copy-outline" size={18} color="#2196F3" />
<Text style={styles.iconText}>Copy</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.iconButton} onPress={openWebView}>
{type === 'URL' && (
<TouchableOpacity style={styles.iconButton} onPress={() => openWebView(contents)}>
<Ionicons name="open" size={18} color="#2196F3" />
<Text style={styles.iconText}>Open</Text>
</TouchableOpacity>
)}
</View>
<View style={styles.divider} />
@@ -127,20 +180,17 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
<View style={styles.modalContainer}>
<View style={styles.modalContent}>
<Text style={styles.modalTitle}>Security Headers</Text>
<Text style={styles.modalText}>Name: Strict-Transport-Security</Text>
<Text style={styles.modalText}>Value: max-age=31536000; includeSubDomains</Text>
<Text style={styles.modalText}>Name: X-Frame-Options</Text>
<Text style={styles.modalText}>Value: DENY</Text>
<Text style={styles.modalText}>Name: X-Content-Type-Options</Text>
<Text style={styles.modalText}>Value: nosniff</Text>
<Text style={styles.modalText}>Name: Content-Security-Policy</Text>
<Text style={styles.modalText}>Value: default-src 'self'</Text>
{securityHeaders.map((header, index) => (
<Text key={index} style={styles.modalText}>{header}</Text>
))}
<TouchableOpacity style={styles.closeModalButton} onPress={() => setIsModalVisible(false)}>
<Text style={styles.closeModalButtonText}>Close</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
{/* SecureWebView Modal */}
<Modal
visible={isWebViewVisible}
transparent={true}
@@ -149,14 +199,7 @@ const ScannedDataBox: React.FC<ScannedDataBoxProps> = ({ data, dataType, clearSc
>
<View style={styles.modalContainer}>
<View style={styles.webViewContainer}>
<WebView
source={{ uri: data }}
javaScriptEnabled={false}
domStorageEnabled={false}
allowFileAccess={false}
originWhitelist={['*']}
onShouldStartLoadWithRequest={(request) => true}
/>
<SecureWebView url={webViewUrl} />
<TouchableOpacity style={styles.closeModalButton} onPress={() => setIsWebViewVisible(false)}>
<Text style={styles.closeModalButtonText}>Close</Text>
</TouchableOpacity>
@@ -303,13 +346,28 @@ const styles = StyleSheet.create({
fontSize: 12,
color: '#fff',
},
loadingContainer: {
justifyContent: 'center',
alignItems: 'center',
},
showAllButton: {
backgroundColor: '#2196F3',
borderRadius: 7.5,
padding: 5,
marginTop: 5,
},
showAllButtonText: {
color: '#fff',
fontSize: 12,
textAlign: 'center',
},
webViewContainer: {
width: '100%',
height: '80%',
backgroundColor: 'white',
borderRadius: 7.5,
overflow: 'hidden'
},
}
});
export default ScannedDataBox;

View File

@@ -1,5 +1,5 @@
import React, { useCallback, useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, BackHandler, Modal } from 'react-native';
import React, { useCallback, useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, Modal, ActivityIndicator } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import ScannedDataBox from '../components/ScannedDataBox';
import { Ionicons } from '@expo/vector-icons';
@@ -20,6 +20,9 @@ const HistoryScreen: React.FC = () => {
const [historiesLoading, setHistoriesLoading] = useState(false);
const [historiesError, setHistoriesError] = useState<string | null>(null);
const [selectedQrCodeId, setSelectedQrCodeId] = useState<string | null>(null);
const fetchHistories = useCallback(async () => {
if (!userAttributes?.sub) return;
@@ -27,8 +30,6 @@ const HistoryScreen: React.FC = () => {
setHistoriesLoading(true);
const historiesData = await getScannedHistories();
dispatch(setScannedHistories(historiesData));
setHistoriesLoading(false);
} catch (error: any) {
setHistoriesError(error.message);
} finally {
@@ -50,44 +51,18 @@ const HistoryScreen: React.FC = () => {
}, [dispatch, userAttributes]);
const [selectedData, setSelectedData] = useState<string | null>(null);
const [selectedScanResult, setSelectedScanResult] = useState<any | null>(null);
const [selectedType, setSelectedType] = useState<string | null>(null);
useEffect(() => {
const backAction = () => {
if (selectedData) {
setSelectedData(null);
setSelectedScanResult(null);
setSelectedType(null);
return true;
}
return false;
};
const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
return () => backHandler.remove();
}, [selectedData]);
const filteredQrCodes = showBookmarks ? histories.filter(qr => qr.bookmarked) : histories;
const handleItemPress = (item: QRCodeType) => {
// setSelectedData(item.data);
// setSelectedScanResult(item.scanResult);
// setSelectedType(item.type);
//setSelectedData(item.contents);
setSelectedType(item.data.type);
console.log('Selected QR code data:', item);
// console.log('Selected QR code type:', item.type);
setSelectedQrCodeId(item.data.id || null);
};
const clearSelectedData = () => {
setSelectedData(null);
setSelectedScanResult(null);
setSelectedType(null);
setSelectedQrCodeId(null);
};
return (
<View style={styles.container}>
{/* Header for toggling between History and Bookmarks */}
@@ -99,18 +74,28 @@ const HistoryScreen: React.FC = () => {
<Text style={showBookmarks ? styles.headerTextActive : styles.headerTextInactive}>Bookmarks</Text>
</TouchableOpacity>
</View>
{/* Loading Indicator */}
{historiesLoading && <ActivityIndicator size="large" color="#ff69b4" />}
{/* Display message when there are no histories or bookmarks */}
{!historiesLoading && filteredQrCodes.length === 0 && (
<Text style={styles.emptyMessage}>
{showBookmarks ? 'No bookmarks available' : 'No history available'}
</Text>
)}
{/* Display scanned data details */}
{selectedData && (
{selectedQrCodeId && (
<View style={styles.scannedDataBoxContainer}>
<ScannedDataBox data={selectedData} scanResult={selectedScanResult} dataType={selectedType} clearScanData={clearSelectedData} />
<ScannedDataBox qrCodeId={selectedQrCodeId} clearScanData={clearSelectedData} />
</View>
)}
{/* List of QR codes */}
<FlatList
data={filteredQrCodes}
renderItem={({ item }) => {
// console.log('Rendering QR code item:', item);
return (
renderItem={({ item }) => (
<View style={styles.itemContainer}>
<View style={styles.itemLeft}>
<TouchableOpacity onPress={() => handleItemPress(item)} style={styles.itemContent}>
@@ -135,15 +120,11 @@ const HistoryScreen: React.FC = () => {
</TouchableOpacity>
</View>
</View>
);
}}
keyExtractor={(item, index) => {
//console.log(item, index);
return index.toString();
}}
)}
keyExtractor={(item, index) => index.toString()}
contentContainerStyle={styles.flatListContent}
/>
{/* Modal for delete confirmation */}
<Modal
transparent={true}
@@ -234,6 +215,15 @@ const styles = StyleSheet.create({
flatListContent: {
paddingBottom: 100,
},
emptyMessage: {
textAlign: 'center',
fontSize: 16,
color: '#ff69b4',
marginVertical: 20,
},
scannedDataBoxContainer: {
marginBottom: 20,
},
modalContainer: {
flex: 1,
justifyContent: 'center',
@@ -271,9 +261,6 @@ const styles = StyleSheet.create({
fontSize: 16,
color: '#000',
},
scannedDataBoxContainer: {
marginBottom: 20,
},
});
export default HistoryScreen;

View File

@@ -1,40 +1,29 @@
import React, { useState, useEffect, useContext, useCallback } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, TouchableOpacity, Alert, Modal } from 'react-native';
import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, TouchableOpacity, Modal, TouchableWithoutFeedback } from 'react-native';
import { Camera, CameraView, scanFromURLAsync } from 'expo-camera';
import { QRCodeContext } from '../types';
import axios from 'axios'; // For URL calls
import { Ionicons } from '@expo/vector-icons'; // For icons
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import * as ImagePicker from 'expo-image-picker';
import ScannedDataBox from '../components/ScannedDataBox';
import { useDispatch } from 'react-redux';
import { RootState, AppDispatch } from '../store';
import { addQRCode } from '../reducers/qrCodesReducer'; // Assuming you have actions defined for Redux
import { detectQRCodeType, verifyURL, checkRedirects } from '../api/qrCodeAPI'; // Import utility functions
import SettingsScreen from './SettingsScreen'; // Import the Settings screen
import { AppDispatch } from '../store';
import { addQRCode } from '../reducers/qrCodesReducer';
import { scanQRCode, getUserInfo } from '../api/qrCodeAPI';
import SettingsScreen from './SettingsScreen';
const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanData }) => {
const navigation = useNavigation(); // call Navigation bar
const navigation = useNavigation(); // Navigation hook
const dispatch = useDispatch<AppDispatch>(); // Use dispatch for Redux actions
const [showSplash, setShowSplash] = useState<boolean>(true); // call splash screen
const qrCodeContext = useContext(QRCodeContext); // From ./types.ts
const { qrCodes, setQrCodes } = qrCodeContext || { qrCodes: [], setQrCodes: () => {} };
// State variables
const [showSplash, setShowSplash] = useState<boolean>(true); // State for splash screen visibility
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
const [scanned, setScanned] = useState<boolean>(false);
const [scannedData, setScannedData] = useState<string>(''); // State for QR scanned Data
const [dataType, setDataType] = useState<string>(''); // State for data type
const [qrCodeId, setQRCodeId] = useState<string | null>(null); // State for QR code ID
const [enableTorch, setEnableTorch] = useState<boolean>(false); // State for torch
const [cameraVisible, setCameraVisible] = useState<boolean>(true); // State to control camera visibility
// State to control the visibility of the modal
const [isSettingsModalVisible, setIsSettingsModalVisible] = useState<boolean>(false);
// Add state variables for scan results
const [secureConnection, setSecureConnection] = useState<boolean | null>(null);
const [virusTotalCheck, setVirusTotalCheck] = useState<boolean | null>(null);
const [redirects, setRedirects] = useState<number | null>(null);
const [isScannedDataBoxVisible, setIsScannedDataBoxVisible] = useState<boolean>(false); // State for ScannedDataBox modal visibility
const [isSettingsModalVisible, setIsSettingsModalVisible] = useState<boolean>(false); // State for modal visibility
// Request Camera Permission and initialize the app
useEffect(() => {
@@ -43,79 +32,71 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
setHasPermission(status === 'granted');
setShowSplash(false);
console.log("Camera permissions initialized");
// Fetch and log user information
fetchUserInformation();
};
initializeApp();
}, []);
// Focus effect to enable camera and clear data on focus
useFocusEffect(
useCallback(() => {
setCameraVisible(true);
clearScanDataInternal();
console.log("Screen focused, scan data cleared and camera enabled");
return () => {
setCameraVisible(false);
console.log("Screen unfocused, camera disabled");
};
}, [navigation])
);
// Clear Scan Data
const clearScanDataInternal = () => {
setScannedData('');
setScanned(false);
setDataType('');
setQRCodeId(null);
console.log("Scan data cleared");
};
// Handle scanning of payload (QR code data) and get the QR-ID
const handlePayload = async (payload: string) => {
setScanned(true);
console.log("Scanning Completed. Payload is:", payload);
const type = await detectQRCodeType(payload);
const secureConnectionResult = await verifyURL(payload);
const redirectResult = await checkRedirects(payload);
setSecureConnection(secureConnectionResult.isSecure);
setVirusTotalCheck(!secureConnectionResult.isMalicious); // Assuming you have virusTotalCheck logic integrated here
setRedirects(redirectResult.redirects);
const qrCode = {
data: payload,
type,
scanResult: {
secureConnection: secureConnectionResult.isSecure,
virusTotalCheck: !secureConnectionResult.isMalicious,
redirects: redirectResult.redirects
},
bookmarked: false // by default
};
setScannedData(payload);
console.log("Payload received:", payload);
console.log("Type received from server:", type);
setDataType(type);
dispatch(addQRCode(qrCode)); // Dispatch action to save QR code data
console.log("QR code data added to history");
};
const sendToAPIServer = async (payload: string): Promise<string> => {
console.log('Sending QR code data to backend:', payload);
console.info("Decoded QR Code, Payload is: ", payload);
try {
const response = await axios.post('http://192.168.1.30:8080/v1/qrcodetypes/scan', {
data: payload,
}, {
headers: {
'Content-Type': 'application/json',
},
});
console.log('Response from backend:', response.data);
return response.data;
const response = await scanQRCode(payload);
const qrCodeId = response.qrcode.data.id;
// Store the QR code ID for later use
setQRCodeId(qrCodeId);
setIsScannedDataBoxVisible(true); // Show ScannedDataBox modal
// Optionally, show a message or perform another action
console.log("QR code scanned successfully, ID:", qrCodeId);
} catch (error) {
console.error('Error detecting QR code type:', error);
return 'UNKNOWN';
console.error("Error scanning QR code:", error);
}
};
// Fetch and log user information
const fetchUserInformation = async () => {
try {
const userInfo = await getUserInfo();
console.log('User Info:', userInfo);
} catch (error) {
console.error('Error fetching user information:', error);
}
};
// Toggle torch (flashlight) on/off
const toggleTorch = () => {
setEnableTorch((prev) => !prev);
console.log("Torch toggled:", enableTorch ? "off" : "on");
};
const handleTestScan = () => {
handlePayload('TEST123');
console.log("Test scan executed");
};
// Read QR from image
const readQRFromImage = async () => {
clearScanDataInternal();
console.log("Reading QR code from image");
@@ -133,30 +114,15 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
handlePayload(scannedResult[0].data);
console.log('QR code data from image:', scannedResult[0].data);
} else {
setScannedData("No QR Code Found");
console.log("No QR code found in the selected image");
Alert.alert('No QR code found in the selected image.');
}
} catch (error) {
console.error('Error scanning QR code from image:', error);
Alert.alert('Failed to scan QR code from image.');
}
}
};
useFocusEffect(
useCallback(() => {
setCameraVisible(true);
clearScanDataInternal();
console.log("Screen focused, scan data cleared and camera enabled");
return () => {
setCameraVisible(false);
console.log("Screen unfocused, camera disabled");
};
}, [navigation])
);
// Conditional rendering based on state
if (showSplash) {
return (
<View style={styles.splashContainer}>
@@ -175,7 +141,7 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
return (
<View style={styles.container}>
<Text style={styles.headerText}>SafeQR v0.89</Text>
<Text style={styles.headerText}>SafeQR</Text>
<Text style={styles.welcomeText}>Welcome to SafeQR code Scanner</Text>
<View style={styles.cameraContainer}>
@@ -196,21 +162,17 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
</TouchableOpacity>
</View>
{scannedData !== '' && (
<View style={styles.scannedDataBox}>
{/* Scanned Data Box */}
{isScannedDataBoxVisible && (
<View style={styles.scannedDataBoxPopup}>
<ScannedDataBox
data={scannedData}
dataType={dataType}
clearScanData={clearScanDataInternal}
scanResult={{
secureConnection,
virusTotalCheck,
redirects
}}
qrCodeId={qrCodeId}
clearScanData={() => setIsScannedDataBoxVisible(false)}
/>
</View>
)}
{/* Settings Icon */}
<TouchableOpacity onPress={() => setIsSettingsModalVisible(true)} style={styles.settingsButton}>
<Ionicons name="settings" size={24} color="#000" />
@@ -222,9 +184,10 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat
transparent={true}
visible={isSettingsModalVisible}
onRequestClose={() => setIsSettingsModalVisible(false)}
style={styles.settingsModal}
>
<View style={styles.modalContainer}>
<View style={styles.modalContent}>
<View style={styles.settingsModalContainer}>
<View style={styles.settingsModalContent}>
<SettingsScreen />
<TouchableOpacity onPress={() => setIsSettingsModalVisible(false)} style={styles.closeButton}>
<Text style={styles.closeButtonText}>Close</Text>
@@ -290,13 +253,18 @@ const styles = StyleSheet.create({
backgroundColor: '#000',
borderRadius: 25,
},
scannedDataBox: {
scannedDataBoxPopup: {
position: 'absolute',
top: '10%',
left: '5%',
right: '5%',
zIndex: 2,
backgroundColor: 'white', // Optional: Set a background color if needed
borderRadius: 10, // Optional: Add rounded corners
padding: 10, // Optional: Add padding around the content
elevation: 5, // Optional: Add elevation for shadow effect
},
welcomeText: {
textAlign: 'center',
fontSize: 20,
@@ -309,19 +277,21 @@ const styles = StyleSheet.create({
right: 20,
zIndex: 2,
},
modalContainer: {
flex: 1,
justifyContent: 'center',
height: '90%',
alignItems: 'center',
settingsModal: {
backgroundColor: 'rgba(0, 0, 0, 0.5)', // Semi-transparent background
},
settingsModalContainer: {
flex: 2,
justifyContent: 'center', // Center the modal vertically
backgroundColor: 'rgba(0, 0, 0, 0.5)',
},
modalContent: {
width: '100%', // Adjust the width to cover more space
height: '90%', // Adjust the height to cover more space
settingsModalContent: {
width: '100%',
height: '80%', // Increase the height to make the modal taller
backgroundColor: 'white',
padding: 20, // Reduce the padding
borderRadius: 10,
padding: 20,
borderTopLeftRadius: 10,
borderTopRightRadius: 10,
alignItems: 'center',
},
closeButton: {
@@ -333,6 +303,7 @@ const styles = StyleSheet.create({
closeButtonText: {
color: 'white',
fontWeight: 'bold',
},
}
});
export default QRScannerScreen;

View File

@@ -1,16 +1,16 @@
import { View, Text, StyleSheet, TouchableOpacity, Linking, Button } from 'react-native';
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Linking, Alert, Button } from 'react-native';
import { useAuthenticator } from '@aws-amplify/ui-react-native';
import useFetchUserAttributes from '../hooks/useFetchUserAttributes';
import { fetchAuthSession, getCurrentUser, signInWithRedirect } from 'aws-amplify/auth';
import { useEffect, useState } from 'react';
import { deleteAllScannedHistories } from '../api/qrCodeAPI'; // Import the API function
import { Buffer } from 'buffer';
import { createDrawerNavigator } from '@react-navigation/drawer';
function SignOutButton() {
const { signOut } = useAuthenticator();
return <Button title="Sign Out" onPress={signOut} />;
}
const handleSignInWithRedirect = async () => {
try {
await signInWithRedirect();
@@ -42,7 +42,6 @@ const SettingsScreen: React.FC = () => {
const parts = idToken.split('.');
if (parts.length !== 3) {
throw new Error('ID token is not a valid JWT');
}
const payload = parts[1];
@@ -70,7 +69,6 @@ const SettingsScreen: React.FC = () => {
second: '2-digit'
};
if (parsedPayload["custom:access_token"]) {
console.log('Google Access Token:', parsedPayload["custom:access_token"]);
console.log('Google Refresh Token: ', parsedPayload["custom:refresh_token"]);
@@ -84,7 +82,6 @@ const SettingsScreen: React.FC = () => {
} else {
console.error('No Google access token found in the payload');
}
} else {
console.error('No ID token found in the session');
}
@@ -102,14 +99,25 @@ const SettingsScreen: React.FC = () => {
Linking.openURL(url);
};
const handleDeleteAllHistories = async () => {
try {
const response = await deleteAllScannedHistories();
Alert.alert('Success', response.message);
} catch (error) {
Alert.alert('Error', 'Failed to delete histories. Please try again.');
}
};
return (
<View style={styles.container}>
<Text style={styles.header}>Settings</Text>
<View style={styles.profileSection}>
{/* Profile Section */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>Profile</Text>
{userAttributes ? (
<View>
<Text style={styles.userName}>Hello, {userAttributes?.name}</Text>
<Text style={styles.userName}>Hello, {userAttributes.name || 'Unknown User'}</Text>
{googleAccessToken && (
<Text>Google Access Token: {googleAccessToken.substring(0, 10)}...</Text>
)}
@@ -121,8 +129,22 @@ const SettingsScreen: React.FC = () => {
</TouchableOpacity>
)}
</View>
<View style={styles.divider} />
<View style={styles.aboutUsSection}>
{/* History & Bookmarks Section */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>History & Bookmarks</Text>
<TouchableOpacity style={styles.deleteAllButton} onPress={handleDeleteAllHistories}>
<Text style={styles.deleteAllButtonText}>Delete All History</Text>
</TouchableOpacity>
</View>
<View style={styles.divider} />
{/* About Us Section */}
<View style={styles.section}>
<Text style={styles.sectionTitle}>About Us</Text>
<TouchableOpacity onPress={() => handleLinkPress('https://safeqr.github.io/marketing/')}>
<Text style={styles.linkText}>safeqr.github.io/marketing</Text>
@@ -134,6 +156,7 @@ const SettingsScreen: React.FC = () => {
<Text style={styles.linkText}>Terms Of Service</Text>
</TouchableOpacity>
</View>
<Text style={styles.versionText}>Version 1.2</Text>
</View>
);
@@ -143,17 +166,17 @@ const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f8f0fc',
padding: 10, // Reduce padding
width: '100%', // Increase width to fill the modal
padding: 10,
width: '100%',
},
header: {
fontSize: 24,
fontWeight: 'bold',
color: '#ff69b4',
marginBottom: 20,
textAlign: 'center', // Center the header text
textAlign: 'center',
},
profileSection: {
section: {
marginBottom: 20,
},
sectionTitle: {
@@ -162,6 +185,11 @@ const styles = StyleSheet.create({
color: '#000',
marginBottom: 10,
},
userName: {
fontSize: 16,
color: '#000',
marginBottom: 10,
},
loginButton: {
backgroundColor: '#ff69b4',
paddingVertical: 8,
@@ -175,14 +203,26 @@ const styles = StyleSheet.create({
color: '#000',
fontSize: 16,
},
deleteAllButton: {
backgroundColor: '#ff0000', // Red color
borderRadius: 25, // Round button
paddingVertical: 10,
paddingHorizontal: 20,
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'flex-start',
marginVertical: 10,
},
deleteAllButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
divider: {
height: 1,
backgroundColor: '#ccc',
marginVertical: 20,
},
aboutUsSection: {
marginBottom: 20,
},
linkText: {
fontSize: 16,
color: '#0000ff',
@@ -194,7 +234,7 @@ const styles = StyleSheet.create({
color: '#aaa',
marginTop: 20,
},
});
export default SettingsScreen;