-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
182 lines (165 loc) · 6 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
* Author:
* Zhizhou Li <[email protected]>
*
Copyright 2016 Meteroi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// call the packages we need
var pjson = require('./package.json');
var config = require('./config.json');
var path = require('path');
var events = require('events');
var log4js = require('log4js');
var http = require('http');
var promise = require("bluebird");
var fs = promise.promisifyAll(require('fs'),{filter: function(name) {
return !(name === "read" || name === "write");
},});
fs.readAsync = promise.promisify(fs.read, {multiArgs:true});
fs.writeAsnyc = promise.promisify(fs.write, {multiArgs:true});
var express = require('express');
var helmet = require('helmet')
var session = require('express-session');
var proxy = require('express-http-proxy');
var bodyParser = require('body-parser');
var loadDir = require('./loaddir');
var module = loadDir(config.app_path);
var multer = require('multer');
var sockectio = require('socket.io');
//var PouchDB = require('pouchdb');
//var pouchdb = new PouchDB('dbname');
var tingodb = require('tingodb')();
//var Gun = require('gun');
var optimist = require('optimist');
var figlet = require('figlet');
var node_uuid = require('node-uuid');
var cron = require('cron').CronJob;
var List = require("collections/list");
var Set = require("collections/set");
var Map = require("collections/map");
var numeric = require('numeric');
var equal = require('deep-equal');
var KafkaRest = require('kafka-rest');
var kafka = new KafkaRest({ 'url': config.kafka });
var https = require('https');
var privateKey = fs.readFileSync('keys/server-key.pem', 'utf8');
var certificate = fs.readFileSync('keys/server-cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
require('tingyun');
log4js.configure({appenders:config.appenders,levels:config.levels});
var logger = log4js.getLogger('server'); // start logging
var app = express(); // start express
var router = express.Router(); // start routee for express
var db = new tingodb.Db(config.db_path, {}); // embeded json database
var argv = optimist.argv; // argument object
var event = new events.EventEmitter(); //event
var uuid = node_uuid.v4();
if (argv.debug) {
logger.info("Set Log to Debug")
logger.setLevel('DEBUG'); // Set the log level
}
figlet('Openfpgaduino', function(err, data) {
if (err) {
return;
}
logger.info("\n" + data);
});
logger.info(pjson.name + " Version:" + pjson.version);
logger.info(pjson.description);
logger.info("Runing at Node Version:" + process.version);
logger.info("Write by:" + pjson.author);
logger.info("UUID", uuid);
//app.use(helmet())
//app.disable('x-powered-by')
app.set("etag", false);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.raw());
// configure app to use /page to store static files
app.use(express.static(__dirname + '/page'));
// configure app to use /uploads to store upload files
app.use(multer({
dest: './uploads/'
}));
//app.use(Gun.serve).use(express.static(__dirname));
function parser_parameter(fun_str) {
return fun_str.toString()
.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg, '') // remove spaces and comments
.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] // get parameter
}
var httpsServer = https.createServer(credentials, app);
var port = argv.port || process.env.PORT || config.port; // set our port
var sshport = argv.sshport || process.env.SSHPORT || config.sshport; // set our port
var server = http.createServer(app);
var io = sockectio.listen(server);
var data = require('data.io')(io);
var messages = data.resource('messages');
var request = require('request').defaults({
baseUrl: "http://localhost:" + port + "/"
});
//Gun({file: 'gundata.json', web: server});
function loadmodule(module) {
for (m in module) { // load all modules in apps
var parameter = parser_parameter(module[m]);
logger.debug('parameter is ' + parameter);
eval('module[m]' + '(' + parameter + ')'); // dependency injection, inject the var the apps needs in it parameter
}
}
if (argv.sim) {
var mock = loadDir(config.mock_path);
loadmodule(mock);
var map = new Map(module).filter(function(value, index) {
for (v in mock) {
if (index == v) {
logger.info("Replace real module " + v + " with mockup");
return false;
}
}
return true;
});
module = map.toArray();
loadmodule(module);
} else {
loadmodule(module);
}
function dynamicloadmodule(filename) {
var name = path.basename(filename, '.js');
var apppath = __dirname + '/' + config.app_path + filename;
var script = "require(\'" + apppath + "\');"
logger.debug("Dynamic load module");
logger.debug(script);
var ret = eval(script);
var parameter = parser_parameter(ret)
logger.debug('parameter is ' + parameter);
script = "ret(" + parameter + ");";
eval(script);
}
event.addListener('load', dynamicloadmodule);
// pouchdb.put({
// _id: '[email protected]',
// name: 'David',
// age: 69
// });
// pouchdb.changes().on('change', function() {
// logger.info('Ch-Ch-Changes');
// });
// pouchdb.replicate.to('http://example.com/mydb');
// console.log(numeric.add([1,2],[3,4],[5,6],[7,8]))
server.listen(port);
httpsServer.listen(sshport);
logger.info("Restful API server run on port", port)
logger.info("Restful SSH API server run on port", sshport)