Moved submodules and every stuff into seperate folders neatly #4

This commit is contained in:
mrfry 2020-10-01 14:16:19 +02:00
parent 7e44ca30f1
commit ae91801fbd
51 changed files with 0 additions and 799 deletions

780
src/modules/api/api.js Normal file
View file

@ -0,0 +1,780 @@
/* ----------------------------------------------------------------------------
Question Server
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const uuidv4 = require('uuid/v4') // TODO: deprecated, but imports are not supported
const fs = require('fs')
const app = express()
// other requires
const logger = require('../../utils/logger.js')
const utils = require('../../utils/utils.js')
const actions = require('../../utils/actions.js')
const dbtools = require('../../utils/dbtools.js')
const auth = require('../../middlewares/auth.middleware.js')
// files
const msgFile = 'stats/msgs'
const passwordFile = 'data/dataEditorPasswords.json'
const dataEditsLog = 'stats/dataEdits'
const dailyDataCountFile = 'stats/dailyDataCount'
const usersDbBackupPath = 'data/dbs/backup'
const quickVoteResultsDir = 'stats/qvote'
const quickVotes = 'stats/qvote/votes.json'
const testUsersFile = 'data/testUsers.json'
// other constants
const maxVeteranPwGetCount = 10
const addPWPerDay = 3 // every x day a user can give a pw
const maxPWCount = 6 // maximum pw give opportunities a user can have at once
// const daysAfterUserGetsPWs = 2 // days after user gets pw-s
// stuff gotten from server.js
let userDB
let url // eslint-disable-line
let publicdirs = []
function GetApp () {
const p = publicdirs[0]
if (!p) {
throw new Error(`No public dir! ( API )`)
}
// files in public dirs
const recivedFiles = p + 'recivedfiles'
const uloadFiles = p + 'f'
const dataFile = p + 'data.json'
const motdFile = p + 'motd'
const versionFile = p + 'version'
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'
]
}))
publicdirs.forEach((pdir) => {
logger.Log(`Using public dir: ${pdir}`)
app.use(express.static(pdir))
})
app.use(busboy({
limits: {
fileSize: 50000 * 1024 * 1024
}
}))
var data = actions.LoadJSON(dataFile)
var version = ''
var motd = ''
var testUsers = []
function LoadVersion () {
version = utils.ReadFile(versionFile)
}
function LoadMOTD () {
motd = utils.ReadFile(motdFile)
}
function LoadTestUsers () {
testUsers = utils.ReadJSON(testUsersFile)
if (testUsers) {
testUsers = testUsers.userIds
}
}
function Load () {
utils.WatchFile(motdFile, (newData) => {
logger.Log(`Motd changed: ${newData.replace(/\/n/g, '')}`)
LoadMOTD()
})
utils.WatchFile(versionFile, (newData) => {
logger.Log(`Version changed: ${newData.replace(/\/n/g, '')}`)
LoadVersion()
})
utils.WatchFile(testUsersFile, (newData) => {
logger.Log(`Test Users file changed: ${newData.replace(/\/n/g, '')}`)
LoadTestUsers()
})
LoadTestUsers()
LoadVersion()
LoadMOTD()
}
Load()
// -------------------------------------------------------------
app.get('/quickvote', (req, res) => {
const key = req.query.key
const val = req.query.val
const user = req.session.user
if (!key || !val) {
res.render('votethank', {
results: 'error',
msg: 'no key or val query param!'
})
return
}
let votes = {}
if (utils.FileExists(quickVotes)) {
votes = utils.ReadJSON(quickVotes)
} else {
logger.Log(`No such vote "${key}", and quickVotes.json is missing ( #${user.id}: ${key}-${val} )`, logger.GetColor('blue'))
res.render('votethank', {
result: 'no such pool'
})
return
}
if (!votes.voteNames.includes(key)) {
logger.Log(`No such vote "${key}" ( #${user.id}: ${key}-${val} )`, logger.GetColor('blue'))
res.render('votethank', {
result: 'no such pool'
})
return
}
const voteFile = quickVoteResultsDir + '/' + key + '.json'
let voteData = {
votes: {},
users: []
}
if (utils.FileExists(voteFile)) {
voteData = utils.ReadJSON(voteFile)
} else {
utils.CreatePath(quickVoteResultsDir)
}
if (!voteData.users.includes(user.id)) {
if (voteData.votes[val]) {
voteData.votes[val]++
} else {
voteData.votes[val] = 1
}
voteData.users.push(user.id)
logger.Log(`Vote from #${user.id}: ${key}: ${val}`, logger.GetColor('blue'))
res.render('votethank', {
result: 'success',
msg: 'vote added'
})
} else {
logger.Log(`#${user.id} already voted for: ${key}: ${val}`, logger.GetColor('blue'))
res.render('votethank', {
result: 'already voted',
msg: 'already voted'
})
}
utils.WriteFile(JSON.stringify(voteData), voteFile)
})
app.get('/avaiblePWS', (req, res) => {
logger.LogReq(req)
const user = req.session.user
res.json({
result: 'success',
userCreated: user.created,
avaiblePWS: user.avaiblePWRequests,
requestedPWS: user.pwRequestCount,
maxPWCount: maxPWCount,
// daysAfterUserGetsPWs: daysAfterUserGetsPWs,
addPWPerDay: addPWPerDay
})
})
app.post('/getpw', function (req, res) {
logger.LogReq(req)
const requestingUser = req.session.user
if (requestingUser.avaiblePWRequests <= 0) {
res.json({
result: 'error',
msg: 'Too many passwords requested or cant request password yet, try later'
})
logger.Log(`User #${requestingUser.id} requested too much passwords`, logger.GetColor('cyan'))
return
}
dbtools.Update(userDB, 'users', {
avaiblePWRequests: requestingUser.avaiblePWRequests - 1,
pwRequestCount: requestingUser.pwRequestCount + 1
}, {
id: requestingUser.id
})
const pw = uuidv4()
const insertRes = dbtools.Insert(userDB, 'users', {
pw: pw,
avaiblePWRequests: 0,
created: utils.GetDateString()
})
logger.Log(`User #${requestingUser.id} created new user #${insertRes.lastInsertRowid}`, logger.GetColor('cyan'))
res.json({
result: 'success',
pw: pw,
requestedPWS: requestingUser.pwRequestCount + 1,
remaining: requestingUser.avaiblePWRequests - 1
})
})
app.post('/getveteranpw', function (req, res) {
logger.LogReq(req)
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
const tries = dbtools.Select(userDB, 'veteranPWRequests', {
ip: ip
})[0]
if (tries) {
if (tries.count > maxVeteranPwGetCount) {
res.json({
result: 'error',
msg: 'Too many tries from this IP'
})
logger.Log(`Too many veteran PW requests from ${ip}!`, logger.GetColor('cyan'))
return
} else {
dbtools.Update(userDB, 'veteranPWRequests', {
count: tries.count + 1,
lastDate: utils.GetDateString()
}, {
id: tries.id
})
}
} else {
dbtools.Insert(userDB, 'veteranPWRequests', {
ip: ip,
lastDate: utils.GetDateString()
})
}
const oldUserID = req.body.cid
if (!oldUserID) {
res.json({
result: 'error',
msg: 'No Client ID recieved'
})
logger.Log(`No client ID recieved`, logger.GetColor('cyan'))
return
}
const user = dbtools.Select(userDB, 'users', {
oldCID: oldUserID
})[0]
if (user) {
if (user.pwGotFromCID === 0) {
logger.Log(`Sent password to veteran user #${user.id}`, logger.GetColor('cyan'))
dbtools.Update(userDB, 'users', {
pwGotFromCID: 1
}, {
id: user.id
})
res.json({
result: 'success',
pw: user.pw
})
} else {
logger.Log(`Veteran user #${user.id} already requested password`, logger.GetColor('cyan'))
res.json({
result: 'error',
msg: 'Password already requested'
})
}
} else {
logger.Log(`Invalid password request with CID: ${oldUserID}`, logger.GetColor('cyan'))
res.json({
result: 'error',
msg: 'No such Client ID'
})
}
})
app.post('/login', (req, res) => {
logger.LogReq(req)
const pw = req.body.pw || false
const cid = req.body.cid
const isScript = req.body.script
const ip = req.headers['cf-connecting-ip'] || req.connection.remoteAddress
const user = dbtools.Select(userDB, 'users', {
pw: pw
})[0]
if (user) {
const sessionID = uuidv4()
// 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
})
if (existingSessions.length > 0) {
logger.Log(`Multiple ${isScript ? 'script' : 'website'} sessions ( ${existingSessions.length} ) for #${user.id}, deleting olds`, logger.GetColor('cyan'))
existingSessions.forEach((sess) => {
dbtools.Delete(userDB, 'sessions', {
id: sess.id,
isScript: isScript ? 1 : 0
})
})
}
dbtools.Update(userDB, 'users', {
loginCount: user.loginCount + 1,
lastIP: ip,
lastLogin: utils.GetDateString()
}, {
id: user.id
})
dbtools.Insert(userDB, 'sessions', {
id: sessionID,
ip: ip,
userID: user.id,
isScript: isScript ? 1 : 0,
createDate: utils.GetDateString()
})
// https://www.npmjs.com/package/cookie
// 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)),
sameSite: 'none',
secure: true
})
res.cookie('sessionID', sessionID, {
expires: new Date(new Date().getTime() + (10 * 365 * 24 * 60 * 60 * 1000)),
sameSite: 'none',
secure: true
})
res.json({
result: 'success',
msg: 'you are now logged in'
})
logger.Log(`Successfull login to ${isScript ? 'script' : 'website'} with user ID: #${user.id}`, logger.GetColor('cyan'))
} else {
logger.Log(`Login attempt with invalid pw: ${pw} to ${isScript ? 'script' : 'website'}${cid ? ', CID:' + cid : ''}`, logger.GetColor('cyan'))
res.json({
result: 'error',
msg: 'Invalid password'
})
}
})
app.post('/logout', (req, res) => {
logger.LogReq(req)
const sessionID = req.cookies.sessionID
// removing session from db
dbtools.Delete(userDB, 'sessions', {
id: sessionID
})
// TODO: remove old sessions every once in a while
res.clearCookie('sessionID').json({
result: 'success'
})
})
// --------------------------------------------------------------
app.get('/', function (req, res) {
logger.LogReq(req)
res.redirect('https://www.youtube.com/watch?v=ieqGJgqiXFk')
})
app.post('/postfeedbackfile', function (req, res) {
UploadFile(req, res, uloadFiles, (fn) => {
res.json({ success: true })
})
logger.LogReq(req)
logger.Log('New feedback file', logger.GetColor('bluebg'), true)
})
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)
} else {
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)
res.json({ success: true })
})
function UploadFile (req, res, path, next) {
try {
var fstream
req.pipe(req.busboy)
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
fstream = fs.createWriteStream(path + '/' + fn)
file.pipe(fstream)
fstream.on('close', function () {
logger.Log('Upload Finished of ' + path + '/' + fn, logger.GetColor('blue'))
next(fn)
})
fstream.on('error', function (err) {
console.log(err)
res.end('something bad happened :s')
})
})
} catch (e) {
logger.Log(`Unable to upload file!`, logger.GetColor('redbg'))
console.log(e)
}
}
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) {
UploadFile(req, res, recivedFiles, (fn) => {
res.redirect('back')
})
logger.LogReq(req)
})
app.get('/allqr.txt', function (req, res) {
res.set('Content-Type', 'text/plain')
res.send(data.toString())
res.end()
logger.LogReq(req)
})
// -------------------------------------------------------------------------------------------
// API
app.post('/uploaddata', (req, res) => {
// body: JSON.stringify({
// newData: data,
// count: getCount(data),
// initialCount: initialCount,
// password: password,
// editedQuestions: editedQuestions
// })
const { count, initialCount, editedQuestions, password, newData } = req.body
const respStatuses = {
invalidPass: 'invalidPass',
ok: 'ok',
error: 'error'
}
logger.LogReq(req)
try {
// finding user
const pwds = JSON.parse(utils.ReadFile(passwordFile))
let user = Object.keys(pwds).find((key) => {
const u = pwds[key]
return u.password === password
})
user = pwds[user]
// logging and stuff
logger.Log(`Data upload`, logger.GetColor('bluebg'))
logger.Log(`PWD: ${password}`, logger.GetColor('bluebg'))
// returning if user password is not ok
if (!user) {
logger.Log(`Data upload: invalid password ${password}`, logger.GetColor('red'))
utils.AppendToFile(utils.GetDateString() + '\n' + password + '(FAILED PASSWORD)\n' + JSON.stringify(editedQuestions) + '\n\n', dataEditsLog)
res.json({ status: respStatuses.invalidPass })
return
}
logger.Log(`Password accepted for ${user.name}`, logger.GetColor('bluebg'))
logger.Log(`Old Subjects/Questions: ${initialCount.subjectCount} / ${initialCount.questionCount} | New: ${count.subjectCount} / ${count.questionCount} | Edited question count: ${Object.keys(editedQuestions).length}`, logger.GetColor('bluebg'))
// saving detailed editedCount
utils.AppendToFile(utils.GetDateString() + '\n' + JSON.stringify(user) + '\n' + JSON.stringify(editedQuestions) + '\n\n', dataEditsLog)
// making backup
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)
logger.Log('New data file written')
// reloading data file
data = actions.LoadJSON(dataFile)
// data = newData
logger.Log('Data set to newData')
res.json({
status: respStatuses.ok,
user: user.name
})
logger.Log('Data updating done!', logger.GetColor('bluebg'))
} catch (e) {
logger.Log(`Data upload error! `, logger.GetColor('redbg'))
console.error(e)
res.json({ status: respStatuses.error, msg: e.message })
}
})
app.post('/isAdding', function (req, res) {
logger.LogReq(req)
const user = req.session.user
const dryRun = testUsers.includes(user.id)
// 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
})
})
})
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
})
} else {
if (req.query.q && req.query.data) {
let subj = req.query.subj || ''
let question = req.query.q
let recData = {}
try {
recData = JSON.parse(req.query.data)
} catch (e) {
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
})
logger.DebugLog(`Question result length: ${r.length}`, 'ask', 1)
logger.DebugLog(r, 'ask', 2)
} else {
logger.DebugLog(`Invalid question`, 'ask', 1)
res.json({
message: `Invalid question :(`,
result: [],
recievedData: JSON.stringify(req.query),
success: false
})
}
}
})
function getSimplreRes () {
return {
subjects: data.length,
questions: data.Subjects.reduce((acc, subj) => {
return acc + subj.length
}, 0)
}
}
function getDetailedRes () {
return data.Subjects.map((subj) => {
return {
name: subj.Name,
count: subj.length
}
})
}
app.get('/datacount', function (req, res) {
logger.LogReq(req)
if (req.query.detailed === 'all') {
res.json({
detailed: getDetailedRes(),
simple: getSimplreRes()
})
} else if (req.query.detailed) {
res.json(getDetailedRes())
} else {
res.json(getSimplreRes())
}
})
app.get('/infos', function (req, res) {
const user = req.session.user
let result = {
result: 'success',
uid: user.id
}
if (req.query.subjinfo) {
result.subjinfo = getSimplreRes()
}
if (req.query.version) {
result.version = version
}
if (req.query.motd) {
result.motd = motd
}
res.json(result)
})
// -------------------------------------------------------------------------------------------
app.get('*', function (req, res) {
res.status(404).render('404')
})
app.post('*', function (req, res) {
res.status(404).render('404')
})
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)
}
function BackupDB () {
logger.Log('Backing up auth DB ...')
utils.CreatePath(usersDbBackupPath, true)
userDB.backup(`${usersDbBackupPath}/users.${utils.GetDateString().replace(/ /g, '_')}.db`)
.then(() => {
logger.Log('Auth DB backup complete!')
})
.catch((err) => {
logger.Log('Auth DB backup failed!', logger.GetColor('redbg'))
console.error(err)
})
}
function IncrementAvaiblePWs () {
// FIXME: check this if this is legit and works
logger.Log('Incrementing avaible PW-s ...')
const users = dbtools.SelectAll(userDB, 'users')
const today = new Date()
const getDayDiff = (dateString) => {
let msdiff = today - new Date(dateString)
return Math.floor(msdiff / (1000 * 3600 * 24))
}
users.forEach((u) => {
if (u.avaiblePWRequests >= maxPWCount) {
return
}
const dayDiff = getDayDiff(u.created)
// if (dayDiff < daysAfterUserGetsPWs) {
// logger.Log(`User #${u.id} is not registered long enough to get password ( ${dayDiff} days, ${daysAfterUserGetsPWs} needed)`, logger.GetColor('cyan'))
// return
// }
if (dayDiff % addPWPerDay === 0) {
logger.Log(`Incrementing avaible PW-s for user #${u.id}: ${u.avaiblePWRequests} -> ${u.avaiblePWRequests + 1}`, logger.GetColor('cyan'))
dbtools.Update(userDB, 'users', {
avaiblePWRequests: u.avaiblePWRequests + 1
}, {
id: u.id
})
}
})
}
function DailyAction () {
ExportDailyDataCount()
BackupDB()
IncrementAvaiblePWs()
}
return {
dailyAction: DailyAction,
app: app
}
}
exports.name = 'API'
exports.getApp = GetApp
exports.setup = (data) => {
userDB = data.userDB
url = data.url
publicdirs = data.publicdirs
}

View file

@ -0,0 +1,148 @@
{
"users": {
"tableStruct": {
"id": {
"type": "integer",
"primary": true,
"autoIncrement": true
},
"pw": {
"type": "text",
"notNull": true,
"unique": true
},
"oldCID": {
"type": "text",
"unique": true
},
"lastIP": {
"type": "text"
},
"notes": {
"type": "text"
},
"loginCount": {
"type": "number",
"defaultZero": true
},
"created": {
"type": "text",
"notNull": true
},
"lastLogin": {
"type": "text"
},
"lastAccess": {
"type": "text"
},
"avaiblePWRequests": {
"type": "number",
"defaultZero": true
},
"pwRequestCount": {
"type": "number",
"defaultZero": true
},
"pwGotFromCID": {
"type": "number",
"defaultZero": true
}
}
},
"sessions": {
"foreignKey": [
{
"keysFrom": [
"userID"
],
"table": "users",
"keysTo": [
"id"
]
}
],
"tableStruct": {
"id": {
"type": "text",
"primary": true,
"notNull": true
},
"ip": {
"type": "text",
"notNull": true
},
"userID": {
"type": "number",
"notNull": true
},
"createDate": {
"type": "text",
"notNull": true
},
"lastAccess": {
"type": "text"
},
"isScript": {
"type": "number",
"notNull": true
}
}
},
"accesses": {
"foreignKey": [
{
"keysFrom": [
"userID"
],
"table": "users",
"keysTo": [
"id"
]
}
],
"tableStruct": {
"accessID": {
"type": "integer",
"primary": true,
"autoIncrement": true
},
"userID": {
"type": "number",
"notNull": true
},
"ip": {
"type": "text",
"notNull": true
},
"date": {
"type": "text",
"notNull": true
},
"sessionID": {
"type": "text",
"notNull": true
}
}
},
"veteranPWRequests": {
"tableStruct": {
"id": {
"type": "integer",
"primary": true,
"autoIncrement": true
},
"ip": {
"type": "text",
"notNull": true
},
"count": {
"type": "number",
"defaultZero": true
},
"lastDate": {
"type": "text",
"notNull": true
}
}
}
}

View file

@ -0,0 +1,30 @@
<html>
<body bgcolor="#212127">
<head>
<title>Shit uploader</title>
<meta charset="UTF-8">
<style>
.main {
font-size: 28px;
color: #ffffff;
text-align: center;
}
</style>
</head>
<div class='main'>
<%
if (result == 'success') {
%> ty a szavazásért c: <%
} else if (result == 'no such pool') {
%> Ilyen nevű szavazás nincs :c <%
} else if (result == 'already voted') {
%> Már szavaztál, de azért ty c: <%
} else if (result == 'error') {
%> Helytelen url paraméterek :c <%
} else {
%> bit of a fuckup here <%
}
%>
</div>
</body>
</html>

View file

@ -0,0 +1,116 @@
/* ----------------------------------------------------------------------------
Question Server
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const app = express()
// other requires
const utils = require('../../utils/utils.js')
const logger = require('../../utils/logger.js')
const auth = require('../../middlewares/auth.middleware.js')
// stuff gotten from server.js
let userDB
let publicdirs = []
let nextdir = ''
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/dataEditor/views',
'./sharedViews'
])
app.use(auth({
userDB: userDB,
jsonResponse: false,
exceptions: [
'/favicon.ico',
'/getVeteranPw'
]
}))
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
}
}))
// --------------------------------------------------------------
function AddHtmlRoutes (files) {
const routes = files.reduce((acc, f) => {
if (f.includes('html')) {
acc.push(f.split('.')[0])
return acc
}
return acc
}, [])
routes.forEach((route) => {
logger.DebugLog(`Added route /${route}`, 'DataEditor routes', 1)
app.get(`/${route}`, function (req, res) {
logger.LogReq(req)
res.redirect(`${route}.html`)
})
})
}
AddHtmlRoutes(utils.ReadDir(nextdir))
// --------------------------------------------------------------
app.get('/', function (req, res) {
res.end('hai')
logger.LogReq(req)
})
app.get('*', function (req, res) {
res.status(404).render('404')
})
app.post('*', function (req, res) {
res.status(404).render('404')
})
return {
app: app
}
}
exports.name = 'Data editor'
exports.getApp = GetApp
exports.setup = (data) => {
userDB = data.userDB
publicdirs = data.publicdirs
nextdir = data.nextdir
}

84
src/modules/main/main.js Normal file
View file

@ -0,0 +1,84 @@
/* ----------------------------------------------------------------------------
Question Server
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const app = express()
// other requires
const logger = require('../../utils/logger.js')
// stuff gotten from server.js
let publicdirs = []
let url = '' // http(s)//asd.basd
function GetApp () {
app.set('view engine', 'ejs')
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(bodyParser.json())
app.use(bodyParser.urlencoded({
limit: '5mb',
extended: true
}))
app.use(bodyParser.json({
limit: '5mb'
}))
// --------------------------------------------------------------
app.get('/', function (req, res) {
res.render('main', {
siteurl: url
})
})
app.get('*', function (req, res) {
res.status(404).render('404')
})
app.post('*', function (req, res) {
res.status(404).render('404')
})
return {
app: app
}
}
exports.name = 'Main'
exports.getApp = GetApp
exports.setup = (data) => {
url = data.url
publicdirs = data.publicdirs
}

41
src/modules/main/views/main.ejs Executable file
View file

@ -0,0 +1,41 @@
<html>
<body bgcolor="#212127">
<head>
<title>FryLabs.net</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.8" />
<style>
body {
font: normal 14px Verdana;
color: #999999;
}
td {
vertical-align: top
}
a {
color: #9999ff;
text-decoration: none;
}
</style>
</head>
</p>
<h2>
<a>
<pre>
____ __ __
/ __/_____ __ / /__ _/ / ___
/ _// __/ // / / / _ `/ _ \(_-<
/_/ /_/ \_, / /_/\_,_/_.__/___/
/___/
</pre>
</a>
</h2>
</body>
</html>

View file

@ -0,0 +1,218 @@
/* ----------------------------------------------------------------------------
Question Server
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const app = express()
// other requires
const utils = require('../../utils/utils.js')
const logger = require('../../utils/logger.js')
const auth = require('../../middlewares/auth.middleware.js')
// stuff gotten from server.js
let donateURL = ''
let publicdirs = []
let userDB
let nextdir = ''
try {
donateURL = utils.ReadFile('./data/donateURL')
} catch (e) {
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'
}))
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'
]
}))
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
}
}))
// --------------------------------------------------------------
// REDIRECTS
// --------------------------------------------------------------
// to be backwards compatible
app.get('/ask', function (req, res) {
logger.DebugLog(`Qmining module ask redirect`, 'ask', 1)
res.redirect(`http://api.frylabs.net/ask?q=${req.query.q}&subj=${req.query.subj}&data=${req.query.data}`)
})
const simpleRedirects = [
{
from: '/dataeditor',
to: 'https://dataeditor.frylabs.net'
},
{
from: '/install',
to: 'https://qmining.frylabs.net/moodle-test-userscript/stable.user.js'
},
{
from: '/servergit',
to: 'https://gitlab.com/MrFry/mrfrys-node-server'
},
{
from: '/scriptgit',
to: 'https://gitlab.com/MrFry/moodle-test-userscript'
},
{
from: '/qminingSite',
to: 'https://gitlab.com/MrFry/qmining-page'
},
{
from: '/classesgit',
to: 'https://gitlab.com/MrFry/question-classes'
},
{
from: '/menuClick',
to: '/'
},
{
from: '/lred',
to: '/allQuestions.html'
},
{
from: '/donate',
to: donateURL
},
{ // to be backwards compatible
from: '/legacy',
to: '/allQuestions.html'
},
{
from: '/allqr',
to: 'http://api.frylabs.net/allqr.txt'
},
{
from: '/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
},
{
from: '/irc',
to: 'https://kiwiirc.com/nextclient/irc.sub.fm/#qmining'
}
]
simpleRedirects.forEach((redirect) => {
app.get(redirect.from, function (req, res) {
if (!redirect.nolog) {
logger.LogReq(req)
}
logger.DebugLog(`Qmining module ${redirect.from} redirect`, 'infos', 1)
res.redirect(`${redirect.to}`)
})
})
// --------------------------------------------------------------
function AddHtmlRoutes (files) {
const routes = files.reduce((acc, f) => {
if (f.includes('html')) {
acc.push(f.split('.')[0])
return acc
}
return acc
}, [])
routes.forEach((route) => {
logger.DebugLog(`Added route /${route}`, 'Qmining routes', 1)
app.get(`/${route}`, function (req, res) {
logger.LogReq(req)
res.redirect(`${route}.html`)
})
})
}
AddHtmlRoutes(utils.ReadDir(nextdir))
// --------------------------------------------------------------
app.get('/', function (req, res) {
res.end('hai')
logger.LogReq(req)
})
app.get('/getVeteranPw', function (req, res) {
res.render('veteranPw', {
cid: req.query.cid || '',
devel: process.env.NS_DEVEL
})
logger.LogReq(req)
})
app.get('*', function (req, res) {
res.status(404).render('404')
})
app.post('*', function (req, res) {
res.status(404).render('404')
})
return {
app: app
}
}
exports.name = 'Qmining'
exports.getApp = GetApp
exports.setup = (data) => {
userDB = data.userDB
publicdirs = data.publicdirs
nextdir = data.nextdir
}

View file

@ -0,0 +1,150 @@
<html>
<body bgcolor="#222426">
<head>
<title>Frylabs</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6" />
<style>
a {
color: lightblue;
}
.center {
width: 440px;
height: 340px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
max-width: 100%;
max-height: 100%;
overflow: auto;
text-align: center;
}
.text {
font-size: 18px;
color: white;
margin: 20px;
}
.title {
font-size: 50px;
font-weight: bold;
color: white;
}
.inputContainer {
width: 100%;
}
.showpwContainer {
color: white;
width: 40px;
cursor: pointer;
}
input[type=text], input[type=password] {
font-size: 20px;
color: #ffffff;
background-color: #181a1b;
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
border: 2px solid #333333;
text-align: center;
}
input[type=text], input[type=password]:focus {
border: 2px solid #000;
}
button {
width: 100px;
background-color: #9999ff;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
#irc {
display: none;
}
</style>
</head>
<div class='center'>
<div class='title'>
Frylabs
</div>
<div id='text' class='text'>
Másold be ide régi kliens ID-d, és az alapján jelszót kapsz. Ezt csak egyszer teheted meg,
ezért a kapott jelszót tuti helyre írd le!
</div>
<div id='irc'>
<a class='ircLink' href='<%= devel? 'http' : 'https' %>://qmining.frylabs.net/irc?vetPwReqClick'>IRC</a>
</div>
<div id='form'>
<div class='inputContainer'>
<input type='text' id='cid' name='pw' value='<%= cid %>' autocomplete="off"/>
</div>
<input type='hidden' name='redirect' value='asd' autocomplete="off"/>
<button id='sendButton' onclick="GetVeteranPW(this)">Submit</button>
</div>
</div>
</body>
<script>
function HandleResp (resp) {
const textNode = document.getElementById('text')
document.getElementById('sendButton').innerText = 'Submit'
if (resp.result === 'success') {
document.getElementById('form').style.display = 'none'
textNode.innerText = 'Password:'
const pwDiv = document.createElement('div')
pwDiv.innerText = resp.pw
pwDiv.style.fontSize = '20px'
textNode.appendChild(pwDiv)
} else {
textNode.innerText = resp.msg
}
}
function HandleZeroStart () {
document.getElementById('form').style.display = 'none'
document.getElementById('irc').style.display = 'block'
document.getElementById('text').innerText = 'Client ID-d 0-val kezdődik. Ez azt jelenti hogy a jelszavasítás után telepítetted a scriptet, ezért nem vagy jogosult itt jelszót kérni. Ennek ellenére más felhasználóktól (akiknek már van jelszavuk) kérhetsz. Ha úgy gondolod valami nem stimmel:'
}
async function GetVeteranPW(button) {
button.innerText = '...'
const cid = document.getElementById('cid').value
if (cid[0] === '0') {
HandleZeroStart()
return
}
const rawResponse = await fetch('<%= devel? 'http' : 'https' %>://api.frylabs.net/getveteranpw', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
cid: cid
})
})
if (!rawResponse.ok) {
document.getElementById('text').innerText = 'Internal server error'
document.getElementById('sendButton').innerText = 'Submit'
}
try {
rawResponse.json()
.then((resp) => {
HandleResp(resp)
})
} catch (e) {
document.getElementById('text').innerText = 'Invalid data recieved from server'
document.getElementById('sendButton').innerText = 'Submit'
console.log(e)
}
}
</script>
</html>

119
src/modules/sio/sio.js Normal file
View file

@ -0,0 +1,119 @@
/* ----------------------------------------------------------------------------
Question Server
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const fs = require('fs')
const app = express()
// other requires
const logger = require('../../utils/logger.js')
const utils = require('../../utils/utils.js')
// stuff gotten from server.js
let publicdirs = []
function GetApp () {
const p = publicdirs[0]
if (!p) {
throw new Error(`No public dir! ( SIO )`)
}
// files in public dirs
const uloadFiles = p + 'f'
app.set('view engine', 'ejs')
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(bodyParser.json())
app.use(bodyParser.urlencoded({
limit: '5mb',
extended: true
}))
app.use(bodyParser.json({
limit: '5mb'
}))
// --------------------------------------------------------------
app.get('/', function (req, res) {
res.render('uload')
res.end()
})
function UploadFile (req, res, path, next) {
var fstream
req.pipe(req.busboy)
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
fstream = fs.createWriteStream(path + '/' + fn)
file.pipe(fstream)
fstream.on('close', function () {
logger.Log('Upload Finished of ' + path + '/' + fn, logger.GetColor('blue'))
next(fn)
})
fstream.on('error', function (err) {
console.log(err)
res.end('something bad happened :s')
})
})
}
app.route('/fosuploader').post(function (req, res, next) {
UploadFile(req, res, uloadFiles, (fn) => {
res.redirect('/f/' + fn)
})
})
app.get('*', function (req, res) {
res.status(404).render('404')
})
app.post('*', function (req, res) {
res.status(404).render('404')
})
return {
app: app
}
}
exports.name = 'Sio'
exports.getApp = GetApp
exports.setup = (data) => {
publicdirs = data.publicdirs
}

39
src/modules/sio/views/uload.ejs Executable file
View file

@ -0,0 +1,39 @@
<html>
<body bgcolor="#212127">
<head>
<title>Shit uploader</title>
<meta charset="UTF-8">
<style>
body {
font: normal 14px Verdana;
color: #999999;
}
td {
vertical-align: top
}
textarea {
font: normal 14px Verdana;
color: #999999;
background-color: #212127;
width: 100%;
height: 700;
}
a {
color: #9999ff;
}
</style>
</head>
<form action="/fosuploader" enctype=multipart/form-data method="post">
<input type="file" name="dasfile" />
<input type="submit" value="Upload" />
</form>
</body>
</html>

237
src/modules/stuff/stuff.js Normal file
View file

@ -0,0 +1,237 @@
/* ----------------------------------------------------------------------------
Question Server
GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const fs = require('fs')
const app = express()
// other requires
const logger = require('../../utils/logger.js')
// stuff gotten from server.js
let publicdirs = []
let url = ''
function GetApp () {
const p = publicdirs[0]
if (!p) {
throw new Error(`No public dir! ( Stuff )`)
}
// files in public dirs
const listedFiles = './' + p + 'files'
app.set('view engine', 'ejs')
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(bodyParser.json())
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) {
let p = decodeURI(req.url)
let fp = p
if (p.includes('?')) {
fp = p.split('?')
fp.pop()
fp = fp.join('/')
}
const fpath = listedFiles + fp
if (!fs.existsSync(fpath)) {
res.render('nofile', {
missingFile: fpath,
url
})
return
}
if (req.query.stream || !pageToRender) {
const stat = fs.statSync(fpath)
const fileSize = stat.size
const range = req.headers.range
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 file = fs.createReadStream(fpath, { start, end })
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': contentType
}
res.writeHead(200, head)
fs.createReadStream(fpath).pipe(res)
}
} else {
logger.LogReq(req)
let fname = fpath.split('/')
fname = fname.pop()
res.render(pageToRender, {
path: fp,
fname,
url,
contentType,
albumArt: GetAlbumArt(p)
})
}
})
}
const fileTypes = [
['/*.mp4', 'video/mp4', 'video'],
['/*.mkv', 'audio/x-matroska', 'video'],
['/*.mp3', 'audio/mpeg', 'audio'],
['/*.pdf', 'application/pdf'],
['/*.zip', 'application/zip']
]
function GetAlbumArt (path) {
let tmp = path.split('.')
tmp.pop()
tmp = tmp.join('.').split('/')
let last = tmp.pop()
return tmp.join('/') + '/.' + last + '.png'
}
fileTypes.forEach((t) => {
appGetFileType(app, t[0], t[1], t[2])
})
app.get('/*', function (req, res) {
let parsedUrl = decodeURI(req.url)
let curr = listedFiles + '/' + parsedUrl.substring('/'.length, parsedUrl.length).split('?')[0]
let relPath = curr.substring(listedFiles.length, curr.length)
if (relPath[relPath.length - 1] !== '/') { relPath += '/' }
let t = relPath.split('/')
let prevDir = ''
for (let i = 0; i < t.length - 2; i++) { prevDir += t[i] + '/' }
// curr = curr.replace(/\//g, "/");
// relPath = relPath.replace(/\//g, "/");
logger.LogReq(req)
try {
const stat = fs.lstatSync(curr)
if (stat.isDirectory() || stat.isSymbolicLink()) {
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.forEach((item) => {
if (item[0] !== '.') {
let res = { name: item }
let stat = fs.statSync(curr + '/' + item)
let fileSizeInBytes = stat['size']
res.size = Math.round(fileSizeInBytes / 1000000)
res.path = relPath
if (res.path[res.path.length - 1] !== '/') { res.path += '/' }
res.path += item
res.mtime = stat['mtime'].toLocaleString()
res.isDir = stat.isDirectory()
f.push(res)
}
})
res.render('folders', {
folders: f,
dirname: relPath,
prevDir,
url
})
} else {
let fileStream = fs.createReadStream(curr)
fileStream.pipe(res)
}
} catch (e) {
res.render('nofile', {
missingFile: curr,
url
})
}
})
// -----------------------------------------------------------------------------------------------
app.get('*', function (req, res) {
res.status(404).render('404')
})
app.post('*', function (req, res) {
res.status(404).render('404')
})
return {
app: app
}
}
exports.name = 'Stuff'
exports.getApp = GetApp
exports.setup = (data) => {
url = data.url
publicdirs = data.publicdirs
}

View file

@ -0,0 +1,39 @@
<html>
<body bgcolor="#212127">
<head>
<title><%= fname %></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6" />
<style>
body {
font: normal 14px Verdana;
color: #999999;
}
video {
width: 100%
}
</style>
</head>
<center>
<h2>
<%= fname %>
</h2>
<img
id="coverArt"
style="width:auto; max-height: 100%;"
src="<%= url + albumArt %>"
alt=' '
/>
<audio id="audioPlayer" controls style="width:100%">
<source src="<%= url %><%= path %>?stream=true" type=<%= contentType %>>
</audio>
</center>
</body>
<script>
console.log('a')
document.getElementById('coverArt').style.height = window.innerHeight - 140
</script>
</html>

View file

@ -0,0 +1,130 @@
<html>
<body bgcolor="#212127">
<head>
<title><%=dirname%></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6" />
<style>
body {
font: normal 14px Verdana;
color: #999999;
}
td {
vertical-align: top;
word-wrap: break-word;
word-break: break-all;
table-layout: fixed;
padding: 0 12;
vertical-align: middle;
}
textarea {
font: normal 14px Verdana;
color: #999999;
background-color: #212127;
width: 100%;
height: 700;
}
a {
color: #9999ff;
}
.subtable {
border-collapse: collapse;
table-layout:fixed;
width:100%
}
.maintable {
border-collapse: collapse;
table-layout:fixed;
width:100%
padding:0; margin:0;
border: none !important;
}
tr {
width:32%;
}
.butt {
background-color: #212127;
color: #999999;
cursor: pointer;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 13px;
}
</style>
</head>
<center>
<h1>
<%=dirname%>
</h1>
</center>
<h2>
<a href="<%= url + prevDir%>" > Up one level </a>
</h2>
</p>
<table class="maintable">
<% for (var i = 0; i < folders.length; i++) { %>
<tr>
<td>
<a
href="<%= url + folders[i].path %>"
style="font-size: 0px"
>
<button
class="butt"
style='<%= i % 2 === 0 ? "background-color: #2f2f37" : "" %>'
onmouseenter='mouseEnter(this, <%= i %>)'
onmouseleave='mouseLeave(this, <%= i %>)'
>
<table class="subtable">
<tr height="62">
<td style='width:30%;'>
<%=folders[i].name %>
</td>
<td style='width:20%;'>
<%=folders[i].mtime %>
</td>
<td style='width:10%;'>
<%
if (folders[i].isDir) {
%> <%= "DIR" %> <%
} else {
if (folders[i].size === 0) {
%> <%= "~0 MB" %> <%
} else {
%> <%= folders[i].size + ' MB' %> <%
}
}
%>
</td>
</tr>
</table>
</button>
</a>
</td>
</tr>
<% } %>
</table>
</body>
<script>
console.log('hi')
function mouseEnter (e, i) {
e.style.backgroundColor = "#555"
}
function mouseLeave (e, i) {
if (i % 2 == 0) {
e.style.backgroundColor = "#2f2f37"
} else {
e.style.backgroundColor = "#212127"
}
}
</script>
</html>

View file

@ -0,0 +1,94 @@
<html>
<body bgcolor="#212127">
<head>
<title>No such file/folder</title>
<meta charset="UTF-8">
<style>
body {
font: normal 14px Verdana;
color: #999999;
}
td {
vertical-align: top
}
textarea {
font: normal 14px Verdana;
color: #999999;
background-color: #212127;
width: 100%;
height: 700;
}
a {
color: #9999ff;
}
.subtable {
border-collapse: collapse;
table-layout:fixed;
width:100%
}
.maintable {
border-collapse: collapse;
table-layout:fixed;
width:100%
padding:0; margin:0;
border: none !important;
}
tr {
line-height: 29px;
width:32%;
}
.butt {
background-color: #212127;
color: #999999;
cursor: pointer;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 13px;
}
.active,
.butt:hover {
background-color: #555;
}
</style>
</head>
<center>
<h1>
No such file / folder:
</br>
<%= missingFile %>
</br>
<a href="<%= url %>" > Back to root </a>
</br>
<a
onclick='goBack("<%=missingFile%>")'
href="#"
>
Go back
</a>
</h1>
</center>
</body>
<script>
function goBack(path) {
path = path.replace('./public/files', '')
if (path[path.length - 1] == '/') {
path = path.substring(0, path.length -2)
}
let p = path.split('/')
p.pop()
if (p.length > 1) {
location.href = p.join('/')
} else {
location.href = '/'
}
}
</script>
</html>

View file

@ -0,0 +1,34 @@
<html>
<body bgcolor="#212127">
<head>
<title><%= fname %></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6" />
<style>
body {
font: normal 14px Verdana;
color: #999999;
}
video {
width: 100%
}
</style>
</head>
<center>
<h2>
<%= fname %>
</h2>
</center>
<video id="videoPlayer" controls>
<source src="<%= url %><%= path %>?stream=true" type="video/mp4">
</video>
</body>
<script>
var v = document.getElementsByTagName('video')[0]
v.style.maxHeight = window.innerHeight - 100
v.maxWidth = window.innerWidth
console.log('a')
</script>
</html>