-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
209 lines (188 loc) · 5.64 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import React, { useEffect, useState } from "react";
import {
View,
Image,
TouchableOpacity,
Text,
Button,
StyleSheet,
ScrollView,
} from "react-native";
import RNFS from "react-native-fs";
// @ts-ignore
import Reactotron from "reactotron-react-native/src";
Reactotron.configure().useReactNative().connect();
const DummyImages = [
"https://dummyimage.com/600x400/000/fff&text=01",
"https://dummyimage.com/600x400/000/fff&text=02",
"https://dummyimage.com/600x400/000/fff&text=03",
"https://dummyimage.com/600x400/000/fff&text=04",
"https://dummyimage.com/600x400/000/fff&text=05",
"https://dummyimage.com/600x400/000/fff&text=06",
"https://dummyimage.com/600x400/000/fff&text=07",
"https://dummyimage.com/600x400/000/fff&text=08",
];
const HTTP_DOWNLOAD_LABEL = "http";
const CACHED_LABEL = "cached";
// todo fix the cache glitch
const App = () => {
const [imagesLoaded, setImagesLoaded] = useState(false);
const [localImageURIs, setLocalImageURIs] = useState([]);
const [sourceLabels, setSourceLabels] = useState([]);
useEffect(() => {
preloadImages();
return () => {
clearCache();
};
}, []);
const preloadImages = async () => {
setLocalImageURIs(DummyImages);
setSourceLabels(DummyImages.map(() => HTTP_DOWNLOAD_LABEL));
setImagesLoaded(true);
DummyImages.forEach(async (uri, index) => {
const localFilePath = `${RNFS.TemporaryDirectoryPath}/image_${index}.jpg`;
const fileExists = await RNFS.exists(localFilePath);
if (!fileExists) {
// Adding a delay before downloading each image
await new Promise(resolve => setTimeout(resolve, 1000)); // 1000 ms delay
await RNFS.downloadFile({
fromUrl: uri,
toFile: localFilePath,
}).promise;
}
setLocalImageURIs(prevURIs =>
prevURIs.map((currentURI, uriIndex) =>
uriIndex === index ? `file://${localFilePath}` : currentURI
)
);
setSourceLabels(prevLabels =>
prevLabels.map((label, labelIndex) =>
labelIndex === index ? CACHED_LABEL : label
)
);
});
};
const getImageSource = (index: number): string => {
const localURI = localImageURIs[index];
return localURI ? `file://${localURI}` : DummyImages[index];
};
// todo: fwe can improve the handle download function to fetch the image from the source if it does not exist
const handleDownload = async (index: number) => {
try {
const localURI = localImageURIs[index];
const downloadDir = `${RNFS.DownloadDirectoryPath}`;
const fileName = `image_${index}.jpg`;
const downloadPath = `${downloadDir}/${fileName}`;
await RNFS.copyFile(localURI, downloadPath);
console.log("Image copied to downloads folder:", downloadPath);
} catch (error) {
console.error("Error saving image:", error);
}
};
const downloadAllImages = async () => {
try {
const downloadDir = `${RNFS.DownloadDirectoryPath}`;
const directoryExists = await RNFS.exists(downloadDir);
if (!directoryExists) {
await RNFS.mkdir(downloadDir);
}
await Promise.all(
localImageURIs.map(async (uri, index) => {
const fileName = `image_${index}.jpg`;
const downloadPath = `${downloadDir}/${fileName}`;
await RNFS.copyFile(uri, downloadPath);
})
);
console.log("All images copied to downloads folder");
} catch (error) {
console.log("Error downloading all images:", error);
}
};
const clearCache = async () => {
try {
const promises = localImageURIs.map((uri) => RNFS.unlink(uri));
await Promise.all(promises);
console.log("Cache cleared successfully");
setSourceLabels(Array(sourceLabels.length).fill(HTTP_DOWNLOAD_LABEL));
} catch (error) {
console.error("Failed to clear cache:", error);
} finally {
preloadImages();
}
};
return (
<View style={styles.fullScreen}>
<View style={styles.header}>
<Button
title="Download All"
onPress={downloadAllImages}
color="green"
/>
<Button title="Clear Cache" onPress={clearCache} color="red" />
</View>
<ScrollView contentContainerStyle={styles.container}>
{imagesLoaded ? (
localImageURIs.map((uri, index) => (
<View key={index} style={styles.imageContainer}>
<Image source={{ uri }} style={styles.image} resizeMode="cover" />
<Text style={styles.label}>{sourceLabels[index]}</Text>
<TouchableOpacity onPress={() => handleDownload(index)}>
<Text style={styles.downloadButton}>
{uri}
</Text>
</TouchableOpacity>
</View>
))
) : (
<Text>Loading...</Text>
)}
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
fullScreen: {
flex: 1,
paddingTop: 60,
},
header: {
position: "absolute",
top: 0,
left: 0,
right: 0,
backgroundColor: "#f0f0f0",
zIndex: 10,
flexDirection: "row",
justifyContent: "space-around",
padding: 10,
},
container: {
paddingTop: 60,
paddingBottom: 20,
justifyContent: "center",
alignItems: "center",
flexWrap: "wrap",
flexDirection: "row",
},
imageContainer: {
width: "25%",
padding: 5,
alignItems: "center",
marginBottom: 20,
},
image: {
width: "100%",
aspectRatio: 1,
},
downloadButton: {
marginTop: 5,
color: "blue",
textDecorationLine: "underline",
fontSize: 12,
},
label: {
color: "green",
fontSize: 14,
},
});
export default App;