Prettied all js in src/

This commit is contained in:
mrfry 2020-10-01 14:44:24 +02:00
parent 3f081d8dff
commit ee0f0a9f3b
17 changed files with 1012 additions and 688 deletions

View file

@ -1,68 +1,42 @@
{
"dataEditor": {
"path": "./modules/dataEditor/dataEditor.js",
"publicdirs": [
"qminingPublic/"
],
"publicdirs": ["qminingPublic/"],
"nextdir": "modules/dataEditor/public/",
"name": "dataeditor",
"urls": [
"dataeditor.frylabs.net"
],
"urls": ["dataeditor.frylabs.net"],
"isNextJs": true
},
"qmining": {
"path": "./modules/qmining/qmining.js",
"publicdirs": [
"qminingPublic/"
],
"publicdirs": ["qminingPublic/"],
"nextdir": "modules/qmining/public/",
"name": "qmining",
"urls": [
"qmining.frylabs.net"
],
"urls": ["qmining.frylabs.net"],
"isNextJs": true
},
"api": {
"path": "./modules/api/api.js",
"publicdirs": [
"qminingPublic/"
],
"publicdirs": ["qminingPublic/"],
"name": "api",
"urls": [
"api.frylabs.net",
"localhost"
]
"urls": ["api.frylabs.net", "localhost"]
},
"main": {
"path": "./modules/main/main.js",
"publicdirs": [
"public/"
],
"publicdirs": ["public/"],
"name": "main",
"urls": [
"frylabs.net",
"www.frylabs.net"
]
"urls": ["frylabs.net", "www.frylabs.net"]
},
"sio": {
"path": "./modules/sio/sio.js",
"publicdirs": [
"sioPublic/"
],
"publicdirs": ["sioPublic/"],
"name": "sio",
"urls": [
"sio.frylabs.net"
]
"urls": ["sio.frylabs.net"]
},
"stuff": {
"path": "./modules/stuff/stuff.js",
"publicdirs": [
"stuffPublic/"
],
"publicdirs": ["stuffPublic/"],
"name": "stuff",
"urls": [
"stuff.frylabs.net"
]
"urls": ["stuff.frylabs.net"]
}
}

View file

@ -67,19 +67,21 @@ function GetApp () {
const motdFile = p + 'motd'
const versionFile = p + 'version'
app.use(bodyParser.urlencoded({
app.use(
bodyParser.urlencoded({
limit: '10mb',
extended: true
}))
app.use(bodyParser.json({
limit: '10mb'
}))
extended: true,
})
)
app.use(
bodyParser.json({
limit: '10mb',
})
)
app.set('view engine', 'ejs')
app.set('views', [
'./modules/api/views',
'./sharedViews'
])
app.use(auth({
app.set('views', ['./modules/api/views', './sharedViews'])
app.use(
auth({
userDB: userDB,
jsonResponse: true,
exceptions: [
@ -89,18 +91,21 @@ function GetApp () {
'/postfeedbackfile',
'/postfeedback',
'/fosuploader',
'/badtestsender'
]
}))
'/badtestsender',
],
})
)
publicdirs.forEach((pdir) => {
logger.Log(`Using public dir: ${pdir}`)
app.use(express.static(pdir))
})
app.use(busboy({
app.use(
busboy({
limits: {
fileSize: 50000 * 1024 * 1024
}
}))
fileSize: 50000 * 1024 * 1024,
},
})
)
var data = actions.LoadJSON(dataFile)
var version = ''
@ -153,7 +158,7 @@ function GetApp () {
if (!key || !val) {
res.render('votethank', {
results: 'error',
msg: 'no key or val query param!'
msg: 'no key or val query param!',
})
return
}
@ -162,17 +167,23 @@ function GetApp () {
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'))
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'
result: 'no such pool',
})
return
}
if (!votes.voteNames.includes(key)) {
logger.Log(`No such vote "${key}" ( #${user.id}: ${key}-${val} )`, logger.GetColor('blue'))
logger.Log(
`No such vote "${key}" ( #${user.id}: ${key}-${val} )`,
logger.GetColor('blue')
)
res.render('votethank', {
result: 'no such pool'
result: 'no such pool',
})
return
}
@ -181,7 +192,7 @@ function GetApp () {
let voteData = {
votes: {},
users: []
users: [],
}
if (utils.FileExists(voteFile)) {
@ -198,16 +209,22 @@ function GetApp () {
}
voteData.users.push(user.id)
logger.Log(`Vote from #${user.id}: ${key}: ${val}`, logger.GetColor('blue'))
logger.Log(
`Vote from #${user.id}: ${key}: ${val}`,
logger.GetColor('blue')
)
res.render('votethank', {
result: 'success',
msg: 'vote added'
msg: 'vote added',
})
} else {
logger.Log(`#${user.id} already voted for: ${key}: ${val}`, logger.GetColor('blue'))
logger.Log(
`#${user.id} already voted for: ${key}: ${val}`,
logger.GetColor('blue')
)
res.render('votethank', {
result: 'already voted',
msg: 'already voted'
msg: 'already voted',
})
}
@ -226,7 +243,7 @@ function GetApp () {
requestedPWS: user.pwRequestCount,
maxPWCount: maxPWCount,
// daysAfterUserGetsPWs: daysAfterUserGetsPWs,
addPWPerDay: addPWPerDay
addPWPerDay: addPWPerDay,
})
})
@ -238,33 +255,45 @@ function GetApp () {
if (requestingUser.avaiblePWRequests <= 0) {
res.json({
result: 'error',
msg: 'Too many passwords requested or cant request password yet, try later'
msg:
'Too many passwords requested or cant request password yet, try later',
})
logger.Log(`User #${requestingUser.id} requested too much passwords`, logger.GetColor('cyan'))
logger.Log(
`User #${requestingUser.id} requested too much passwords`,
logger.GetColor('cyan')
)
return
}
dbtools.Update(userDB, 'users', {
dbtools.Update(
userDB,
'users',
{
avaiblePWRequests: requestingUser.avaiblePWRequests - 1,
pwRequestCount: requestingUser.pwRequestCount + 1
}, {
id: requestingUser.id
})
pwRequestCount: requestingUser.pwRequestCount + 1,
},
{
id: requestingUser.id,
}
)
const pw = uuidv4()
const insertRes = dbtools.Insert(userDB, 'users', {
pw: pw,
avaiblePWRequests: 0,
created: utils.GetDateString()
created: utils.GetDateString(),
})
logger.Log(`User #${requestingUser.id} created new user #${insertRes.lastInsertRowid}`, logger.GetColor('cyan'))
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
remaining: requestingUser.avaiblePWRequests - 1,
})
})
@ -272,29 +301,37 @@ function GetApp () {
logger.LogReq(req)
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
const tries = dbtools.Select(userDB, 'veteranPWRequests', {
ip: ip
ip: ip,
})[0]
if (tries) {
if (tries.count > maxVeteranPwGetCount) {
res.json({
result: 'error',
msg: 'Too many tries from this IP'
msg: 'Too many tries from this IP',
})
logger.Log(`Too many veteran PW requests from ${ip}!`, logger.GetColor('cyan'))
logger.Log(
`Too many veteran PW requests from ${ip}!`,
logger.GetColor('cyan')
)
return
} else {
dbtools.Update(userDB, 'veteranPWRequests', {
dbtools.Update(
userDB,
'veteranPWRequests',
{
count: tries.count + 1,
lastDate: utils.GetDateString()
}, {
id: tries.id
})
lastDate: utils.GetDateString(),
},
{
id: tries.id,
}
)
}
} else {
dbtools.Insert(userDB, 'veteranPWRequests', {
ip: ip,
lastDate: utils.GetDateString()
lastDate: utils.GetDateString(),
})
}
@ -303,41 +340,55 @@ function GetApp () {
if (!oldUserID) {
res.json({
result: 'error',
msg: 'No Client ID recieved'
msg: 'No Client ID recieved',
})
logger.Log(`No client ID recieved`, logger.GetColor('cyan'))
return
}
const user = dbtools.Select(userDB, 'users', {
oldCID: oldUserID
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
})
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
pw: user.pw,
})
} else {
logger.Log(`Veteran user #${user.id} already requested password`, logger.GetColor('cyan'))
logger.Log(
`Veteran user #${user.id} already requested password`,
logger.GetColor('cyan')
)
res.json({
result: 'error',
msg: 'Password already requested'
msg: 'Password already requested',
})
}
} else {
logger.Log(`Invalid password request with CID: ${oldUserID}`, logger.GetColor('cyan'))
logger.Log(
`Invalid password request with CID: ${oldUserID}`,
logger.GetColor('cyan')
)
res.json({
result: 'error',
msg: 'No such Client ID'
msg: 'No such Client ID',
})
}
})
@ -349,7 +400,7 @@ function GetApp () {
const isScript = req.body.script
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
const user = dbtools.Select(userDB, 'users', {
pw: pw
pw: pw,
})[0]
if (user) {
@ -358,59 +409,83 @@ function GetApp () {
// FIXME: Users now can only log in in one session, this might be too strict.
const existingSessions = dbtools.Select(userDB, 'sessions', {
userID: user.id,
isScript: isScript ? 1 : 0
isScript: isScript ? 1 : 0,
})
if (existingSessions.length > 0) {
logger.Log(`Multiple ${isScript ? 'script' : 'website'} sessions ( ${existingSessions.length} ) for #${user.id}, deleting olds`, logger.GetColor('cyan'))
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
isScript: isScript ? 1 : 0,
})
})
}
dbtools.Update(userDB, 'users', {
dbtools.Update(
userDB,
'users',
{
loginCount: user.loginCount + 1,
lastIP: ip,
lastLogin: utils.GetDateString()
}, {
id: user.id
})
lastLogin: utils.GetDateString(),
},
{
id: user.id,
}
)
dbtools.Insert(userDB, 'sessions', {
id: sessionID,
ip: ip,
userID: user.id,
isScript: isScript ? 1 : 0,
createDate: utils.GetDateString()
createDate: utils.GetDateString(),
})
// https://www.npmjs.com/package/cookie
// TODO: cookie age
res.cookie('sessionID', sessionID, {
domain: '.frylabs.net', // TODO: use url. url: "https://api.frylabs.net"
expires: new Date(new Date().getTime() + (10 * 365 * 24 * 60 * 60 * 1000)),
expires: new Date(
new Date().getTime() + 10 * 365 * 24 * 60 * 60 * 1000
),
sameSite: 'none',
secure: true
secure: true,
})
res.cookie('sessionID', sessionID, {
expires: new Date(new Date().getTime() + (10 * 365 * 24 * 60 * 60 * 1000)),
expires: new Date(
new Date().getTime() + 10 * 365 * 24 * 60 * 60 * 1000
),
sameSite: 'none',
secure: true
secure: true,
})
res.json({
result: 'success',
msg: 'you are now logged in'
msg: 'you are now logged in',
})
logger.Log(`Successfull login to ${isScript ? 'script' : 'website'} with user ID: #${user.id}`, logger.GetColor('cyan'))
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'))
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'
msg: 'Invalid password',
})
}
})
@ -421,11 +496,11 @@ function GetApp () {
// removing session from db
dbtools.Delete(userDB, 'sessions', {
id: sessionID
id: sessionID,
})
// TODO: remove old sessions every once in a while
res.clearCookie('sessionID').json({
result: 'success'
result: 'success',
})
})
@ -448,19 +523,32 @@ function GetApp () {
app.post('/postfeedback', function(req, res) {
logger.LogReq(req)
if (req.body.fromLogin) {
logger.Log('New feedback message from Login page', logger.GetColor('bluebg'), true)
logger.Log(
'New feedback message from Login page',
logger.GetColor('bluebg'),
true
)
} else {
logger.Log('New feedback message from feedback page', logger.GetColor('bluebg'), true)
logger.Log(
'New feedback message from feedback page',
logger.GetColor('bluebg'),
true
)
}
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
const user = req.session.user
utils.AppendToFile(utils.GetDateString() + ':\n' + JSON.stringify({
utils.AppendToFile(
utils.GetDateString() +
':\n' +
JSON.stringify({
...req.body,
userID: user ? user.id : 'no user',
ip: ip
}), msgFile)
ip: ip,
}),
msgFile
)
res.json({ success: true })
})
@ -473,12 +561,22 @@ function GetApp () {
utils.CreatePath(path, true)
let d = new Date()
let fn = d.getHours() + '' + d.getMinutes() + '' + d.getSeconds() + '_' + filename
let fn =
d.getHours() +
'' +
d.getMinutes() +
'' +
d.getSeconds() +
'_' +
filename
fstream = fs.createWriteStream(path + '/' + fn)
file.pipe(fstream)
fstream.on('close', function() {
logger.Log('Upload Finished of ' + path + '/' + fn, logger.GetColor('blue'))
logger.Log(
'Upload Finished of ' + path + '/' + fn,
logger.GetColor('blue')
)
next(fn)
})
fstream.on('error', function(err) {
@ -528,7 +626,7 @@ function GetApp () {
const respStatuses = {
invalidPass: 'invalidPass',
ok: 'ok',
error: 'error'
error: 'error',
}
logger.LogReq(req)
@ -547,19 +645,53 @@ function GetApp () {
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)
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'))
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)
utils.AppendToFile(
utils.GetDateString() +
'\n' +
JSON.stringify(user) +
'\n' +
JSON.stringify(editedQuestions) +
'\n\n',
dataEditsLog
)
// making backup
utils.CopyFile('./' + dataFile, `./qminingPublic/backs/data_before_${user.name}_${utils.GetDateString().replace(/ /g, '_')}`) // TODO: rewrite to dinamyc public!!!
utils.CopyFile(
'./' + dataFile,
`./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)
@ -571,7 +703,7 @@ function GetApp () {
res.json({
status: respStatuses.ok,
user: user.name
user: user.name,
})
logger.Log('Data updating done!', logger.GetColor('bluebg'))
} catch (e) {
@ -590,15 +722,17 @@ function GetApp () {
// automatically saves to dataFile every n write
// FIXME: req.body.datatoadd is for backwards compatibility, remove this sometime in the future
actions.ProcessIncomingRequest(
actions
.ProcessIncomingRequest(
req.body.datatoadd || req.body,
data,
{ motd, version },
dryRun
).then((r) => {
)
.then((r) => {
res.json({
success: r !== -1,
newQuestions: r
newQuestions: r,
})
})
})
@ -610,7 +744,7 @@ function GetApp () {
message: `ask something! ?q=[question]&subj=[subject]&data=[question data]. 'subj' is optimal for faster result`,
result: [],
recievedData: JSON.stringify(req.query),
success: false
success: false,
})
} else {
if (req.query.q && req.query.data) {
@ -620,13 +754,16 @@ function GetApp () {
try {
recData = JSON.parse(req.query.data)
} catch (e) {
logger.Log(`Unable to parse recieved question data! '${req.query.data}'`, logger.GetColor('redbg'))
logger.Log(
`Unable to parse recieved question data! '${req.query.data}'`,
logger.GetColor('redbg')
)
}
let r = data.Search(question, subj, recData)
res.json({
result: r,
success: true
success: true,
})
logger.DebugLog(`Question result length: ${r.length}`, 'ask', 1)
logger.DebugLog(r, 'ask', 2)
@ -636,7 +773,7 @@ function GetApp () {
message: `Invalid question :(`,
result: [],
recievedData: JSON.stringify(req.query),
success: false
success: false,
})
}
}
@ -647,14 +784,14 @@ function GetApp () {
subjects: data.length,
questions: data.Subjects.reduce((acc, subj) => {
return acc + subj.length
}, 0)
}, 0),
}
}
function getDetailedRes() {
return data.Subjects.map((subj) => {
return {
name: subj.Name,
count: subj.length
count: subj.length,
}
})
}
@ -664,7 +801,7 @@ function GetApp () {
if (req.query.detailed === 'all') {
res.json({
detailed: getDetailedRes(),
simple: getSimplreRes()
simple: getSimplreRes(),
})
} else if (req.query.detailed) {
res.json(getDetailedRes())
@ -678,7 +815,7 @@ function GetApp () {
let result = {
result: 'success',
uid: user.id
uid: user.id,
}
if (req.query.subjinfo) {
result.subjinfo = getSimplreRes()
@ -704,20 +841,28 @@ function GetApp () {
function ExportDailyDataCount() {
logger.Log('Saving daily data count ...')
utils.AppendToFile(JSON.stringify({
utils.AppendToFile(
JSON.stringify({
date: utils.GetDateString(),
subjectCount: data.Subjects.length,
questionCOunt: data.Subjects.reduce((acc, subj) => {
return acc + subj.Questions.length
}, 0),
userCount: dbtools.TableInfo(userDB, 'users').dataCount
}), dailyDataCountFile)
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`)
userDB
.backup(
`${usersDbBackupPath}/users.${utils
.GetDateString()
.replace(/ /g, '_')}.db`
)
.then(() => {
logger.Log('Auth DB backup complete!')
})
@ -749,12 +894,22 @@ function GetApp () {
// }
if (dayDiff % addPWPerDay === 0) {
logger.Log(`Incrementing avaible PW-s for user #${u.id}: ${u.avaiblePWRequests} -> ${u.avaiblePWRequests + 1}`, logger.GetColor('cyan'))
dbtools.Update(userDB, 'users', {
avaiblePWRequests: u.avaiblePWRequests + 1
}, {
id: u.id
})
logger.Log(
`Incrementing avaible PW-s for user #${u.id}: ${
u.avaiblePWRequests
} -> ${u.avaiblePWRequests + 1}`,
logger.GetColor('cyan')
)
dbtools.Update(
userDB,
'users',
{
avaiblePWRequests: u.avaiblePWRequests + 1,
},
{
id: u.id,
}
)
}
})
}
@ -767,7 +922,7 @@ function GetApp () {
return {
dailyAction: DailyAction,
app: app
app: app,
}
}

View file

@ -52,13 +52,9 @@
"sessions": {
"foreignKey": [
{
"keysFrom": [
"userID"
],
"keysFrom": ["userID"],
"table": "users",
"keysTo": [
"id"
]
"keysTo": ["id"]
}
],
"tableStruct": {
@ -91,13 +87,9 @@
"accesses": {
"foreignKey": [
{
"keysFrom": [
"userID"
],
"keysFrom": ["userID"],
"table": "users",
"keysTo": [
"id"
]
"keysTo": ["id"]
}
],
"tableStruct": {

View file

@ -33,33 +33,36 @@ let url = '' // http(s)//asd.basd
function GetApp() {
app.set('view engine', 'ejs')
app.set('views', [
'./modules/main/views',
'./sharedViews'
])
app.set('views', ['./modules/main/views', './sharedViews'])
publicdirs.forEach((pdir) => {
logger.Log(`Using public dir: ${pdir}`)
app.use(express.static(pdir))
})
app.use(busboy({
app.use(
busboy({
limits: {
fileSize: 10000 * 1024 * 1024
}
}))
fileSize: 10000 * 1024 * 1024,
},
})
)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
app.use(
bodyParser.urlencoded({
limit: '5mb',
extended: true
}))
app.use(bodyParser.json({
limit: '5mb'
}))
extended: true,
})
)
app.use(
bodyParser.json({
limit: '5mb',
})
)
// --------------------------------------------------------------
app.get('/', function(req, res) {
res.render('main', {
siteurl: url
siteurl: url,
})
})
@ -72,7 +75,7 @@ function GetApp () {
})
return {
app: app
app: app,
}
}

View file

@ -42,19 +42,21 @@ try {
}
function GetApp() {
app.use(bodyParser.urlencoded({
app.use(
bodyParser.urlencoded({
limit: '5mb',
extended: true
}))
app.use(bodyParser.json({
limit: '5mb'
}))
extended: true,
})
)
app.use(
bodyParser.json({
limit: '5mb',
})
)
app.set('view engine', 'ejs')
app.set('views', [
'./modules/qmining/views',
'./sharedViews'
])
app.use(auth({
app.set('views', ['./modules/qmining/views', './sharedViews'])
app.use(
auth({
userDB: userDB,
jsonResponse: false,
exceptions: [
@ -66,19 +68,22 @@ function GetApp () {
'/getVeteranPw',
'/moodle-test-userscript/stable.user.js',
'/donate',
'/irc'
]
}))
'/irc',
],
})
)
publicdirs.forEach((pdir) => {
logger.Log(`Using public dir: ${pdir}`)
app.use(express.static(pdir))
})
app.use(express.static(nextdir))
app.use(busboy({
app.use(
busboy({
limits: {
fileSize: 10000 * 1024 * 1024
}
}))
fileSize: 10000 * 1024 * 1024,
},
})
)
// --------------------------------------------------------------
// REDIRECTS
@ -87,67 +92,70 @@ function GetApp () {
// to be backwards compatible
app.get('/ask', function(req, res) {
logger.DebugLog(`Qmining module ask redirect`, 'ask', 1)
res.redirect(`http://api.frylabs.net/ask?q=${req.query.q}&subj=${req.query.subj}&data=${req.query.data}`)
res.redirect(
`http://api.frylabs.net/ask?q=${req.query.q}&subj=${req.query.subj}&data=${req.query.data}`
)
})
const simpleRedirects = [
{
from: '/dataeditor',
to: 'https://dataeditor.frylabs.net'
to: 'https://dataeditor.frylabs.net',
},
{
from: '/install',
to: 'https://qmining.frylabs.net/moodle-test-userscript/stable.user.js'
to: 'https://qmining.frylabs.net/moodle-test-userscript/stable.user.js',
},
{
from: '/servergit',
to: 'https://gitlab.com/MrFry/mrfrys-node-server'
to: 'https://gitlab.com/MrFry/mrfrys-node-server',
},
{
from: '/scriptgit',
to: 'https://gitlab.com/MrFry/moodle-test-userscript'
to: 'https://gitlab.com/MrFry/moodle-test-userscript',
},
{
from: '/qminingSite',
to: 'https://gitlab.com/MrFry/qmining-page'
to: 'https://gitlab.com/MrFry/qmining-page',
},
{
from: '/classesgit',
to: 'https://gitlab.com/MrFry/question-classes'
to: 'https://gitlab.com/MrFry/question-classes',
},
{
from: '/menuClick',
to: '/'
to: '/',
},
{
from: '/lred',
to: '/allQuestions.html'
to: '/allQuestions.html',
},
{
from: '/donate',
to: donateURL
to: donateURL,
},
{ // to be backwards compatible
{
// to be backwards compatible
from: '/legacy',
to: '/allQuestions.html'
to: '/allQuestions.html',
},
{
from: '/allqr',
to: 'http://api.frylabs.net/allqr.txt'
to: 'http://api.frylabs.net/allqr.txt',
},
{
from: '/allqr.txt',
to: 'http://api.frylabs.net/allqr.txt'
to: 'http://api.frylabs.net/allqr.txt',
},
{
from: '/infos',
to: 'http://api.frylabs.net/infos?version=true&motd=true&subjinfo=true',
nolog: true
nolog: true,
},
{
from: '/irc',
to: 'https://kiwiirc.com/nextclient/irc.sub.fm/#qmining'
}
to: 'https://kiwiirc.com/nextclient/irc.sub.fm/#qmining',
},
]
simpleRedirects.forEach((redirect) => {
@ -191,7 +199,7 @@ function GetApp () {
app.get('/getVeteranPw', function(req, res) {
res.render('veteranPw', {
cid: req.query.cid || '',
devel: process.env.NS_DEVEL
devel: process.env.NS_DEVEL,
})
logger.LogReq(req)
})
@ -205,7 +213,7 @@ function GetApp () {
})
return {
app: app
app: app,
}
}

View file

@ -42,27 +42,30 @@ function GetApp () {
const uloadFiles = p + 'f'
app.set('view engine', 'ejs')
app.set('views', [
'./modules/sio/views',
'./sharedViews'
])
app.set('views', ['./modules/sio/views', './sharedViews'])
publicdirs.forEach((pdir) => {
logger.Log(`Using public dir: ${pdir}`)
app.use(express.static(pdir))
})
app.use(busboy({
app.use(
busboy({
limits: {
fileSize: 10000 * 1024 * 1024
}
}))
fileSize: 10000 * 1024 * 1024,
},
})
)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
app.use(
bodyParser.urlencoded({
limit: '5mb',
extended: true
}))
app.use(bodyParser.json({
limit: '5mb'
}))
extended: true,
})
)
app.use(
bodyParser.json({
limit: '5mb',
})
)
// --------------------------------------------------------------
@ -79,12 +82,22 @@ function GetApp () {
utils.CreatePath(path, true)
let d = new Date()
let fn = d.getHours() + '' + d.getMinutes() + '' + d.getSeconds() + '_' + filename
let fn =
d.getHours() +
'' +
d.getMinutes() +
'' +
d.getSeconds() +
'_' +
filename
fstream = fs.createWriteStream(path + '/' + fn)
file.pipe(fstream)
fstream.on('close', function() {
logger.Log('Upload Finished of ' + path + '/' + fn, logger.GetColor('blue'))
logger.Log(
'Upload Finished of ' + path + '/' + fn,
logger.GetColor('blue')
)
next(fn)
})
fstream.on('error', function(err) {
@ -108,7 +121,7 @@ function GetApp () {
})
return {
app: app
app: app,
}
}

View file

@ -42,27 +42,30 @@ function GetApp () {
const listedFiles = './' + p + 'files'
app.set('view engine', 'ejs')
app.set('views', [
'./modules/stuff/views',
'./sharedViews'
])
app.set('views', ['./modules/stuff/views', './sharedViews'])
publicdirs.forEach((pdir) => {
logger.Log(`Using public dir: ${pdir}`)
app.use(express.static(pdir))
})
app.use(busboy({
app.use(
busboy({
limits: {
fileSize: 10000 * 1024 * 1024
}
}))
fileSize: 10000 * 1024 * 1024,
},
})
)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
app.use(
bodyParser.urlencoded({
limit: '5mb',
extended: true
}))
app.use(bodyParser.json({
limit: '5mb'
}))
extended: true,
})
)
app.use(
bodyParser.json({
limit: '5mb',
})
)
// --------------------------------------------------------------
@ -80,7 +83,7 @@ function GetApp () {
if (!fs.existsSync(fpath)) {
res.render('nofile', {
missingFile: fpath,
url
url,
})
return
}
@ -91,23 +94,21 @@ function GetApp () {
if (range) {
const parts = range.replace(/bytes=/, '').split('-')
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize - 1
const chunksize = (end - start) + 1
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1
const chunksize = end - start + 1
const file = fs.createReadStream(fpath, { start, end })
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType
'Content-Type': contentType,
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': contentType
'Content-Type': contentType,
}
res.writeHead(200, head)
fs.createReadStream(fpath).pipe(res)
@ -121,7 +122,7 @@ function GetApp () {
fname,
url,
contentType,
albumArt: GetAlbumArt(p)
albumArt: GetAlbumArt(p),
})
}
})
@ -132,7 +133,7 @@ function GetApp () {
['/*.mkv', 'audio/x-matroska', 'video'],
['/*.mp3', 'audio/mpeg', 'audio'],
['/*.pdf', 'application/pdf'],
['/*.zip', 'application/zip']
['/*.zip', 'application/zip'],
]
function GetAlbumArt(path) {
@ -150,14 +151,21 @@ function GetApp () {
app.get('/*', function(req, res) {
let parsedUrl = decodeURI(req.url)
let curr = listedFiles + '/' + parsedUrl.substring('/'.length, parsedUrl.length).split('?')[0]
let curr =
listedFiles +
'/' +
parsedUrl.substring('/'.length, parsedUrl.length).split('?')[0]
let relPath = curr.substring(listedFiles.length, curr.length)
if (relPath[relPath.length - 1] !== '/') { relPath += '/' }
if (relPath[relPath.length - 1] !== '/') {
relPath += '/'
}
let t = relPath.split('/')
let prevDir = ''
for (let i = 0; i < t.length - 2; i++) { prevDir += t[i] + '/' }
for (let i = 0; i < t.length - 2; i++) {
prevDir += t[i] + '/'
}
// curr = curr.replace(/\//g, "/");
// relPath = relPath.replace(/\//g, "/");
@ -167,14 +175,18 @@ function GetApp () {
try {
const stat = fs.lstatSync(curr)
if (stat.isDirectory() || stat.isSymbolicLink()) {
if (curr[curr.length - 1] !== '/') { curr += '/' }
if (curr[curr.length - 1] !== '/') {
curr += '/'
}
let f = []
let files = fs.readdirSync(curr)
files.sort(function(a, b) {
return fs.statSync(curr + b).mtime.getTime() -
return (
fs.statSync(curr + b).mtime.getTime() -
fs.statSync(curr + a).mtime.getTime()
)
})
files.forEach((item) => {
@ -186,7 +198,9 @@ function GetApp () {
res.size = Math.round(fileSizeInBytes / 1000000)
res.path = relPath
if (res.path[res.path.length - 1] !== '/') { res.path += '/' }
if (res.path[res.path.length - 1] !== '/') {
res.path += '/'
}
res.path += item
res.mtime = stat['mtime'].toLocaleString()
@ -200,7 +214,7 @@ function GetApp () {
folders: f,
dirname: relPath,
prevDir,
url
url,
})
} else {
let fileStream = fs.createReadStream(curr)
@ -209,7 +223,7 @@ function GetApp () {
} catch (e) {
res.render('nofile', {
missingFile: curr,
url
url,
})
}
})
@ -225,7 +239,7 @@ function GetApp () {
})
return {
app: app
app: app,
}
}

View file

@ -19,7 +19,7 @@ Question Server
module.exports = {
ProcessIncomingRequest: ProcessIncomingRequest,
LoadJSON: LoadJSON
LoadJSON: LoadJSON,
}
const dataFile = './qminingPublic/data.json'
@ -48,13 +48,15 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
try {
let towrite = logger.GetDateString() + '\n'
towrite += '------------------------------------------------------------------------------\n'
towrite +=
'------------------------------------------------------------------------------\n'
if (typeof recievedData === 'object') {
towrite += JSON.stringify(recievedData)
} else {
towrite += recievedData
}
towrite += '\n------------------------------------------------------------------------------\n'
towrite +=
'\n------------------------------------------------------------------------------\n'
utils.AppendToFile(towrite, recDataFile)
logger.DebugLog('recDataFile written', 'actions', 1)
} catch (e) {
@ -78,7 +80,11 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
logger.DebugLog('Question:', 'actions', 2)
logger.DebugLog(question, 'actions', 2)
let q = new classes.Question(question.Q, question.A, question.data)
logger.DebugLog('Searching for question in subj ' + d.subj, 'actions', 3)
logger.DebugLog(
'Searching for question in subj ' + d.subj,
'actions',
3
)
logger.DebugLog(q, 'actions', 3)
let sames = qdb.Search(q, d.subj)
@ -86,7 +92,9 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
logger.DebugLog('Length: ' + sames.length, 'actions', 2)
logger.DebugLog(sames, 'actions', 3)
// if it didnt find any question, or every found questions match is lower thatn 80
let isNew = sames.length === 0 || sames.every(searchResItem => {
let isNew =
sames.length === 0 ||
sames.every((searchResItem) => {
return searchResItem.match < minMatchAmmountToAdd
})
logger.DebugLog('isNew: ' + isNew, 'actions', 2)
@ -102,7 +110,11 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
msg += `New questions: ${allQuestions.length} ( All: ${allQLength} )`
allQuestions.forEach((q) => {
const sName = classes.SUtils.GetSubjNameWithoutYear(d.subj)
logger.DebugLog('Adding question with subjName: ' + sName + ' :', 'actions', 3)
logger.DebugLog(
'Adding question with subjName: ' + sName + ' :',
'actions',
3
)
logger.DebugLog(q, 'actions', 3)
qdb.AddQuestion(sName, q)
})
@ -134,7 +146,9 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
idStats.LogId(d.id, d.subj)
}
logger.Log(subjRow)
if (d.version !== undefined) { msg += '. Version: ' + d.version }
if (d.version !== undefined) {
msg += '. Version: ' + d.version
}
logger.Log('\t' + msg, color)
logger.DebugLog('New Questions:', 'actions', 2)
@ -166,7 +180,7 @@ function LoadJSON (dataFile) {
}
rt.push({
name: d.Subjects[i].Name,
count: j
count: j,
})
r.AddSubject(s)
}

View file

@ -18,22 +18,17 @@ const commonUselessAnswerParts = [
'A helyes válasz: ',
'A helyes válasz:',
'The correct answer is:',
'\''
]
const commonUselessStringParts = [
',',
'\\.',
':',
'!',
'\\+',
'\\s*\\.'
"'",
]
const commonUselessStringParts = [',', '\\.', ':', '!', '\\+', '\\s*\\.']
const specialChars = ['&', '\\+']
const lengthDiffMultiplier = 10 /* Percent minus for length difference */
const minMatchAmmount = 60 /* Minimum ammount to consider that two questions match during answering */
const assert = (val) => {
if (!val) { throw new Error('Assertion failed') }
if (!val) {
throw new Error('Assertion failed')
}
}
class StringUtils {
@ -113,8 +108,15 @@ class StringUtils {
// if the value is empty, or whitespace
EmptyOrWhiteSpace(value) {
// replaces /n-s with "". then replaces spaces with "". if it equals "", then its empty, or only consists of white space
if (value === undefined) { return true }
return (value.replace(/\n/g, '').replace(/ /g, '').replace(/\s/g, ' ') === '')
if (value === undefined) {
return true
}
return (
value
.replace(/\n/g, '')
.replace(/ /g, '')
.replace(/\s/g, ' ') === ''
)
}
// damn nonbreaking space
@ -137,20 +139,23 @@ class StringUtils {
s2 = this.SimplifyStringForComparison(s2).split(' ')
var match = 0
for (var i = 0; i < s1.length; i++) {
if (s2.includes(s1[i])) { match++ }
if (s2.includes(s1[i])) {
match++
}
}
var percent = Math.round(((match / s1.length) * 100).toFixed(2)) // matched words percent
var lengthDifference = Math.abs(s2.length - s1.length)
percent -= lengthDifference * lengthDiffMultiplier
if (percent < 0) { percent = 0 }
if (percent < 0) {
percent = 0
}
return percent
}
AnswerPreProcessor(value) {
assert(value)
return this.RemoveStuff(
value, commonUselessAnswerParts)
return this.RemoveStuff(value, commonUselessAnswerParts)
}
// 'a. pécsi sör' -> 'pécsi sör'
@ -167,7 +172,9 @@ class StringUtils {
}
SimplifyQA(value, mods) {
if (!value) { return }
if (!value) {
return
}
const reducer = (res, fn) => {
return fn(res)
@ -177,22 +184,18 @@ class StringUtils {
}
SimplifyAnswer(value) {
return this.SimplifyQA(
value,
[
return this.SimplifyQA(value, [
this.RemoveSpecialChars.bind(this),
this.RemoveUnnecesarySpaces.bind(this),
this.AnswerPreProcessor.bind(this),
this.RemoveAnswerLetters.bind(this)
this.RemoveAnswerLetters.bind(this),
])
}
SimplifyQuestion(value) {
return this.SimplifyQA(
value,
[
return this.SimplifyQA(value, [
this.RemoveSpecialChars.bind(this),
this.RemoveUnnecesarySpaces.bind(this)
this.RemoveUnnecesarySpaces.bind(this),
])
}
@ -235,7 +238,10 @@ class Question {
}
CompareImage(data2) {
return SUtils.CompareString(this.data.images.join(' '), data2.images.join(' '))
return SUtils.CompareString(
this.data.images.join(' '),
data2.images.join(' ')
)
}
// returns -1 if botth is simple
@ -248,7 +254,11 @@ class Question {
} else if (dataType === 'image') {
return this.CompareImage(qObj.data)
} else {
debugLog(`Unhandled data type ${dataType}`, 'Compare question data', 1)
debugLog(
`Unhandled data type ${dataType}`,
'Compare question data',
1
)
debugLog(qObj, 'Compare question data', 2)
}
} else {
@ -277,7 +287,7 @@ class Question {
if (typeof q2 === 'string') {
qObj = {
Q: q2,
data: data
data: data,
}
} else {
qObj = q2
@ -307,7 +317,7 @@ class Question {
qMatch: qMatch,
aMatch: aMatch,
dMatch: dMatch,
avg: avg
avg: avg,
}
}
}
@ -361,7 +371,7 @@ class Subject {
r.push({
q: this.Questions[i],
match: percent.avg,
detailedMatch: percent
detailedMatch: percent,
})
}
}
@ -381,7 +391,9 @@ class Subject {
toString() {
var r = []
for (var i = 0; i < this.Questions.length; i++) { r.push(this.Questions[i].toString()) }
for (var i = 0; i < this.Questions.length; i++) {
r.push(this.Questions[i].toString())
}
return '+' + this.Name + '\n' + r.join('\n')
}
}
@ -401,8 +413,12 @@ class QuestionDB {
assert(subj)
var i = 0
while (i < this.Subjects.length &&
!subj.toLowerCase().includes(this.Subjects[i].getSubjNameWithoutYear().toLowerCase())) {
while (
i < this.Subjects.length &&
!subj
.toLowerCase()
.includes(this.Subjects[i].getSubjNameWithoutYear().toLowerCase())
) {
i++
}
@ -447,7 +463,11 @@ class QuestionDB {
var r = []
this.Subjects.forEach((subj) => {
if (subjName.toLowerCase().includes(subj.getSubjNameWithoutYear().toLowerCase())) {
if (
subjName
.toLowerCase()
.includes(subj.getSubjNameWithoutYear().toLowerCase())
) {
debugLog(`Searching in ${subj.Name} `, 2)
r = r.concat(subj.Search(q, data))
}
@ -455,12 +475,20 @@ class QuestionDB {
// FIXME: try to remove this? but this is also a good backup plan so idk
if (r.length === 0) {
debugLog('Reqults length is zero when comparing names, trying all subjects', 'qdb search', 1)
debugLog(
'Reqults length is zero when comparing names, trying all subjects',
'qdb search',
1
)
this.Subjects.forEach((subj) => {
r = r.concat(subj.Search(q, data))
})
if (r.length > 0) {
debugLog(`FIXME: '${subjName}' gave no result but '' did!`, 'qdb search', 1)
debugLog(
`FIXME: '${subjName}' gave no result but '' did!`,
'qdb search',
1
)
console.error(`FIXME: '${subjName}' gave no result but '' did!`)
}
}
@ -483,7 +511,9 @@ class QuestionDB {
assert(subj)
var i = 0
while (i < this.length && subj.Name !== this.Subjects[i].Name) { i++ }
while (i < this.length && subj.Name !== this.Subjects[i].Name) {
i++
}
if (i < this.length) {
this.Subjects.concat(subj.Questions)
@ -494,7 +524,9 @@ class QuestionDB {
toString() {
var r = []
for (var i = 0; i < this.Subjects.length; i++) { r.push(this.Subjects[i].toString()) }
for (var i = 0; i < this.Subjects.length; i++) {
r.push(this.Subjects[i].toString())
}
return r.join('\n\n')
}
}

View file

@ -20,7 +20,12 @@ function CreateDB () {
Object.keys(dbStruct).forEach((tableName) => {
const tableData = dbStruct[tableName]
dbtools.CreateTable(authDB, tableName, tableData.tableStruct, tableData.foreignKey)
dbtools.CreateTable(
authDB,
tableName,
tableData.tableStruct,
tableData.foreignKey
)
})
try {
@ -28,14 +33,16 @@ function CreateDB () {
const uids = utils.ReadFile('./ids').split('\n')
uids.forEach((cid, i) => {
if (!cid) { return }
if (!cid) {
return
}
logger.Log(`[ ${i} / ${uids.length} ]`)
try {
dbtools.Insert(authDB, 'users', {
pw: uuidv4(),
oldCID: cid,
avaiblePWRequests: 4,
created: utils.GetDateString()
created: utils.GetDateString(),
})
} catch (e) {
logger.Log('Error during inserting', logger.GetColor('redbg'))
@ -52,10 +59,13 @@ function CreateDB () {
Object.keys(dbStruct).forEach((key) => {
const path = `${dir}/${key}.json`
logger.Log(`Writing ${path}...`)
utils.WriteFile(JSON.stringify({
utils.WriteFile(
JSON.stringify({
tableInfo: dbtools.TableInfo(authDB, key),
tableRows: dbtools.SelectAll(authDB, key)
}), path)
tableRows: dbtools.SelectAll(authDB, key),
}),
path
)
})
logger.Log('Done')

View file

@ -11,7 +11,7 @@ module.exports = {
SelectAll,
Select,
Insert,
CloseDB
CloseDB,
}
const Sqlite = require('better-sqlite3')
@ -69,7 +69,6 @@ function AddColumn (db, table, col) {
function TableInfo(db, table) {
try {
} catch (e) {
console.error(e)
}
@ -85,13 +84,16 @@ function TableInfo (db, table) {
return {
columns: infoRes,
dataCount: countRes[Object.keys(countRes)[0]]
dataCount: countRes[Object.keys(countRes)[0]],
}
}
function Update(db, table, newData, conditions) {
try {
const s = `UPDATE ${table} SET ${GetSqlQuerry(newData, 'set')} WHERE ${GetSqlQuerry(conditions, 'where')}`
const s = `UPDATE ${table} SET ${GetSqlQuerry(
newData,
'set'
)} WHERE ${GetSqlQuerry(conditions, 'where')}`
const stmt = PrepareStatement(db, s)
return stmt.run()
@ -118,7 +120,8 @@ function CreateTable (db, name, columns, foreignKeys) {
// FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist, albumname) )
try {
const cols = Object.keys(columns).reduce((acc, key) => {
const cols = Object.keys(columns)
.reduce((acc, key) => {
const item = columns[key]
// FIXME: array, and push stuff, then join()
const flags = []
@ -127,7 +130,7 @@ function CreateTable (db, name, columns, foreignKeys) {
notNull: 'NOT NULL',
unique: 'UNIQUE',
autoIncrement: 'AUTOINCREMENT',
defaultZero: 'DEFAULT 0'
defaultZero: 'DEFAULT 0',
}
Object.keys(toCheck).forEach((key) => {
if (item[key]) {
@ -137,13 +140,18 @@ function CreateTable (db, name, columns, foreignKeys) {
acc.push(`${key} ${item.type} ${flags.join(' ')}`)
return acc
}, []).join(', ')
}, [])
.join(', ')
let fKeys = []
if (foreignKeys) {
foreignKeys.forEach((f) => {
const { keysFrom, table, keysTo } = f
fKeys.push(`, FOREIGN KEY(${keysFrom.join(', ')}) REFERENCES ${table}(${keysTo.join(', ')})`)
fKeys.push(
`, FOREIGN KEY(${keysFrom.join(
', '
)}) REFERENCES ${table}(${keysTo.join(', ')})`
)
})
}
@ -180,12 +188,15 @@ function Select (db, from, conditions) {
function Insert(db, table, data) {
try {
const cols = Object.keys(data).reduce((acc, key) => {
const cols = Object.keys(data)
.reduce((acc, key) => {
acc.push(`${key}`)
return acc
}, []).join(', ')
}, [])
.join(', ')
const values = Object.keys(data).reduce((acc, key) => {
const values = Object.keys(data)
.reduce((acc, key) => {
const item = data[key]
if (typeof item === 'string') {
acc.push(`'${item}'`)
@ -193,7 +204,8 @@ function Insert (db, table, data) {
acc.push(`${item}`)
}
return acc
}, []).join(', ')
}, [])
.join(', ')
const s = `INSERT INTO ${table} (${cols}) VALUES (${values})`
const stmt = PrepareStatement(db, s)
@ -217,7 +229,9 @@ function CloseDB (db) {
function PrepareStatement(db, s) {
if (!db) {
throw new Error('DB is undefined in prepare statement! DB action called with undefined db')
throw new Error(
'DB is undefined in prepare statement! DB action called with undefined db'
)
}
DebugLog(s)
return db.prepare(s)

View file

@ -20,7 +20,7 @@
module.exports = {
LogId: LogId,
Load: Load
Load: Load,
}
const utils = require('../utils/utils.js')
@ -39,7 +39,10 @@ function Load () {
var prevData = utils.ReadFile(idStatFile)
data = JSON.parse(prevData)
} catch (e) {
logger.Log('Error at loading id logs! (@ first run its normal)', logger.GetColor('redbg'))
logger.Log(
'Error at loading id logs! (@ first run its normal)',
logger.GetColor('redbg')
)
console.log(e)
}
@ -47,7 +50,10 @@ function Load () {
var prevVData = utils.ReadFile(idVStatFile)
vData = JSON.parse(prevVData)
} catch (e) {
logger.Log('Error at loading id logs! (@ first run its normal)', logger.GetColor('redbg'))
logger.Log(
'Error at loading id logs! (@ first run its normal)',
logger.GetColor('redbg')
)
console.log(e)
}
}
@ -69,7 +75,7 @@ function Inc (value, subj) {
if (data[value] === undefined) {
data[value] = {
count: 0,
subjs: {}
subjs: {},
}
}
data[value].count++
@ -78,12 +84,19 @@ function Inc (value, subj) {
function AddVisitStat(name, subj) {
var m = new Date()
const now = m.getFullYear() + '/' + ('0' + (m.getMonth() + 1)).slice(-2) + '/' + ('0' + m.getDate()).slice(-2)
if (vData[now] === undefined) { vData[now] = {} }
const now =
m.getFullYear() +
'/' +
('0' + (m.getMonth() + 1)).slice(-2) +
'/' +
('0' + m.getDate()).slice(-2)
if (vData[now] === undefined) {
vData[now] = {}
}
if (vData[now][name] === undefined) {
vData[now][name] = {
count: 0,
subjs: {}
subjs: {},
}
}
vData[now][name].count++

View file

@ -18,7 +18,8 @@
------------------------------------------------------------------------- */
const hr = '---------------------------------------------------------------------------------'
const hr =
'---------------------------------------------------------------------------------'
module.exports = {
GetDateString: GetDateString,
@ -30,7 +31,7 @@ module.exports = {
Load: Load,
logHashed: logHashed,
hr: hr,
C: C
C: C,
}
const DELIM = C('green') + '|' + C()
@ -45,14 +46,7 @@ const uStatsFile = 'stats/ustats'
const uvStatsFile = 'stats/uvstats'
const nologFile = './nolog'
const colors = [
'green',
'red',
'yellow',
'blue',
'magenta',
'cyan'
]
const colors = ['green', 'red', 'yellow', 'blue', 'magenta', 'cyan']
const writeInterval = 10
const debugLevel = parseInt(process.env.NS_LOGLEVEL) || 0
@ -78,7 +72,9 @@ function DebugLog (msg, name, lvl) {
msg = hr
}
let s = msg
let header = `${C('red')}#DEBUG${lvl}#${C('yellow')}${name.toUpperCase()}${C('red')}#${C()}${DELIM}${C()}`
let header = `${C('red')}#DEBUG${lvl}#${C(
'yellow'
)}${name.toUpperCase()}${C('red')}#${C()}${DELIM}${C()}`
if (typeof msg !== 'object') {
s = header + msg
} else {
@ -122,12 +118,13 @@ function LogReq (req, toFile, sc) {
hostname = req.hostname.replace('www.', '').split('.')[0]
} else {
hostname = 'NOHOST'
Log('req.hostname is undefined! req.hostname: ' + req.hostname, GetColor('redbg'))
Log(
'req.hostname is undefined! req.hostname: ' + req.hostname,
GetColor('redbg')
)
}
logEntry += dl +
hostname + dl +
req.headers['user-agent'] + dl +
req.method + dl
logEntry +=
dl + hostname + dl + req.headers['user-agent'] + dl + req.method + dl
if (req.session && req.session.user) {
logEntry += C('cyan') + req.session.user.id + C() + dl
@ -139,7 +136,9 @@ function LogReq (req, toFile, sc) {
logEntry += GetRandomColor(req.url.split('?')[0]) + req.url
if (sc !== undefined) { logEntry += dl + sc }
if (sc !== undefined) {
logEntry += dl + sc
}
logEntry += C()
if (!toFile) {
@ -203,7 +202,10 @@ function Load () {
var prevVData = utils.ReadFile(vStatFile)
vData = JSON.parse(prevVData)
} catch (e) {
Log('Error at loading visit logs! (@ first run its normal)', GetColor('redbg'))
Log(
'Error at loading visit logs! (@ first run its normal)',
GetColor('redbg')
)
console.log(e)
}
setNoLogReadInterval()
@ -227,7 +229,9 @@ function LogStat (url, ip, hostname, userId) {
function IncUserStat(userId) {
try {
if (uData[userId] === undefined) { uData[userId] = 0 }
if (uData[userId] === undefined) {
uData[userId] = 0
}
uData[userId]++
} catch (e) {
Log('Error at making user ID stats!', GetColor('redbg'))
@ -238,9 +242,18 @@ function IncUserStat (userId) {
function AddUserIdStat(userId) {
try {
var m = new Date()
const now = m.getFullYear() + '/' + ('0' + (m.getMonth() + 1)).slice(-2) + '/' + ('0' + m.getDate()).slice(-2)
if (uvData[now] === undefined) { uvData[now] = {} }
if (uvData[now][userId] === undefined) { uvData[now][userId] = 0 }
const now =
m.getFullYear() +
'/' +
('0' + (m.getMonth() + 1)).slice(-2) +
'/' +
('0' + m.getDate()).slice(-2)
if (uvData[now] === undefined) {
uvData[now] = {}
}
if (uvData[now][userId] === undefined) {
uvData[now][userId] = 0
}
uvData[now][userId]++
} catch (e) {
Log('Error at making user ID stats!', GetColor('redbg'))
@ -249,16 +262,29 @@ function AddUserIdStat (userId) {
}
function Inc(value) {
if (value.startsWith('/?')) { value = '/' }
if (data[value] === undefined) { data[value] = 0 }
if (value.startsWith('/?')) {
value = '/'
}
if (data[value] === undefined) {
data[value] = 0
}
data[value]++
}
function AddVisitStat(name) {
var m = new Date()
const now = m.getFullYear() + '/' + ('0' + (m.getMonth() + 1)).slice(-2) + '/' + ('0' + m.getDate()).slice(-2)
if (vData[now] === undefined) { vData[now] = {} }
if (vData[now][name] === undefined) { vData[now][name] = 0 }
const now =
m.getFullYear() +
'/' +
('0' + (m.getMonth() + 1)).slice(-2) +
'/' +
('0' + m.getDate()).slice(-2)
if (vData[now] === undefined) {
vData[now] = {}
}
if (vData[now][name] === undefined) {
vData[now][name] = 0
}
vData[now][name]++
}
@ -315,15 +341,33 @@ function GetColor (c) {
}
function C(c) {
if (c !== undefined) { c = c.toLowerCase() }
if (c !== undefined) {
c = c.toLowerCase()
}
if (c === 'redbg') { return '\x1b[41m' }
if (c === 'bluebg') { return '\x1b[44m' }
if (c === 'green') { return '\x1b[32m' }
if (c === 'red') { return '\x1b[31m' }
if (c === 'yellow') { return '\x1b[33m' }
if (c === 'blue') { return '\x1b[34m' }
if (c === 'magenta') { return '\x1b[35m' }
if (c === 'cyan') { return '\x1b[36m' }
if (c === 'redbg') {
return '\x1b[41m'
}
if (c === 'bluebg') {
return '\x1b[44m'
}
if (c === 'green') {
return '\x1b[32m'
}
if (c === 'red') {
return '\x1b[31m'
}
if (c === 'yellow') {
return '\x1b[33m'
}
if (c === 'blue') {
return '\x1b[34m'
}
if (c === 'magenta') {
return '\x1b[35m'
}
if (c === 'cyan') {
return '\x1b[36m'
}
return '\x1b[0m'
}

View file

@ -103,7 +103,16 @@ function LogDataCount (data) {
return acc + subj.Questions.length
}, 0)
console.log('Subjects: ' + C('green') + subjLength + C() + ', Questions: ' + C('green') + qLength + C())
console.log(
'Subjects: ' +
C('green') +
subjLength +
C() +
', Questions: ' +
C('green') +
qLength +
C()
)
}
function PrintDB(data) {
@ -152,7 +161,8 @@ function RemoveDuplicates (data) {
const stats = []
data.Subjects.forEach((subj, i) => {
const logFile = logPath + '/' + subj.Name.replace(/ /g, '_').replace(/\//g, '-')
const logFile =
logPath + '/' + subj.Name.replace(/ /g, '_').replace(/\//g, '-')
LogSubjProgress(i, subj, data.Subjects.length)
let addedQuestions = 0
let removedQuestions = 0
@ -185,7 +195,7 @@ function RemoveDuplicates (data) {
name: subj.Name,
prevQuestions: subj.Questions.length,
addedQuestions: addedQuestions,
removedQuestions: removedQuestions
removedQuestions: removedQuestions,
})
})
return { res, stats }
@ -250,11 +260,17 @@ function GetParams () {
function GetDateString() {
const m = new Date()
const d = m.getFullYear() + '-' +
('0' + (m.getMonth() + 1)).slice(-2) + '-' +
('0' + m.getDate()).slice(-2) + ' ' +
('0' + m.getHours()).slice(-2) + ':' +
('0' + m.getMinutes()).slice(-2) + ':' +
const d =
m.getFullYear() +
'-' +
('0' + (m.getMonth() + 1)).slice(-2) +
'-' +
('0' + m.getDate()).slice(-2) +
' ' +
('0' + m.getHours()).slice(-2) +
':' +
('0' + m.getMinutes()).slice(-2) +
':' +
('0' + m.getSeconds()).slice(-2)
return d
}

View file

@ -11,7 +11,7 @@ module.exports = {
WatchFile: WatchFile,
ReadDir: ReadDir,
CopyFile: CopyFile,
GetDateString: GetDateString
GetDateString: GetDateString,
}
var fs = require('fs')
@ -22,12 +22,19 @@ const dataFile = './qminingPublic/data.json'
function GetDateString() {
const m = new Date()
return m.getFullYear() + '-' +
('0' + (m.getMonth() + 1)).slice(-2) + '-' +
('0' + m.getDate()).slice(-2) + ' ' +
('0' + m.getHours()).slice(-2) + ':' +
('0' + m.getMinutes()).slice(-2) + ':' +
return (
m.getFullYear() +
'-' +
('0' + (m.getMonth() + 1)).slice(-2) +
'-' +
('0' + m.getDate()).slice(-2) +
' ' +
('0' + m.getHours()).slice(-2) +
':' +
('0' + m.getMinutes()).slice(-2) +
':' +
('0' + m.getSeconds()).slice(-2)
)
}
function CopyFile(from, to) {
@ -49,7 +56,9 @@ function ReadJSON (name) {
}
function ReadFile(name) {
if (!FileExists(name)) { throw new Error('No such file: ' + name) }
if (!FileExists(name)) {
throw new Error('No such file: ' + name)
}
return fs.readFileSync(name, 'utf8')
}
@ -77,7 +86,9 @@ function WatchFile (file, callback) {
}
function CreatePath(path, onlyPath) {
if (FileExists(path)) { return }
if (FileExists(path)) {
return
}
var p = path.split('/')
var currDir = p[0]
@ -85,7 +96,9 @@ function CreatePath (path, onlyPath) {
if (currDir !== '' && !fs.existsSync(currDir)) {
try {
fs.mkdirSync(currDir)
} catch (e) { console.log('Failed to make ' + currDir + ' directory... ') }
} catch (e) {
console.log('Failed to make ' + currDir + ' directory... ')
}
}
currDir += '/' + p[i]
}
@ -104,7 +117,10 @@ function WriteFileAsync (content, path) {
CreatePath(path)
fs.writeFile(path, content, function(err) {
if (err) {
logger.Log('Error writing file: ' + path + ' (sync)', logger.GetColor('redbg'))
logger.Log(
'Error writing file: ' + path + ' (sync)',
logger.GetColor('redbg')
)
}
})
}
@ -114,7 +130,10 @@ function AppendToFile (data, file) {
try {
fs.appendFileSync(file, '\n' + data)
} catch (e) {
logger.Log('Error appendig to file log file: ' + file + ' (sync)', logger.GetColor('redbg'))
logger.Log(
'Error appendig to file log file: ' + file + ' (sync)',
logger.GetColor('redbg')
)
logger.Log(data)
console.log(e)
}
@ -130,7 +149,10 @@ function Beep () {
function WriteBackup() {
try {
WriteFileAsync(ReadFile(dataFile), 'public/backs/data_' + new Date().toString())
WriteFileAsync(
ReadFile(dataFile),
'public/backs/data_' + new Date().toString()
)
} catch (e) {
logger.Log('Error backing up data json file!', logger.GetColor('redbg'))
console.log(e)