-
Notifications
You must be signed in to change notification settings - Fork 31
/
server.js
89 lines (82 loc) · 1.98 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
var http = require('http');
var natUpnp = require('nat-upnp');
var os = require('os');
var async = require('async');
var express = require('express');
var body_parser = require('body-parser');
function Server(domain, port) {
//self
var self = this;
//config
this.domain = domain;
this.port = port;
//prices
this.data = undefined
//upnp punch
if (this.domain==undefined) {
var client = natUpnp.createClient();
client.timeout = 1000000;
//get local ip
var ifaces = os.networkInterfaces();
var ips = [];
for (ifname in ifaces) {
for (i in ifaces[ifname]) {
var iface = ifaces[ifname][i];
if ('IPv4' === iface.family && iface.internal == false) {
ips.push(iface.address)
}
}
}
var ip = ips[0];
//upnp punch the port
client.portMapping(
{
public: { host: '', port: self.port },
private: { host: ip, port: self.port },
protocol: 'tcp',
ttl: 0,
description: 'Etheropt'
},
function(err) {
}
);
//get external ip
client.externalIp(function(err, ip) {
self.domain = ip;
self.url = 'http://'+self.domain+':'+self.port;
});
} else {
this.url = 'http://'+this.domain+':'+this.port;
}
this.app = express();
this.app.use(body_parser.json());
this.app.use(body_parser.urlencoded({ extended: true }));
this.server = http.Server(this.app);
this.server.timeout = 1000*10;
this.server.listen(this.port);
this.app.get('/', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.writeHead(200);
res.end(JSON.stringify(self.data));
});
//begin loop
this.loop();
}
Server.prototype.loop = function() {
var self = this;
async.until(
function() { return self.url!=undefined; },
function(callback) { setTimeout(function () { callback(null); }, 1000); },
function(err) {
async.forever(
function(next) {
setTimeout(function () { next(); }, 2000);
},
function(err) {
console.log(err);
}
);
}
);
}
module.exports = {Server: Server}