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
|
@ -54,7 +54,7 @@ let userDB
|
|||
let url // eslint-disable-line
|
||||
let publicdirs = []
|
||||
|
||||
function GetApp () {
|
||||
function GetApp() {
|
||||
const p = publicdirs[0]
|
||||
if (!p) {
|
||||
throw new Error(`No public dir! ( API )`)
|
||||
|
@ -67,62 +67,67 @@ function GetApp () {
|
|||
const motdFile = p + 'motd'
|
||||
const versionFile = p + 'version'
|
||||
|
||||
app.use(bodyParser.urlencoded({
|
||||
limit: '10mb',
|
||||
extended: true
|
||||
}))
|
||||
app.use(bodyParser.json({
|
||||
limit: '10mb'
|
||||
}))
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
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({
|
||||
userDB: userDB,
|
||||
jsonResponse: true,
|
||||
exceptions: [
|
||||
'/favicon.ico',
|
||||
'/login',
|
||||
'/getveteranpw',
|
||||
'/postfeedbackfile',
|
||||
'/postfeedback',
|
||||
'/fosuploader',
|
||||
'/badtestsender'
|
||||
]
|
||||
}))
|
||||
app.set('views', ['./modules/api/views', './sharedViews'])
|
||||
app.use(
|
||||
auth({
|
||||
userDB: userDB,
|
||||
jsonResponse: true,
|
||||
exceptions: [
|
||||
'/favicon.ico',
|
||||
'/login',
|
||||
'/getveteranpw',
|
||||
'/postfeedbackfile',
|
||||
'/postfeedback',
|
||||
'/fosuploader',
|
||||
'/badtestsender',
|
||||
],
|
||||
})
|
||||
)
|
||||
publicdirs.forEach((pdir) => {
|
||||
logger.Log(`Using public dir: ${pdir}`)
|
||||
app.use(express.static(pdir))
|
||||
})
|
||||
app.use(busboy({
|
||||
limits: {
|
||||
fileSize: 50000 * 1024 * 1024
|
||||
}
|
||||
}))
|
||||
app.use(
|
||||
busboy({
|
||||
limits: {
|
||||
fileSize: 50000 * 1024 * 1024,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
var data = actions.LoadJSON(dataFile)
|
||||
var version = ''
|
||||
var motd = ''
|
||||
var testUsers = []
|
||||
|
||||
function LoadVersion () {
|
||||
function LoadVersion() {
|
||||
version = utils.ReadFile(versionFile)
|
||||
}
|
||||
|
||||
function LoadMOTD () {
|
||||
function LoadMOTD() {
|
||||
motd = utils.ReadFile(motdFile)
|
||||
}
|
||||
|
||||
function LoadTestUsers () {
|
||||
function LoadTestUsers() {
|
||||
testUsers = utils.ReadJSON(testUsersFile)
|
||||
if (testUsers) {
|
||||
testUsers = testUsers.userIds
|
||||
}
|
||||
}
|
||||
|
||||
function Load () {
|
||||
function Load() {
|
||||
utils.WatchFile(motdFile, (newData) => {
|
||||
logger.Log(`Motd changed: ${newData.replace(/\/n/g, '')}`)
|
||||
LoadMOTD()
|
||||
|
@ -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,11 +243,11 @@ function GetApp () {
|
|||
requestedPWS: user.pwRequestCount,
|
||||
maxPWCount: maxPWCount,
|
||||
// daysAfterUserGetsPWs: daysAfterUserGetsPWs,
|
||||
addPWPerDay: addPWPerDay
|
||||
addPWPerDay: addPWPerDay,
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/getpw', function (req, res) {
|
||||
app.post('/getpw', function(req, res) {
|
||||
logger.LogReq(req)
|
||||
|
||||
const requestingUser = req.session.user
|
||||
|
@ -238,63 +255,83 @@ 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', {
|
||||
avaiblePWRequests: requestingUser.avaiblePWRequests - 1,
|
||||
pwRequestCount: requestingUser.pwRequestCount + 1
|
||||
}, {
|
||||
id: requestingUser.id
|
||||
})
|
||||
dbtools.Update(
|
||||
userDB,
|
||||
'users',
|
||||
{
|
||||
avaiblePWRequests: requestingUser.avaiblePWRequests - 1,
|
||||
pwRequestCount: requestingUser.pwRequestCount + 1,
|
||||
},
|
||||
{
|
||||
id: requestingUser.id,
|
||||
}
|
||||
)
|
||||
|
||||
const pw = uuidv4()
|
||||
const insertRes = dbtools.Insert(userDB, 'users', {
|
||||
pw: pw,
|
||||
avaiblePWRequests: 0,
|
||||
created: utils.GetDateString()
|
||||
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,
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/getveteranpw', function (req, res) {
|
||||
app.post('/getveteranpw', function(req, res) {
|
||||
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', {
|
||||
count: tries.count + 1,
|
||||
lastDate: utils.GetDateString()
|
||||
}, {
|
||||
id: tries.id
|
||||
})
|
||||
dbtools.Update(
|
||||
userDB,
|
||||
'veteranPWRequests',
|
||||
{
|
||||
count: tries.count + 1,
|
||||
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', {
|
||||
loginCount: user.loginCount + 1,
|
||||
lastIP: ip,
|
||||
lastLogin: utils.GetDateString()
|
||||
}, {
|
||||
id: user.id
|
||||
})
|
||||
dbtools.Update(
|
||||
userDB,
|
||||
'users',
|
||||
{
|
||||
loginCount: user.loginCount + 1,
|
||||
lastIP: ip,
|
||||
lastLogin: utils.GetDateString(),
|
||||
},
|
||||
{
|
||||
id: user.id,
|
||||
}
|
||||
)
|
||||
|
||||
dbtools.Insert(userDB, 'sessions', {
|
||||
id: sessionID,
|
||||
ip: ip,
|
||||
userID: user.id,
|
||||
isScript: isScript ? 1 : 0,
|
||||
createDate: utils.GetDateString()
|
||||
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,22 +496,22 @@ 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',
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------
|
||||
|
||||
app.get('/', function (req, res) {
|
||||
app.get('/', function(req, res) {
|
||||
logger.LogReq(req)
|
||||
res.redirect('https://www.youtube.com/watch?v=ieqGJgqiXFk')
|
||||
})
|
||||
|
||||
app.post('/postfeedbackfile', function (req, res) {
|
||||
app.post('/postfeedbackfile', function(req, res) {
|
||||
UploadFile(req, res, uloadFiles, (fn) => {
|
||||
res.json({ success: true })
|
||||
})
|
||||
|
@ -445,43 +520,66 @@ function GetApp () {
|
|||
logger.Log('New feedback file', logger.GetColor('bluebg'), true)
|
||||
})
|
||||
|
||||
app.post('/postfeedback', function (req, res) {
|
||||
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({
|
||||
...req.body,
|
||||
userID: user ? user.id : 'no user',
|
||||
ip: ip
|
||||
}), msgFile)
|
||||
utils.AppendToFile(
|
||||
utils.GetDateString() +
|
||||
':\n' +
|
||||
JSON.stringify({
|
||||
...req.body,
|
||||
userID: user ? user.id : 'no user',
|
||||
ip: ip,
|
||||
}),
|
||||
msgFile
|
||||
)
|
||||
res.json({ success: true })
|
||||
})
|
||||
|
||||
function UploadFile (req, res, path, next) {
|
||||
function UploadFile(req, res, path, next) {
|
||||
try {
|
||||
var fstream
|
||||
req.pipe(req.busboy)
|
||||
req.busboy.on('file', function (fieldname, file, filename) {
|
||||
req.busboy.on('file', function(fieldname, file, filename) {
|
||||
logger.Log('Uploading: ' + filename, logger.GetColor('blue'))
|
||||
|
||||
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'))
|
||||
fstream.on('close', function() {
|
||||
logger.Log(
|
||||
'Upload Finished of ' + path + '/' + fn,
|
||||
logger.GetColor('blue')
|
||||
)
|
||||
next(fn)
|
||||
})
|
||||
fstream.on('error', function (err) {
|
||||
fstream.on('error', function(err) {
|
||||
console.log(err)
|
||||
res.end('something bad happened :s')
|
||||
})
|
||||
|
@ -492,20 +590,20 @@ function GetApp () {
|
|||
}
|
||||
}
|
||||
|
||||
app.route('/fosuploader').post(function (req, res, next) {
|
||||
app.route('/fosuploader').post(function(req, res, next) {
|
||||
UploadFile(req, res, uloadFiles, (fn) => {
|
||||
res.redirect('/f/' + fn)
|
||||
})
|
||||
})
|
||||
|
||||
app.route('/badtestsender').post(function (req, res, next) {
|
||||
app.route('/badtestsender').post(function(req, res, next) {
|
||||
UploadFile(req, res, recivedFiles, (fn) => {
|
||||
res.redirect('back')
|
||||
})
|
||||
logger.LogReq(req)
|
||||
})
|
||||
|
||||
app.get('/allqr.txt', function (req, res) {
|
||||
app.get('/allqr.txt', function(req, res) {
|
||||
res.set('Content-Type', 'text/plain')
|
||||
res.send(data.toString())
|
||||
res.end()
|
||||
|
@ -516,25 +614,25 @@ function GetApp () {
|
|||
// API
|
||||
|
||||
app.post('/uploaddata', (req, res) => {
|
||||
// body: JSON.stringify({
|
||||
// newData: data,
|
||||
// count: getCount(data),
|
||||
// initialCount: initialCount,
|
||||
// password: password,
|
||||
// editedQuestions: editedQuestions
|
||||
// })
|
||||
// body: JSON.stringify({
|
||||
// newData: data,
|
||||
// count: getCount(data),
|
||||
// initialCount: initialCount,
|
||||
// password: password,
|
||||
// editedQuestions: editedQuestions
|
||||
// })
|
||||
|
||||
const { count, initialCount, editedQuestions, password, newData } = req.body
|
||||
const respStatuses = {
|
||||
invalidPass: 'invalidPass',
|
||||
ok: 'ok',
|
||||
error: 'error'
|
||||
error: 'error',
|
||||
}
|
||||
|
||||
logger.LogReq(req)
|
||||
|
||||
try {
|
||||
// finding user
|
||||
// finding user
|
||||
const pwds = JSON.parse(utils.ReadFile(passwordFile))
|
||||
let user = Object.keys(pwds).find((key) => {
|
||||
const u = pwds[key]
|
||||
|
@ -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) {
|
||||
|
@ -581,7 +713,7 @@ function GetApp () {
|
|||
}
|
||||
})
|
||||
|
||||
app.post('/isAdding', function (req, res) {
|
||||
app.post('/isAdding', function(req, res) {
|
||||
logger.LogReq(req)
|
||||
|
||||
const user = req.session.user
|
||||
|
@ -590,27 +722,29 @@ 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(
|
||||
req.body.datatoadd || req.body,
|
||||
data,
|
||||
{ motd, version },
|
||||
dryRun
|
||||
).then((r) => {
|
||||
res.json({
|
||||
success: r !== -1,
|
||||
newQuestions: r
|
||||
actions
|
||||
.ProcessIncomingRequest(
|
||||
req.body.datatoadd || req.body,
|
||||
data,
|
||||
{ motd, version },
|
||||
dryRun
|
||||
)
|
||||
.then((r) => {
|
||||
res.json({
|
||||
success: r !== -1,
|
||||
newQuestions: r,
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
app.get('/ask', function (req, res) {
|
||||
app.get('/ask', function(req, res) {
|
||||
if (Object.keys(req.query).length === 0) {
|
||||
logger.DebugLog(`No query params`, 'ask', 1)
|
||||
res.json({
|
||||
message: `ask something! ?q=[question]&subj=[subject]&data=[question data]. 'subj' is optimal for faster result`,
|
||||
result: [],
|
||||
recievedData: JSON.stringify(req.query),
|
||||
success: false
|
||||
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,35 +773,35 @@ function GetApp () {
|
|||
message: `Invalid question :(`,
|
||||
result: [],
|
||||
recievedData: JSON.stringify(req.query),
|
||||
success: false
|
||||
success: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function getSimplreRes () {
|
||||
function getSimplreRes() {
|
||||
return {
|
||||
subjects: data.length,
|
||||
questions: data.Subjects.reduce((acc, subj) => {
|
||||
return acc + subj.length
|
||||
}, 0)
|
||||
}, 0),
|
||||
}
|
||||
}
|
||||
function getDetailedRes () {
|
||||
function getDetailedRes() {
|
||||
return data.Subjects.map((subj) => {
|
||||
return {
|
||||
name: subj.Name,
|
||||
count: subj.length
|
||||
count: subj.length,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
app.get('/datacount', function (req, res) {
|
||||
app.get('/datacount', function(req, res) {
|
||||
logger.LogReq(req)
|
||||
if (req.query.detailed === 'all') {
|
||||
res.json({
|
||||
detailed: getDetailedRes(),
|
||||
simple: getSimplreRes()
|
||||
simple: getSimplreRes(),
|
||||
})
|
||||
} else if (req.query.detailed) {
|
||||
res.json(getDetailedRes())
|
||||
|
@ -673,12 +810,12 @@ function GetApp () {
|
|||
}
|
||||
})
|
||||
|
||||
app.get('/infos', function (req, res) {
|
||||
app.get('/infos', function(req, res) {
|
||||
const user = req.session.user
|
||||
|
||||
let result = {
|
||||
result: 'success',
|
||||
uid: user.id
|
||||
uid: user.id,
|
||||
}
|
||||
if (req.query.subjinfo) {
|
||||
result.subjinfo = getSimplreRes()
|
||||
|
@ -694,30 +831,38 @@ function GetApp () {
|
|||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
|
||||
app.get('*', function (req, res) {
|
||||
app.get('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
app.post('*', function (req, res) {
|
||||
app.post('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
function ExportDailyDataCount () {
|
||||
function ExportDailyDataCount() {
|
||||
logger.Log('Saving daily data count ...')
|
||||
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)
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
function BackupDB () {
|
||||
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!')
|
||||
})
|
||||
|
@ -727,7 +872,7 @@ function GetApp () {
|
|||
})
|
||||
}
|
||||
|
||||
function IncrementAvaiblePWs () {
|
||||
function IncrementAvaiblePWs() {
|
||||
// FIXME: check this if this is legit and works
|
||||
logger.Log('Incrementing avaible PW-s ...')
|
||||
const users = dbtools.SelectAll(userDB, 'users')
|
||||
|
@ -749,17 +894,27 @@ 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,
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function DailyAction () {
|
||||
function DailyAction() {
|
||||
ExportDailyDataCount()
|
||||
BackupDB()
|
||||
IncrementAvaiblePWs()
|
||||
|
@ -767,7 +922,7 @@ function GetApp () {
|
|||
|
||||
return {
|
||||
dailyAction: DailyAction,
|
||||
app: app
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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": {
|
||||
|
|
|
@ -31,48 +31,51 @@ const logger = require('../../utils/logger.js')
|
|||
let publicdirs = []
|
||||
let url = '' // http(s)//asd.basd
|
||||
|
||||
function GetApp () {
|
||||
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({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024
|
||||
}
|
||||
}))
|
||||
app.use(
|
||||
busboy({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024,
|
||||
},
|
||||
})
|
||||
)
|
||||
app.use(bodyParser.json())
|
||||
app.use(bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true
|
||||
}))
|
||||
app.use(bodyParser.json({
|
||||
limit: '5mb'
|
||||
}))
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true,
|
||||
})
|
||||
)
|
||||
app.use(
|
||||
bodyParser.json({
|
||||
limit: '5mb',
|
||||
})
|
||||
)
|
||||
|
||||
// --------------------------------------------------------------
|
||||
|
||||
app.get('/', function (req, res) {
|
||||
app.get('/', function(req, res) {
|
||||
res.render('main', {
|
||||
siteurl: url
|
||||
siteurl: url,
|
||||
})
|
||||
})
|
||||
|
||||
app.get('*', function (req, res) {
|
||||
app.get('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
app.post('*', function (req, res) {
|
||||
app.post('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
return {
|
||||
app: app
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -41,117 +41,125 @@ try {
|
|||
logger.Log('Couldnt read donate URL file!', logger.GetColor('red'))
|
||||
}
|
||||
|
||||
function GetApp () {
|
||||
app.use(bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true
|
||||
}))
|
||||
app.use(bodyParser.json({
|
||||
limit: '5mb'
|
||||
}))
|
||||
function GetApp() {
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
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({
|
||||
userDB: userDB,
|
||||
jsonResponse: false,
|
||||
exceptions: [
|
||||
'/thanks',
|
||||
'/thanks.html',
|
||||
'/img/thanks.gif',
|
||||
'/install',
|
||||
'/favicon.ico',
|
||||
'/getVeteranPw',
|
||||
'/moodle-test-userscript/stable.user.js',
|
||||
'/donate',
|
||||
'/irc'
|
||||
]
|
||||
}))
|
||||
app.set('views', ['./modules/qmining/views', './sharedViews'])
|
||||
app.use(
|
||||
auth({
|
||||
userDB: userDB,
|
||||
jsonResponse: false,
|
||||
exceptions: [
|
||||
'/thanks',
|
||||
'/thanks.html',
|
||||
'/img/thanks.gif',
|
||||
'/install',
|
||||
'/favicon.ico',
|
||||
'/getVeteranPw',
|
||||
'/moodle-test-userscript/stable.user.js',
|
||||
'/donate',
|
||||
'/irc',
|
||||
],
|
||||
})
|
||||
)
|
||||
publicdirs.forEach((pdir) => {
|
||||
logger.Log(`Using public dir: ${pdir}`)
|
||||
app.use(express.static(pdir))
|
||||
})
|
||||
app.use(express.static(nextdir))
|
||||
app.use(busboy({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024
|
||||
}
|
||||
}))
|
||||
app.use(
|
||||
busboy({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// --------------------------------------------------------------
|
||||
// REDIRECTS
|
||||
// --------------------------------------------------------------
|
||||
|
||||
// to be backwards compatible
|
||||
app.get('/ask', function (req, res) {
|
||||
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) => {
|
||||
app.get(redirect.from, function (req, res) {
|
||||
app.get(redirect.from, function(req, res) {
|
||||
if (!redirect.nolog) {
|
||||
logger.LogReq(req)
|
||||
}
|
||||
|
@ -162,7 +170,7 @@ function GetApp () {
|
|||
|
||||
// --------------------------------------------------------------
|
||||
|
||||
function AddHtmlRoutes (files) {
|
||||
function AddHtmlRoutes(files) {
|
||||
const routes = files.reduce((acc, f) => {
|
||||
if (f.includes('html')) {
|
||||
acc.push(f.split('.')[0])
|
||||
|
@ -173,7 +181,7 @@ function GetApp () {
|
|||
|
||||
routes.forEach((route) => {
|
||||
logger.DebugLog(`Added route /${route}`, 'Qmining routes', 1)
|
||||
app.get(`/${route}`, function (req, res) {
|
||||
app.get(`/${route}`, function(req, res) {
|
||||
logger.LogReq(req)
|
||||
res.redirect(`${route}.html`)
|
||||
})
|
||||
|
@ -183,29 +191,29 @@ function GetApp () {
|
|||
|
||||
// --------------------------------------------------------------
|
||||
|
||||
app.get('/', function (req, res) {
|
||||
app.get('/', function(req, res) {
|
||||
res.end('hai')
|
||||
logger.LogReq(req)
|
||||
})
|
||||
|
||||
app.get('/getVeteranPw', function (req, res) {
|
||||
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)
|
||||
})
|
||||
|
||||
app.get('*', function (req, res) {
|
||||
app.get('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
app.post('*', function (req, res) {
|
||||
app.post('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
return {
|
||||
app: app
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ const utils = require('../../utils/utils.js')
|
|||
// stuff gotten from server.js
|
||||
let publicdirs = []
|
||||
|
||||
function GetApp () {
|
||||
function GetApp() {
|
||||
const p = publicdirs[0]
|
||||
if (!p) {
|
||||
throw new Error(`No public dir! ( SIO )`)
|
||||
|
@ -42,73 +42,86 @@ 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({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024
|
||||
}
|
||||
}))
|
||||
app.use(
|
||||
busboy({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024,
|
||||
},
|
||||
})
|
||||
)
|
||||
app.use(bodyParser.json())
|
||||
app.use(bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true
|
||||
}))
|
||||
app.use(bodyParser.json({
|
||||
limit: '5mb'
|
||||
}))
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true,
|
||||
})
|
||||
)
|
||||
app.use(
|
||||
bodyParser.json({
|
||||
limit: '5mb',
|
||||
})
|
||||
)
|
||||
|
||||
// --------------------------------------------------------------
|
||||
|
||||
app.get('/', function (req, res) {
|
||||
app.get('/', function(req, res) {
|
||||
res.render('uload')
|
||||
res.end()
|
||||
})
|
||||
|
||||
function UploadFile (req, res, path, next) {
|
||||
function UploadFile(req, res, path, next) {
|
||||
var fstream
|
||||
req.pipe(req.busboy)
|
||||
req.busboy.on('file', function (fieldname, file, filename) {
|
||||
req.busboy.on('file', function(fieldname, file, filename) {
|
||||
logger.Log('Uploading: ' + filename, logger.GetColor('blue'))
|
||||
|
||||
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'))
|
||||
fstream.on('close', function() {
|
||||
logger.Log(
|
||||
'Upload Finished of ' + path + '/' + fn,
|
||||
logger.GetColor('blue')
|
||||
)
|
||||
next(fn)
|
||||
})
|
||||
fstream.on('error', function (err) {
|
||||
fstream.on('error', function(err) {
|
||||
console.log(err)
|
||||
res.end('something bad happened :s')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
app.route('/fosuploader').post(function (req, res, next) {
|
||||
app.route('/fosuploader').post(function(req, res, next) {
|
||||
UploadFile(req, res, uloadFiles, (fn) => {
|
||||
res.redirect('/f/' + fn)
|
||||
})
|
||||
})
|
||||
app.get('*', function (req, res) {
|
||||
app.get('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
app.post('*', function (req, res) {
|
||||
app.post('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
return {
|
||||
app: app
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ const logger = require('../../utils/logger.js')
|
|||
let publicdirs = []
|
||||
let url = ''
|
||||
|
||||
function GetApp () {
|
||||
function GetApp() {
|
||||
const p = publicdirs[0]
|
||||
if (!p) {
|
||||
throw new Error(`No public dir! ( Stuff )`)
|
||||
|
@ -42,33 +42,36 @@ 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({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024
|
||||
}
|
||||
}))
|
||||
app.use(
|
||||
busboy({
|
||||
limits: {
|
||||
fileSize: 10000 * 1024 * 1024,
|
||||
},
|
||||
})
|
||||
)
|
||||
app.use(bodyParser.json())
|
||||
app.use(bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true
|
||||
}))
|
||||
app.use(bodyParser.json({
|
||||
limit: '5mb'
|
||||
}))
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
limit: '5mb',
|
||||
extended: true,
|
||||
})
|
||||
)
|
||||
app.use(
|
||||
bodyParser.json({
|
||||
limit: '5mb',
|
||||
})
|
||||
)
|
||||
|
||||
// --------------------------------------------------------------
|
||||
|
||||
// app, '/*.mp4', 'video/mp4', 'stuff/video'
|
||||
function appGetFileType (app, wildcard, contentType, pageToRender) {
|
||||
app.get(wildcard, function (req, res) {
|
||||
function appGetFileType(app, wildcard, contentType, pageToRender) {
|
||||
app.get(wildcard, function(req, res) {
|
||||
let p = decodeURI(req.url)
|
||||
let fp = p
|
||||
if (p.includes('?')) {
|
||||
|
@ -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,10 +133,10 @@ function GetApp () {
|
|||
['/*.mkv', 'audio/x-matroska', 'video'],
|
||||
['/*.mp3', 'audio/mpeg', 'audio'],
|
||||
['/*.pdf', 'application/pdf'],
|
||||
['/*.zip', 'application/zip']
|
||||
['/*.zip', 'application/zip'],
|
||||
]
|
||||
|
||||
function GetAlbumArt (path) {
|
||||
function GetAlbumArt(path) {
|
||||
let tmp = path.split('.')
|
||||
tmp.pop()
|
||||
tmp = tmp.join('.').split('/')
|
||||
|
@ -148,16 +149,23 @@ function GetApp () {
|
|||
appGetFileType(app, t[0], t[1], t[2])
|
||||
})
|
||||
|
||||
app.get('/*', function (req, res) {
|
||||
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() -
|
||||
fs.statSync(curr + a).mtime.getTime()
|
||||
files.sort(function(a, b) {
|
||||
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,23 +223,23 @@ function GetApp () {
|
|||
} catch (e) {
|
||||
res.render('nofile', {
|
||||
missingFile: curr,
|
||||
url
|
||||
url,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------------------------------
|
||||
|
||||
app.get('*', function (req, res) {
|
||||
app.get('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
app.post('*', function (req, res) {
|
||||
app.post('*', function(req, res) {
|
||||
res.status(404).render('404')
|
||||
})
|
||||
|
||||
return {
|
||||
app: app
|
||||
app: app,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue