-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssetUpdater.tsx
234 lines (213 loc) · 7.51 KB
/
AssetUpdater.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { MainBundlePath, DocumentDirectoryPath, downloadFile, exists as fileExists, readDir } from '@dr.pogodin/react-native-fs';
import { createContext, useContext, useEffect, useState } from 'react';
import {
Pressable,
Settings,
StyleSheet,
Text,
View
} from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import * as Progress from 'react-native-progress';
import { subscribe, unzip } from 'react-native-zip-archive';
import Spacer from './Spacer.tsx';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
centeredView: {
padding: 20,
},
buttonStyle: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'black',
},
disabledButtonStyle: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
backgroundColor: 'gray',
},
progressTitle: {
fontSize: 18,
color: 'black',
},
buttonTitle: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
},
});
const AssetContext = createContext(null);
export const useAssetPath = () => {
return useContext(AssetContext);
}
export const AssetUpdater = ({ children }) => {
const [progress, setProgress] = useState(0.0);
const [progressMessage, setProgressMessage] = useState("");
const [assetPath, setAssetPath] = useState('');
const [estimatedTime, setEstimatedTime] = useState("Calculating...");
const onUpdate = async (): Promise<string> => {
const { uri } = await DocumentPicker.pickSingle({
type: "public.zip-archive",
mode: "open",
presentationStyle: 'fullScreen'
});
return unzipLuti(uri);
}
const unzipLuti = async (uri) => {
const subscription = subscribe(function ({
progress: zipProgress,
filePath,
}) {
setProgress(zipProgress);
});
setProgressMessage("Unpacking LUTI from file");
setProgress(0.0);
if (uri !== null) {
const srcPath = decodeURI(uri.substring(7));
const targetPath = `${DocumentDirectoryPath}/luti-${Date.now()}`;
setProgress(0.0);
const unzipPath = await unzip(srcPath, targetPath);
if (await fileExists(unzipPath + "/asset-manifest.json")) {
Settings.set({ admin_mode: 0 });
subscription.remove();
return unzipPath;
}
}
subscription.remove();
setProgressMessage("");
throw new Error("Didn't find a LUTI website in zip file");
};
const full_url = 'https://lifeundertheice.s3.amazonaws.com/luti-2024-06-19T20-47.zip';
const tiny_url = 'https://lifeundertheice.s3.amazonaws.com/tiny-luti-2024-05-12T11-03.zip';
const downloadLuti = async (url): Promise<string> => {
// const url = 'http://localhost:9000/mini-luti-2024-05-11T21-14.zip';
const destPath = `${DocumentDirectoryPath}/luti-${Date.now()}`;
setProgressMessage("Downloading LUTI data");
setProgress(0.0);
const startTime = Date.now();
let estimatedTimes = [];
const options = {
fromUrl: url,
toFile: destPath,
background: false,
progressDivider: 1,
progress: (res) => {
const progressPercent = (res.bytesWritten / res.contentLength);
console.log(`Progress: ${progressPercent.toFixed(2)}%`);
// Update your progress state or UI here
// https://lifeundertheice.s3.amazonaws.com/mini-luti-2024-05-11T21-14.zip
setProgress(progressPercent);
// Calculate estimated remaining time
const elapsedTime = Date.now() - startTime;
const estimatedTotalTime = elapsedTime / progressPercent;
const estimatedRemainingTime = estimatedTotalTime - elapsedTime;
estimatedTimes.push(estimatedRemainingTime);
const lastEstimates = estimatedTimes.slice(-5);
if (lastEstimates.length > 0) {
let averageEstimatedTime = lastEstimates.reduce((sum, time) => sum + time, 0) / lastEstimates.length;
// Format the average estimated time
const seconds = Math.floor((averageEstimatedTime / 1000) % 60);
const minutes = Math.floor((averageEstimatedTime / 1000 / 60) % 60);
const hours = Math.floor((averageEstimatedTime / 1000 / 60 / 60) % 24);
setEstimatedTime(`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`);
} else {
setEstimatedTime("Calculating...");
}
},
};
console.log("DOWNLOADING", url);
return downloadFile(options).promise.then(async res => {
return await unzipLuti("file://" + destPath);
});
};
const getLatestAssetDirectory = async (): Promise<string> => {
if (Settings.get("admin_mode") === undefined) { // first run
const localZip = `file://${MainBundlePath}/tiny-luti-2024-05-12T11-03.zip`;
console.log("Unzipping", localZip);
return await unzipLuti(localZip);
}
if (Settings.get("admin_mode") !== 0) {
throw new Error("Admin Mode");
}
const lutiDir = (await readDir(DocumentDirectoryPath))
const last = lutiDir
.sort((a, b) => a.name.localeCompare(b.name))
.findLast(d => d.isDirectory() && d.name.startsWith("luti-"));
if (last !== undefined) {
return last.path;
}
throw new Error("No LUTI dirs available");
};
useEffect(() => {
const getLatest = async () => {
try {
let path = await getLatestAssetDirectory();
setAssetPath(path);
} catch (err) {
console.log(err);
//pass
}
};
getLatest()
.catch(console.error);
}, []);
if (assetPath === '') {
return <View style={styles.container}>
<View style={styles.centeredView}>
<Text style={styles.progressTitle}>Life Under The Ice needs a dataset to run.</Text>
<Text style={styles.progressTitle}>You can either download a test dataset or insert a USB disk containing a LUTI zip file.</Text>
<Spacer size={50} vertical />
<Pressable
disabled={progress > 0.0}
onPress={async () => {
setAssetPath(await onUpdate())
}}
style={progress > 0.0 ? styles.disabledButtonStyle : styles.buttonStyle}>
<Text style={styles.buttonTitle}>Update from zip file</Text>
</Pressable>
<Spacer size={50} vertical />
<Pressable
disabled={progress > 0.0}
onPress={async () => {
setAssetPath(await downloadLuti(tiny_url))
}}
style={progress > 0.0 ? styles.disabledButtonStyle : styles.buttonStyle}>
<Text style={styles.buttonTitle}>Download test version (20Mb)</Text>
</Pressable>
<Spacer size={50} vertical />
<Pressable
disabled={progress > 0.0}
onPress={async () => {
setAssetPath(await downloadLuti(full_url))
}}
style={progress > 0.0 ? styles.disabledButtonStyle : styles.buttonStyle}>
<Text style={styles.buttonTitle}>Download full version (3.4Gb)</Text>
</Pressable>
<Spacer size={50} vertical />
{progressMessage !== "" ? (
<>
<Progress.Bar progress={progress} width={200} />
<Spacer size={10} vertical />
<Text style={styles.progressTitle}>Estimated time remaining: {estimatedTime}</Text>
</>
) : null}
</View>
</View>;
} else {
return <AssetContext.Provider value={assetPath}>
{children}
</AssetContext.Provider>
}
}