diff --git a/api/handleApiChangeRole.ts b/api/handleApiChangeRole.ts index f1c7889..cc4127a 100644 --- a/api/handleApiChangeRole.ts +++ b/api/handleApiChangeRole.ts @@ -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 = { @@ -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(() => { diff --git a/api/handleApiDeleteUser.ts b/api/handleApiDeleteUser.ts index e66e1b5..b20c887 100644 --- a/api/handleApiDeleteUser.ts +++ b/api/handleApiDeleteUser.ts @@ -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 = { @@ -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(() => { diff --git a/api/handleApiFetchDays.ts b/api/handleApiFetchDays.ts index c071ecd..3afff56 100644 --- a/api/handleApiFetchDays.ts +++ b/api/handleApiFetchDays.ts @@ -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 = { @@ -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(() => { diff --git a/api/handleApiFetchImages.ts b/api/handleApiFetchImages.ts index ca1d5f3..8d8b4c5 100644 --- a/api/handleApiFetchImages.ts +++ b/api/handleApiFetchImages.ts @@ -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 = { @@ -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(() => { diff --git a/api/handleApiFetchLive.ts b/api/handleApiFetchLive.ts index f8bf916..944a838 100644 --- a/api/handleApiFetchLive.ts +++ b/api/handleApiFetchLive.ts @@ -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 = { @@ -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('') diff --git a/api/handleApiFetchStats.ts b/api/handleApiFetchStats.ts new file mode 100644 index 0000000..e1a6f38 --- /dev/null +++ b/api/handleApiFetchStats.ts @@ -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) => void + setIsUserLoggedIn: React.Dispatch> + setStats: React.Dispatch> + setStatsFailed: React.Dispatch> + setStatsUpdatedAt: React.Dispatch> + 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) + } +} diff --git a/api/handleApiFetchUserRole.ts b/api/handleApiFetchUserRole.ts index 968327f..6841dbd 100644 --- a/api/handleApiFetchUserRole.ts +++ b/api/handleApiFetchUserRole.ts @@ -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 = { @@ -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(() => { diff --git a/api/handleApiFetchUsers.ts b/api/handleApiFetchUsers.ts index ec7b697..b7ac800 100644 --- a/api/handleApiFetchUsers.ts +++ b/api/handleApiFetchUsers.ts @@ -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 = { @@ -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(() => { diff --git a/api/handleApiLogin.ts b/api/handleApiLogin.ts index 932da94..3c2a2bb 100644 --- a/api/handleApiLogin.ts +++ b/api/handleApiLogin.ts @@ -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 = { @@ -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) diff --git a/api/handleApiShutdown.ts b/api/handleApiShutdown.ts new file mode 100644 index 0000000..d9764ee --- /dev/null +++ b/api/handleApiShutdown.ts @@ -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) => void + setIsUserLoggedIn: React.Dispatch> + userToken: string +} + +export const handleApiShutdown = async ({ + router, + setError, + setIsUserLoggedIn, + userToken, +}: handleApiShutdownProps): Promise => { + 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) + } +} diff --git a/app.json b/app.json index edd6c15..4da9d2e 100644 --- a/app.json +++ b/app.json @@ -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", diff --git a/app/(tabs)/admin.tsx b/app/(tabs)/admin.tsx index aced289..259333b 100644 --- a/app/(tabs)/admin.tsx +++ b/app/(tabs)/admin.tsx @@ -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' @@ -38,8 +41,23 @@ const AdminScreen = () => { const [isLoading, setIsLoading] = useState(true) const [isLoadingInitially, setIsLoadingInitially] = useState(true) const [isLoadingPull, setIsLoadingPull] = useState(false) + const [stats, setStats] = useState(null) + const [statsFailed, setStatsFailed] = useState(false) + const [statsUpdatedAt, setStatsUpdatedAt] = useState(null) const [users, setUsers] = useState([]) + const handleFetchStats = useCallback(() => { + handleApiFetchStats({ + router, + setError, + setIsUserLoggedIn, + setStats, + setStatsFailed, + setStatsUpdatedAt, + userToken, + }) + }, [router, setError, setIsUserLoggedIn, userToken]) + const handleFetchUsers = useCallback( (setIsLoading: React.Dispatch>) => { handleApiFetchUsers({ @@ -62,6 +80,7 @@ const AdminScreen = () => { const handleFetchUsersPull = () => { handleFetchUsers(setIsLoadingPull) + handleFetchStats() } useFocusEffect( @@ -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', @@ -122,7 +151,13 @@ const AdminScreen = () => { /> )} + + ) } diff --git a/app/(tabs)/error.tsx b/app/(tabs)/error.tsx index 9fd01e2..5f0f355 100644 --- a/app/(tabs)/error.tsx +++ b/app/(tabs)/error.tsx @@ -1,5 +1,5 @@ import { useLocalSearchParams, useRouter } from 'expo-router' -import { useContext, useState } from 'react' +import { useContext, useEffect, useRef, useState } from 'react' import { ActivityIndicator, RefreshControl, @@ -30,8 +30,22 @@ const ErrorScreen = () => { const router = useRouter() const { from } = useLocalSearchParams<{ from: string }>() + const goBackTo = useRef(null) + + useEffect(() => { + if (goBackTo.current === null || error.length) { + return + } + router.replace(`/${goBackTo.current}` as any) + goBackTo.current = null + }, [error, router]) + const handleGoBack = () => { - router.replace(`/${from}` as any) + if (!error.length) { + router.replace(`/${from ?? ''}` as any) + return + } + goBackTo.current = from ?? '' setError('') } diff --git a/components/shutdown-button.tsx b/components/shutdown-button.tsx new file mode 100644 index 0000000..b64c1aa --- /dev/null +++ b/components/shutdown-button.tsx @@ -0,0 +1,174 @@ +import { useRouter } from 'expo-router' +import { useContext, useEffect, useState } from 'react' +import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native' + +import { handleApiShutdown } from '@/api/handleApiShutdown' +import ThemedText from '@/components/themed-text' +import { ContextError } from '@/context/ContextError' +import { ContextUser } from '@/context/ContextUser' +import { useThemeColor } from '@/hooks/use-theme-color' + +type ShutdownStatus = 'idle' | 'confirming' | 'loading' | 'done' + +const CONFIRM_TIMEOUT_MS = 3000 + +const ShutdownButton = () => { + const contextError = useContext(ContextError) + if (!contextError) { + throw new Error( + 'ShutdownButton must be used within a ContextError.Provider' + ) + } + const { setError } = contextError + + const contextUser = useContext(ContextUser) + if (!contextUser) { + throw new Error( + 'ShutdownButton must be used within a ContextUser.Provider' + ) + } + const { setIsUserLoggedIn, userToken } = contextUser + + const router = useRouter() + + const activityColor = useThemeColor({}, 'text') + const backgroundColorActive = useThemeColor({}, 'red') + const backgroundColorInactive = useThemeColor({}, 'background') + const borderColor = useThemeColor({}, 'border') + const borderColorInactive = useThemeColor({}, 'textInactive') + const warningColor = useThemeColor({}, 'red') + + const [status, setStatus] = useState('idle') + const [shutdownError, setShutdownError] = useState('') + + const isDisabled = status === 'loading' || status === 'done' + + useEffect(() => { + if (status !== 'confirming') { + return + } + const timeoutId = setTimeout(() => { + setStatus('idle') + }, CONFIRM_TIMEOUT_MS) + return () => { + clearTimeout(timeoutId) + } + }, [status]) + + const handlePress = async () => { + if (status === 'idle') { + setShutdownError('') + setStatus('confirming') + return + } + if (status !== 'confirming') { + return + } + + setStatus('loading') + const errorMessage = await handleApiShutdown({ + router, + setError, + setIsUserLoggedIn, + userToken, + }) + if (errorMessage) { + setShutdownError(errorMessage) + setStatus('idle') + return + } + setStatus('done') + } + + const label = + status === 'confirming' + ? 'Confirm Shutdown' + : status === 'done' + ? 'Shutting Down' + : 'Shutdown Pi' + + const styles = StyleSheet.create({ + border: { + borderTopColor: borderColor, + borderTopWidth: 2, + gap: 8, + marginBottom: -8, + marginHorizontal: 8, + paddingVertical: 16, + }, + disabled: { + backgroundColor: backgroundColorInactive, + borderColor: borderColorInactive, + }, + enabled: { + backgroundColor: backgroundColorActive, + borderColor, + }, + error: { + color: warningColor, + }, + wrapper: { + borderRadius: 12, + borderWidth: 2, + marginHorizontal: 'auto', + marginTop: 8, + minWidth: 144, + paddingHorizontal: 24, + paddingVertical: 8, + }, + }) + + return ( + + [ + styles.wrapper, + isDisabled ? styles.disabled : styles.enabled, + !isDisabled && pressed && { opacity: 0.75 }, + ]} + > + {status === 'loading' ? ( + + ) : ( + + {label} + + )} + + {status === 'done' && ( + + The Raspberry Pi is shutting down. Wait until the green LED + stays off before unplugging it. + + )} + {shutdownError !== '' && ( + + {shutdownError} + + )} + + ) +} + +export default ShutdownButton diff --git a/components/system-stats.tsx b/components/system-stats.tsx new file mode 100644 index 0000000..53bfbbd --- /dev/null +++ b/components/system-stats.tsx @@ -0,0 +1,204 @@ +import { StyleSheet, View } from 'react-native' + +import { SystemStatsType } from '@/api/handleApiFetchStats' +import ThemedText from '@/components/themed-text' +import { useThemeColor } from '@/hooks/use-theme-color' +import { formatBytes, formatDuration, formatTime } from '@/utils/formatStats' + +type SystemStatsProps = { + stats: SystemStatsType | null + statsFailed: boolean + statsUpdatedAt: Date | null +} + +type StatRow = { + label: string + value: string + warning: boolean +} + +const buildRows = (stats: SystemStatsType): StatRow[] => { + const loadAverage = stats.load_average + const rows: (StatRow | null)[] = [ + stats.cpu_temperature !== null + ? { + label: 'CPU Temperature', + value: `${stats.cpu_temperature.toFixed(1)} °C`, + warning: stats.cpu_temperature >= 70, + } + : null, + stats.throttling + ? { + label: 'Power Supply', + value: stats.throttling.under_voltage_now + ? 'Under-voltage' + : stats.throttling.throttled_now + ? 'Throttled' + : stats.throttling.under_voltage_occurred + ? 'Under-voltage since boot' + : 'OK', + warning: + stats.throttling.under_voltage_now || + stats.throttling.throttled_now || + stats.throttling.under_voltage_occurred, + } + : null, + stats.disk + ? { + label: 'Storage', + value: `${formatBytes(stats.disk.free)} free of ${formatBytes(stats.disk.total)}`, + warning: stats.disk.free / stats.disk.total < 0.1, + } + : null, + stats.memory + ? { + label: 'Memory', + value: `${formatBytes(stats.memory.available)} free of ${formatBytes(stats.memory.total)}`, + warning: stats.memory.available / stats.memory.total < 0.15, + } + : null, + stats.memory && stats.memory.swap_total > 0 + ? { + label: 'Swap', + value: `${formatBytes(stats.memory.swap_total - stats.memory.swap_free)} used of ${formatBytes(stats.memory.swap_total)}`, + warning: + stats.memory.swap_free / stats.memory.swap_total < 0.5, + } + : null, + ...(loadAverage + ? ['1 min', '5 min', '15 min'].map((period, index) => ({ + label: `Load (${period})`, + value: loadAverage[index].toFixed(2), + warning: index > 0 && loadAverage[index] > 2, + })) + : []), + stats.uptime_seconds !== null + ? { + label: 'Uptime', + value: formatDuration(stats.uptime_seconds), + warning: false, + } + : null, + { + label: 'Last Live Image', + value: + stats.live.newest_age_seconds !== null + ? `${formatDuration(stats.live.newest_age_seconds)} ago` + : 'None', + warning: + stats.live.newest_age_seconds === null || + stats.live.newest_age_seconds > 60, + }, + { + label: 'Last Archive Image', + value: + stats.archive.newest_age_seconds !== null + ? `${formatDuration(stats.archive.newest_age_seconds)} ago` + : 'None', + warning: + stats.archive.newest_age_seconds === null || + stats.archive.newest_age_seconds > 600, + }, + { + label: 'Archive Images', + value: + stats.archive.count >= stats.archive.max + ? `${stats.archive.count} (full)` + : `${stats.archive.count} of ${stats.archive.max}`, + warning: false, + }, + ] + + return rows.filter((row): row is StatRow => row !== null) +} + +const SystemStats = ({ + stats, + statsFailed, + statsUpdatedAt, +}: SystemStatsProps) => { + const borderColor = useThemeColor({}, 'border') + const backgroundColor = useThemeColor({}, 'background') + const warningColor = useThemeColor({}, 'red') + + const styles = StyleSheet.create({ + border: { + borderTopColor: borderColor, + borderTopWidth: 2, + marginBottom: -8, + marginHorizontal: 8, + paddingVertical: 16, + }, + label: { + flexShrink: 1, + }, + row: { + flexDirection: 'row', + gap: 16, + justifyContent: 'space-between', + }, + value: { + flexShrink: 1, + textAlign: 'right', + }, + warning: { + color: warningColor, + fontWeight: 'bold', + }, + wrapper: { + backgroundColor, + borderColor, + borderRadius: 12, + borderWidth: 2, + gap: 8, + padding: 12, + }, + }) + + return ( + + + System + {stats ? ( + buildRows(stats).map((row) => ( + + + {row.label} + + + {row.value} + + + )) + ) : ( + + {statsFailed + ? 'System stats are currently unavailable.' + : 'Loading system stats…'} + + )} + {stats && statsUpdatedAt && ( + + {statsFailed + ? `Last update failed, showing values from ${formatTime(statsUpdatedAt)}.` + : `Last updated at ${formatTime(statsUpdatedAt)}.`} + + )} + + + ) +} + +export default SystemStats diff --git a/helper/getErrorMessage.ts b/helper/getErrorMessage.ts new file mode 100644 index 0000000..facc0e7 --- /dev/null +++ b/helper/getErrorMessage.ts @@ -0,0 +1,15 @@ +const NETWORK_ERROR_PATTERN = + /network request failed|fetch failed|connectexception|failed to connect|unable to resolve host|unreachable|timed out/i + +export const getErrorMessage = (error: unknown) => { + if (!(error instanceof Error)) { + return 'Unknown error' + } + if (error.name === 'AbortError' || error.message.includes('Aborted')) { + return 'Response from Server took too long' + } + if (NETWORK_ERROR_PATTERN.test(error.message)) { + return 'Server is not reachable.\nCheck that the Raspberry Pi is running and that you are connected to the same network.' + } + return error.message +} diff --git a/package-lock.json b/package-lock.json index 3902948..3ba8b06 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "security-app", - "version": "1.2.1", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "security-app", - "version": "1.2.1", + "version": "1.3.0", "dependencies": { "@expo/vector-icons": "^15.1.1", "@react-native-async-storage/async-storage": "^2.2.0", diff --git a/package.json b/package.json index 5f4618c..f33ebde 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "security-app", "main": "expo-router/entry", - "version": "1.2.1", + "version": "1.3.0", "scripts": { "start": "expo start --go", "android": "expo start --android", diff --git a/utils/formatStats.ts b/utils/formatStats.ts new file mode 100644 index 0000000..9dfacfc --- /dev/null +++ b/utils/formatStats.ts @@ -0,0 +1,29 @@ +export const formatBytes = (bytes: number) => { + const gigabytes = bytes / 1024 ** 3 + if (gigabytes >= 1) { + return `${gigabytes.toFixed(1)} GB` + } + return `${Math.round(bytes / 1024 ** 2)} MB` +} + +export const formatDuration = (seconds: number) => { + const days = Math.floor(seconds / 86400) + const hours = Math.floor((seconds % 86400) / 3600) + const minutes = Math.floor((seconds % 3600) / 60) + + if (days > 0) { + return `${days} d ${hours} h` + } + if (hours > 0) { + return `${hours} h ${minutes} min` + } + if (minutes > 0) { + return `${minutes} min` + } + return `${seconds} s` +} + +export const formatTime = (date: Date) => + [date.getHours(), date.getMinutes(), date.getSeconds()] + .map((value) => `${value}`.padStart(2, '0')) + .join(':')