const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const cors = require('cors'); const logger = require('morgan'); const path = require('path'); const config = require('./config'); const so = require('./includes/storeObject'); const exec = require('child_process').exec; const fs = require('fs'); const app = express(); const api_route = require('./route/api'); // storeObject interval clear const clearStore = setInterval(() => { so.clear(); }, 30000) app.set('port', process.env.PORT || config.system.port); app.use(logger('short')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ resave: false, saveUninitialized: true, secret: '6520833345e05e0dcfce' })); app.use(cors()); app.use(express.static(path.resolve(__dirname, 'public'))); app.use('/semantic', express.static(path.resolve(__dirname, 'node_modules', 'semantic-ui-css'))); app.use('/react-datetime', express.static(path.resolve(__dirname, 'node_modules', 'react-datetime', 'css'))); app.use(/\/locales\/(\w+).json/, (req, res, n) => { res.sendFile(path.resolve(__dirname, 'public', 'locales', 'zh.json')); }) const server = app.listen(app.get('port'), () => { console.log(`Server start on port ${server.address().port}`); }); // use route app.use('/api', api_route); app.get('/', (req, res) => { res.sendFile(path.resolve(__dirname, 'views', 'index.html')); }); app.get(['/admin', '/admin/*'], (req, res) => { res.sendFile(path.resolve(__dirname, 'views', 'admin.html')); }); app.get('/camevent', (req, res) => { let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; ip = ip.split(':').pop(); let cmd = `camcam ${ip} ${Math.floor(Date.now() / 1000)}`; exec(cmd, (err, sout, serr) => { res.send({ ip }); }); }) app.get('/viewcamimg/:dir/:img', async(req, res) => { let dir = req.params.dir; let img = req.params.img; if (!dir || !img) return res.status(404).end(); try { let stat = await new Promise((resolve, reject) => { fs.stat(path.resolve(config.cmdpath.ipcamsave, dir, img), (err, stats) => { if (err) return reject(err); return resolve(stats); }) }) if (!stat.isFile()) return res.status(404).end(); } catch (e) { return res.status(404).end(); } res.sendfile(path.resolve(config.cmdpath.ipcamsave, dir, img)) }) app.get('/servcmd', (req, res) => { res.send({ status: `exit time ${(new Date()).toString()}` }); setTimeout(() => { process.exit(1) }, 2000); }); app.get('/fixmysql', (req, res) => { exec('systemctl stop mysqld', (err, sout, serr) => { let cmd = 'rm /home/www/mydb/aria*'; let json = { rm: '', restart: '' }; exec(cmd, (err, stdout, stderr) => { let cmd = 'systemctl start mysqld'; json.rm = stdout; exec(cmd, (err, sout, serr) => { json.restart = sout; res.send(json); }) }) }) });