Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions api/handleApiChangeRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ImperativeRouter } from 'expo-router'

import { handleApiFetchUsers, UsersType } from '@/api/handleApiFetchUsers'
import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

type handleApiChangeRoleProps = {
Expand Down Expand Up @@ -80,10 +81,7 @@ export const handleApiChangeRole = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)

queueMicrotask(() => {
Expand Down
6 changes: 2 additions & 4 deletions api/handleApiDeleteUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ImperativeRouter } from 'expo-router'

import { handleApiFetchUsers, UsersType } from '@/api/handleApiFetchUsers'
import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

type handleApiDeleteUserProps = {
Expand Down Expand Up @@ -77,10 +78,7 @@ export const handleApiDeleteUser = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)

queueMicrotask(() => {
Expand Down
6 changes: 2 additions & 4 deletions api/handleApiFetchDays.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

export type RecordingDay = {
Expand Down Expand Up @@ -66,10 +67,7 @@ export const handleApiFetchDays = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)

queueMicrotask(() => {
Expand Down
6 changes: 2 additions & 4 deletions api/handleApiFetchImages.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, ITEMS_PER_PAGE, URL } from '@/constants/api'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

type handleApiFetchImagesProps = {
Expand Down Expand Up @@ -94,10 +95,7 @@ export const handleApiFetchImages = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)

queueMicrotask(() => {
Expand Down
6 changes: 2 additions & 4 deletions api/handleApiFetchLive.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

type handleApiFetchLiveProps = {
Expand Down Expand Up @@ -66,10 +67,7 @@ export const handleApiFetchLive = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)
setImageName('')

Expand Down
85 changes: 85 additions & 0 deletions api/handleApiFetchStats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { clearData } from '@/helper/storeData'

type ImageFolderStats = {
count: number
newest_age_seconds: number | null
}

export type SystemStatsType = {
archive: ImageFolderStats & { max: number }
cpu_temperature: number | null
disk: { free: number; total: number } | null
live: ImageFolderStats
load_average: number[] | null
memory: {
available: number
swap_free: number
swap_total: number
total: number
} | null
throttling: {
throttled_now: boolean
throttled_occurred: boolean
under_voltage_now: boolean
under_voltage_occurred: boolean
} | null
uptime_seconds: number | null
}

type handleApiFetchStatsProps = {
router: ImperativeRouter
setError: (value: React.SetStateAction<string>) => void
setIsUserLoggedIn: React.Dispatch<React.SetStateAction<boolean>>
setStats: React.Dispatch<React.SetStateAction<SystemStatsType | null>>
setStatsFailed: React.Dispatch<React.SetStateAction<boolean>>
setStatsUpdatedAt: React.Dispatch<React.SetStateAction<Date | null>>
userToken: string
}

export const handleApiFetchStats = async ({
router,
setError,
setIsUserLoggedIn,
setStats,
setStatsFailed,
setStatsUpdatedAt,
userToken,
}: handleApiFetchStatsProps) => {
const controller = new AbortController()
const timeoutId = setTimeout(() => {
controller.abort()
}, API_TIMEOUT_MS)

try {
const response = await fetch(`${URL}/admin/stats`, {
headers: {
Authorization: `Bearer ${userToken}`,
},
signal: controller.signal,
})

if (response.status === 403) {
setIsUserLoggedIn(false)
setError('')
await clearData(['authToken', 'authRole', 'authName'])
router.replace('/')
return
}

if (!response.ok) {
throw new Error(`Error ${response.status}`)
}

const stats: SystemStatsType = await response.json()
setStats(stats)
setStatsFailed(false)
setStatsUpdatedAt(new Date())
} catch {
setStatsFailed(true)
} finally {
clearTimeout(timeoutId)
}
}
6 changes: 2 additions & 4 deletions api/handleApiFetchUserRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { UserRoleType } from '@/context/ContextUser'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData, saveData } from '@/helper/storeData'

type handleApiFetchRoleProps = {
Expand Down Expand Up @@ -68,10 +69,7 @@ export const handleApiFetchRole = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)

queueMicrotask(() => {
Expand Down
6 changes: 2 additions & 4 deletions api/handleApiFetchUsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { UserRoleType } from '@/context/ContextUser'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

export type UsersType = {
Expand Down Expand Up @@ -68,10 +69,7 @@ export const handleApiFetchUsers = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)

queueMicrotask(() => {
Expand Down
6 changes: 2 additions & 4 deletions api/handleApiLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { UserRoleType } from '@/context/ContextUser'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData, saveData } from '@/helper/storeData'

type handleApiLoginProps = {
Expand Down Expand Up @@ -91,10 +92,7 @@ export const handleApiLogin = async ({
} catch (error: any) {
clearTimeout(timeoutId)

const errorMessage =
error.name === 'AbortError' || error.message.includes('Aborted')
? 'Response from Server took too long'
: error.message
const errorMessage = getErrorMessage(error)
setError(errorMessage)
setIsUserLoggedIn(false)

Expand Down
53 changes: 53 additions & 0 deletions api/handleApiShutdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { ImperativeRouter } from 'expo-router'

import { API_TIMEOUT_MS, URL } from '@/constants/api'
import { getErrorMessage } from '@/helper/getErrorMessage'
import { clearData } from '@/helper/storeData'

type handleApiShutdownProps = {
router: ImperativeRouter
setError: (value: React.SetStateAction<string>) => void
setIsUserLoggedIn: React.Dispatch<React.SetStateAction<boolean>>
userToken: string
}

export const handleApiShutdown = async ({
router,
setError,
setIsUserLoggedIn,
userToken,
}: handleApiShutdownProps): Promise<string | null> => {
const controller = new AbortController()
const timeoutId = setTimeout(() => {
controller.abort()
}, API_TIMEOUT_MS)

try {
const response = await fetch(`${URL}/admin/shutdown`, {
method: 'POST',
headers: {
Authorization: `Bearer ${userToken}`,
},
signal: controller.signal,
})

if (response.status === 403) {
setIsUserLoggedIn(false)
setError('')
await clearData(['authToken', 'authRole', 'authName'])
router.replace('/')
return null
}

if (!response.ok) {
const data = await response.json().catch(() => ({}))
return `Error ${response.status}: ${data.error || 'Unknown error'}`
}

return null
} catch (error: any) {
return getErrorMessage(error)
} finally {
clearTimeout(timeoutId)
}
}
2 changes: 1 addition & 1 deletion app.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"expo": {
"name": "Security Application",
"slug": "security-app",
"version": "1.2.1",
"version": "1.3.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "securityapp",
Expand Down
35 changes: 35 additions & 0 deletions app/(tabs)/admin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import { useFocusEffect, useRouter } from 'expo-router'
import { useCallback, useContext, useState } from 'react'
import { RefreshControl, StyleSheet, View } from 'react-native'

import { handleApiFetchStats, SystemStatsType } from '@/api/handleApiFetchStats'
import { handleApiFetchUsers, UsersType } from '@/api/handleApiFetchUsers'
import Button from '@/components/button'
import { noUsers } from '@/components/icon-symbol'
import MainView from '@/components/main-view'
import ShutdownButton from '@/components/shutdown-button'
import SkeletonUserGrid from '@/components/skeleton-user-grid'
import SystemStats from '@/components/system-stats'
import ThemedText from '@/components/themed-text'
import UserGrid from '@/components/user-grid'
import UserHeader from '@/components/user-header'
Expand Down Expand Up @@ -38,8 +41,23 @@ const AdminScreen = () => {
const [isLoading, setIsLoading] = useState<boolean>(true)
const [isLoadingInitially, setIsLoadingInitially] = useState<boolean>(true)
const [isLoadingPull, setIsLoadingPull] = useState<boolean>(false)
const [stats, setStats] = useState<SystemStatsType | null>(null)
const [statsFailed, setStatsFailed] = useState<boolean>(false)
const [statsUpdatedAt, setStatsUpdatedAt] = useState<Date | null>(null)
const [users, setUsers] = useState<UsersType[]>([])

const handleFetchStats = useCallback(() => {
handleApiFetchStats({
router,
setError,
setIsUserLoggedIn,
setStats,
setStatsFailed,
setStatsUpdatedAt,
userToken,
})
}, [router, setError, setIsUserLoggedIn, userToken])

const handleFetchUsers = useCallback(
(setIsLoading: React.Dispatch<React.SetStateAction<boolean>>) => {
handleApiFetchUsers({
Expand All @@ -62,6 +80,7 @@ const AdminScreen = () => {

const handleFetchUsersPull = () => {
handleFetchUsers(setIsLoadingPull)
handleFetchStats()
}

useFocusEffect(
Expand All @@ -70,6 +89,16 @@ const AdminScreen = () => {
}, [handleFetchUsersManual])
)

useFocusEffect(
useCallback(() => {
handleFetchStats()
const refresh = setInterval(handleFetchStats, 30000)
return () => {
clearInterval(refresh)
}
}, [handleFetchStats])
)

const styles = StyleSheet.create({
activityLoader: {
alignItems: 'center',
Expand Down Expand Up @@ -122,7 +151,13 @@ const AdminScreen = () => {
/>
</View>
)}
<SystemStats
stats={stats}
statsFailed={statsFailed}
statsUpdatedAt={statsUpdatedAt}
/>
<UserSettings handleFetchUserRole={undefined} />
<ShutdownButton />
</MainView>
)
}
Expand Down
Loading