mirror of
https://gitlab.com/MrFry/mrfrys-node-server
synced 2025-04-01 20:24:18 +02:00
1272 lines
32 KiB
TypeScript
1272 lines
32 KiB
TypeScript
/* ----------------------------------------------------------------------------
|
|
|
|
Question Server
|
|
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
|
|
|
|
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 <https://www.gnu.org/licenses/>.
|
|
|
|
------------------------------------------------------------------------- */
|
|
|
|
// package requires
|
|
import express from 'express'
|
|
import bodyParser from 'body-parser'
|
|
import busboy from 'connect-busboy'
|
|
import { v4 as uuidv4 } from 'uuid'
|
|
import fs from 'fs'
|
|
|
|
// other requires
|
|
|
|
import logger from '../../utils/logger'
|
|
import utils from '../../utils/utils'
|
|
import {
|
|
processIncomingRequest,
|
|
logResult,
|
|
backupData,
|
|
loadJSON,
|
|
RecievedData,
|
|
} from '../../utils/actions'
|
|
import dbtools from '../../utils/dbtools'
|
|
import auth from '../../middlewares/auth.middleware'
|
|
import { dataToString, searchDatas } from '../../utils/classes'
|
|
|
|
import { SetupData } from '../../server'
|
|
import { ModuleType, User, DataFile, Request } from '../../types/basicTypes'
|
|
|
|
// files
|
|
const msgFile = 'stats/msgs'
|
|
const passwordFile = 'data/dataEditorPasswords.json'
|
|
const dataEditsLog = 'stats/dataEdits'
|
|
const dailyDataCountFile = 'stats/dailyDataCount'
|
|
const usersDbBackupPath = 'data/dbs/backup'
|
|
const quickVoteResultsDir = 'stats/qvote'
|
|
const quickVotes = 'stats/qvote/votes.json'
|
|
const testUsersFile = 'data/testUsers.json'
|
|
const idStatFile = 'stats/idstats'
|
|
const idvStatFile = 'stats/idvstats'
|
|
const todosFile = 'data/todos.json'
|
|
|
|
// other constants
|
|
const line = '====================================================' // lol
|
|
const maxVeteranPwGetCount = 10
|
|
const addPWPerDay = 3 // every x day a user can give a pw
|
|
const maxPWCount = 6 // maximum pw give opportunities a user can have at once
|
|
const addPWCount = 1 // how many pw gen opportunities to add each time
|
|
const daysAfterUserGetsPWs = 5 // days after user gets pw-s
|
|
const minimumAlowwedSessions = 2 // how many sessions are allowed for a user
|
|
|
|
// stuff gotten from server.js
|
|
let userDB
|
|
let url // eslint-disable-line
|
|
let publicdirs = []
|
|
|
|
function GetApp(): ModuleType {
|
|
const app = express()
|
|
|
|
const publicDir = publicdirs[0]
|
|
if (!publicDir) {
|
|
throw new Error(`No public dir! ( API )`)
|
|
}
|
|
|
|
// files in public dirs
|
|
const recivedFiles = publicDir + 'recivedfiles'
|
|
const uloadFiles = publicDir + 'f'
|
|
// FIXME: this to seperate file?
|
|
const dataFiles: Array<DataFile> = [
|
|
{
|
|
path: `${publicDir}oldData.json`,
|
|
name: 'oldData',
|
|
shouldSave: (recData: RecievedData): boolean => {
|
|
return recData.version.startsWith('2.0.')
|
|
},
|
|
},
|
|
{
|
|
path: `${publicDir}data.json`,
|
|
name: 'newData',
|
|
shouldSave: (recData: RecievedData): boolean => {
|
|
return recData.version.startsWith('2.1.')
|
|
},
|
|
},
|
|
{
|
|
path: `${publicDir}fromwebsiteData.json`,
|
|
name: 'fromwebsiteData',
|
|
shouldSave: (recData: RecievedData): boolean => {
|
|
return recData.version === 'WEBSITE'
|
|
},
|
|
},
|
|
]
|
|
const motdFile = publicDir + 'motd'
|
|
const userSpecificMotdFile = publicDir + 'userSpecificMotd.json'
|
|
const versionFile = publicDir + 'version'
|
|
|
|
let domain = url.split('.') // [ "https://api", "frylabs", "net" ]
|
|
domain.shift() // [ "frylabs", "net" ]
|
|
domain = domain.join('.') // "frylabs.net"
|
|
logger.DebugLog(`Cookie domain: ${domain}`, 'cookie', 1)
|
|
|
|
app.use(
|
|
bodyParser.urlencoded({
|
|
limit: '10mb',
|
|
extended: true,
|
|
})
|
|
)
|
|
app.use(
|
|
bodyParser.json({
|
|
limit: '10mb',
|
|
})
|
|
)
|
|
app.set('view engine', 'ejs')
|
|
app.set('views', ['./src/modules/api/views', './src/sharedViews'])
|
|
app.use(
|
|
auth({
|
|
userDB: userDB,
|
|
jsonResponse: true,
|
|
exceptions: [
|
|
'/favicon.ico',
|
|
'/login',
|
|
'/getveteranpw',
|
|
'/postfeedbackfile',
|
|
'/postfeedback',
|
|
'/fosuploader',
|
|
'/badtestsender',
|
|
],
|
|
})
|
|
)
|
|
publicdirs.forEach((pdir) => {
|
|
logger.Log(`Using public dir: ${pdir}`)
|
|
app.use(express.static(pdir))
|
|
})
|
|
app.use(
|
|
busboy({
|
|
limits: {
|
|
fileSize: 50000 * 1024 * 1024,
|
|
},
|
|
})
|
|
)
|
|
|
|
const questionDbs = loadJSON(dataFiles)
|
|
let version = ''
|
|
let motd = ''
|
|
let userSpecificMotd = {}
|
|
// FIXME: check type from file
|
|
let testUsers: any = []
|
|
|
|
function mergeObjSum(a, b) {
|
|
const res = { ...b }
|
|
Object.keys(a).forEach((key) => {
|
|
if (res[key]) {
|
|
res[key] += a[key]
|
|
} else {
|
|
res[key] = a[key]
|
|
}
|
|
})
|
|
|
|
return res
|
|
}
|
|
|
|
function LoadVersion() {
|
|
version = utils.ReadFile(versionFile)
|
|
}
|
|
|
|
function LoadMOTD() {
|
|
motd = utils.ReadFile(motdFile)
|
|
}
|
|
|
|
function LoadUserSpecificMOTD() {
|
|
try {
|
|
userSpecificMotd = utils.ReadJSON(userSpecificMotdFile)
|
|
} catch (err) {
|
|
logger.Log('Couldnt parse user specific motd!', logger.GetColor('redbg'))
|
|
console.error(err)
|
|
}
|
|
}
|
|
|
|
function LoadTestUsers() {
|
|
testUsers = utils.ReadJSON(testUsersFile)
|
|
if (testUsers) {
|
|
testUsers = testUsers.userIds
|
|
}
|
|
}
|
|
|
|
function userShouldGetUserSpecificMOTD(id) {
|
|
let shouldSee = true
|
|
let write = false
|
|
|
|
if (!userSpecificMotd[id].seen) {
|
|
logger.Log(
|
|
`User #${id}'s user specific motd is now seen.`,
|
|
logger.GetColor('bluebg')
|
|
)
|
|
logger.Log(userSpecificMotd[id].msg)
|
|
|
|
userSpecificMotd[id].seen = true
|
|
write = true
|
|
}
|
|
|
|
if (userSpecificMotd[id].seeCounter) {
|
|
if (userSpecificMotd[id].seeCounter <= 1) {
|
|
shouldSee = false
|
|
} else {
|
|
userSpecificMotd[id].seeCounter -= 1
|
|
write = true
|
|
}
|
|
}
|
|
|
|
if (write) {
|
|
utils.WriteFile(
|
|
JSON.stringify(userSpecificMotd, null, 2),
|
|
userSpecificMotdFile
|
|
)
|
|
}
|
|
return shouldSee
|
|
}
|
|
|
|
function Load() {
|
|
backupData(questionDbs)
|
|
|
|
utils.WatchFile(userSpecificMotdFile, () => {
|
|
logger.Log(`User Specific Motd updated`, logger.GetColor('green'))
|
|
LoadUserSpecificMOTD()
|
|
})
|
|
utils.WatchFile(motdFile, () => {
|
|
logger.Log(`Motd updated`, logger.GetColor('green'))
|
|
LoadMOTD()
|
|
})
|
|
utils.WatchFile(versionFile, (newData) => {
|
|
logger.Log(`Version changed: ${newData.replace(/\/n/g, '')}`)
|
|
LoadVersion()
|
|
})
|
|
utils.WatchFile(testUsersFile, () => {
|
|
logger.Log(`Test Users file changed`, logger.GetColor('green'))
|
|
LoadTestUsers()
|
|
})
|
|
|
|
LoadUserSpecificMOTD()
|
|
LoadTestUsers()
|
|
LoadVersion()
|
|
LoadMOTD()
|
|
}
|
|
|
|
Load()
|
|
|
|
// -------------------------------------------------------------
|
|
|
|
app.get('/getDbs', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
|
|
res.json(
|
|
dataFiles.map((df) => {
|
|
return {
|
|
path: df.path.split('/').pop(),
|
|
name: df.name,
|
|
}
|
|
})
|
|
)
|
|
})
|
|
|
|
app.get('/voteTodo', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
const userId = req.session.user.id
|
|
const id: any = req.query.id
|
|
const todos = utils.ReadJSON(todosFile)
|
|
|
|
if (!id) {
|
|
res.json({
|
|
msg: 'id query undefined',
|
|
result: 'not ok',
|
|
})
|
|
}
|
|
|
|
const cardIndex = todos.cards.findIndex((currcard) => {
|
|
return currcard.id === parseInt(id)
|
|
})
|
|
if (cardIndex === -1) {
|
|
res.json({
|
|
msg: 'card not found',
|
|
result: 'not ok',
|
|
})
|
|
return
|
|
}
|
|
|
|
const ind = todos.cards[cardIndex].votes.indexOf(userId)
|
|
if (ind === -1) {
|
|
todos.cards[cardIndex].votes.push(userId)
|
|
} else {
|
|
todos.cards[cardIndex].votes.splice(ind, 1)
|
|
}
|
|
|
|
utils.WriteFile(JSON.stringify(todos, null, 2), todosFile)
|
|
res.json({
|
|
todos: todos,
|
|
userId: userId,
|
|
msg: 'updated',
|
|
result: 'ok',
|
|
})
|
|
})
|
|
|
|
app.get('/todos', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
const userId = req.session.user.id
|
|
const todos = utils.ReadJSON(todosFile)
|
|
|
|
res.json({
|
|
todos: todos,
|
|
userId: userId,
|
|
result: 'ok',
|
|
})
|
|
})
|
|
|
|
app.get('/ranklist', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
let result
|
|
const querySince: any = req.query.since
|
|
const user: User = req.session.user
|
|
|
|
if (!querySince) {
|
|
result = utils.ReadJSON(idStatFile)
|
|
} else {
|
|
try {
|
|
const since = new Date(querySince)
|
|
if (!(since instanceof Date) || isNaN(since.getTime())) {
|
|
throw new Error('Not a date')
|
|
}
|
|
const data = utils.ReadJSON(idvStatFile)
|
|
result = {}
|
|
|
|
Object.keys(data).forEach((key) => {
|
|
const dailyStat = data[key]
|
|
|
|
if (new Date(key) > since) {
|
|
Object.keys(dailyStat).forEach((userId) => {
|
|
const userStat = dailyStat[userId]
|
|
const uidRes = result[userId]
|
|
|
|
if (!uidRes) {
|
|
result[userId] = userStat
|
|
} else {
|
|
result[userId] = {
|
|
count: uidRes.count + userStat.count,
|
|
newQuestions: uidRes.newQuestions + userStat.newQuestions,
|
|
allQuestions: uidRes.allQuestions + userStat.allQuestions,
|
|
subjs: mergeObjSum(uidRes.subjs, userStat.subjs),
|
|
}
|
|
}
|
|
})
|
|
}
|
|
})
|
|
} catch (err) {
|
|
res.json({
|
|
msg: 'invalid date format, or other error occured',
|
|
})
|
|
}
|
|
}
|
|
|
|
const list = []
|
|
const sum = {
|
|
count: 0,
|
|
newQuestions: 0,
|
|
allQuestions: 0,
|
|
}
|
|
Object.keys(result).forEach((key) => {
|
|
list.push({
|
|
userId: parseInt(key),
|
|
...result[key],
|
|
})
|
|
|
|
sum.count = sum.count + result[key].count
|
|
sum.newQuestions = sum.newQuestions + result[key].newQuestions
|
|
sum.allQuestions = sum.allQuestions + result[key].allQuestions
|
|
})
|
|
|
|
if (list.length === 0) {
|
|
res.json({
|
|
msg: 'There are no users in the stats db :c',
|
|
})
|
|
return
|
|
}
|
|
|
|
res.json({
|
|
since: querySince,
|
|
sum: sum,
|
|
list: list,
|
|
selfuserId: user.id,
|
|
})
|
|
})
|
|
|
|
app.get('/quickvote', (req: Request, res: any) => {
|
|
const key = req.query.key
|
|
const val: any = req.query.val
|
|
const user: User = req.session.user
|
|
|
|
if (!key || !val) {
|
|
res.render('votethank', {
|
|
results: 'error',
|
|
msg: 'no key or val query param!',
|
|
})
|
|
return
|
|
}
|
|
|
|
// FIXME: check vote type in file
|
|
let votes: any = {}
|
|
if (utils.FileExists(quickVotes)) {
|
|
votes = utils.ReadJSON(quickVotes)
|
|
} else {
|
|
logger.Log(
|
|
`No such vote "${key}", and quickVotes.json is missing ( #${user.id}: ${key}-${val} )`,
|
|
logger.GetColor('blue')
|
|
)
|
|
res.render('votethank', {
|
|
result: 'no such pool',
|
|
})
|
|
return
|
|
}
|
|
|
|
if (!votes.voteNames.includes(key)) {
|
|
logger.Log(
|
|
`No such vote "${key}" ( #${user.id}: ${key}-${val} )`,
|
|
logger.GetColor('blue')
|
|
)
|
|
res.render('votethank', {
|
|
result: 'no such pool',
|
|
})
|
|
return
|
|
}
|
|
|
|
const voteFile = quickVoteResultsDir + '/' + key + '.json'
|
|
|
|
let voteData = {
|
|
votes: {},
|
|
sum: {},
|
|
}
|
|
|
|
if (utils.FileExists(voteFile)) {
|
|
voteData = utils.ReadJSON(voteFile)
|
|
} else {
|
|
utils.CreatePath(quickVoteResultsDir)
|
|
}
|
|
|
|
const prevVote = voteData.votes[user.id]
|
|
|
|
voteData.votes[user.id] = val
|
|
if (voteData.sum[val]) {
|
|
voteData.sum[val]++
|
|
} else {
|
|
voteData.sum[val] = 1
|
|
}
|
|
if (prevVote) {
|
|
if (voteData.sum[prevVote]) {
|
|
voteData.sum[prevVote] -= 1
|
|
}
|
|
}
|
|
|
|
logger.Log(`Vote from #${user.id}: ${key}: ${val}`, logger.GetColor('blue'))
|
|
res.render('votethank', {
|
|
result: prevVote ? 'already voted' : 'success',
|
|
prevVote: prevVote,
|
|
msg: 'vote added',
|
|
})
|
|
|
|
utils.WriteFile(JSON.stringify(voteData), voteFile)
|
|
})
|
|
|
|
app.get('/avaiblePWS', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
|
|
const user: User = req.session.user
|
|
|
|
res.json({
|
|
result: 'success',
|
|
userCreated: user.created,
|
|
avaiblePWS: user.avaiblePWRequests,
|
|
requestedPWS: user.pwRequestCount,
|
|
maxPWCount: maxPWCount,
|
|
daysAfterUserGetsPWs: daysAfterUserGetsPWs,
|
|
addPWPerDay: addPWPerDay,
|
|
addPWCount: addPWCount,
|
|
dayDiff: getDayDiff(user.created),
|
|
})
|
|
})
|
|
|
|
app.post('/getpw', function(req: Request, res: any) {
|
|
logger.LogReq(req)
|
|
|
|
const requestingUser = req.session.user
|
|
|
|
if (requestingUser.avaiblePWRequests <= 0) {
|
|
res.json({
|
|
result: 'error',
|
|
msg:
|
|
'Too many passwords requested or cant request password yet, try later',
|
|
})
|
|
logger.Log(
|
|
`User #${requestingUser.id} requested too much passwords`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
return
|
|
}
|
|
|
|
dbtools.Update(
|
|
userDB,
|
|
'users',
|
|
{
|
|
avaiblePWRequests: requestingUser.avaiblePWRequests - 1,
|
|
pwRequestCount: requestingUser.pwRequestCount + 1,
|
|
},
|
|
{
|
|
id: requestingUser.id,
|
|
}
|
|
)
|
|
|
|
const pw = uuidv4()
|
|
const insertRes = dbtools.Insert(userDB, 'users', {
|
|
pw: pw,
|
|
avaiblePWRequests: 0,
|
|
created: utils.GetDateString(),
|
|
})
|
|
|
|
logger.Log(
|
|
`User #${requestingUser.id} created new user #${insertRes.lastInsertRowid}`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
|
|
res.json({
|
|
result: 'success',
|
|
pw: pw,
|
|
requestedPWS: requestingUser.pwRequestCount + 1,
|
|
remaining: requestingUser.avaiblePWRequests - 1,
|
|
})
|
|
})
|
|
|
|
app.post('/getveteranpw', function(req: Request, res: any) {
|
|
logger.LogReq(req)
|
|
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
|
|
const tries = dbtools.Select(userDB, 'veteranPWRequests', {
|
|
ip: ip,
|
|
})[0]
|
|
|
|
if (tries) {
|
|
if (tries.count > maxVeteranPwGetCount) {
|
|
res.json({
|
|
result: 'error',
|
|
msg: 'Too many tries from this IP',
|
|
})
|
|
logger.Log(
|
|
`Too many veteran PW requests from ${ip}!`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
return
|
|
} else {
|
|
dbtools.Update(
|
|
userDB,
|
|
'veteranPWRequests',
|
|
{
|
|
count: tries.count + 1,
|
|
lastDate: utils.GetDateString(),
|
|
},
|
|
{
|
|
id: tries.id,
|
|
}
|
|
)
|
|
}
|
|
} else {
|
|
dbtools.Insert(userDB, 'veteranPWRequests', {
|
|
ip: ip,
|
|
lastDate: utils.GetDateString(),
|
|
})
|
|
}
|
|
|
|
const oldUserID = req.body.cid
|
|
|
|
if (!oldUserID) {
|
|
res.json({
|
|
result: 'error',
|
|
msg: 'No Client ID recieved',
|
|
})
|
|
logger.Log(`No client ID recieved`, logger.GetColor('cyan'))
|
|
return
|
|
}
|
|
|
|
const user: User = dbtools.Select(userDB, 'users', {
|
|
oldCID: oldUserID,
|
|
})[0]
|
|
|
|
if (user) {
|
|
if (user.pwGotFromCID === 0) {
|
|
logger.Log(
|
|
`Sent password to veteran user #${user.id}`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
dbtools.Update(
|
|
userDB,
|
|
'users',
|
|
{
|
|
pwGotFromCID: 1,
|
|
},
|
|
{
|
|
id: user.id,
|
|
}
|
|
)
|
|
|
|
res.json({
|
|
result: 'success',
|
|
pw: user.pw,
|
|
})
|
|
} else {
|
|
logger.Log(
|
|
`Veteran user #${user.id} already requested password`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
res.json({
|
|
result: 'error',
|
|
msg: 'Password already requested',
|
|
})
|
|
}
|
|
} else {
|
|
logger.Log(
|
|
`Invalid password request with CID: ${oldUserID}`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
res.json({
|
|
result: 'error',
|
|
msg: 'No such Client ID',
|
|
})
|
|
}
|
|
})
|
|
|
|
app.post('/login', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
const pw = req.body.pw
|
|
? req.body.pw
|
|
.replace(/'/g, '')
|
|
.replace(/"/g, '')
|
|
.replace(/;/g, '')
|
|
: false
|
|
const cid = req.body.cid
|
|
const isScript = req.body.script
|
|
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
|
|
const user: User = dbtools.Select(userDB, 'users', {
|
|
pw: pw,
|
|
})[0]
|
|
|
|
if (user) {
|
|
const sessionID = uuidv4()
|
|
|
|
const existingSessions = dbtools.Select(userDB, 'sessions', {
|
|
userID: user.id,
|
|
isScript: isScript ? 1 : 0,
|
|
})
|
|
|
|
if (existingSessions.length >= minimumAlowwedSessions) {
|
|
logger.Log(
|
|
`Multiple ${isScript ? 'script' : 'website'} sessions ( ${
|
|
existingSessions.length
|
|
} ) for #${user.id}, deleting olds`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
existingSessions.forEach((sess) => {
|
|
dbtools.Delete(userDB, 'sessions', {
|
|
id: sess.id,
|
|
isScript: isScript ? 1 : 0,
|
|
})
|
|
})
|
|
}
|
|
|
|
dbtools.Update(
|
|
userDB,
|
|
'users',
|
|
{
|
|
loginCount: user.loginCount + 1,
|
|
lastIP: ip,
|
|
lastLogin: utils.GetDateString(),
|
|
},
|
|
{
|
|
id: user.id,
|
|
}
|
|
)
|
|
|
|
dbtools.Insert(userDB, 'sessions', {
|
|
id: sessionID,
|
|
ip: ip,
|
|
userID: user.id,
|
|
isScript: isScript ? 1 : 0,
|
|
createDate: utils.GetDateString(),
|
|
})
|
|
|
|
// https://www.npmjs.com/package/cookie
|
|
// FIXME: cookies are not configured coorectly
|
|
res.cookie('sessionID', sessionID, {
|
|
domain: domain,
|
|
expires: new Date(
|
|
new Date().getTime() + 10 * 365 * 24 * 60 * 60 * 1000
|
|
),
|
|
sameSite: 'none',
|
|
secure: true,
|
|
})
|
|
res.cookie('sessionID', sessionID, {
|
|
expires: new Date(
|
|
new Date().getTime() + 10 * 365 * 24 * 60 * 60 * 1000
|
|
),
|
|
sameSite: 'none',
|
|
secure: true,
|
|
})
|
|
|
|
res.json({
|
|
result: 'success',
|
|
msg: 'you are now logged in',
|
|
})
|
|
logger.Log(
|
|
`Successfull login to ${
|
|
isScript ? 'script' : 'website'
|
|
} with user ID: #${user.id}`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
} else {
|
|
logger.Log(
|
|
`Login attempt with invalid pw: ${pw} to ${
|
|
isScript ? 'script' : 'website'
|
|
}${cid ? ', CID:' + cid : ''}`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
res.json({
|
|
result: 'error',
|
|
msg: 'Invalid password',
|
|
})
|
|
}
|
|
})
|
|
|
|
app.post('/logout', (req: Request, res: any) => {
|
|
logger.LogReq(req)
|
|
const sessionID = req.cookies.sessionID
|
|
|
|
// removing session from db
|
|
dbtools.Delete(userDB, 'sessions', {
|
|
id: sessionID,
|
|
})
|
|
res.clearCookie('sessionID').json({
|
|
result: 'success',
|
|
})
|
|
})
|
|
|
|
// --------------------------------------------------------------
|
|
|
|
app.get('/', function(req: Request, res: any) {
|
|
logger.LogReq(req)
|
|
res.redirect('https://www.youtube.com/watch?v=qLrnkK2YEcE')
|
|
})
|
|
|
|
app.post('/postfeedbackfile', function(req: Request, res: any) {
|
|
UploadFile(req, res, uloadFiles, () => {
|
|
res.json({ success: true })
|
|
})
|
|
|
|
logger.LogReq(req)
|
|
logger.Log('New feedback file', logger.GetColor('bluebg'))
|
|
})
|
|
|
|
app.post('/postfeedback', function(req: Request, res: any) {
|
|
logger.LogReq(req)
|
|
if (req.body.fromLogin) {
|
|
logger.Log(
|
|
'New feedback message from Login page',
|
|
logger.GetColor('bluebg')
|
|
)
|
|
} else {
|
|
logger.Log(
|
|
'New feedback message from feedback page',
|
|
logger.GetColor('bluebg')
|
|
)
|
|
}
|
|
|
|
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
|
|
const user: User = req.session.user
|
|
|
|
utils.AppendToFile(
|
|
utils.GetDateString() +
|
|
':\n' +
|
|
JSON.stringify({
|
|
...req.body,
|
|
userID: user ? user.id : 'no user',
|
|
ip: ip,
|
|
}),
|
|
msgFile
|
|
)
|
|
res.json({ success: true })
|
|
})
|
|
|
|
function UploadFile(req: Request, res: any, path, next) {
|
|
try {
|
|
req.pipe(req.busboy)
|
|
req.busboy.on('file', function(fieldname, file, filename) {
|
|
logger.Log('Uploading: ' + filename, logger.GetColor('blue'))
|
|
|
|
utils.CreatePath(path, true)
|
|
const date = new Date()
|
|
const fn =
|
|
date.getHours() +
|
|
'' +
|
|
date.getMinutes() +
|
|
'' +
|
|
date.getSeconds() +
|
|
'_' +
|
|
filename
|
|
|
|
const fstream = fs.createWriteStream(path + '/' + fn)
|
|
file.pipe(fstream)
|
|
fstream.on('close', function() {
|
|
logger.Log(
|
|
'Upload Finished of ' + path + '/' + fn,
|
|
logger.GetColor('blue')
|
|
)
|
|
next(fn)
|
|
})
|
|
fstream.on('error', function(err) {
|
|
console.error(err)
|
|
res.end('something bad happened :s')
|
|
})
|
|
})
|
|
} catch (err) {
|
|
logger.Log(`Unable to upload file!`, logger.GetColor('redbg'))
|
|
console.error(err)
|
|
}
|
|
}
|
|
|
|
app.route('/fosuploader').post(function(req: Request, res: any) {
|
|
UploadFile(req, res, uloadFiles, (fn) => {
|
|
res.redirect('/f/' + fn)
|
|
})
|
|
})
|
|
|
|
app.route('/badtestsender').post(function(req: Request, res: any) {
|
|
UploadFile(req, res, recivedFiles, () => {
|
|
res.redirect('back')
|
|
})
|
|
logger.LogReq(req)
|
|
})
|
|
|
|
app.get('/allqr.txt', function(req: Request, res: any) {
|
|
// TODO: if dataId param exists download only that db
|
|
res.set('Content-Type', 'text/plain')
|
|
const stringifiedData = questionDbs.map((qdb) => {
|
|
let result = ''
|
|
result += '\n' + line
|
|
result += ` Questions in ${qdb.name}: `
|
|
result += line + '\n'
|
|
result += dataToString(qdb.data)
|
|
result += '\n' + line + line + '\n'
|
|
return result
|
|
})
|
|
res.send(stringifiedData.join('\n\n'))
|
|
res.end()
|
|
logger.LogReq(req)
|
|
})
|
|
|
|
// -------------------------------------------------------------------------------------------
|
|
// API
|
|
|
|
app.post('/uploaddata', (req: Request, res: any) => {
|
|
// body: JSON.stringify({
|
|
// newData: data,
|
|
// count: getCount(data),
|
|
// initialCount: initialCount,
|
|
// password: password,
|
|
// editedQuestions: editedQuestions
|
|
// })
|
|
|
|
const {
|
|
count,
|
|
initialCount,
|
|
editedQuestions,
|
|
password /*, newData*/,
|
|
} = req.body
|
|
const respStatuses = {
|
|
invalidPass: 'invalidPass',
|
|
ok: 'ok',
|
|
error: 'error',
|
|
}
|
|
|
|
logger.LogReq(req)
|
|
|
|
try {
|
|
// finding user
|
|
const pwds = JSON.parse(utils.ReadFile(passwordFile))
|
|
const userKey = Object.keys(pwds).find((key) => {
|
|
const userKey = pwds[key]
|
|
return userKey.password === password
|
|
})
|
|
// FIXME: check user type in dataeditorPW-s json
|
|
const user: any = pwds[userKey]
|
|
|
|
// logging and stuff
|
|
logger.Log(`Data upload`, logger.GetColor('bluebg'))
|
|
logger.Log(`PWD: ${password}`, logger.GetColor('bluebg'))
|
|
// returning if user password is not ok
|
|
if (!user) {
|
|
logger.Log(
|
|
`Data upload: invalid password ${password}`,
|
|
logger.GetColor('red')
|
|
)
|
|
utils.AppendToFile(
|
|
utils.GetDateString() +
|
|
'\n' +
|
|
password +
|
|
'(FAILED PASSWORD)\n' +
|
|
JSON.stringify(editedQuestions) +
|
|
'\n\n',
|
|
dataEditsLog
|
|
)
|
|
res.json({ status: respStatuses.invalidPass })
|
|
return
|
|
}
|
|
|
|
logger.Log(
|
|
`Password accepted for ${user.name}`,
|
|
logger.GetColor('bluebg')
|
|
)
|
|
logger.Log(
|
|
`Old Subjects/Questions: ${initialCount.subjectCount} / ${
|
|
initialCount.questionCount
|
|
} | New: ${count.subjectCount} / ${
|
|
count.questionCount
|
|
} | Edited question count: ${Object.keys(editedQuestions).length}`,
|
|
logger.GetColor('bluebg')
|
|
)
|
|
// saving detailed editedCount
|
|
utils.AppendToFile(
|
|
utils.GetDateString() +
|
|
'\n' +
|
|
JSON.stringify(user) +
|
|
'\n' +
|
|
JSON.stringify(editedQuestions) +
|
|
'\n\n',
|
|
dataEditsLog
|
|
)
|
|
|
|
// making backup
|
|
// TODO
|
|
// utils.CopyFile(
|
|
// './' + dataFile,
|
|
// `./publicDirs/qminingPublic/backs/data_before_${
|
|
// user.name
|
|
// }_${utils.GetDateString().replace(/ /g, '_')}`
|
|
// ) // TODO: rewrite to dinamyc public!!!
|
|
// logger.Log('Backup made')
|
|
// // writing data
|
|
// utils.WriteFile(JSON.stringify(newData), dataFile)
|
|
// logger.Log('New data file written')
|
|
// // reloading data file
|
|
// data = [...newData]
|
|
// data = newData
|
|
logger.Log('Data set to newData')
|
|
|
|
res.json({
|
|
status: respStatuses.ok,
|
|
user: user.name,
|
|
})
|
|
logger.Log('Data updating done!', logger.GetColor('bluebg'))
|
|
} catch (error) {
|
|
logger.Log(`Data upload error! `, logger.GetColor('redbg'))
|
|
console.error(error)
|
|
res.json({ status: respStatuses.error, msg: error.message })
|
|
}
|
|
})
|
|
|
|
app.post('/isAdding', function(req: Request, res: any) {
|
|
logger.LogReq(req)
|
|
const user: User = req.session.user
|
|
const dryRun = testUsers.includes(user.id)
|
|
|
|
try {
|
|
processIncomingRequest(req.body, questionDbs, dryRun, user)
|
|
.then((resultArray) => {
|
|
logResult(req.body, resultArray, user.id, dryRun)
|
|
res.json({
|
|
success: resultArray.length > 0,
|
|
newQuestions: resultArray,
|
|
})
|
|
})
|
|
.catch((err) => {
|
|
logger.Log(
|
|
'Error during processing incoming request',
|
|
logger.GetColor('redbg')
|
|
)
|
|
console.error(err)
|
|
res.json({
|
|
success: false,
|
|
})
|
|
})
|
|
} catch (err) {
|
|
logger.Log(
|
|
'Error during getting incoming request processor promises ',
|
|
logger.GetColor('redbg')
|
|
)
|
|
console.error(err)
|
|
res.json({
|
|
success: false,
|
|
})
|
|
}
|
|
})
|
|
|
|
app.get('/ask', function(req: Request, res) {
|
|
if (Object.keys(req.query).length === 0) {
|
|
logger.DebugLog(`No query params`, 'ask', 1)
|
|
res.json({
|
|
message: `ask something! ?q=[question]&subj=[subject]&data=[question data]. 'subj' is optimal for faster result`,
|
|
result: [],
|
|
recievedData: JSON.stringify(req.query),
|
|
success: false,
|
|
})
|
|
} else {
|
|
if (req.query.q && req.query.data) {
|
|
const subj: any = req.query.subj || ''
|
|
const question = req.query.q
|
|
const recData: any = req.query.data
|
|
|
|
searchDatas(questionDbs, question, subj, recData)
|
|
.then((result) => {
|
|
try {
|
|
const mergedResult = result.reduce((acc, dbRes) => {
|
|
return [...acc, ...dbRes.result]
|
|
}, [])
|
|
const sortedResult = mergedResult.sort((q1, q2) => {
|
|
if (q1.match < q2.match) {
|
|
return 1
|
|
} else if (q1.match > q2.match) {
|
|
return -1
|
|
} else {
|
|
return 0
|
|
}
|
|
})
|
|
|
|
res.json({
|
|
result: sortedResult,
|
|
success: true,
|
|
})
|
|
logger.DebugLog(
|
|
`Question result length: ${result.length}`,
|
|
'ask',
|
|
1
|
|
)
|
|
logger.DebugLog(result, 'ask', 2)
|
|
} catch (err) {
|
|
console.error(err)
|
|
logger.Log(
|
|
'Error while sending ask results',
|
|
logger.GetColor('redbg')
|
|
)
|
|
}
|
|
})
|
|
.catch((err) => {
|
|
logger.Log('Search Data error!', logger.GetColor('redbg'))
|
|
console.error(err)
|
|
res.json({
|
|
message: `There was an error processing the question: ${err.message}`,
|
|
result: [],
|
|
recievedData: JSON.stringify(req.query),
|
|
success: false,
|
|
})
|
|
})
|
|
} else {
|
|
logger.DebugLog(`Invalid question`, 'ask', 1)
|
|
res.json({
|
|
message: `Invalid question :(`,
|
|
result: [],
|
|
recievedData: JSON.stringify(req.query),
|
|
success: false,
|
|
})
|
|
}
|
|
}
|
|
})
|
|
|
|
function getSubjCount(qdbs) {
|
|
return qdbs.reduce((acc, qdb) => {
|
|
return acc + qdb.data.length
|
|
}, 0)
|
|
}
|
|
|
|
function getQuestionCount(qdbs) {
|
|
return qdbs.reduce((acc, qdb) => {
|
|
return (
|
|
acc +
|
|
qdb.data.reduce((qacc, subject) => {
|
|
return qacc + subject.Questions.length
|
|
}, 0)
|
|
)
|
|
}, 0)
|
|
}
|
|
|
|
function getSimplreRes() {
|
|
return {
|
|
subjects: getSubjCount(questionDbs),
|
|
questions: getQuestionCount(questionDbs),
|
|
}
|
|
}
|
|
|
|
function getDetailedRes() {
|
|
return questionDbs.map((qdb) => {
|
|
return {
|
|
dbName: qdb.name,
|
|
subjs: qdb.data.map((subj) => {
|
|
return {
|
|
name: subj.Name,
|
|
count: subj.Questions.length,
|
|
}
|
|
}),
|
|
}
|
|
})
|
|
}
|
|
|
|
app.get('/datacount', function(req: Request, res: any) {
|
|
logger.LogReq(req)
|
|
if (req.query.detailed === 'all') {
|
|
res.json({
|
|
detailed: getDetailedRes(),
|
|
simple: getSimplreRes(),
|
|
})
|
|
} else if (req.query.detailed) {
|
|
res.json(getDetailedRes())
|
|
} else {
|
|
res.json(getSimplreRes())
|
|
}
|
|
})
|
|
|
|
app.get('/infos', function(req: Request, res) {
|
|
const user: User = req.session.user
|
|
|
|
const result: any = {
|
|
result: 'success',
|
|
uid: user.id,
|
|
}
|
|
|
|
if (req.query.subjinfo) {
|
|
result.subjinfo = getSimplreRes()
|
|
}
|
|
if (req.query.version) {
|
|
result.version = version
|
|
}
|
|
if (req.query.motd) {
|
|
result.motd = motd
|
|
if (userSpecificMotd[user.id] && userShouldGetUserSpecificMOTD(user.id)) {
|
|
result.userSpecificMotd = userSpecificMotd[user.id].msg
|
|
}
|
|
}
|
|
res.json(result)
|
|
})
|
|
|
|
// -------------------------------------------------------------------------------------------
|
|
|
|
app.get('*', function(req: Request, res: any) {
|
|
res.status(404).render('404')
|
|
})
|
|
|
|
app.post('*', function(req: Request, res: any) {
|
|
res.status(404).render('404')
|
|
})
|
|
|
|
function ExportDailyDataCount() {
|
|
logger.Log('Saving daily data count ...')
|
|
utils.AppendToFile(
|
|
JSON.stringify({
|
|
date: utils.GetDateString(),
|
|
subjectCount: getSubjCount(questionDbs),
|
|
questionCount: getQuestionCount(questionDbs),
|
|
userCount: dbtools.TableInfo(userDB, 'users').dataCount,
|
|
}),
|
|
dailyDataCountFile
|
|
)
|
|
}
|
|
|
|
function BackupDB() {
|
|
logger.Log('Backing up auth DB ...')
|
|
utils.CreatePath(usersDbBackupPath, true)
|
|
userDB
|
|
.backup(
|
|
`${usersDbBackupPath}/users.${utils
|
|
.GetDateString()
|
|
.replace(/ /g, '_')}.db`
|
|
)
|
|
.then(() => {
|
|
logger.Log('Auth DB backup complete!')
|
|
})
|
|
.catch((err) => {
|
|
logger.Log('Auth DB backup failed!', logger.GetColor('redbg'))
|
|
console.error(err)
|
|
})
|
|
}
|
|
|
|
function getDayDiff(dateString) {
|
|
const msdiff = new Date().getTime() - new Date(dateString).getTime()
|
|
return Math.floor(msdiff / (1000 * 3600 * 24))
|
|
}
|
|
|
|
function IncrementAvaiblePWs() {
|
|
// FIXME: check this if this is legit and works
|
|
logger.Log('Incrementing avaible PW-s ...')
|
|
const users: Array<User> = dbtools.SelectAll(userDB, 'users')
|
|
|
|
users.forEach((user) => {
|
|
if (user.avaiblePWRequests >= maxPWCount) {
|
|
return
|
|
}
|
|
|
|
const dayDiff = getDayDiff(user.created)
|
|
if (dayDiff < daysAfterUserGetsPWs) {
|
|
logger.Log(
|
|
`User #${user.id} is not registered long enough to get password ( ${dayDiff} days, ${daysAfterUserGetsPWs} needed)`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
return
|
|
}
|
|
|
|
if (dayDiff % addPWPerDay === 0) {
|
|
logger.Log(
|
|
`Incrementing avaible PW-s for user #${user.id}: ${
|
|
user.avaiblePWRequests
|
|
} -> ${user.avaiblePWRequests + addPWCount}`,
|
|
logger.GetColor('cyan')
|
|
)
|
|
dbtools.Update(
|
|
userDB,
|
|
'users',
|
|
{
|
|
avaiblePWRequests: user.avaiblePWRequests + addPWCount,
|
|
},
|
|
{
|
|
id: user.id,
|
|
}
|
|
)
|
|
}
|
|
})
|
|
}
|
|
|
|
function DailyAction() {
|
|
backupData(questionDbs)
|
|
BackupDB()
|
|
ExportDailyDataCount()
|
|
IncrementAvaiblePWs()
|
|
}
|
|
|
|
return {
|
|
dailyAction: DailyAction,
|
|
app: app,
|
|
}
|
|
}
|
|
|
|
export default {
|
|
name: 'API',
|
|
getApp: GetApp,
|
|
setup: (data: SetupData): void => {
|
|
userDB = data.userDB
|
|
url = data.url // eslint-disable-line
|
|
publicdirs = data.publicdirs
|
|
},
|
|
}
|