-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrecord.html
256 lines (224 loc) · 8.02 KB
/
record.html
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CriticalSnake Recorder</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@exampledev/[email protected]/new.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
margin: 0;
padding: 0;
max-width: initial;
font-family: sans-serif;
font-size: 1rem;
}
div.panel {
background: #eee;
padding: 0 5px;
}
div.panel > *, div.panel > div > * {
display: inline-block;
margin: 5px 0 5px 5px;
}
div.panel #intervalField {
width: 5rem;
}
div.panel #urlField {
width: 15rem;
}
pre {
font-size: 0.5rem;
border-radius: 0;
padding: 5px;
display: none;
}
</style>
</head>
<body>
<div class="panel">
<button id="nextButton">
<i id="spinner"></i>
<label id="nextButtonLabel"></label>
</button>
<div>
<label for="intervalField">Interval (sec):</label>
<input type="number" id="intervalField" value="30" min="10" max="300">
</div>
<div>
<label for="urlField">Source:</label>
<input type="text" id="urlField" value="https://api.criticalmaps.net/postv2">
</div>
</div>
<pre id="output"></pre>
<script src="3rd-party/filesaver20/FileSaver.min.js"></script>
<script src="3rd-party/lzstring14/lz-string.min.js"></script>
<script>
const controls = ["nextButton", "nextButtonLabel", "spinner",
"intervalField", "urlField", "output"];
const panel = {};
controls.forEach(id => { panel[id] = document.getElementById(id); });
function setButtonState(state) {
const spinClasses = ["fa", "fa-spinner", "fa-spin"].join(" ");
if (state == "Loading") {
panel.nextButtonLabel.innerText = "";
panel.spinner.className = spinClasses;
panel.spinner.style.display = "inline-block";
} else {
panel.spinner.style.display = "none";
panel.spinner.className = spinClasses;
panel.nextButtonLabel.innerText = state;
}
}
function getButtonState() {
return panel.nextButtonLabel.innerText || "Loading";
}
setButtonState("Record");
panel.nextButton.addEventListener("click", () => {
switch (getButtonState()) {
case "Record":
panel.intervalField.disabled = true;
panel.intervalField.style.color = "#888";
panel.urlField.disabled = true;
panel.urlField.style.color = "#888";
panel.output.style.display = "block";
panel.output.innerText = "";
startRecording(panel.intervalField.value, panel.urlField.value);
setButtonState("Finish");
return;
case "Finish":
setButtonState("Loading");
panel.output.innerText = finishRecording();
setButtonState("Download");
return;
case "Download":
setButtonState("Loading");
const blob = compressRecording();
setButtonState("Download");
download(blob);
return;
case "Loading":
console.warn("Please wait until the processed finished");
return;
}
});
function print(txt) {
panel.output.append(txt);
}
function formatDate(timestamp) {
const d = timestamp ? new Date(timestamp * 1000) : new Date();
const pad2 = (val) => (val < 10 ? "0" : "") + val;
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
};
function formatTime(timestamp) {
const d = timestamp ? new Date(timestamp * 1000) : new Date();
const pad2 = (val) => (val < 10 ? "0" : "") + val;
return `${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`
};
let fetchTimer = null;
function startRecording(interval, url) {
// Make sure the value is in the expected range.
const min = 15;
const max = 300;
const seconds = Math.min(max, Math.max(min, parseInt(interval)));
console.log("Start recording", url, "with interval:", seconds * 1000);
fetchData(url);
fetchTimer = setInterval(() => fetchData(url), seconds * 1000);
}
// Expecting a CORS-enabled endpoint, so reponse header should include:
// { access-control-allow-origin: *, ... }
function fetchData(url) {
fetch(url).then(async (response) => {
if (!response.ok)
throw response.status;
const data = await response.json();
if (!data["locations"] || data["locations"] === {}) {
console.warn("No locations in response data");
}
else {
// Success
appendSnapshot(data);
}
})
.catch(err => {
console.error("Error querying data from", url, ":", err);
});
}
function filterMapEntries(map, allowed) {
for (const hash in map)
map[hash] = Object.keys(map[hash])
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = map[hash][key];
return obj;
}, {});
return map;
}
const recording = {};
function appendSnapshot(data) {
const key = `${formatDate()}_${formatTime()}`;
const entries = ["timestamp", "latitude", "longitude"];
const value = filterMapEntries(data.locations, entries);
recording[key] = value;
print(`"${key}":${JSON.stringify(value)},\n`);
}
function finishRecording() {
clearInterval(fetchTimer);
console.log("Finished recording. Snapshots:", recording);
// Human-readable format with indentation of 2 spaces.
return JSON.stringify(recording, null, 2);
}
function compressRecording() {
const kilobyte = (str) => Math.round((str.length * 2) / 1024);
const text = JSON.stringify(recording);
console.log("Raw size is:", kilobyte(text), "KB");
const compressed = LZString.compressToUTF16(text);
console.log("Compressed size is:", kilobyte(compressed), "KB");
return compressed;
}
function deduceType(content) {
if (typeof(content) == "object") {
return [JSON.stringify(content), "json"];
} else {
return [content, "recording"];
}
}
function download(content) {
const [ data, extension ] = deduceType(content);
const filename = `${formatDate()}_${formatTime()}.${extension}`;
console.log("Starting download for", filename);
const blob = new Blob([data], {type: "text/plain;charset=utf-16"});
saveAs(blob, filename);
}
function asciiBanner() {
return String.raw`
_____ _ _ _ _ _____ _
/ ____| (_) | (_) | |/ ____| | |
| | _ __ _| |_ _ ___ __ _| | (___ _ __ __ _| | _____
| | | '__| | __| |/ __/ _' | |\___ \| '_ \ / _' | |/ / _ \
| |____| | | | |_| | (_| (_| | |____) | | | | (_| | < __/
\_____|_| |_|\__|_|\___\__,_|_|_____/|_| |_|\__,_|_|\_\___| Recorder
`;
}
function dumpUsage() {
console.log(asciiBanner());
console.log(
"Welcome to the CriticalSnake Recorder. The graphical user-interface",
"provides a minimal toolset for recordings with a focus on simplicty",
"and reliability. On top of that, the interactive console gives you",
"full access and additional control over the process.");
console.log(
"\nExamples:\n",
"\n* Store intermediate backups of your recording",
"\n https://github.com/weliveindetail/CriticalSnake/blob/master/docs/record.md#example-store-intermediate-backups-of-your-recording",
"\n",
"\n");
console.warn("The project is still work-in-progress and contributions of",
"any kind are welcome. Please report bugs at",
"https://github.com/weliveindetail/CriticalSnake/issues");
}
dumpUsage();
</script>
</body>
</html>