From 220fa2dfd4531dfe1e46243109a8fff3f7fdef06 Mon Sep 17 00:00:00 2001 From: heyethereum Date: Mon, 22 Jul 2024 00:41:05 +0800 Subject: [PATCH] solve camera off focus, load user histories --- .env.development | 1 + .env.production | 2 + App.tsx | 2 +- api/qrCodeAPI.tsx | 85 +++++++++++++----- app.config.js | 10 +++ hooks/useFetchUserAttributes.ts | 13 +-- ios/Podfile.lock | 35 +++++++- .../xcshareddata/IDEWorkspaceChecks.plist | 8 ++ package-lock.json | 74 +++++++++------ package.json | 16 ++-- reducers/qrCodesReducer.ts | 29 +++--- screens/HistoryScreen.tsx | 89 ++++++++++++++----- screens/QRScannerScreen.tsx | 50 +++++++---- screens/SettingsScreen.tsx | 27 +----- types.ts | 25 ++++++ 15 files changed, 329 insertions(+), 137 deletions(-) create mode 100644 .env.development create mode 100644 .env.production create mode 100644 app.config.js create mode 100644 ios/SafeQR.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/.env.development b/.env.development new file mode 100644 index 0000000..04bf676 --- /dev/null +++ b/.env.development @@ -0,0 +1 @@ +BASE_URL=http://192.168.1.30:8080 \ No newline at end of file diff --git a/.env.production b/.env.production new file mode 100644 index 0000000..55de816 --- /dev/null +++ b/.env.production @@ -0,0 +1,2 @@ +BASE_URL=https://bk5wiynzsi.execute-api.ap-southeast-1.amazonaws.com/api/ +ENV=production \ No newline at end of file diff --git a/App.tsx b/App.tsx index b4d2f79..7aa504c 100644 --- a/App.tsx +++ b/App.tsx @@ -47,4 +47,4 @@ const App: React.FC = () => { ); }; -export default withAuthenticator(App); \ No newline at end of file +export default withAuthenticator(App); \ No newline at end of file diff --git a/api/qrCodeAPI.tsx b/api/qrCodeAPI.tsx index 45a50bb..5cb7aa1 100644 --- a/api/qrCodeAPI.tsx +++ b/api/qrCodeAPI.tsx @@ -1,31 +1,74 @@ import axios from 'axios'; +import Constants from 'expo-constants'; +const { API_BASE_URL } = Constants.expoConfig.extra; +//const API_BASE_URL = 'http://192.168.1.30:8080/v1/qrcodetypes'; -const API_BASE_URL = 'http://192.168.10.247:8080/v1/api/qrcodetypes'; +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" -export const detectQRCodeType = async (data: string) => { - console.log('API Call - Detect QR Code Type:', data); - const response = await axios.post(`${API_BASE_URL}/detect`, { data }); - console.log('API Response - QR Code Type:', response.data); - return response.data; +// Define a generic function to handle all types of requests +export const apiRequest = async (config) => { + try { + console.log(`API Call - ${config.method.toUpperCase()}:`, config.url, config.data || ''); + console.log(config); + + const response = await axios(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; + } }; -export const verifyURL = async (data: string) => { - console.log('API Call - Verify URL:', data); - const response = await axios.post(`${API_BASE_URL}/verifyURL`, { data }); - console.log('API Response - Verify URL:', response.data); - return response.data; +export const detectQRCodeType = async (data) => { + return apiRequest({ + method: 'post', + url: `${API_BASE_URL}${API_URL_DETECT}`, + data: { data } + }); }; -export const virusTotalCheck = async (data: string) => { - console.log('API Call - Virus Total Check:', data); - const response = await axios.post(`${API_BASE_URL}/virusTotalCheck`, { data }); - console.log('API Response - Virus Total Check:', response.data); - return response.data; +export const verifyURL = async (data) => { + return apiRequest({ + method: 'post', + url: `${API_BASE_URL}${API_URL_VERIFY_URL}`, + data: { data } + }); }; -export const checkRedirects = async (data: string) => { - console.log('API Call - Check Redirects:', data); - const response = await axios.post(`${API_BASE_URL}/checkRedirects`, { data }); - console.log('API Response - Check Redirects:', response.data); - return response.data; +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 } + }); +}; + +export const getScannedHistories = async (userId: String) => { + return apiRequest({ + method: 'get', + url: `${API_BASE_URL}${API_URL_GET_HISTORIES}`, + headers: { "X-USER-ID": userId }, + }); }; diff --git a/app.config.js b/app.config.js new file mode 100644 index 0000000..b5ce77a --- /dev/null +++ b/app.config.js @@ -0,0 +1,10 @@ +import 'dotenv/config'; + +export default ({ config }) => { + return { + ...config, + extra: { + API_BASE_URL: process.env.BASE_URL, + }, + }; +}; diff --git a/hooks/useFetchUserAttributes.ts b/hooks/useFetchUserAttributes.ts index 5e8d30d..171bc37 100644 --- a/hooks/useFetchUserAttributes.ts +++ b/hooks/useFetchUserAttributes.ts @@ -1,15 +1,6 @@ import { useState, useEffect } from 'react'; import { fetchUserAttributes } from 'aws-amplify/auth'; - -interface UserAttributes { - email: string; - email_verified: string; - family_name: string; - given_name: string; - identities: string; - name: string; - sub: string; -} +import { UserAttributes } from '../types' const useFetchUserAttributes = () => { const [userAttributes, setUserAttributes] = useState(null); @@ -22,6 +13,8 @@ const useFetchUserAttributes = () => { const attributes = await fetchUserAttributes(); setUserAttributes(attributes as unknown as UserAttributes); } catch (error: any) { + console.log("Error in use fetch user attributes: ", error); + setError(error.message); } finally { setLoading(false); diff --git a/ios/Podfile.lock b/ios/Podfile.lock index ec1b1fe..d35a497 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -263,6 +263,8 @@ PODS: - ReactCommon/turbomodule/bridging - ReactCommon/turbomodule/core - Yoga + - ExpoSharing (12.0.1): + - ExpoModulesCore - EXUpdatesInterface (0.16.2): - ExpoModulesCore - FBLazyVector (0.74.3) @@ -1215,8 +1217,29 @@ PODS: - React-Core - react-native-netinfo (11.3.1): - React-Core - - react-native-safe-area-context (4.10.1): + - react-native-safe-area-context (4.10.8): - React-Core + - react-native-webview (13.10.4): + - DoubleConversion + - glog + - hermes-engine + - RCT-Folly (= 2024.01.01.00) + - RCTRequired + - RCTTypeSafety + - React-Codegen + - React-Core + - React-debug + - React-Fabric + - React-featureflags + - React-graphics + - React-ImageManager + - React-NativeModulesApple + - React-RCTFabric + - React-rendererdebug + - React-utils + - ReactCommon/turbomodule/bridging + - ReactCommon/turbomodule/core + - Yoga - React-nativeconfig (0.74.3) - React-NativeModulesApple (0.74.3): - glog @@ -1506,6 +1529,7 @@ DEPENDENCIES: - ExpoImagePicker (from `../node_modules/expo-image-picker/ios`) - ExpoKeepAwake (from `../node_modules/expo-keep-awake/ios`) - ExpoModulesCore (from `../node_modules/expo-modules-core`) + - ExpoSharing (from `../node_modules/expo-sharing/ios`) - EXUpdatesInterface (from `../node_modules/expo-updates-interface/ios`) - FBLazyVector (from `../node_modules/react-native/Libraries/FBLazyVector`) - fmt (from `../node_modules/react-native/third-party-podspecs/fmt.podspec`) @@ -1540,6 +1564,7 @@ DEPENDENCIES: - react-native-get-random-values (from `../node_modules/react-native-get-random-values`) - "react-native-netinfo (from `../node_modules/@react-native-community/netinfo`)" - react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`) + - react-native-webview (from `../node_modules/react-native-webview`) - React-nativeconfig (from `../node_modules/react-native/ReactCommon`) - React-NativeModulesApple (from `../node_modules/react-native/ReactCommon/react/nativemodule/core/platform/ios`) - React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`) @@ -1619,6 +1644,8 @@ EXTERNAL SOURCES: :path: "../node_modules/expo-keep-awake/ios" ExpoModulesCore: :path: "../node_modules/expo-modules-core" + ExpoSharing: + :path: "../node_modules/expo-sharing/ios" EXUpdatesInterface: :path: "../node_modules/expo-updates-interface/ios" FBLazyVector: @@ -1684,6 +1711,8 @@ EXTERNAL SOURCES: :path: "../node_modules/@react-native-community/netinfo" react-native-safe-area-context: :path: "../node_modules/react-native-safe-area-context" + react-native-webview: + :path: "../node_modules/react-native-webview" React-nativeconfig: :path: "../node_modules/react-native/ReactCommon" React-NativeModulesApple: @@ -1761,6 +1790,7 @@ SPEC CHECKSUMS: ExpoImagePicker: 12a420923383ae38dccb069847218f27a3b87816 ExpoKeepAwake: 3b8815d9dd1d419ee474df004021c69fdd316d08 ExpoModulesCore: 30e1ed4659356cb9a84e0e5ddf1d090d735973c1 + ExpoSharing: 8db05dd85081219f75989a3db2c92fe5e9741033 EXUpdatesInterface: 996527fd7d1a5d271eb523258d603f8f92038f24 FBLazyVector: 7e977dd099937dc5458851233141583abba49ff2 fmt: 4c2741a687cc09f0634a2e2c72a838b99f1ff120 @@ -1793,7 +1823,8 @@ SPEC CHECKSUMS: React-Mapbuffer: 9f68550e7c6839d01411ac8896aea5c868eff63a react-native-get-random-values: 21325b2244dfa6b58878f51f9aa42821e7ba3d06 react-native-netinfo: bdb108d340cdb41875c9ced535977cac6d2ff321 - react-native-safe-area-context: dcab599c527c2d7de2d76507a523d20a0b83823d + react-native-safe-area-context: b7daa1a8df36095a032dff095a1ea8963cb48371 + react-native-webview: 596fb33d67a3cde5a74bf1f6b4c28d3543477fdd React-nativeconfig: fa5de9d8f4dbd5917358f8ad3ad1e08762f01dcb React-NativeModulesApple: 585d1b78e0597de364d259cb56007052d0bda5e5 React-perflogger: 7bb9ba49435ff66b666e7966ee10082508a203e8 diff --git a/ios/SafeQR.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/SafeQR.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/SafeQR.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/package-lock.json b/package-lock.json index 3c7e8f9..10db63f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "@reduxjs/toolkit": "^2.2.6", "aws-amplify": "^6.3.8", "axios": "^1.7.2", + "dotenv": "^16.4.5", "expo": "~51.0.17", "expo-camera": "~15.0.13", "expo-dev-client": "~4.0.19", @@ -28,9 +29,10 @@ "expo-status-bar": "~1.12.1", "react": "18.2.0", "react-native": "^0.74.3", + "react-native-dotenv": "^3.4.11", "react-native-get-random-values": "^1.11.0", "react-native-qrcode-svg": "^6.3.1", - "react-native-safe-area-context": "4.10.1", + "react-native-safe-area-context": "^4.10.4", "react-native-screens": "3.31.1", "react-native-svg": "15.2.0", "react-native-webview": "^13.10.4", @@ -228,6 +230,16 @@ "isarray": "^1.0.0" } }, + "node_modules/@aws-amplify/datastore/node_modules/immer": { + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/immer/-/immer-9.0.6.tgz", + "integrity": "sha512-G95ivKpy+EvVAnAab4fVa4YGYn24J1SpEktnJX7JJ45Bd7xqME/SCplFzYFmTbrkwZbQ4xJK1xMTUYBkN6pWsQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, "node_modules/@aws-amplify/notifications": { "version": "2.0.36", "resolved": "https://registry.npmjs.org/@aws-amplify/notifications/-/notifications-2.0.36.tgz", @@ -16235,6 +16247,18 @@ } } }, + "node_modules/react-native-dotenv": { + "version": "3.4.11", + "resolved": "https://registry.npmjs.org/react-native-dotenv/-/react-native-dotenv-3.4.11.tgz", + "integrity": "sha512-6vnIE+WHABSeHCaYP6l3O1BOEhWxKH6nHAdV7n/wKn/sciZ64zPPp2NUdEUf1m7g4uuzlLbjgr+6uDt89q2DOg==", + "license": "MIT", + "dependencies": { + "dotenv": "^16.4.5" + }, + "peerDependencies": { + "@babel/runtime": "^7.20.6" + } + }, "node_modules/react-native-get-random-values": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/react-native-get-random-values/-/react-native-get-random-values-1.11.0.tgz", @@ -16262,9 +16286,9 @@ } }, "node_modules/react-native-safe-area-context": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-4.10.1.tgz", - "integrity": "sha512-w8tCuowDorUkPoWPXmhqosovBr33YsukkwYCDERZFHAxIkx6qBadYxfeoaJ91nCQKjkNzGrK5qhoNOeSIcYSpA==", + "version": "4.10.8", + "resolved": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-4.10.8.tgz", + "integrity": "sha512-Jx1lovhvIdYygg0UsMCBUJN0Wvj9GlA5bbcBLzjZf93uJpNHzaiHC4hR280+sNVK1+/pMHEyEkXVHDZE5JWn0w==", "license": "MIT", "peerDependencies": { "react": "*", @@ -16299,27 +16323,6 @@ "react-native": "*" } }, - "node_modules/react-native-webview": { - "version": "13.10.4", - "resolved": "https://registry.npmjs.org/react-native-webview/-/react-native-webview-13.10.4.tgz", - "integrity": "sha512-kRn70M7vyBS3IDaX2KqyF66ovUkrBS6LiHOgrEmRdZFO0i3hYY0wldEv1fJuKvgQIPMfo7GtGAjozFrk2vQdBw==", - "dependencies": { - "escape-string-regexp": "2.0.0", - "invariant": "2.2.4" - }, - "peerDependencies": { - "react": "*", - "react-native": "*" - } - }, - "node_modules/react-native-webview/node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "engines": { - "node": ">=8" - } - }, "node_modules/react-native-svg-transformer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/react-native-svg-transformer/-/react-native-svg-transformer-1.4.0.tgz", @@ -16349,6 +16352,27 @@ "react-native": "*" } }, + "node_modules/react-native-webview": { + "version": "13.10.4", + "resolved": "https://registry.npmjs.org/react-native-webview/-/react-native-webview-13.10.4.tgz", + "integrity": "sha512-kRn70M7vyBS3IDaX2KqyF66ovUkrBS6LiHOgrEmRdZFO0i3hYY0wldEv1fJuKvgQIPMfo7GtGAjozFrk2vQdBw==", + "dependencies": { + "escape-string-regexp": "2.0.0", + "invariant": "2.2.4" + }, + "peerDependencies": { + "react": "*", + "react-native": "*" + } + }, + "node_modules/react-native-webview/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "engines": { + "node": ">=8" + } + }, "node_modules/react-native/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", diff --git a/package.json b/package.json index 4dbde49..7f029f5 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,10 @@ "main": "expo/AppEntry.js", "scripts": { "start": "expo start", - "android": "expo run:android", - "ios": "expo run:ios", + "android:dev": "ENVFILE=.env.development expo run:android", + "android:prod": "ENVFILE=.env.production expo run:android", + "ios:dev": "ENVFILE=.env.development expo run:ios", + "ios:prod": "ENVFILE=.env.production expo run:ios", "web": "expo start --web" }, "dependencies": { @@ -17,26 +19,28 @@ "@react-native-community/netinfo": "11.3.1", "@react-navigation/bottom-tabs": "^6.5.20", "@react-navigation/native": "^6.1.17", - "aws-amplify": "^6.3.8", "@reduxjs/toolkit": "^2.2.6", + "aws-amplify": "^6.3.8", "axios": "^1.7.2", + "dotenv": "^16.4.5", "expo": "~51.0.17", "expo-camera": "~15.0.13", + "expo-dev-client": "~4.0.19", "expo-image-manipulator": "^12.0.5", "expo-image-picker": "~15.0.7", + "expo-sharing": "~12.0.1", "expo-status-bar": "~1.12.1", "react": "18.2.0", "react-native": "^0.74.3", + "react-native-dotenv": "^3.4.11", "react-native-get-random-values": "^1.11.0", "react-native-qrcode-svg": "^6.3.1", "react-native-safe-area-context": "^4.10.4", "react-native-screens": "3.31.1", "react-native-svg": "15.2.0", - "expo-dev-client": "~4.0.19", "react-native-webview": "^13.10.4", "react-redux": "^9.1.2", - "redux": "^5.0.1", - "expo-sharing": "~12.0.1" + "redux": "^5.0.1" }, "devDependencies": { "@babel/core": "^7.20.0", diff --git a/reducers/qrCodesReducer.ts b/reducers/qrCodesReducer.ts index 6a4b458..3c56225 100644 --- a/reducers/qrCodesReducer.ts +++ b/reducers/qrCodesReducer.ts @@ -1,30 +1,39 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'; -import { QRCode } from '../types'; +import { QRCode, UserAttributes } from '../types'; + +const initialState: QRCodeState = { + qrCodes: [], + userAttributes: null, +}; const qrCodesSlice = createSlice({ name: 'qrCodes', - initialState: [] as QRCode[], + initialState, reducers: { addQRCode(state, action: PayloadAction) { - state.push(action.payload); + state.qrCodes.push(action.payload); console.log('Added QR code to state:', action.payload); }, toggleBookmark(state, action: PayloadAction) { - const index = state.length - 1 - action.payload; - if (state[index]) { - state[index].bookmarked = !state[index].bookmarked; + const index = state.qrCodes.length - 1 - action.payload; + if (state.qrCodes[index]) { + state.qrCodes[index].bookmarked = !state.qrCodes[index].bookmarked; console.log('Toggled bookmark for QR code at index:', index); } }, deleteQRCode(state, action: PayloadAction) { - const index = state.length - 1 - (action.payload as number); - if (state[index]) { + const index = state.qrCodes.length - 1 - (action.payload as number); + if (state.qrCodes[index]) { console.log('Deleting QR code at index:', index); - state.splice(index, 1); + state.qrCodes.splice(index, 1); } }, + setUserAttributes(state, action: PayloadAction) { + state.userAttributes = action.payload; + console.log('(Store)Set user attributes:', action.payload); + }, }, }); -export const { addQRCode, toggleBookmark, deleteQRCode } = qrCodesSlice.actions; +export const { addQRCode, toggleBookmark, deleteQRCode, setUserAttributes } = qrCodesSlice.actions; export default qrCodesSlice.reducer; diff --git a/screens/HistoryScreen.tsx b/screens/HistoryScreen.tsx index f840103..7ad14d5 100644 --- a/screens/HistoryScreen.tsx +++ b/screens/HistoryScreen.tsx @@ -1,15 +1,45 @@ -import React, { useContext, useState, useEffect } from 'react'; +import React, { useCallback, useState, useEffect } from 'react'; import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, BackHandler, Modal } from 'react-native'; import { useDispatch, useSelector } from 'react-redux'; import ScannedDataBox from '../components/ScannedDataBox'; import { Ionicons } from '@expo/vector-icons'; import { RootState } from '../store'; -import { QRCode } from '../types'; +import { QRCode, QRCodeType } from '../types'; import { toggleBookmark, deleteQRCode } from '../actions/qrCodeActions'; +import useFetchUserAttributes from '../hooks/useFetchUserAttributes'; +import useFetchScannedHistories from '../hooks/useFetchScannedHistories'; +import { getScannedHistories } from '../api/qrCodeAPI'; const HistoryScreen: React.FC = () => { const dispatch = useDispatch(); - const qrCodes = useSelector((state: RootState) => state.qrCodes); + const qrCodes = useSelector((state: RootState) => state.qrCodes.qrCodes); + const { userAttributes } = useFetchUserAttributes(); + console.log("sub: ", userAttributes?.sub); + const [scannedHistories, setScannedHistories] = useState(null); + const [historiesLoading, setHistoriesLoading] = useState(false); + const [historiesError, setHistoriesError] = useState(null); + + const fetchHistories = useCallback(async () => { + if (!userAttributes?.sub) return; + + try { + const data = await getScannedHistories(userAttributes.sub); + setScannedHistories(data as unknown as QRCodeType[]); + } catch (error: any) { + setHistoriesError(error.message); + } finally { + setHistoriesLoading(false); + } + }, [userAttributes?.sub]); + + useEffect(() => { + if (userAttributes?.sub) { + fetchHistories(); + } + }, [userAttributes?.sub, fetchHistories]); + console.log("scanned history: ", scannedHistories); + + const [selectedData, setSelectedData] = useState(null); const [selectedScanResult, setSelectedScanResult] = useState(null); @@ -34,14 +64,22 @@ const HistoryScreen: React.FC = () => { return () => backHandler.remove(); }, [selectedData]); - const filteredQrCodes = showBookmarks ? qrCodes.filter(qr => qr.bookmarked) : qrCodes.slice().reverse(); + //const filteredQrCodes = showBookmarks ? qrCodes.filter(qr => qr.bookmarked) : qrCodes.slice().reverse(); + const filteredQrCodes = showBookmarks ? scannedHistories.filter(qr => { + return qr.bookmarked + }) : scannedHistories; - const handleItemPress = (item: QRCode) => { - setSelectedData(item.data); - setSelectedScanResult(item.scanResult); - setSelectedType(item.type); - console.log('Selected QR code data:', item.data); - console.log('Selected QR code type:', item.type); + console.log("filtered", filteredQrCodes); + console.log("slice", qrCodes.slice().reverse()); + + 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); }; const confirmDelete = (index: number) => { @@ -78,17 +116,18 @@ const HistoryScreen: React.FC = () => { data={filteredQrCodes} renderItem={({ item, index }) => { console.log('Rendering QR code item:', item); - const itemData = item.data; return ( handleItemPress(item)} style={styles.itemContent}> - {itemData} + + {item.data.contents} + - {new Date().toLocaleDateString('en-GB', { - day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' - })} + {new Date(item.data.createdAt).toLocaleDateString('en-GB', { + day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit'})} + dispatch(toggleBookmark(index))}> @@ -101,7 +140,11 @@ const HistoryScreen: React.FC = () => { ); }} - keyExtractor={(item, index) => index.toString()} + keyExtractor={(item, index) => { + //console.log(item, index); + + return index.toString(); + }} contentContainerStyle={styles.flatListContent} /> {/* Modal for delete confirmation */} @@ -161,7 +204,8 @@ const styles = StyleSheet.create({ marginBottom: 10, }, itemLeft: { - flexDirection: 'column', + flex: 1, + marginRight: 2, }, itemContent: { flexDirection: 'row', @@ -171,15 +215,20 @@ const styles = StyleSheet.create({ flexDirection: 'row', alignItems: 'center', }, + textContainer: { + flex: 1, + marginLeft: 0, + }, dataText: { - fontSize: 11, + fontSize: 12, color: '#000', - marginLeft: 10, + marginBottom: 7 }, dateText: { fontSize: 12, - color: '#000', + color: '#666', marginLeft: 10, + flex: 1 }, scanIcon: { width: 40, diff --git a/screens/QRScannerScreen.tsx b/screens/QRScannerScreen.tsx index f30ff06..5e9d527 100644 --- a/screens/QRScannerScreen.tsx +++ b/screens/QRScannerScreen.tsx @@ -1,10 +1,10 @@ -import React, { useState, useEffect, useContext } from 'react'; +import React, { useState, useEffect, useContext, useCallback } from 'react'; import { View, Text, StyleSheet, ActivityIndicator, TouchableOpacity, Alert, Image } 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 { useNavigation } from '@react-navigation/native'; +import { useFocusEffect, useNavigation } from '@react-navigation/native'; import * as ImagePicker from 'expo-image-picker'; import ScannedDataBox from '../components/ScannedDataBox'; import { useDispatch } from 'react-redux'; @@ -25,6 +25,7 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat const [scannedData, setScannedData] = useState(''); // State for QR scanned Data const [dataType, setDataType] = useState(''); // State for data type const [enableTorch, setEnableTorch] = useState(false); // State for torch + const [cameraVisible, setCameraVisible] = useState(true); // State to control camera visibility // Add state variables for scan results const [secureConnection, setSecureConnection] = useState(null); @@ -88,7 +89,7 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat console.log('Sending QR code data to backend:', payload); try { - const response = await axios.post('https://localhost:8443/v1/api/qrcodetypes/detect', { + const response = await axios.post('http://192.168.1.30:8080/v1/qrcodetypes/scan', { data: payload, }, { headers: { @@ -135,8 +136,9 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat console.log('QR code data from image:', scannedResult[0].data); } else { setScannedData("No QR Code Found"); - setTimeout(() => setScannedData(""), 4000); + //setTimeout(() => setScannedData(""), 4000); 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); @@ -145,14 +147,28 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat } }; + // // Clear scan data when screen is focused + // useEffect(() => { + // const unsubscribe = navigation.addListener('focus', () => { + // clearScanDataInternal(); + // console.log("Screen focused, scan data cleared"); + // }); + // return unsubscribe; + // }, [navigation]); + // Clear scan data when screen is focused - useEffect(() => { - const unsubscribe = navigation.addListener('focus', () => { + useFocusEffect( + useCallback(() => { + setCameraVisible(true); clearScanDataInternal(); - console.log("Screen focused, scan data cleared"); - }); - return unsubscribe; - }, [navigation]); + console.log("Screen focused, scan data cleared and camera enabled"); + + return () => { + setCameraVisible(false); + console.log("Screen unfocused, camera disabled"); + }; + }, [navigation]) + ); if (showSplash) { return ( @@ -178,12 +194,14 @@ const QRScannerScreen: React.FC<{ clearScanData: () => void }> = ({ clearScanDat Welcome to SafeQR code Scanner - handlePayload(data)} - barcodeScannerSettings={{ barcodeTypes: ['qr', 'pdf417'] }} - style={styles.camera} - enableTorch={enableTorch} - /> + {cameraVisible && ( + handlePayload(data)} + barcodeScannerSettings={{ barcodeTypes: ['qr', 'pdf417'] }} + style={styles.camera} + enableTorch={enableTorch} + /> + )} diff --git a/screens/SettingsScreen.tsx b/screens/SettingsScreen.tsx index 01e2878..84042a7 100644 --- a/screens/SettingsScreen.tsx +++ b/screens/SettingsScreen.tsx @@ -1,18 +1,7 @@ -import React, { useContext, useState } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Linking, Button } from 'react-native'; -import { QRCodeContext } from '../types'; import { useAuthenticator } from '@aws-amplify/ui-react-native'; -import { fetchUserAttributes } from 'aws-amplify/auth'; import useFetchUserAttributes from '../hooks/useFetchUserAttributes'; -async function handleFetchUserAttributes() { - try { - const userAttributes = await fetchUserAttributes(); - console.log(userAttributes); - } catch (error) { - console.log(error); - } -} function SignOutButton() { const { signOut } = useAuthenticator(); @@ -20,21 +9,7 @@ function SignOutButton() { } const SettingsScreen: React.FC = () => { - const qrCodeContext = useContext(QRCodeContext); - const setQrCodes = qrCodeContext ? qrCodeContext.setQrCodes : () => {}; const { userAttributes } = useFetchUserAttributes(); - - const { user } = useAuthenticator((context) => { - console.log(context.user); - handleFetchUserAttributes(); - return [context.user] - }); - - - const clearHistory = () => { - setQrCodes([]); - }; - const handleLinkPress = (url: string) => { Linking.openURL(url); }; @@ -44,7 +19,7 @@ const SettingsScreen: React.FC = () => { Settings Profile - {user ? ( + {userAttributes ? ( Hello, {userAttributes?.name} diff --git a/types.ts b/types.ts index 5d76e36..38a4100 100644 --- a/types.ts +++ b/types.ts @@ -11,6 +11,31 @@ export interface QRCode { }; } +export interface UserAttributes { + email: string; + email_verified: string; + family_name: string; + given_name: string; + identities: string; + name: string; + sub: string; +} + +export interface QRCodeType { + data: { + id: string; + contents: string; + info: { + type: string; + description: string; + }; + createdAt: string; + type: string; + }, + bookmarked: boolean; +} + + export const QRCodeContext = createContext<{ qrCodes: QRCode[]; setQrCodes: React.Dispatch>;