const express = require('express'); const axios = require('axios'); const path = require('path'); const fs = require('fs'); const app = express(); const port = 80; const url = 'http://transport.tallinn.ee/gps.txt'; const fetchInterval = 10 * 1000; // 10 seconds const retentionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days in ms const gpsFilePath = 'gps/'; const logFilePath = 'logs/'; app.use(express.static(path.join(__dirname, 'public'))); app.use('/gps', express.static(path.join(__dirname, 'gps'))); // Serve static files from the gps directory app.get('/gps-files', (req, res) => { const gpsFilePath = path.join(__dirname, 'gps'); fs.readdir(gpsFilePath, (err, files) => { if (err) return res.status(500).send(err.message); const gpsFiles = files .filter(file => file.startsWith('gps-') && file.endsWith('.txt')) .map(file => ({ name: file, timestamp: file.split('-').slice(1, 4).join('-') + ' ' + file.split('-')[4].replace('.txt', '') })); res.json(gpsFiles); }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); if (!fs.existsSync(gpsFilePath)) fs.mkdirSync(gpsFilePath); function writeToLog(filename, data) { fs.appendFileSync(filename, data); } function deleteOldFiles() { const now = Date.now(); fs.readdirSync(gpsFilePath).forEach(file => { const filePath = path.join(gpsFilePath, file); const stats = fs.statSync(filePath); if (now - stats.mtimeMs > retentionPeriod) { fs.unlinkSync(filePath); } }); } async function fetchAndSaveData() { try { console.log(`Fetch started`); const date = new Date(); const timestamp = `gps-${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}-${String(date.getHours()).padStart(2,'0')}_${String(date.getMinutes()).padStart(2,'0')}_${String(date.getSeconds()).padStart(2,'0')}.txt`; const filePath = path.join(gpsFilePath, timestamp); const logData = `${date} - Fetching new data...\n`; writeToLog('fetch_log.txt', logData); const response = await axios.get(url); if (response.status === 200) { fs.writeFileSync(filePath, response.data, 'utf8'); console.log("Fetch completed."); writeToLog('fetch_log.txt', `${date} - Fetching completed!\n`); } else { writeToLog('errors_log.txt', `${date} - Fetching failed. Got: ${response.status}\n`); } deleteOldFiles(); } catch (error) { const date = new Date(); writeToLog('errors_log.txt', `${date} - Error fetching data: ${error.message}\n`); } } function writeToLog(logfile, logdata) { const realLogFile = path.join(logFilePath, logfile); const dir = path.dirname(realLogFile); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } if (!fs.existsSync(realLogFile)) { fs.writeFileSync(realLogFile, '', 'utf8'); } fs.appendFile(realLogFile, logdata, 'utf8', (err) => { if (err) { console.error('Error writing to file:', err); } }); } setInterval(fetchAndSaveData, fetchInterval); fetchAndSaveData();