代码拉取完成,页面将自动刷新
/**
* MixIO NodeJS Build V1.1
* 2022.01.29
* Author: 宋义深
*/
var fs = require('fs')
var configs = fs.readFileSync('config.json')
configs = JSON.parse(configs.toString())
var express = require('express');
var session = require('express-session');
const sqlite3 = require('sqlite3').verbose();
var md5 = require('js-md5');
var ejs = require('ejs');
var bodyParser = require("body-parser");
const { send } = require('express/lib/response');
const aedes = require('aedes')()
const http = require('http')
const httpServer = http.createServer()
var https = require('https');
var privateKey = fs.readFileSync(configs['HTTPS_PRIVATE_PEM'], 'utf8');
var certificate = fs.readFileSync(configs['HTTPS_CRT_FILE'], 'utf8');
var credentials = {key: privateKey, cert: certificate};
const ws = require('websocket-stream');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
ws.createServer({ server: httpServer }, aedes.handle)
const plainServer = require('net').createServer(aedes.handle)
const httpsServer = https.createServer(credentials)
ws.createServer({server:httpsServer},aedes.handle)
aedes.authenticate = function(client, username, password, callback) {
if(username=="MixIO_public"&&password=="MixIO_public")
{
client.user = "MixIO"
callback(null, true)
}
else
db.get("select password from user where username = ?",[username],function(err,row){
var auth = false
if(err)
console.log(err)
else if(row&&(row["password"]==password))
{
auth = true
client.user = username
}
callback(null, auth)
})
}
aedes.authorizePublish = function(client, packet, callback) {
if(client.user != packet.topic.split('/')[0])
return callback(new Error('wrong topic'))
else
callback(null)
}
aedes.authorizeSubscribe = function(client, subscription, callback) {
if (client.user != subscription.topic.split('/')[0])
return callback(new Error('wrong topic'))
else
callback(null,subscription);
}
aedes.on('publish', function(packet, client){
var topic = packet.topic.split('/')
var payload = String(packet.payload)
if(topic.length==3)
{
if(topic[2] == 'b640a0ce465fa2a4150c36b305c1c11b')
{
db.run("insert or ignore into devices (userName, clientid) values (?,?)",[topic[0],payload])
}
else if(topic[2] == '9d634e1a156dc0c1611eb4c3cff57276')
{
db.run("delete from devices where userName = ? and clientid = ?",[topic[0],payload])
}
else if(configs["MESSAGE_HOOK"])
{
var userName = topic[0]
if(userName!="$SYS")
db.get("select COUNT(*) from devices where userName = ? and (clientid like 'MixIO_%' or clientid like 'mixio_%')",[userName],function(err,row){
if(err)
console.log(err)
else
if(row["COUNT(*)"]==0){
db.get("select COUNT(*) from reserve where userName = ?",[userName],function(err,row){
if(err)
console.log(err)
else if(row['COUNT(*)']<configs['MAX_HOOKED_MESSAGE_NUM_PER_USER'])
db.run("insert into reserve (userName,projectName,topicName,msg) values(?,?,?,?)",[topic[0],topic[1],topic[2],payload])
})
}
})
}
}
})
var app = express();
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(session({
secret: 'mixio',
name: 'mixio',
resave: false,
rolling: true,
saveUninitialized: true,
cookie: {
path: '/',
httpOnly: true,
maxAge: 1800000
}
}));
app.set('trust proxy', 1)
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "ejs/index.html" );
})
app.get('/index', function (req, res) {
res.sendFile( __dirname + "/" + "ejs/index.html" );
})
app.get('/observe', function (req, res) {
ejs.renderFile('ejs/observe.ejs',{
'configs':configs
},function(err,data){
res.send(data)
})
})
app.get('/storage', function (req, res) {
if(req.session.userName)
{
db.all("select projectName, COUNT(*) as count from `reserve` where userName=? group by projectName",[req.session.userName],function(err,rows){
if(err)
console.log(err)
else
{
db.all("select projectName from `project` where userName=?",[req.session.userName],function(err,rows2){
if(err)
console.log(err)
else
{
var history = {}
var count = 0
var prjcount = 0
for (row2 in rows2)
{
prjcount = prjcount +1
history[rows2[row2]["projectName"]] = 0
}
for (row in rows)
{
count = count + parseInt(rows[row]["count"])
history[rows[row]["projectName"]] = parseInt(rows[row]["count"])
}
hisArray = []
for (his in history)
{
hisArray.push({
'key':his,
'value':history[his]
})
}
ejs.renderFile('ejs/storage.ejs',{
'histories':hisArray,
'prjcount':prjcount,
'count':count,
'configs':configs
},function(err,data){
res.send(data)
})
}
})
}
})
}
else
res.redirect('/')
})
app.get('/removeReserve',function(req,res){
if(req.session.userName&&req.query.projectName)
{
db.run("delete from `reserve` where userName=? and projectName=?",[req.session.userName,req.query.projectName])
res.send('1')
}
else
res.redirect('/')
})
app.get('/webapps', function (req, res) {
if(req.session.userName)
{
db.all("select * from `share` where userName=?",[req.session.userName],function(err,rows){
if(err)
console.log(err)
else
ejs.renderFile('ejs/apps.ejs',{
'rows':rows
},function(err,data){
res.send(data)
})
})
}
else
res.redirect('/')
})
app.get('/register', function (req, res) {
res.sendFile( __dirname + "/" + "ejs/register.html" );
})
app.get('/forgot',function(req,res){
res.sendFile( __dirname + "/" + "ejs/forgot-password.html" );
})
app.get('/verify',function(req,res){
if(req.session.userName&&req.session.salt)
{
ejs.renderFile('ejs/verify.ejs',{
userName:req.session.userName
},function(err,data){
res.send(data)
})
}
else
res.redirect('/')
})
app.get('/android',function(req,res){
res.download( __dirname + "/" + "ejs/MixIO.apk" )
})
app.get('/fetchObserve',function(req,res){
if(req.query.sid)
{
var sid = req.query.sid
db.get("select * from `share` where shareid=?",[sid],function(err,row)
{
if(err)
{
console.log(err)
res.send('-1')
}
else
{
if(row&&row["status"]==1)
{
var userName = row["userName"]
db.get("select * from `user` where username =?",[userName],function(err,row2){
if(err)
{
console.log(err)
res.send('-1')
}
else if(row2)
{
row["projectPass"] = row2["password"]
res.send(JSON.stringify(row))
}
else
res.send('-1')
})
}
else
res.send('-1')
}
})
}
else
res.send('-1')
})
app.get('/reset',function(req,res){
if(req.query.target&&req.query.vfcode&&req.query.pass)
{
db.get("select * from `user` where username=?",[req.query.target],function(err,row){
if(err)
console.log(err)
else
if(row)
{
if(row["answer"]==req.query.vfcode)
{
var salt = randomString(16,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var password = md5(req.query.pass+salt)
db.run("update `user` set password = ?,salt = ? where username=?",[password,salt,req.query.target],function(err){
if(err)
console.log(err)
else
res.send('1')
})
}
else
res.send('2')
}
else
res.send('2')
})
}
else
res.send('2')
})
app.get('/setProtect',function(req,res){
if(req.session.userName&&req.query.question&&req.query.answer)
{
db.run("update `user` set question=? , answer=? , verified=1 where username=?",[req.query.question,req.query.answer,req.session.userName],function(err){
if(err)
console.log(err)
else
res.send('1')
})
}
else
res.redirect('/')
})
app.get('/registerAccount',function(req,res){
if(req.query.userName&&req.query.password)
{
db.get("select * from `user` where username=?",[req.query.userName],function(err,row){
if(err)
console.log(err)
else
{
if(row)
{
if(req.session.salt)
req.session.salt = undefined
res.send('2')
}
else
{
var salt = randomString(16,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
req.session.userName = req.query.userName
req.session.salt = salt
var password = md5(req.query.password+salt)
db.run("insert into `user` (username, password, salt, verified, question, answer) values(?,?,?,0, '', '')",[req.query.userName,password,salt],function(err){
if(err)
console.log(err)
else
res.send('1')
})
}
}
})
}
})
app.get('/getDevices',function(req,res){
if(req.session.userName&&req.query.userName)
{
var userName = req.query.userName
db.all("select clientid from devices where userName = ?",[userName],function(err,rows){
res.send(JSON.stringify(rows))
})
}
else
res.redirect('/')
})
app.get('/projects',function(req,res){
if(req.session.userName)
{
db.get("select COUNT(*) from `reserve` where userName=?",[req.session.userName],function(err,row){
var count = 0
if(row)
{
count = row['COUNT(*)']
}
ejs.renderFile('ejs/projects.ejs',{
isMixly:0,
userName:req.session.userName,
projectPass:req.session.projectPass,
count:count,
prjid:req.query.prjid?req.query.prjid:'no',
'configs':configs
},function(err,data){
res.send(data)
})
})
}
else
res.redirect('/')
})
app.get('/projects-mixly',function(req,res){
ejs.renderFile('ejs/projects.ejs',{
isMixly:1,
userName:req.session.userName,
projectPass:req.session.projectPass,
count:0,
prjid:req.query.prjid?req.query.prjid:'no',
'configs':configs
},function(err,data){
res.send(data)
})
})
app.get('/getProjects',function(req,res){
if(req.session.userName&&req.query.page)
{
var pageStart = parseInt(req.query.page)*8
db.get("select COUNT(*) from `project` where userName=?",[req.session.userName],function(err,row){
var count = row['COUNT(*)']
db.all("select projectName,projectLayout,timestamp,projectType,userName from `project` where userName=? order by timestamp desc limit ?,8",[req.session.userName,pageStart],function(err,rows){
res.send(JSON.stringify({
rows:rows,
count:count
}))
})
})
}
else
res.send('-1')
})
app.get('/modifyShare',function(req,res){
if(req.session.userName&&req.query.shareid&&req.query.method)
{
if(req.query.method==2)
{
db.run("delete from `share` where shareid=?",[req.query.shareid],function(err){
if(err)
{
console.log(err)
res.send('2')
}
else
res.send('1')
})
}
else if(req.query.method==1||req.query.method==0)
{
db.run("update `share` set status = ? where shareid=?",[req.query.method,req.query.shareid],function(err){
if(err)
{
console.log(err)
res.send('2')
}
else
res.send('1')
})
}
else
res.send('2')
}
else
res.redirect('/')
})
app.get('/share',function(req,res){
if(req.session.userName&&req.query.projectName)
{
var userName = req.session.userName
var projectName = req.query.projectName
var shareid = randomString(6,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
db.run("insert into `share` (shareid, userName, projectName, projectLayout, dataStorage, logicStorage) values(?,?,?,(select projectLayout from `project` where userName = ? and projectName = ?),(select dataStorage from `project` where userName = ? and projectName = ?),(select logicStorage from `project` where userName = ? and projectName = ?))",[shareid,userName,projectName,userName,projectName,userName,projectName],function(err){
if(err)
console.log(err)
else
res.send(shareid)
})
}
else
res.redirect('/')
})
app.get('/getShare',function(req,res){
if(req.session.userName&&req.query.shareid)
{
db.get("select * from `share` where shareid=?",[req.query.shareid],function(err,row){
if(err)
console.log(err)
else
{
if(row&&row["status"]==1)
{
var userName = req.session.userName
var projectName = row['shareid'];
var projectCount = parseInt(row['shareCount'])+1;
projectName = projectName + projectCount
db.run("update `share` set shareCount = ? where shareid=?",[projectCount,req.query.shareid],function(err){
if(err)
{
console.log(err)
res.send(err)
}
else
{
db.run("insert into `project`(projectName, userName, projectLayout, dataStorage, logicStorage) values(?,?,(select projectLayout from `share` where shareid = ?),(select dataStorage from `share` where shareid = ?),(select logicStorage from `share` where shareid = ?))",[projectName,userName,req.query.shareid,req.query.shareid,req.query.shareid],function(err){
if(err)
{
console.log(err)
res.send(err)
}
else
res.send('1')
})
}
})
}
else
res.send('2')
}
})
}
else
res.redirect('/')
})
app.post('/getProject',function(req,res){
var projectName = req.body.projectName
if(req.session.userName&&projectName){
db.get("select * from `project` where userName=? and projectName=?",[req.session.userName, projectName],function(err,row){
if(row)
{
var result = {}
result['userName'] = req.session.userName
result['projectPass'] = req.session.projectPass
result['projectLayout'] = row['projectLayout']
result['dataStorage'] = row['dataStorage']
result['logicStorage'] = row['logicStorage']
db.all("select * from `reserve` where userName=? and projectName=?",[req.session.userName, projectName],function(err,rows){
if(rows)
result['history'] = rows
else
result['history'] = []
res.send(JSON.stringify(result))
})
}
else
res.send('0')
})
}
else
res.redirect('/')
})
app.post('/saveProject',function(req,res){
var projectLayout = req.body.layout
var projectName = req.body.projectName
var projectType = req.body.projectType
var dataStorage = req.body.dataStorage
var logicStorage = req.body.logicStorage
if(req.session.userName&&projectName&&projectType&&dataStorage&&logicStorage&&projectLayout)
{
db.run("update `project` set projectLayout=?, dataStorage=?, logicStorage=?, projectType=? where userName=? and projectName=?",[projectLayout,dataStorage,logicStorage,projectType,req.session.userName,projectName],function(err){
if(err)
{
res.send(err)
}
else
{
db.run("delete from `reserve` where userName=? and projectName=?",[req.session.userName,projectName],function(err){
res.send('1')
})
}
})
}
else
res.send('会话已过期')
})
app.get('/getSession',function(req, res){
result = {}
if(req.session.userName)
{
result['userName'] = req.session.userName
result['flag'] = true
}
else
result['flag'] = false
res.send(JSON.stringify(result))
})
app.get('/queryShareKey',function(req,res){
if(req.session.userName&&req.query.projectName&&req.query.projectPass){
var userName = req.session.userName
var projectName = req.query.projectName
var projectPass = req.query.projectPass
db.get("select share_key from `share_key` where userName=? and projectPass=? and projectName=?",[userName,projectPass,projectName],function(err,row){
if(row)
{
res.send(JSON.stringify(row))
}
else
{
res.send('-1')
}
})
}
else
res.redirect('/')
})
app.get('/login',function(req, res){
var userName = req.query.userName
var password = req.query.password
if(userName&&password)
db.get("select * from `user` where username=?",[userName],function(err,row){
if(row)
{
if(row['password'] == md5(password+row['salt']))
{
if(row['verified'] == 1)
{
req.session.userName = row['username']
req.session.projectPass = row['password']
if(req.session.salt)
req.session.salt = undefined
res.send('1')
}
else if(row['verified'] == 0)
{
req.session.userName = row['username']
req.session.salt = row['salt']
res.send('3')
}
}
else
res.send('2')
}
else
res.send('2')
})
else
res.send('2')
})
app.get('/createProject',function(req,res){
if(req.session.userName&&req.query.projectName&&req.query.projectType){
var userName = req.session.userName
var projectName = req.query.projectName
var projectType = req.query.projectType
var projectInfo = '{"layout_info":[]}';
db.get("select COUNT(*) from `project` where userName=? and projectName=?",[userName,projectName],function(err,row){
if(err)
console.log(err)
else
if(row["COUNT(*)"]>0)
res.send('2')
else
{
db.get("select COUNT(*) from `project` where userName=?",[userName],function(err,row){
if(err)
console.log(err)
else
if(row["COUNT(*)"]>=configs['MAX_PROJECT_NUM_PER_USER'])
res.send(3)
else
db.run("insert into `project` (projectName,userName,projectLayout,projectType) values(?,?,?,?)",[projectName,userName,projectInfo,projectType],function(err){
if(err)
console.log(err)
else
res.send('1')
})
})
}
})
}
else
res.redirect('/')
})
app.get('/renameProject',function(req,res){
if(req.session.userName&&req.query.oldProjectName&&req.query.newProjectName){
var userName = req.session.userName
var oldProjectName = req.query.oldProjectName
var newProjectName = req.query.newProjectName
db.get("select * from `project` where userName=? and projectName=?",[userName,newProjectName],function(err,row){
if(err)
console.log(err)
else
if(row)
res.send('2')
else
{
db.run("update `project` set projectName=? where userName=? and projectName=?",[newProjectName,userName,oldProjectName],function(err){
if(err)
console.log(err)
else
{
db.run("update `reserve` set projectName=? where userName=? and projectName=?",[newProjectName,userName,oldProjectName],function(err){
if(err)
console.log(err)
else
res.send('1')
})
}
})
}
})
}
else
res.redirect('/')
})
app.get('/copyProject',function(req,res){
if(req.session.userName&&req.query.oldProjectName&&req.query.newProjectName){
var userName = req.session.userName
var oldProjectName = req.query.oldProjectName
var newProjectName = req.query.newProjectName
db.get("select * from `project` where userName=? and projectName=?",[userName,newProjectName],function(err,row){
if(err)
console.log(err)
else
if(row)
res.send('2')
else
{
db.get("select COUNT(*) from `project` where userName=?",[userName],function(err,row){
if(err)
console.log(err)
else
if(row["COUNT(*)"]>=configs['MAX_PROJECT_NUM_PER_USER'])
res.send('3')
else
db.run("insert into `project` (userName, projectLayout, projectName) VALUES (?,(select a.projectLayout from (select projectLayout from `project` where userName=? and projectName=?)a),?)",[userName,userName,oldProjectName,newProjectName],function(err){
if(err)
console.log(err)
else
res.send('1')
})
})
}
})
}
else
res.redirect('/')
})
app.get('/addShareKey',function(req,res){
var rString = randomString(6, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
if(req.session.userName&&req.query.projectName&&req.query.projectPass)
{
db.run("insert into `share_key` (userName,projectPass,projectName,share_key) values (?,?,?,?)",[req.session.userName,req.query.projectPass,req.query.projectName,rString],function(err){
if(err)
{
console.log(err)
res.send(err)
}
else
{
res.send(rString)
}
})
}
else
res.redirect('/')
})
app.get('/removeShareKey',function(req,res){
if(req.session.userName&&req.query.projectName&&req.query.projectPass)
{
db.run("delete from `share_key` where userName=? and projectPass=? and projectName=?",[req.session.userName,req.query.projectPass,req.query.projectName],function(err){
if(err)
{
console.log(err)
res.send(err)
}
else
{
res.send('1')
}
})
}
else
res.redirect('/')
})
app.get('/getWeather',function(req,res){
if(req.query.dsc_code&&!configs["OFFLINE_MODE"]){
http.get('http://api.map.baidu.com/weather/v1/?district_id='+req.query.dsc_code+'&data_type=now&ak='+configs["BAIDU_MAP_SERVER_AK"],function(req,res2){
var html = ''
req.on('data',function(data){
html+=data;
});
req.on('end',function(){
res.send(html)
});
})
}
else
res.send('-1')
})
app.post('/deleteProject',function(req,res){
if(req.session.userName&&req.body.projectName)
{
db.run("delete from `project` where userName=? and projectName=?",[req.session.userName,req.body.projectName],function(err){
if(err)
res.send('2')
else
db.run("delete from `reserve` where userName=? and projectName=?",[req.session.userName,req.body.projectName],function(err){
if(err)
res.send('2')
else
res.send('1')
})
})
}
else
res.redirect('/')
})
app.get('/resetQuestion',function(req,res){
if(req.query.target)
{
db.get("select * from `user` where username=?",[req.query.target],function(err,row){
if(err||!row)
res.send({
'code':999,
'question':''
})
else
res.send({
'code':1,
'question':row['question']
})
})
}
})
app.get('/logout', function(req, res) {
req.session.destroy(function(err) {
res.redirect('/');
})
})
app.get('/keyLogin', function(req,res){
if(req.query.userName)
{
req.session.userName = '@'+req.query.userName
req.session.projectPass = 'MixIO_public'
db.get("select COUNT(*) from `project` where username=?",[req.session.userName],function(err,row){
if(err)
{
console.log(err)
res.send('-1')
}
else
{
if(row["COUNT(*)"]>0)
{
res.send('1')
}
else
{
var layout = '{"layout_info":[]}';
db.run("insert into `project` (projectName,userName,projectLayout,projectType) values('default',?,?,'1')",[req.session.userName,layout],function(err){
if(err)
{
console.log(err)
res.send('-1')
}
else
res.send('1')
})
}
}
})
}
else
res.send('-1')
})
app.get('/time.php',function(req, res){
var date = new Date()
res.send([date.getFullYear(),date.getMonth()+1,date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),date.getDay()].join(','))
})
app.get('/mixio-php/sharekey.php',function(req, res){
if(req.query.sk)
{
db.get("select userName,projectName,projectPass from `share_key` where share_key = ?",[req.query.sk],function(err,row){
if(err)
console.log(err)
else
{
if(row)
res.send(row)
else
res.send('-1')
}
})
}
else
res.send('-1')
})
app.get('/devAPI',function(req, res){
res.sendFile( __dirname + "/ejs/" + "dev.html" );
})
app.use('/js', express.static('js'));
app.use('/css', express.static('css'));
app.use('/img', express.static('img'));
app.use('/fonts', express.static('fonts'));
app.use('/blockly', express.static('blockly'));
app.use('/icons', express.static('icons'));
app.use('/documentation', express.static('documentation'));
var db = new sqlite3.Database(
'./mixio.db',
sqlite3.OPEN_READWRITE,
function (err) {
if (err) {
return console.log(err.message)
}
db.run('delete from devices')
console.log('[INFO] Database Connected!')
}
)
plainServer.listen(1883, function () {
console.log('[INFO] Plain MQTT server listening on port', 1883)
})
httpServer.listen(8083, function () {
console.log('[INFO] WebSocket MQTT server listening on port', 8083)
})
httpsServer.listen(8084,function(){
console.log('[INFO] WebSocketS MQTT server listening on port', 8084)
})
var server = app.listen(configs['MIXIO_HTTP_PORT'], function () {
console.log("[INFO] MixIO server listening on port", configs['MIXIO_HTTP_PORT'])
})
https.createServer(credentials, app).listen(configs['MIXIO_HTTPS_PORT'], function() {
console.log("[INFO] MixIO server (HTTPS) listening on port", configs['MIXIO_HTTPS_PORT'])
});
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。