93 lines
2.7 KiB
JavaScript
93 lines
2.7 KiB
JavaScript
require('dotenv').config();
|
|
const { createClient } = require('webdav');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
// init db
|
|
const low = require('lowdb');
|
|
const FileSync = require('lowdb/adapters/FileSync');
|
|
const adapter = new FileSync('db.json');
|
|
const db = low(adapter);
|
|
db.defaults({ files: [], count: 0}).write();
|
|
|
|
// create webdav-client
|
|
const client = createClient(
|
|
process.env.WEBDAV_URL,
|
|
{
|
|
username: process.env.WEBDAV_USER,
|
|
password: process.env.WEBDAV_PW
|
|
}
|
|
);
|
|
|
|
/**
|
|
* webserver
|
|
*/
|
|
const express = require('express');
|
|
const { stringify } = require('querystring');
|
|
const app = express();
|
|
|
|
const expressWs = require('express-ws')(app);
|
|
app.ws('/watchdog', function(ws, req) {
|
|
ws.on('message', function(msg) {
|
|
// echo
|
|
ws.send(msg);
|
|
});
|
|
});
|
|
|
|
app.use('/files', express.static(path.join(__dirname, 'files')));
|
|
app.get('/api/files', (req, res) => {
|
|
res.json({resource: db.get('files').value()});
|
|
});
|
|
app.use(express.static(path.join(__dirname, 'public')));
|
|
app.listen(process.env.PORT, () => console.log(`Example app listening at http://localhost:${process.env.PORT}`));
|
|
|
|
/**
|
|
* backend functions
|
|
*/
|
|
|
|
async function listDir(dir = process.env.WEBFRAME_PATH) {
|
|
const directoryItems = await client.getDirectoryContents(dir);
|
|
return directoryItems;
|
|
}
|
|
|
|
async function dlFile(file, dir = process.env.WEBFRAME_PATH) {
|
|
const isDirExists = fs.existsSync(dir) && fs.lstatSync(dir).isDirectory();
|
|
if (!isDirExists) {
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
console.log('Created dir:', dir);
|
|
}
|
|
// return client.createReadStream(dir+'/'+file).pipe(fs.createWriteStream('./files/'+file));
|
|
return client.getFileContents(dir+'/'+file);
|
|
}
|
|
|
|
async function loadImages() {
|
|
try {
|
|
const data = await client.exists(process.env.WEBFRAME_PATH);
|
|
if (data) {
|
|
const list = await listDir(process.env.WEBFRAME_PATH);
|
|
for (let i = 0; i < list.length; i++) {
|
|
const file = list[i];
|
|
const path = './files/'
|
|
const inDb = db.get('files').find({ basename: file.basename }).value() !== undefined ? true : false;
|
|
if (!inDb) {
|
|
const blob = await dlFile(file.basename);
|
|
console.log('Downloaded new File:', file.basename);
|
|
fs.writeFile(path+file.basename, blob, () => {
|
|
db.get('files').push(file).write();
|
|
db.update('count', n => n + 1).write();
|
|
// notify clients via ws
|
|
expressWs.getWss().clients.forEach(ws => ws.send(JSON.stringify({
|
|
code: 201,
|
|
message: 'pls update'
|
|
})));
|
|
});
|
|
}
|
|
}
|
|
}
|
|
setTimeout(() => loadImages(), 2000); //process.env.POLL_TIMEOUT);
|
|
} catch (e) {
|
|
console.error('[loadImages]', e);
|
|
}
|
|
}
|
|
|
|
loadImages();
|