-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcollectionServer.js
More file actions
226 lines (186 loc) · 6.28 KB
/
collectionServer.js
File metadata and controls
226 lines (186 loc) · 6.28 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
require('dotenv').config()
const axios = require('axios')
// For writing logs
const fs = require('fs')
const path = require('path')
const morgan = require('morgan')
const Writable = require('stream').Writable
//this will allow us to pull params from .env file
const express = require('express')
// HTTPS
const port = process.env.PORT
// Task Managers
const TaskManager = require('./TaskManager.js')
const DatabaseManager = require('./DatabaseManager.js')
const app = express()
app.use(express.json())
// Terminal QR Code
var qrcode = require('qrcode-terminal')
// ngrok
// Get constant url from paid ngrok
let url = undefined
let setup = async () => {
try {
url = await axios.get('http://localhost:4040/api/tunnels')
.then((res) => {
// console.log(res.data.tunnels[0])
return res.data.tunnels[0].public_url
})
console.log(url)
if (url.startsWith('https://')) {
const https = 'https://'
return url.slice(https.length)
}
if (url.startsWith('http://')) {
const http = 'http://'
return url.slice(http.length)
}
} catch (e) {
console.log('\nngrok link is not setup/running\n')
}
return url
}
// Logging stuff
var logStream = fs.createWriteStream(path.join(`${__dirname}/logs`, `Logs_${new Date()}.log`), { flags: 'a' })
// setup the logger
app.use(morgan('combined', {
stream: logStream
}))
class MyStream extends Writable {
write(line) {
// Write to console
console.log('Logger - ', line)
}
}
// Create a new named format
morgan.token('readable', ':status A new :method request from :remote-addr for :url was received. It took :total-time[2] milliseconds to be resolved')
let writer = new MyStream()
// Use the new format by name
app.use(morgan('readable', {
stream: writer
}))
// More middleware to allow Access-Control-Allow-Origin
// const cors = require('cors')
// app.use(cors({
// origin: true
// }))
// app.options('*', cors())
// app.options('/API/manager/:task', cors())
// Temporary if others want to use old endpoints for integration test day, will force changing endpoints later
const Manager = require('./manager/dbmanager.js')
// Tasks map
const uuidToTask = new Map()
const tasks = new Map()
app.listen(port, async () => {
console.log(`Collection Server running on ${port}...`)
// Scannable qr code with ngrok link
if (await setup()) {
qrcode.generate(url)
}
// Init server here, idk what it would init but possibly could run + cache analysis engine, all it does is turn foreign keys on
await new DatabaseManager().runTask('initServer', {})
.then((results) => {
if (results) {
console.log(results)
} else {
console.log('Initializing server')
}
})
})
app.get('/', async (req, res) => {
res.status(200).send('All good my dude')
})
// Manager
app.post('/API/manager/:task', async (req, res) => {
if (req.params.task) {
await new DatabaseManager().runTask(req.params.task, req.body)
.then((result) => {
res.status(200).send(result)
})
.catch((err) => {
console.log('Detected error')
if (err.customCode) {
res.status(err.customCode).send(err)
} else {
res.status(400).send(err)
}
})
} else {
res.status(404).send('Missing Task Name')
}
})
app.get('/API/manager/:task', async (req, res) => {
if (req.params.task) {
await new DatabaseManager().runTask(req.params.task, req.query)
.then((result) => {
res.status(200).send(result)
})
.catch((err) => {
console.log('Detected error')
console.log(err)
if (err.customCode) {
res.status(err.customCode).send(err)
} else {
res.status(400).send(err)
}
})
} else {
res.status(404).send('Missing Task Name')
}
})
app.get('/API/analysis/:task', async (req, res) => {
// Run analysis engine
if (req.query) {
let task = {
'name': req.params.task
}
Object.keys(req.query).forEach((key) => {
task[key] = req.query[key]
})
let results = await new TaskManager().runTasks(task)
// console.log(`Results: ${JSON.stringify(results)}`)
res.status(200).send(results)
} else {
res.status(404).send('Missing task')
}
})
// Reset DB (testing only)
app.post('/resetDB', async (req,res) => {
if (req.body.uuid) {
let taskNumber = uuidToTask.size
uuidToTask.set(req.body.uuid, taskNumber)
tasks.set(taskNumber, Manager.resetAndPopulateDB())
res.status(200).send(`${JSON.stringify({'taskNumber': taskNumber})}`)
} else {
res.status(400).send('Missing uuid')
}
})
// Old system
const promiseWithTimeout = ((promise) => {
// Times out after 1 ms, assumes promise is still pending (usually takes ~0ms)
var timeOutTime = 1
const timeoutPromise = new Promise(async (resolve) => {
setTimeout(resolve, timeOutTime, 'Requested task is unfinished, come back later')
})
return Promise.race([promise, timeoutPromise])
})
app.get('/getTaskData', async (req,res) => {
// Get cached/Rerun analysis engine and send it
if (req.body.taskNumber != undefined && req.body.taskNumber < tasks.size) {
console.log(`Task Number: ${req.body.taskNumber}`)
promiseWithTimeout(tasks.get(req.body.taskNumber))
.then((response) => {
// console.log(response)
res.status(200).send(`${JSON.stringify(response)}`)
})
} else if (req.body.uuid != undefined && Array.from(uuidToTask.values()).includes(req.body.uuid)) {
console.log(`UUID: ${req.body.uuid}`)
promiseWithTimeout(tasks.get(uuidToTask.get(req.body.uuid)))
.then((response) => {
res.status(200).send(`${JSON.stringify(response)}`)
})
} else {
res.status(400).send('Missing task number or uuid or task number/uuid doesn\'t have a task')
return
}
})