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
10 changes: 6 additions & 4 deletions app/(tabs)/live.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Image } from 'expo-image'
import { useFocusEffect, useRouter } from 'expo-router'
import { useCallback, useContext, useState } from 'react'
import {
ActivityIndicator,
Image,
Pressable,
RefreshControl,
StyleSheet,
Expand Down Expand Up @@ -65,11 +65,11 @@ const LiveScreen = () => {
)
const router = useRouter()

const fullUriWithToken = `${URL}/live?token=${userToken}&time=${refreshTime}`
const fullUri = `${URL}/live?time=${refreshTime}`

const imageSource = imageLoadFailed
? errorImageSource
: { uri: fullUriWithToken }
: { uri: fullUri, headers: { Authorization: `Bearer ${userToken}` } }

const formattedDate = () => {
if (
Expand Down Expand Up @@ -241,7 +241,9 @@ const LiveScreen = () => {
alt={formattedDate()}
source={imageSource}
style={styles.image}
resizeMode="cover"
contentFit="cover"
// every refresh has a new URL, so don't fill the disk cache
cachePolicy="none"
onError={() => {
setImageLoadFailed(true)
setImageIsLoaded(true)
Expand Down
32 changes: 21 additions & 11 deletions components/highlight-image.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { useContext, useRef, useState } from 'react'
import { Image } from 'expo-image'
import { useContext, useMemo, useState } from 'react'
import {
ActivityIndicator,
Dimensions,
Image,
ImageInstance,
Pressable,
StyleSheet,
View,
} from 'react-native'

import ThemedText from '@/components/themed-text'
import { ContextImageRotation } from '@/context/ContextImageRotation'
import { ContextUser } from '@/context/ContextUser'
import { useHighlightImageSize } from '@/hooks/use-highlight-image-size'
import { useThemeColor } from '@/hooks/use-theme-color'
import { downloadImage } from '@/utils/downloadImage'
Expand All @@ -34,20 +34,32 @@ const HighlightImage = ({
}
const { imageRotation } = contextImageRotation

const contextUser = useContext(ContextUser)
if (!contextUser) {
throw new Error(
'HighlightImage must be used within a ContextUser.Provider'
)
}
const { userToken } = contextUser

const imageHeaders = useMemo(
() => ({ Authorization: `Bearer ${userToken}` }),
[userToken]
)

const { width, height } = Dimensions.get('window')

const activityColor = useThemeColor({}, 'text')
const backgroundColor = useThemeColor({}, 'background')
const highlightColor = useThemeColor({}, 'highlight')

const imageRef = useRef<ImageInstance>(null)
const [imageHeight, setImageHeight] = useState<number>(256)
const [imageIsLoaded, setImageIsLoaded] = useState<boolean>(false)
const [imageIsLoadedSuccess, setImageIsLoadedSuccess] =
useState<boolean>(false)

const imageSource = imageIsLoadedSuccess
? { uri: imageHighlighted! }
? { uri: imageHighlighted!, headers: imageHeaders }
: errorImageSource

const formattedDate = () => {
Expand Down Expand Up @@ -88,6 +100,7 @@ const HighlightImage = ({
useHighlightImageSize({
height,
imageHighlighted,
imageHeaders,
setImageHeight,
setImageIsLoaded,
setImageIsLoadedSuccess,
Expand All @@ -106,6 +119,7 @@ const HighlightImage = ({
backgroundColor,
height: imageHeight,
transform: [{ rotate: `${imageRotation}deg` }],
width,
},
wrapper: {
backgroundColor: highlightColor,
Expand Down Expand Up @@ -133,12 +147,10 @@ const HighlightImage = ({
{imageIsLoaded && imageIsLoadedSuccess && imageSource.uri && (
<>
<Image
ref={imageRef}
alt={formattedDate() || 'Past Recording'}
source={imageSource}
style={styles.image}
width={width}
resizeMode="contain"
contentFit="contain"
onError={handleErrorImage}
/>
{formattedDate().length ? (
Expand All @@ -152,12 +164,10 @@ const HighlightImage = ({
)}
{imageIsLoaded && !imageIsLoadedSuccess && (
<Image
ref={imageRef}
alt="Error Image"
source={imageSource}
style={styles.image}
width={width}
resizeMode="contain"
contentFit="contain"
onError={handleErrorImage}
/>
)}
Expand Down
17 changes: 6 additions & 11 deletions components/image-grid-item.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import { Image } from 'expo-image'
import { useContext, useState } from 'react'
import {
ActivityIndicator,
Image,
Pressable,
StyleSheet,
View,
} from 'react-native'
import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native'

import { URL } from '@/constants/api'
import { Colors } from '@/constants/theme'
Expand Down Expand Up @@ -48,11 +43,11 @@ const ImageGridItem = ({
)

const safeItem = encodeURI(item)
const fullUriWithToken = `${URL}${safeItem}?token=${userToken}`
const fullUri = `${URL}${safeItem}`

const imageSource = imageLoadFailed
? errorImageSource
: { uri: fullUriWithToken }
: { uri: fullUri, headers: { Authorization: `Bearer ${userToken}` } }

const [prevItem, setPrevItem] = useState(item)
if (item !== prevItem) {
Expand All @@ -63,7 +58,7 @@ const ImageGridItem = ({

const handlePress = () => {
if (imageIsLoaded) {
setImageHighlighted(fullUriWithToken)
setImageHighlighted(fullUri)
}
}

Expand Down Expand Up @@ -116,7 +111,7 @@ const ImageGridItem = ({
alt={item}
source={imageSource}
style={styles.image}
resizeMode="cover"
contentFit="cover"
onError={() => {
setImageLoadFailed(true)
setImageIsLoaded(true)
Expand Down
27 changes: 18 additions & 9 deletions hooks/use-highlight-image-size.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Image } from 'expo-image'
import { useEffect } from 'react'
import { Image } from 'react-native'

type useHighlightImageSizeProps = {
height: number
imageHighlighted: string | null
imageHeaders: Record<string, string>
setImageHeight: (value: React.SetStateAction<number>) => void
setImageIsLoaded: (value: React.SetStateAction<boolean>) => void
setImageIsLoadedSuccess: (value: React.SetStateAction<boolean>) => void
Expand All @@ -13,6 +14,7 @@ type useHighlightImageSizeProps = {
export const useHighlightImageSize = ({
height,
imageHighlighted,
imageHeaders,
setImageHeight,
setImageIsLoaded,
setImageIsLoadedSuccess,
Expand All @@ -22,26 +24,33 @@ export const useHighlightImageSize = ({
setImageIsLoaded(false)
setImageIsLoadedSuccess(false)

let cancelled = false

if (imageHighlighted) {
Image.getSize(
imageHighlighted,
(originalWidth, originalHeight) => {
Image.loadAsync({ uri: imageHighlighted, headers: imageHeaders })
.then((image) => {
if (cancelled) return
const calculatedHeight =
(width / originalWidth) * originalHeight
(width / image.width) * image.height
setImageHeight(Math.min(calculatedHeight, height))
setImageIsLoaded(true)
setImageIsLoadedSuccess(true)
},
() => {
})
.catch(() => {
if (cancelled) return
setImageHeight(256)
setImageIsLoaded(true)
setImageIsLoadedSuccess(false)
}
)
})
}

return () => {
cancelled = true
}
}, [
height,
imageHighlighted,
imageHeaders,
setImageHeight,
setImageIsLoaded,
setImageIsLoadedSuccess,
Expand Down
55 changes: 44 additions & 11 deletions utils/downloadImage.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,67 @@
import * as FileSystem from 'expo-file-system/legacy'
import { manipulateAsync, SaveFormat } from 'expo-image-manipulator'
import { ImageManipulator, SaveFormat } from 'expo-image-manipulator'
import { shareAsync } from 'expo-sharing'
import { Alert } from 'react-native'

type downloadImageProps = {
imageName: string
imageSource: any
imageRotation: number
}

const IMAGE_NAME_PATTERN =
/^security_image_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.jpg$/

const getServedImageName = (headers: Record<string, string>) => {
const key = Object.keys(headers).find(
(header) => header.toLowerCase() === 'x-image-name'
)
const name = key ? headers[key] : undefined
return name && IMAGE_NAME_PATTERN.test(name) ? name : undefined
}

export const downloadImage = async ({
imageName,
imageSource,
imageRotation,
}: downloadImageProps) => {
const tempDownloadUri =
FileSystem.cacheDirectory + 'raw_download_' + imageName
const finalTargetUri = FileSystem.cacheDirectory + imageName

try {
const checkTarget = await FileSystem.getInfoAsync(finalTargetUri)
if (checkTarget.exists) {
await FileSystem.deleteAsync(finalTargetUri, { idempotent: true })
const download = await FileSystem.downloadAsync(
imageSource.uri,
tempDownloadUri,
{ headers: imageSource.headers }
)

if (download.status !== 200) {
await FileSystem.deleteAsync(tempDownloadUri, { idempotent: true })
Alert.alert(
'Image not available',
download.status === 404
? 'This image no longer exists. It has probably been replaced by a newer one.'
: `The image could not be downloaded (HTTP ${download.status}).`
)
return
}

await FileSystem.downloadAsync(imageSource.uri, tempDownloadUri)
const finalImageName = getServedImageName(download.headers) ?? imageName
const finalTargetUri = FileSystem.cacheDirectory + finalImageName

await FileSystem.deleteAsync(finalTargetUri, { idempotent: true })

if (imageRotation) {
const manipulatedImage = await manipulateAsync(
tempDownloadUri,
[{ rotate: imageRotation }],
{ compress: 1, format: SaveFormat.JPEG }
const rotatedImage = await ImageManipulator.manipulate(
tempDownloadUri
)
.rotate(imageRotation)
.renderAsync()
const manipulatedImage = await rotatedImage.saveAsync({
compress: 1,
format: SaveFormat.JPEG,
})
rotatedImage.release()

await FileSystem.copyAsync({
from: manipulatedImage.uri,
Expand All @@ -51,9 +82,11 @@ export const downloadImage = async ({

await shareAsync(finalTargetUri, {
mimeType: 'image/jpeg',
dialogTitle: imageName,
dialogTitle: finalImageName,
})
} catch (error: any) {
console.error('Download/Processing failed:', error)
await FileSystem.deleteAsync(tempDownloadUri, { idempotent: true })
Alert.alert('Download failed', 'The image could not be shared.')
}
}