Skip to content

Commit 2563321

Browse files
Backup my security camera videos using Bun
1 parent bf325ab commit 2563321

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Languages/Bun/download-files.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// This script downloads my security camera videos for backup purposes
2+
3+
console.log("init");
4+
5+
const BASE_URL = "http://192.168.11.4:8082";
6+
7+
(async function main() {
8+
const dirPaths = await getPaths(BASE_URL);
9+
dirPaths.forEach(getFiles);
10+
})();
11+
12+
async function getPaths(url: string) {
13+
const response = await fetch(url);
14+
const pageText = await response.text();
15+
const textLines = pageText.split("\n");
16+
17+
const paths = textLines.reduce((acc, line) => {
18+
if (line.match("href")) {
19+
const path = line.split('"')[1];
20+
console.log(path);
21+
acc.push(path);
22+
}
23+
24+
return acc;
25+
}, [] as string[]);
26+
27+
return paths;
28+
}
29+
30+
async function getFiles(dirPath: string) {
31+
const dirUrl = `${BASE_URL}/${dirPath}`;
32+
const paths = await getPaths(dirUrl);
33+
paths.forEach((path) => {
34+
const fullUrl = dirUrl + path;
35+
fetchFiles(fullUrl, path);
36+
});
37+
}
38+
39+
async function fetchFiles(url: string, name: string) {
40+
const response = await fetch(url);
41+
const path = `security_cam_videos/${name}`;
42+
try {
43+
const exists = await Bun.file(path).exists();
44+
if (exists) {
45+
console.log(`${name} file already exists`);
46+
return;
47+
}
48+
writeFile(path, response);
49+
console.log(`Successfully saved ${name}`);
50+
} catch (e) {
51+
console.error(e);
52+
}
53+
}
54+
55+
async function writeFile(path: string, response: Response) {
56+
Bun.write(path, response);
57+
}

0 commit comments

Comments
 (0)