redo with comments, still pending secScanned(false) fix

This commit is contained in:
2024-06-09 23:39:18 +08:00
parent 1363b245d7
commit a61bf8a887

100
App.tsx
View File

@@ -2,39 +2,41 @@ import React, { useState, useEffect, createContext, useContext } from 'react';
import { Text, View, StyleSheet, ActivityIndicator, TouchableOpacity, FlatList } from 'react-native'; import { Text, View, StyleSheet, ActivityIndicator, TouchableOpacity, FlatList } from 'react-native';
import { NavigationContainer } from '@react-navigation/native'; import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { CameraView, Camera } from 'expo-camera'; import { CameraView, Camera } from 'expo-camera'; // The icons used in the navigation bar
import { Ionicons } from '@expo/vector-icons'; import { Ionicons } from '@expo/vector-icons'; // Import Axios for HTTP requests for the VT API call
import axios from 'axios'; import axios from 'axios';
// Create a Context for QR code data
const QRCodeContext = createContext(null); const QRCodeContext = createContext(null);
const Tab = createBottomTabNavigator(); const Tab = createBottomTabNavigator();
// Component for QR Scanner Screen
const QRScannerScreen: React.FC = () => { const QRScannerScreen: React.FC = () => {
const { qrCodes, setQrCodes } = useContext(QRCodeContext); const { qrCodes, setQrCodes } = useContext(QRCodeContext); // Access context
const [hasPermission, setHasPermission] = useState<boolean | null>(null); const [hasPermission, setHasPermission] = useState<boolean | null>(null); // State for camera permission
const [scanned, setScanned] = useState<boolean>(false); const [scanned, setScanned] = useState<boolean>(false); // State for scanned status
const [showSplash, setShowSplash] = useState<boolean>(true); const [showSplash, setShowSplash] = useState<boolean>(true); // State for splash screen
const [scannedData, setScannedData] = useState<string>(''); const [scannedData, setScannedData] = useState<string>(''); // State for scanned data
const [scanResult, setScanResult] = useState<any>(null); const [scanResult, setScanResult] = useState<any>(null); // State for VirusTotal scan result
useEffect(() => { useEffect(() => {
const initializeApp = async () => { const initializeApp = async () => {
const { status } = await Camera.requestCameraPermissionsAsync(); const { status } = await Camera.requestCameraPermissionsAsync(); // Request camera permissions
setHasPermission(status === 'granted'); setHasPermission(status === 'granted'); // Set permission status
setShowSplash(false); setShowSplash(false); // Hide splash screen
}; };
initializeApp(); initializeApp(); // Initialize app
}, []); }, []);
// Function to handle barcode scanned event
const handleQRCodeSanned = async ({ type, data }: { type: string; data: string }) => { const handleQRCodeSanned = async ({ type, data }: { type: string; data: string }) => {
setScanned(true); setScanned(true);// Mark as scanned
// Determine the type of data (URL, text, or just numbers)
let dataType; let dataType;
if (/^(http|https):\/\//.test(data)) { if (/^(http|https):\/\//.test(data)) {
dataType = 'URL'; dataType = 'URL';
@@ -44,37 +46,42 @@ const QRScannerScreen: React.FC = () => {
dataType = 'Text'; dataType = 'Text';
} }
let newScannedData = `Type: ${dataType}\nData: ${data}`; // Construct the scanned data with the data type
let newScannedData = `Type: ${dataType}\nData: ${data}`; // Initialize with type and data
try { try {
const scanId = await scanWithVirusTotal(data); const scanId = await scanWithVirusTotal(data); // Send data to VirusTotal and get scan ID
const positive = await getScanResult(scanId); const positive = await getScanResult(scanId); // Get scan result and extract positive score
newScannedData += `\nScore: ${positive}`; newScannedData += `\nScore: ${positive}`; // Append positive score to newScannedData
} catch (error) { } catch (error) {
console.error('Error handling barcode scan:', error); console.error('Error handling barcode scan:', error); // Handle error
} }
setScannedData(newScannedData); setScannedData(newScannedData); // Save scanned data
setQrCodes([...qrCodes, newScannedData]); setQrCodes([...qrCodes, newScannedData]); // Add scanned data to history
}; };
// Function to send data to VirusTotal and get the scan ID
const scanWithVirusTotal = async (data: any) => { const scanWithVirusTotal = async (data: any) => {
const apiKey = '3566a17933bb36dd97cb35e84d0446e5ab8ad623e6de968d34b655c79485251e'; const apiKey = '3566a17933bb36dd97cb35e84d0446e5ab8ad623e6de968d34b655c79485251e'; // 4/min , 500/day
const url = 'https://www.virustotal.com/vtapi/v2/url/scan'; const url = 'https://www.virustotal.com/vtapi/v2/url/scan';
const params = { const params = {
apikey: apiKey, apikey: apiKey,
url: data url: data
}; };
// The axios to handle URL stuff
try { try {
const response = await axios.post(url, null, { params }); const response = await axios.post(url, null, { params });
return response.data.scan_id; return response.data.scan_id; // Return scanID
} catch (error) { } catch (error) {
console.error('Error scanning with VirusTotal:', error); console.error('Error scanning with VirusTotal:', error);
throw error; throw error;
} }
}; };
// Get the full list of scanned result based on scanID from
// response above, Only want response.data.positive
const getScanResult = async (scanId: Int32Array) => { const getScanResult = async (scanId: Int32Array) => {
const apiKey = '3566a17933bb36dd97cb35e84d0446e5ab8ad623e6de968d34b655c79485251e'; const apiKey = '3566a17933bb36dd97cb35e84d0446e5ab8ad623e6de968d34b655c79485251e';
const url = 'https://www.virustotal.com/vtapi/v2/url/report'; const url = 'https://www.virustotal.com/vtapi/v2/url/report';
@@ -83,9 +90,10 @@ const QRScannerScreen: React.FC = () => {
resource: scanId resource: scanId
}; };
// The axios to handle URL stuff
try { try {
const response = await axios.get(url, { params }); const response = await axios.get(url, { params });
return response.data.positives; return response.data.positives; // Reture the value of positive:
} catch (error) { } catch (error) {
console.error('Error getting scan result:', error); console.error('Error getting scan result:', error);
throw error; throw error;
@@ -110,10 +118,16 @@ const QRScannerScreen: React.FC = () => {
return ( return (
<View style={styles.container}> <View style={styles.container}>
{/* Header banner */}
<View style={styles.banner}> <View style={styles.banner}>
<Text style={styles.headerText}>SafeQR</Text> <Text style={styles.headerText}>SafeQR</Text>
</View> </View>
{/* Welcome message */}
<Text style={styles.welcomeText}>Welcome to SafeQR code Scanner</Text> <Text style={styles.welcomeText}>Welcome to SafeQR code Scanner</Text>
{/* Camera view container */}
<View style={styles.cameraContainer}> <View style={styles.cameraContainer}>
<CameraView <CameraView
onBarcodeScanned={scanned ? undefined : handleQRCodeSanned} onBarcodeScanned={scanned ? undefined : handleQRCodeSanned}
@@ -121,6 +135,8 @@ const QRScannerScreen: React.FC = () => {
style={styles.camera} style={styles.camera}
/> />
</View> </View>
{/* Display scanned data */}
{scannedData !== '' && ( {scannedData !== '' && (
<View style={styles.dataBox}> <View style={styles.dataBox}>
<Text style={styles.dataText}>{scannedData}</Text> <Text style={styles.dataText}>{scannedData}</Text>
@@ -131,6 +147,8 @@ const QRScannerScreen: React.FC = () => {
); );
}; };
// Component for History Screen
function HistoryScreen() { function HistoryScreen() {
const { qrCodes } = useContext(QRCodeContext); const { qrCodes } = useContext(QRCodeContext);
@@ -138,24 +156,24 @@ function HistoryScreen() {
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.welcomeText}>History Screen</Text> <Text style={styles.welcomeText}>History Screen</Text>
<FlatList <FlatList
data={qrCodes} data={qrCodes} // Data for FlatList
renderItem={({ item }) => ( renderItem={({ item }) => (
<View style={styles.dataBox}> <View style={styles.dataBox}>
<Text style={styles.dataText}>{item}</Text> <Text style={styles.dataText}>{item}</Text>
</View> </View>
)} )}
keyExtractor={(item, index) => index.toString()} keyExtractor={(item, index) => index.toString()} // Key extractor for FlatList
/> />
</View> </View>
); );
} }
function SettingsScreen() {
const { setQrCodes } = useContext(QRCodeContext);
const clearHistory = () => { // Component for Settings Screen
setQrCodes([]); function SettingsScreen() {
}; const { setQrCodes } = useContext(QRCodeContext); // Access context
const clearHistory = () => {setQrCodes([]);}; // To clear History
return ( return (
<View style={styles.container}> <View style={styles.container}>
@@ -167,6 +185,7 @@ function SettingsScreen() {
); );
} }
// Component for Profile Screen
function ProfileScreen() { function ProfileScreen() {
return ( return (
<View style={styles.container}> <View style={styles.container}>
@@ -207,7 +226,10 @@ const CustomTabBar = ({ state, descriptors, navigation }) => {
}); });
}; };
const iconName = route.name === 'QR Scanner' ? 'camera' : route.name === 'History' ? 'time' : route.name === 'Settings' ? 'settings' : 'person'; // Set different icons for each tab
const iconName = route.name === 'QR Scanner' ? 'camera'
: route.name === 'History' ? 'time'
: route.name === 'Settings' ? 'settings' : 'person';
return ( return (
<TouchableOpacity <TouchableOpacity
@@ -236,8 +258,16 @@ const CustomTabBar = ({ state, descriptors, navigation }) => {
); );
}; };
// Main App component with bottom tab navigation
export default function App() { export default function App() {
const [qrCodes, setQrCodes] = useState([]); const [qrCodes, setQrCodes] = useState([]); // State to hold QR codes
return ( return (
<QRCodeContext.Provider value={{ qrCodes, setQrCodes }}> <QRCodeContext.Provider value={{ qrCodes, setQrCodes }}>