mirror of
https://gitlab.com/MrFry/mrfrys-node-server
synced 2025-04-01 20:24:18 +02:00
Prettied all js in src/
This commit is contained in:
parent
3f081d8dff
commit
ee0f0a9f3b
17 changed files with 1012 additions and 688 deletions
|
@ -19,7 +19,7 @@ Question Server
|
|||
|
||||
module.exports = {
|
||||
ProcessIncomingRequest: ProcessIncomingRequest,
|
||||
LoadJSON: LoadJSON
|
||||
LoadJSON: LoadJSON,
|
||||
}
|
||||
|
||||
const dataFile = './qminingPublic/data.json'
|
||||
|
@ -38,7 +38,7 @@ const minMatchAmmountToAdd = 90 // FIXME: test this value
|
|||
const writeAfter = 1 // write after # of adds FIXME: set reasonable save rate
|
||||
var currWrites = 0
|
||||
|
||||
function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
|
||||
function ProcessIncomingRequest(recievedData, qdb, infos, dryRun) {
|
||||
return new Promise((resolve, reject) => {
|
||||
logger.DebugLog('Processing incoming request', 'actions', 1)
|
||||
if (recievedData === undefined) {
|
||||
|
@ -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) {
|
||||
|
@ -62,7 +64,7 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
|
|||
}
|
||||
|
||||
try {
|
||||
// recievedData: { version: "", id: "", subj: "" quiz: {} }
|
||||
// recievedData: { version: "", id: "", subj: "" quiz: {} }
|
||||
let d = recievedData
|
||||
// FIXME: if is for backwards compatibility, remove this sometime in the future
|
||||
if (typeof d !== 'object') {
|
||||
|
@ -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,9 +92,11 @@ 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 => {
|
||||
return searchResItem.match < minMatchAmmountToAdd
|
||||
})
|
||||
let isNew =
|
||||
sames.length === 0 ||
|
||||
sames.every((searchResItem) => {
|
||||
return searchResItem.match < minMatchAmmountToAdd
|
||||
})
|
||||
logger.DebugLog('isNew: ' + isNew, 'actions', 2)
|
||||
if (isNew) {
|
||||
allQuestions.push(q)
|
||||
|
@ -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)
|
||||
|
@ -151,7 +165,7 @@ function ProcessIncomingRequest (recievedData, qdb, infos, dryRun) {
|
|||
}
|
||||
|
||||
// loading stuff
|
||||
function LoadJSON (dataFile) {
|
||||
function LoadJSON(dataFile) {
|
||||
try {
|
||||
var d = JSON.parse(utils.ReadFile(dataFile))
|
||||
var r = new classes.QuestionDB()
|
||||
|
@ -166,7 +180,7 @@ function LoadJSON (dataFile) {
|
|||
}
|
||||
rt.push({
|
||||
name: d.Subjects[i].Name,
|
||||
count: j
|
||||
count: j,
|
||||
})
|
||||
r.AddSubject(s)
|
||||
}
|
||||
|
|
|
@ -26,6 +26,6 @@ console.log(parsed.version)
|
|||
utils.WriteFile(JSON.stringify(parsed), dataFile)
|
||||
utils.WriteFile(parsed.version, versionFile)
|
||||
|
||||
function GetParams () {
|
||||
function GetParams() {
|
||||
return process.argv.splice(2)
|
||||
}
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
var debugLogger = null
|
||||
|
||||
function initLogger (logger) {
|
||||
function initLogger(logger) {
|
||||
debugLogger = logger
|
||||
}
|
||||
|
||||
function debugLog (msg, name, lvl) {
|
||||
function debugLog(msg, name, lvl) {
|
||||
if (debugLogger) {
|
||||
debugLogger(msg, name, lvl)
|
||||
}
|
||||
|
@ -18,26 +18,21 @@ const commonUselessAnswerParts = [
|
|||
'A helyes válasz: ',
|
||||
'A helyes válasz:',
|
||||
'The correct answer is:',
|
||||
'\''
|
||||
"'",
|
||||
]
|
||||
const commonUselessStringParts = [
|
||||
',',
|
||||
'\\.',
|
||||
':',
|
||||
'!',
|
||||
'\\+',
|
||||
'\\s*\\.'
|
||||
]
|
||||
const specialChars = [ '&', '\\+' ]
|
||||
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 {
|
||||
GetSubjNameWithoutYear (subjName) {
|
||||
GetSubjNameWithoutYear(subjName) {
|
||||
let t = subjName.split(' - ')
|
||||
if (t[0].match(/^[0-9]{4}\/[0-9]{2}\/[0-9]{1}$/i)) {
|
||||
return t[1] || subjName
|
||||
|
@ -46,7 +41,7 @@ class StringUtils {
|
|||
}
|
||||
}
|
||||
|
||||
RemoveStuff (value, removableStrings, toReplace) {
|
||||
RemoveStuff(value, removableStrings, toReplace) {
|
||||
removableStrings.forEach((x) => {
|
||||
var regex = new RegExp(x, 'g')
|
||||
value = value.replace(regex, toReplace || '')
|
||||
|
@ -54,14 +49,14 @@ class StringUtils {
|
|||
return value
|
||||
}
|
||||
|
||||
SimplifyQuery (q) {
|
||||
SimplifyQuery(q) {
|
||||
assert(q)
|
||||
|
||||
var result = q.replace(/\n/g, ' ').replace(/\s/g, ' ')
|
||||
return this.RemoveUnnecesarySpaces(result)
|
||||
}
|
||||
|
||||
ShortenString (toShorten, ammount) {
|
||||
ShortenString(toShorten, ammount) {
|
||||
assert(toShorten)
|
||||
|
||||
var result = ''
|
||||
|
@ -73,7 +68,7 @@ class StringUtils {
|
|||
return result
|
||||
}
|
||||
|
||||
ReplaceCharsWithSpace (val, char) {
|
||||
ReplaceCharsWithSpace(val, char) {
|
||||
assert(val)
|
||||
assert(char)
|
||||
|
||||
|
@ -86,7 +81,7 @@ class StringUtils {
|
|||
}
|
||||
|
||||
// removes whitespace from begining and and, and replaces multiple spaces with one space
|
||||
RemoveUnnecesarySpaces (toremove) {
|
||||
RemoveUnnecesarySpaces(toremove) {
|
||||
assert(toremove)
|
||||
|
||||
toremove = this.NormalizeSpaces(toremove)
|
||||
|
@ -97,34 +92,41 @@ class StringUtils {
|
|||
}
|
||||
|
||||
// simplifies a string for easier comparison
|
||||
SimplifyStringForComparison (value) {
|
||||
SimplifyStringForComparison(value) {
|
||||
assert(value)
|
||||
|
||||
value = this.RemoveUnnecesarySpaces(value).toLowerCase()
|
||||
return this.RemoveStuff(value, commonUselessStringParts)
|
||||
}
|
||||
|
||||
RemoveSpecialChars (value) {
|
||||
RemoveSpecialChars(value) {
|
||||
assert(value)
|
||||
|
||||
return this.RemoveStuff(value, specialChars, ' ')
|
||||
}
|
||||
|
||||
// if the value is empty, or whitespace
|
||||
EmptyOrWhiteSpace (value) {
|
||||
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
|
||||
NormalizeSpaces (input) {
|
||||
NormalizeSpaces(input) {
|
||||
assert(input)
|
||||
|
||||
return input.replace(/\s/g, ' ')
|
||||
}
|
||||
|
||||
CompareString (s1, s2) {
|
||||
CompareString(s1, s2) {
|
||||
if (!s1 || !s2) {
|
||||
if (!s1 && !s2) {
|
||||
return 100
|
||||
|
@ -137,24 +139,27 @@ 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) {
|
||||
AnswerPreProcessor(value) {
|
||||
assert(value)
|
||||
|
||||
return this.RemoveStuff(
|
||||
value, commonUselessAnswerParts)
|
||||
return this.RemoveStuff(value, commonUselessAnswerParts)
|
||||
}
|
||||
|
||||
// 'a. pécsi sör' -> 'pécsi sör'
|
||||
RemoveAnswerLetters (value) {
|
||||
RemoveAnswerLetters(value) {
|
||||
assert(value)
|
||||
|
||||
let s = value.split('. ')
|
||||
|
@ -166,8 +171,10 @@ class StringUtils {
|
|||
}
|
||||
}
|
||||
|
||||
SimplifyQA (value, mods) {
|
||||
if (!value) { return }
|
||||
SimplifyQA(value, mods) {
|
||||
if (!value) {
|
||||
return
|
||||
}
|
||||
|
||||
const reducer = (res, fn) => {
|
||||
return fn(res)
|
||||
|
@ -176,27 +183,23 @@ class StringUtils {
|
|||
return mods.reduce(reducer, value)
|
||||
}
|
||||
|
||||
SimplifyAnswer (value) {
|
||||
return this.SimplifyQA(
|
||||
value,
|
||||
[
|
||||
this.RemoveSpecialChars.bind(this),
|
||||
this.RemoveUnnecesarySpaces.bind(this),
|
||||
this.AnswerPreProcessor.bind(this),
|
||||
this.RemoveAnswerLetters.bind(this)
|
||||
])
|
||||
SimplifyAnswer(value) {
|
||||
return this.SimplifyQA(value, [
|
||||
this.RemoveSpecialChars.bind(this),
|
||||
this.RemoveUnnecesarySpaces.bind(this),
|
||||
this.AnswerPreProcessor.bind(this),
|
||||
this.RemoveAnswerLetters.bind(this),
|
||||
])
|
||||
}
|
||||
|
||||
SimplifyQuestion (value) {
|
||||
return this.SimplifyQA(
|
||||
value,
|
||||
[
|
||||
this.RemoveSpecialChars.bind(this),
|
||||
this.RemoveUnnecesarySpaces.bind(this)
|
||||
])
|
||||
SimplifyQuestion(value) {
|
||||
return this.SimplifyQA(value, [
|
||||
this.RemoveSpecialChars.bind(this),
|
||||
this.RemoveUnnecesarySpaces.bind(this),
|
||||
])
|
||||
}
|
||||
|
||||
SimplifyStack (stack) {
|
||||
SimplifyStack(stack) {
|
||||
return this.SimplifyQuery(stack)
|
||||
}
|
||||
}
|
||||
|
@ -204,13 +207,13 @@ class StringUtils {
|
|||
const SUtils = new StringUtils()
|
||||
|
||||
class Question {
|
||||
constructor (q, a, data) {
|
||||
constructor(q, a, data) {
|
||||
this.Q = SUtils.SimplifyQuestion(q)
|
||||
this.A = SUtils.SimplifyAnswer(a)
|
||||
this.data = { ...data }
|
||||
}
|
||||
|
||||
toString () {
|
||||
toString() {
|
||||
if (this.data.type !== 'simple') {
|
||||
return '?' + this.Q + '\n!' + this.A + '\n>' + JSON.stringify(this.data)
|
||||
} else {
|
||||
|
@ -218,28 +221,31 @@ class Question {
|
|||
}
|
||||
}
|
||||
|
||||
HasQuestion () {
|
||||
HasQuestion() {
|
||||
return this.Q !== undefined
|
||||
}
|
||||
|
||||
HasAnswer () {
|
||||
HasAnswer() {
|
||||
return this.A !== undefined
|
||||
}
|
||||
|
||||
HasImage () {
|
||||
HasImage() {
|
||||
return this.data.type === 'image'
|
||||
}
|
||||
|
||||
IsComplete () {
|
||||
IsComplete() {
|
||||
return this.HasQuestion() && this.HasAnswer()
|
||||
}
|
||||
|
||||
CompareImage (data2) {
|
||||
return SUtils.CompareString(this.data.images.join(' '), data2.images.join(' '))
|
||||
CompareImage(data2) {
|
||||
return SUtils.CompareString(
|
||||
this.data.images.join(' '),
|
||||
data2.images.join(' ')
|
||||
)
|
||||
}
|
||||
|
||||
// returns -1 if botth is simple
|
||||
CompareData (qObj) {
|
||||
CompareData(qObj) {
|
||||
try {
|
||||
if (qObj.data.type === this.data.type) {
|
||||
let dataType = qObj.data.type
|
||||
|
@ -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 {
|
||||
|
@ -262,22 +272,22 @@ class Question {
|
|||
return 0
|
||||
}
|
||||
|
||||
CompareQuestion (qObj) {
|
||||
CompareQuestion(qObj) {
|
||||
return SUtils.CompareString(this.Q, qObj.Q)
|
||||
}
|
||||
|
||||
CompareAnswer (qObj) {
|
||||
CompareAnswer(qObj) {
|
||||
return SUtils.CompareString(this.A, qObj.A)
|
||||
}
|
||||
|
||||
Compare (q2, data) {
|
||||
Compare(q2, data) {
|
||||
assert(q2)
|
||||
let qObj
|
||||
|
||||
if (typeof q2 === 'string') {
|
||||
qObj = {
|
||||
Q: q2,
|
||||
data: data
|
||||
data: data,
|
||||
}
|
||||
} else {
|
||||
qObj = q2
|
||||
|
@ -307,42 +317,42 @@ class Question {
|
|||
qMatch: qMatch,
|
||||
aMatch: aMatch,
|
||||
dMatch: dMatch,
|
||||
avg: avg
|
||||
avg: avg,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Subject {
|
||||
constructor (n) {
|
||||
constructor(n) {
|
||||
assert(n)
|
||||
|
||||
this.Name = n
|
||||
this.Questions = []
|
||||
}
|
||||
|
||||
setIndex (i) {
|
||||
setIndex(i) {
|
||||
this.index = i
|
||||
}
|
||||
|
||||
getIndex () {
|
||||
getIndex() {
|
||||
return this.index
|
||||
}
|
||||
|
||||
get length () {
|
||||
get length() {
|
||||
return this.Questions.length
|
||||
}
|
||||
|
||||
AddQuestion (q) {
|
||||
AddQuestion(q) {
|
||||
assert(q)
|
||||
|
||||
this.Questions.push(q)
|
||||
}
|
||||
|
||||
getSubjNameWithoutYear () {
|
||||
getSubjNameWithoutYear() {
|
||||
return SUtils.GetSubjNameWithoutYear(this.Name)
|
||||
}
|
||||
|
||||
getYear () {
|
||||
getYear() {
|
||||
let t = this.Name.split(' - ')[0]
|
||||
if (t.match(/^[0-9]{4}\/[0-9]{2}\/[0-9]{1}$/i)) {
|
||||
return t
|
||||
|
@ -351,7 +361,7 @@ class Subject {
|
|||
}
|
||||
}
|
||||
|
||||
Search (q, data) {
|
||||
Search(q, data) {
|
||||
assert(q)
|
||||
|
||||
var r = []
|
||||
|
@ -361,7 +371,7 @@ class Subject {
|
|||
r.push({
|
||||
q: this.Questions[i],
|
||||
match: percent.avg,
|
||||
detailedMatch: percent
|
||||
detailedMatch: percent,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -379,30 +389,36 @@ class Subject {
|
|||
return r
|
||||
}
|
||||
|
||||
toString () {
|
||||
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')
|
||||
}
|
||||
}
|
||||
|
||||
class QuestionDB {
|
||||
constructor () {
|
||||
constructor() {
|
||||
this.Subjects = []
|
||||
}
|
||||
|
||||
get length () {
|
||||
get length() {
|
||||
return this.Subjects.length
|
||||
}
|
||||
|
||||
AddQuestion (subj, q) {
|
||||
AddQuestion(subj, q) {
|
||||
debugLog('Adding new question with subjName: ' + subj, 'qdb add', 1)
|
||||
debugLog(q, 'qdb add', 3)
|
||||
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++
|
||||
}
|
||||
|
||||
|
@ -417,7 +433,7 @@ class QuestionDB {
|
|||
}
|
||||
}
|
||||
|
||||
SimplifyQuestion (q) {
|
||||
SimplifyQuestion(q) {
|
||||
if (typeof q === 'string') {
|
||||
return SUtils.SimplifyQuestion(q)
|
||||
} else {
|
||||
|
@ -427,7 +443,7 @@ class QuestionDB {
|
|||
}
|
||||
}
|
||||
|
||||
Search (q, subjName, data) {
|
||||
Search(q, subjName, data) {
|
||||
assert(q)
|
||||
debugLog('Searching for question', 'qdb search', 1)
|
||||
debugLog('Question:', 'qdb search', 2)
|
||||
|
@ -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!`)
|
||||
}
|
||||
}
|
||||
|
@ -479,11 +507,13 @@ class QuestionDB {
|
|||
return r
|
||||
}
|
||||
|
||||
AddSubject (subj) {
|
||||
AddSubject(subj) {
|
||||
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)
|
||||
|
@ -492,9 +522,11 @@ class QuestionDB {
|
|||
}
|
||||
}
|
||||
|
||||
toString () {
|
||||
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')
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@ CreateDB()
|
|||
|
||||
authDB.close()
|
||||
|
||||
function CreateDB () {
|
||||
function CreateDB() {
|
||||
const dbStruct = utils.ReadJSON(dbStructPath)
|
||||
// authDB = dbtools.GetDB(':memory:')
|
||||
authDB = dbtools.GetDB(usersDBPath)
|
||||
|
@ -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({
|
||||
tableInfo: dbtools.TableInfo(authDB, key),
|
||||
tableRows: dbtools.SelectAll(authDB, key)
|
||||
}), path)
|
||||
utils.WriteFile(
|
||||
JSON.stringify({
|
||||
tableInfo: dbtools.TableInfo(authDB, key),
|
||||
tableRows: dbtools.SelectAll(authDB, key),
|
||||
}),
|
||||
path
|
||||
)
|
||||
})
|
||||
|
||||
logger.Log('Done')
|
||||
|
|
|
@ -11,7 +11,7 @@ module.exports = {
|
|||
SelectAll,
|
||||
Select,
|
||||
Insert,
|
||||
CloseDB
|
||||
CloseDB,
|
||||
}
|
||||
|
||||
const Sqlite = require('better-sqlite3')
|
||||
|
@ -21,7 +21,7 @@ const utils = require('../utils/utils.js')
|
|||
const debugLog = process.env.NS_SQL_DEBUG_LOG
|
||||
|
||||
// { asd: 'asd', basd: 4 } => asd = 'asd', basd = 4
|
||||
function GetSqlQuerry (conditions, type) {
|
||||
function GetSqlQuerry(conditions, type) {
|
||||
const res = Object.keys(conditions).reduce((acc, key) => {
|
||||
const item = conditions[key]
|
||||
if (typeof item === 'string') {
|
||||
|
@ -40,20 +40,20 @@ function GetSqlQuerry (conditions, type) {
|
|||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function GetDB (path) {
|
||||
function GetDB(path) {
|
||||
utils.CreatePath(path)
|
||||
const res = new Sqlite(path)
|
||||
res.pragma('synchronous = OFF')
|
||||
return res
|
||||
}
|
||||
|
||||
function DebugLog (msg) {
|
||||
function DebugLog(msg) {
|
||||
if (debugLog) {
|
||||
logger.DebugLog(msg, 'sql', 0)
|
||||
}
|
||||
}
|
||||
|
||||
function AddColumn (db, table, col) {
|
||||
function AddColumn(db, table, col) {
|
||||
try {
|
||||
const colName = Object.keys(col)[0]
|
||||
const colType = col.type
|
||||
|
@ -67,9 +67,8 @@ function AddColumn (db, table, col) {
|
|||
}
|
||||
}
|
||||
|
||||
function TableInfo (db, table) {
|
||||
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) {
|
||||
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()
|
||||
|
@ -100,7 +102,7 @@ function Update (db, table, newData, conditions) {
|
|||
}
|
||||
}
|
||||
|
||||
function Delete (db, table, conditions) {
|
||||
function Delete(db, table, conditions) {
|
||||
try {
|
||||
const s = `DELETE FROM ${table} WHERE ${GetSqlQuerry(conditions, 'where')}`
|
||||
const stmt = PrepareStatement(db, s)
|
||||
|
@ -111,39 +113,45 @@ function Delete (db, table, conditions) {
|
|||
}
|
||||
}
|
||||
|
||||
function CreateTable (db, name, columns, foreignKeys) {
|
||||
function CreateTable(db, name, columns, foreignKeys) {
|
||||
// CREATE TABLE users(pw text PRIMARY KEY NOT NULL, id number, lastIP text, notes text, loginCount
|
||||
// number, lastLogin text, lastAccess text
|
||||
//
|
||||
// FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist, albumname) )
|
||||
|
||||
try {
|
||||
const cols = Object.keys(columns).reduce((acc, key) => {
|
||||
const item = columns[key]
|
||||
// FIXME: array, and push stuff, then join()
|
||||
const flags = []
|
||||
const toCheck = {
|
||||
primary: 'PRIMARY KEY',
|
||||
notNull: 'NOT NULL',
|
||||
unique: 'UNIQUE',
|
||||
autoIncrement: 'AUTOINCREMENT',
|
||||
defaultZero: 'DEFAULT 0'
|
||||
}
|
||||
Object.keys(toCheck).forEach((key) => {
|
||||
if (item[key]) {
|
||||
flags.push(toCheck[key])
|
||||
const cols = Object.keys(columns)
|
||||
.reduce((acc, key) => {
|
||||
const item = columns[key]
|
||||
// FIXME: array, and push stuff, then join()
|
||||
const flags = []
|
||||
const toCheck = {
|
||||
primary: 'PRIMARY KEY',
|
||||
notNull: 'NOT NULL',
|
||||
unique: 'UNIQUE',
|
||||
autoIncrement: 'AUTOINCREMENT',
|
||||
defaultZero: 'DEFAULT 0',
|
||||
}
|
||||
})
|
||||
Object.keys(toCheck).forEach((key) => {
|
||||
if (item[key]) {
|
||||
flags.push(toCheck[key])
|
||||
}
|
||||
})
|
||||
|
||||
acc.push(`${key} ${item.type} ${flags.join(' ')}`)
|
||||
return acc
|
||||
}, []).join(', ')
|
||||
acc.push(`${key} ${item.type} ${flags.join(' ')}`)
|
||||
return acc
|
||||
}, [])
|
||||
.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(', ')})`
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -156,7 +164,7 @@ function CreateTable (db, name, columns, foreignKeys) {
|
|||
}
|
||||
}
|
||||
|
||||
function SelectAll (db, from) {
|
||||
function SelectAll(db, from) {
|
||||
try {
|
||||
const s = `SELECT * from ${from}`
|
||||
|
||||
|
@ -167,7 +175,7 @@ function SelectAll (db, from) {
|
|||
}
|
||||
}
|
||||
|
||||
function Select (db, from, conditions) {
|
||||
function Select(db, from, conditions) {
|
||||
try {
|
||||
const s = `SELECT * from ${from} WHERE ${GetSqlQuerry(conditions, 'where')}`
|
||||
|
||||
|
@ -178,22 +186,26 @@ function Select (db, from, conditions) {
|
|||
}
|
||||
}
|
||||
|
||||
function Insert (db, table, data) {
|
||||
function Insert(db, table, data) {
|
||||
try {
|
||||
const cols = Object.keys(data).reduce((acc, key) => {
|
||||
acc.push(`${key}`)
|
||||
return acc
|
||||
}, []).join(', ')
|
||||
const cols = Object.keys(data)
|
||||
.reduce((acc, key) => {
|
||||
acc.push(`${key}`)
|
||||
return acc
|
||||
}, [])
|
||||
.join(', ')
|
||||
|
||||
const values = Object.keys(data).reduce((acc, key) => {
|
||||
const item = data[key]
|
||||
if (typeof item === 'string') {
|
||||
acc.push(`'${item}'`)
|
||||
} else {
|
||||
acc.push(`${item}`)
|
||||
}
|
||||
return acc
|
||||
}, []).join(', ')
|
||||
const values = Object.keys(data)
|
||||
.reduce((acc, key) => {
|
||||
const item = data[key]
|
||||
if (typeof item === 'string') {
|
||||
acc.push(`'${item}'`)
|
||||
} else {
|
||||
acc.push(`${item}`)
|
||||
}
|
||||
return acc
|
||||
}, [])
|
||||
.join(', ')
|
||||
|
||||
const s = `INSERT INTO ${table} (${cols}) VALUES (${values})`
|
||||
const stmt = PrepareStatement(db, s)
|
||||
|
@ -204,7 +216,7 @@ function Insert (db, table, data) {
|
|||
}
|
||||
}
|
||||
|
||||
function CloseDB (db) {
|
||||
function CloseDB(db) {
|
||||
db.close((err) => {
|
||||
if (err) {
|
||||
return console.error(err.message)
|
||||
|
@ -215,9 +227,11 @@ function CloseDB (db) {
|
|||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
function PrepareStatement (db, s) {
|
||||
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)
|
||||
|
|
|
@ -20,7 +20,7 @@
|
|||
|
||||
module.exports = {
|
||||
LogId: LogId,
|
||||
Load: Load
|
||||
Load: Load,
|
||||
}
|
||||
|
||||
const utils = require('../utils/utils.js')
|
||||
|
@ -34,12 +34,15 @@ let data = {}
|
|||
let vData = {}
|
||||
let writes = 0
|
||||
|
||||
function Load () {
|
||||
function Load() {
|
||||
try {
|
||||
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,50 +50,60 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
function LogId (id, subj) {
|
||||
function LogId(id, subj) {
|
||||
Inc(id, subj)
|
||||
AddVisitStat(id, subj)
|
||||
Save()
|
||||
}
|
||||
|
||||
function AddSubjToList (list, subj) {
|
||||
function AddSubjToList(list, subj) {
|
||||
if (!list[subj]) {
|
||||
list[subj] = 0
|
||||
}
|
||||
list[subj]++
|
||||
}
|
||||
|
||||
function Inc (value, subj) {
|
||||
function Inc(value, subj) {
|
||||
if (data[value] === undefined) {
|
||||
data[value] = {
|
||||
count: 0,
|
||||
subjs: {}
|
||||
subjs: {},
|
||||
}
|
||||
}
|
||||
data[value].count++
|
||||
AddSubjToList(data[value].subjs, subj)
|
||||
}
|
||||
|
||||
function AddVisitStat (name, 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++
|
||||
AddSubjToList(vData[now][name].subjs, subj)
|
||||
}
|
||||
|
||||
function Save () {
|
||||
function Save() {
|
||||
writes++
|
||||
if (writes === writeInterval) {
|
||||
try {
|
||||
|
|
|
@ -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
|
||||
|
@ -66,19 +60,21 @@ let writes = 0
|
|||
|
||||
let noLogips = []
|
||||
|
||||
function GetDateString () {
|
||||
function GetDateString() {
|
||||
const m = new Date()
|
||||
const d = utils.GetDateString()
|
||||
return GetRandomColor(m.getHours().toString()) + d + C()
|
||||
}
|
||||
|
||||
function DebugLog (msg, name, lvl) {
|
||||
function DebugLog(msg, name, lvl) {
|
||||
if (lvl <= debugLevel) {
|
||||
if (msg === 'hr') {
|
||||
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 {
|
||||
|
@ -89,7 +85,7 @@ function DebugLog (msg, name, lvl) {
|
|||
}
|
||||
}
|
||||
|
||||
function Log (s, c) {
|
||||
function Log(s, c) {
|
||||
let log = s
|
||||
if (typeof s !== 'object') {
|
||||
let dl = DELIM + C(c)
|
||||
|
@ -100,7 +96,7 @@ function Log (s, c) {
|
|||
utils.AppendToFile(log, logFile)
|
||||
}
|
||||
|
||||
function LogReq (req, toFile, sc) {
|
||||
function LogReq(req, toFile, sc) {
|
||||
try {
|
||||
let ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
|
||||
|
||||
|
@ -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) {
|
||||
|
@ -156,7 +155,7 @@ function LogReq (req, toFile, sc) {
|
|||
}
|
||||
}
|
||||
|
||||
function parseNoLogFile (newData) {
|
||||
function parseNoLogFile(newData) {
|
||||
noLogips = newData.split('\n')
|
||||
if (noLogips[noLogips.length - 1] === '') {
|
||||
noLogips.pop()
|
||||
|
@ -167,7 +166,7 @@ function parseNoLogFile (newData) {
|
|||
Log('\tNo Log IP-s changed: ' + noLogips.join(', '))
|
||||
}
|
||||
|
||||
function setNoLogReadInterval () {
|
||||
function setNoLogReadInterval() {
|
||||
utils.WatchFile(nologFile, (newData) => {
|
||||
parseNoLogFile(newData)
|
||||
})
|
||||
|
@ -175,7 +174,7 @@ function setNoLogReadInterval () {
|
|||
parseNoLogFile(utils.ReadFile(nologFile))
|
||||
}
|
||||
|
||||
function Load () {
|
||||
function Load() {
|
||||
Log('Loading logger...')
|
||||
try {
|
||||
uData = JSON.parse(utils.ReadFile(uStatsFile))
|
||||
|
@ -203,13 +202,16 @@ 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()
|
||||
}
|
||||
|
||||
function LogStat (url, ip, hostname, userId) {
|
||||
function LogStat(url, ip, hostname, userId) {
|
||||
let nolog = noLogips.some((x) => {
|
||||
return x.includes(ip)
|
||||
})
|
||||
|
@ -225,9 +227,11 @@ function LogStat (url, ip, hostname, userId) {
|
|||
Save()
|
||||
}
|
||||
|
||||
function IncUserStat (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'))
|
||||
|
@ -235,12 +239,21 @@ function IncUserStat (userId) {
|
|||
}
|
||||
}
|
||||
|
||||
function AddUserIdStat (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'))
|
||||
|
@ -248,21 +261,34 @@ function AddUserIdStat (userId) {
|
|||
}
|
||||
}
|
||||
|
||||
function Inc (value) {
|
||||
if (value.startsWith('/?')) { value = '/' }
|
||||
if (data[value] === undefined) { data[value] = 0 }
|
||||
function Inc(value) {
|
||||
if (value.startsWith('/?')) {
|
||||
value = '/'
|
||||
}
|
||||
if (data[value] === undefined) {
|
||||
data[value] = 0
|
||||
}
|
||||
data[value]++
|
||||
}
|
||||
|
||||
function AddVisitStat (name) {
|
||||
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]++
|
||||
}
|
||||
|
||||
function Save () {
|
||||
function Save() {
|
||||
writes++
|
||||
if (writes === writeInterval) {
|
||||
try {
|
||||
|
@ -295,11 +321,11 @@ function Save () {
|
|||
}
|
||||
}
|
||||
|
||||
function logHashed (x) {
|
||||
function logHashed(x) {
|
||||
return GetRandomColor(x.toString()) + x + C()
|
||||
}
|
||||
|
||||
function GetRandomColor (ip) {
|
||||
function GetRandomColor(ip) {
|
||||
if (!ip) {
|
||||
return 'red'
|
||||
}
|
||||
|
@ -310,20 +336,38 @@ function GetRandomColor (ip) {
|
|||
return C(colors[res % colors.length])
|
||||
}
|
||||
|
||||
function GetColor (c) {
|
||||
function GetColor(c) {
|
||||
return c
|
||||
}
|
||||
|
||||
function C (c) {
|
||||
if (c !== undefined) { c = c.toLowerCase() }
|
||||
function C(c) {
|
||||
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'
|
||||
}
|
||||
|
|
|
@ -17,6 +17,6 @@ utils.WriteFile(JSON.stringify(parsed), dataFile)
|
|||
|
||||
utils.WriteFile(parsed.motd, motdFile)
|
||||
|
||||
function GetParams () {
|
||||
function GetParams() {
|
||||
return process.argv.splice(2)
|
||||
}
|
||||
|
|
|
@ -30,7 +30,7 @@ const logPath = './mergeLogs/mergelog_' + GetDateString().replace(/ /g, '_')
|
|||
|
||||
Main()
|
||||
|
||||
function Main () {
|
||||
function Main() {
|
||||
const params = GetParams()
|
||||
console.log(params)
|
||||
if (params.length === 0) {
|
||||
|
@ -59,7 +59,7 @@ function Main () {
|
|||
console.log(C('green') + 'Done' + C())
|
||||
}
|
||||
|
||||
function LogStats (stats, oldData, newData) {
|
||||
function LogStats(stats, oldData, newData) {
|
||||
const maxSubjNameLength = MaxLengthOf(stats, 'name')
|
||||
const maxPrevLength = MaxLengthOf(stats, 'prevQuestions')
|
||||
const maxAddedLength = MaxLengthOf(stats, 'addedQuestions')
|
||||
|
@ -97,16 +97,25 @@ function LogStats (stats, oldData, newData) {
|
|||
LogDataCount(newData)
|
||||
}
|
||||
|
||||
function LogDataCount (data) {
|
||||
function LogDataCount(data) {
|
||||
const subjLength = data.Subjects.length
|
||||
const qLength = data.Subjects.reduce((acc, subj) => {
|
||||
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) {
|
||||
function PrintDB(data) {
|
||||
const maxSubjNameLength = MaxLengthOf(data.Subjects, 'Name')
|
||||
|
||||
data.Subjects.forEach((subj) => {
|
||||
|
@ -127,7 +136,7 @@ function PrintDB (data) {
|
|||
console.log(hr())
|
||||
}
|
||||
|
||||
function GetExactLength (s, length) {
|
||||
function GetExactLength(s, length) {
|
||||
let toLog = s.toString()
|
||||
const lengthDiff = length - toLog.length
|
||||
for (let i = 0; i < lengthDiff; i++) {
|
||||
|
@ -137,7 +146,7 @@ function GetExactLength (s, length) {
|
|||
return toLog
|
||||
}
|
||||
|
||||
function MaxLengthOf (prop, key) {
|
||||
function MaxLengthOf(prop, key) {
|
||||
return prop.reduce((acc, currStat) => {
|
||||
if (acc < currStat[key].toString().length) {
|
||||
acc = currStat[key].toString().length
|
||||
|
@ -146,13 +155,14 @@ function MaxLengthOf (prop, key) {
|
|||
}, 0)
|
||||
}
|
||||
|
||||
function RemoveDuplicates (data) {
|
||||
function RemoveDuplicates(data) {
|
||||
console.log(C('yellow') + 'Removing duplicates' + C())
|
||||
const res = new classes.QuestionDB()
|
||||
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,53 +195,53 @@ function RemoveDuplicates (data) {
|
|||
name: subj.Name,
|
||||
prevQuestions: subj.Questions.length,
|
||||
addedQuestions: addedQuestions,
|
||||
removedQuestions: removedQuestions
|
||||
removedQuestions: removedQuestions,
|
||||
})
|
||||
})
|
||||
return { res, stats }
|
||||
}
|
||||
|
||||
function LogSubjProgress (i, subj, subjCount) {
|
||||
function LogSubjProgress(i, subj, subjCount) {
|
||||
log(
|
||||
'[ ' +
|
||||
C('cyan') +
|
||||
(i + 1) +
|
||||
C() +
|
||||
' / ' +
|
||||
C('green') +
|
||||
subjCount +
|
||||
C() +
|
||||
' ] ' +
|
||||
C('yellow') +
|
||||
subj.Name +
|
||||
C() +
|
||||
': ' +
|
||||
C('green') +
|
||||
subj.Questions.length
|
||||
C('cyan') +
|
||||
(i + 1) +
|
||||
C() +
|
||||
' / ' +
|
||||
C('green') +
|
||||
subjCount +
|
||||
C() +
|
||||
' ] ' +
|
||||
C('yellow') +
|
||||
subj.Name +
|
||||
C() +
|
||||
': ' +
|
||||
C('green') +
|
||||
subj.Questions.length
|
||||
)
|
||||
}
|
||||
|
||||
function LogResultProgress (subj, addedQuestions, removedQuestions) {
|
||||
function LogResultProgress(subj, addedQuestions, removedQuestions) {
|
||||
log(
|
||||
' ' +
|
||||
C('cyan') +
|
||||
'-> ' +
|
||||
C('green') +
|
||||
addedQuestions +
|
||||
C() +
|
||||
', removed: ' +
|
||||
C('red') +
|
||||
removedQuestions +
|
||||
C() +
|
||||
'\n'
|
||||
C('cyan') +
|
||||
'-> ' +
|
||||
C('green') +
|
||||
addedQuestions +
|
||||
C() +
|
||||
', removed: ' +
|
||||
C('red') +
|
||||
removedQuestions +
|
||||
C() +
|
||||
'\n'
|
||||
)
|
||||
}
|
||||
|
||||
function log (msg) {
|
||||
function log(msg) {
|
||||
process.stdout.write(msg)
|
||||
}
|
||||
|
||||
function hr (char) {
|
||||
function hr(char) {
|
||||
let h = ''
|
||||
const cols = process.stdout.columns || 20
|
||||
for (let i = 0; i < cols; i++) {
|
||||
|
@ -240,21 +250,27 @@ function hr (char) {
|
|||
return h
|
||||
}
|
||||
|
||||
function C (color) {
|
||||
function C(color) {
|
||||
return logger.C(color)
|
||||
}
|
||||
|
||||
function GetParams () {
|
||||
function GetParams() {
|
||||
return process.argv.splice(2)
|
||||
}
|
||||
|
||||
function GetDateString () {
|
||||
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
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ module.exports = {
|
|||
WatchFile: WatchFile,
|
||||
ReadDir: ReadDir,
|
||||
CopyFile: CopyFile,
|
||||
GetDateString: GetDateString
|
||||
GetDateString: GetDateString,
|
||||
}
|
||||
|
||||
var fs = require('fs')
|
||||
|
@ -20,26 +20,33 @@ var logger = require('../utils/logger.js')
|
|||
|
||||
const dataFile = './qminingPublic/data.json'
|
||||
|
||||
function GetDateString () {
|
||||
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) {
|
||||
function CopyFile(from, to) {
|
||||
CreatePath(to)
|
||||
fs.copyFileSync(from, to)
|
||||
}
|
||||
|
||||
function ReadDir (path) {
|
||||
function ReadDir(path) {
|
||||
return fs.readdirSync(path)
|
||||
}
|
||||
|
||||
function ReadJSON (name) {
|
||||
function ReadJSON(name) {
|
||||
try {
|
||||
return JSON.parse(ReadFile(name))
|
||||
} catch (e) {
|
||||
|
@ -48,16 +55,18 @@ function ReadJSON (name) {
|
|||
}
|
||||
}
|
||||
|
||||
function ReadFile (name) {
|
||||
if (!FileExists(name)) { throw new Error('No such file: ' + name) }
|
||||
function ReadFile(name) {
|
||||
if (!FileExists(name)) {
|
||||
throw new Error('No such file: ' + name)
|
||||
}
|
||||
return fs.readFileSync(name, 'utf8')
|
||||
}
|
||||
|
||||
function FileExists (path) {
|
||||
function FileExists(path) {
|
||||
return fs.existsSync(path)
|
||||
}
|
||||
|
||||
function WatchFile (file, callback) {
|
||||
function WatchFile(file, callback) {
|
||||
if (FileExists(file)) {
|
||||
fs.watchFile(file, (curr, prev) => {
|
||||
fs.readFile(file, 'utf8', (err, data) => {
|
||||
|
@ -76,8 +85,10 @@ function WatchFile (file, callback) {
|
|||
}
|
||||
}
|
||||
|
||||
function CreatePath (path, onlyPath) {
|
||||
if (FileExists(path)) { return }
|
||||
function CreatePath(path, onlyPath) {
|
||||
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]
|
||||
}
|
||||
|
@ -95,32 +108,38 @@ function CreatePath (path, onlyPath) {
|
|||
}
|
||||
}
|
||||
|
||||
function WriteFile (content, path) {
|
||||
function WriteFile(content, path) {
|
||||
CreatePath(path)
|
||||
fs.writeFileSync(path, content)
|
||||
}
|
||||
|
||||
function WriteFileAsync (content, path) {
|
||||
function WriteFileAsync(content, path) {
|
||||
CreatePath(path)
|
||||
fs.writeFile(path, content, function (err) {
|
||||
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')
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function AppendToFile (data, file) {
|
||||
function AppendToFile(data, file) {
|
||||
CreatePath(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)
|
||||
}
|
||||
}
|
||||
|
||||
function Beep () {
|
||||
function Beep() {
|
||||
try {
|
||||
process.stdout.write('\x07')
|
||||
} catch (e) {
|
||||
|
@ -128,9 +147,12 @@ function Beep () {
|
|||
}
|
||||
}
|
||||
|
||||
function WriteBackup () {
|
||||
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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue