Renamed js files to ts

This commit is contained in:
mrfry 2020-11-23 15:10:24 +01:00
parent 0bddef2b78
commit 7fcb15da88
54 changed files with 8521 additions and 60 deletions

View file

@ -19,20 +19,20 @@
------------------------------------------------------------------------- */
// package requires
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const { v4: uuidv4 } = require('uuid')
const fs = require('fs')
const app = express()
import express from 'express'
import bodyParser from 'body-parser'
import busboy from 'connect-busboy'
import { uuidv4 } from 'uuid'
import fs from 'fs'
// other requires
const logger = require('../../utils/logger.js')
const utils = require('../../utils/utils.js')
const actions = require('../../utils/actions')
const dbtools = require('../../utils/dbtools.js')
const auth = require('../../middlewares/auth.middleware.js')
const { dataToString, searchData } = require('../../utils/classes.js')
import logger from '../../utils/logger.js'
import utils from '../../utils/utils.js'
import actions from '../../utils/actions'
import dbtools from '../../utils/dbtools.js'
import auth from '../../middlewares/auth.middleware.js'
import { dataToString, searchData } from '../../utils/classes.js'
// files
const msgFile = 'stats/msgs'
@ -59,7 +59,14 @@ let userDB
let url // eslint-disable-line
let publicdirs = []
export interface DataFile {
path: string
name: string
}
function GetApp() {
const app = express()
const publicDir = publicdirs[0]
if (!publicDir) {
throw new Error(`No public dir! ( API )`)
@ -68,7 +75,7 @@ function GetApp() {
// files in public dirs
const recivedFiles = publicDir + 'recivedfiles'
const uloadFiles = publicDir + 'f'
const dataFiles = [
const dataFiles: Array<DataFile> = [
{ path: `${publicDir}oldData.json`, name: 'oldData' },
{ path: `${publicDir}data.json`, name: 'newData' },
]
@ -116,11 +123,11 @@ function GetApp() {
})
)
var questionDbs = actions.LoadJSON(dataFiles)
var version = ''
var motd = ''
var userSpecificMotd = {}
var testUsers = []
const questionDbs = actions.LoadJSON(dataFiles)
const version = ''
const motd = ''
const userSpecificMotd = {}
const testUsers = []
function mergeObjSum(a, b) {
const res = { ...b }
@ -752,14 +759,14 @@ function GetApp() {
function UploadFile(req, res, path, next) {
try {
var fstream
const 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 date = new Date()
let fn =
const date = new Date()
const fn =
date.getHours() +
'' +
date.getMinutes() +
@ -824,7 +831,12 @@ function GetApp() {
// editedQuestions: editedQuestions
// })
const { count, initialCount, editedQuestions, password, newData } = req.body
const {
count,
initialCount,
editedQuestions,
password /*, newData*/,
} = req.body
const respStatuses = {
invalidPass: 'invalidPass',
ok: 'ok',
@ -958,8 +970,8 @@ function GetApp() {
})
} else {
if (req.query.q && req.query.data) {
let subj = req.query.subj || ''
let question = req.query.q
const subj = req.query.subj || ''
const question = req.query.q
let recData = {}
try {
recData = JSON.parse(req.query.data)
@ -1040,7 +1052,7 @@ function GetApp() {
app.get('/infos', function(req, res) {
const user = req.session.user
let result = {
const result = {
result: 'success',
uid: user.id,
}
@ -1104,7 +1116,7 @@ function GetApp() {
}
function getDayDiff(dateString) {
let msdiff = new Date() - new Date(dateString)
const msdiff = new Date() - new Date(dateString)
return Math.floor(msdiff / (1000 * 3600 * 24))
}

View file

@ -0,0 +1,338 @@
/* ----------------------------------------------------------------------------
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/>.
------------------------------------------------------------------------- */
const express = require('express')
const bodyParser = require('body-parser')
const busboy = require('connect-busboy')
const cookieParser = require('cookie-parser')
const fs = require('fs')
const app = express()
let url = ''
const logger = require('../../utils/logger.js')
const utils = require('../../utils/utils.js')
// const actions = require('../utils/actions.js')
const listedFiles = './vids/p'
const userDataDirectory = './data/vidsData'
const passwordFile = 'data/vidsPasswords.json'
if (!utils.FileExists(userDataDirectory)) {
utils.CreatePath(userDataDirectory, true)
}
function GetApp() {
app.set('view engine', 'ejs')
app.set('views', ['./src/modules/pornvids/views', './sharedViews'])
app.use(express.static('p'))
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(cookieParser())
// --------------------------------------------------------------
app.get('/login', (req, res) => {
logger.LogReq(req)
// FIXME: redirect to original url
res.cookie('pw', req.query.pw).redirect('/')
})
app.get('/logout', (req, res) => {
logger.LogReq(req)
// FIXME: redirect to original url
res.clearCookie('pw').redirect('/')
})
// app, '/*.mp4', 'video/mp4', 'stuff/video'
function appGetFileType(app, wildcard, contentType, pageToRender) {
app.get(wildcard, function(req, res) {
const user = GetUserByPW(GetPw(req))
if (!user) {
logger.Log('Vids user: No user', logger.GetColor('blue'))
res.render('login')
return
}
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)
logger.Log(`Vids user: ${user.name}`, logger.GetColor('blue'))
AppendWatchedFileToUser(user, fp)
let fname = fpath.split('/')
fname = fname.pop()
res.render(pageToRender, {
path: fp,
fname,
url,
contentType,
albumArt: GetAlbumArt(p),
})
}
})
}
function WriteUserData(user, uData) {
const dataLoc = userDataDirectory + '/' + user.name + '.json'
utils.WriteFile(JSON.stringify(uData), dataLoc)
}
function GetUserData(user) {
try {
const dataLoc = userDataDirectory + '/' + user.name + '.json'
let uData = utils.ReadFile(dataLoc)
uData = JSON.parse(uData)
return uData
} catch (e) {
return {}
}
}
function AppendWatchedFileToUser(user, file) {
const uData = GetUserData(user)
if (uData) {
if (Array.isArray(uData.watched)) {
if (!uData.watched.includes(file)) {
uData.watched.push(file)
}
} else {
uData.watched = [file]
}
WriteUserData(user, uData)
} else {
logger.Log(
'Error appending to user data, no user data found',
logger.GetColor('redbg')
)
}
}
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) {
logger.LogReq(req)
const user = GetUserByPW(GetPw(req))
let uData = {}
if (!user) {
logger.Log('Vids user: No user', logger.GetColor('blue'))
res.render('login')
return
} else {
logger.Log(`Vids user: ${user.name}`, logger.GetColor('blue'))
uData = GetUserData(user)
}
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, "/");
try {
const stat = fs.lstatSync(curr)
if (stat.isDirectory() || stat.isSymbolicLink()) {
if (curr[curr.length - 1] !== '/') {
curr += '/'
}
let f = []
fs.readdirSync(curr).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()
if (uData && Array.isArray(uData.watched)) {
res.watched = uData.watched.includes(res.path)
} else {
res.watched = false
}
f.push(res)
}
})
res.render('folders', {
folders: f,
user: user,
dirname: relPath,
prevDir,
url,
})
} else {
let watchedFile = relPath
if (watchedFile.charAt(watchedFile.length - 1) === '/') {
watchedFile = watchedFile.substr(0, watchedFile.length - 1)
}
AppendWatchedFileToUser(user, watchedFile)
let fileStream = fs.createReadStream(curr)
fileStream.pipe(res)
}
} catch (e) {
res.render('nofile', {
missingFile: curr,
url,
})
}
})
function GetPw(req) {
return req.cookies.pw
}
function GetUserByPW(password) {
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]
return user
}
// -----------------------------------------------------------------------------------------------
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 = 'Porn vids'
exports.getApp = GetApp
exports.setup = (data) => {
url = data.url
}

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,144 @@
<html>
<body bgcolor="#ffeeee">
<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;
}
td {
vertical-align: top;
word-wrap: break-word;
word-break: break-all;
table-layout: fixed;
padding: 0;
vertical-align: middle;
}
a {
color: #0000ff;
}
.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 td {
font: normal 24px Verdana;
font-weight: bold;
}
.watched {
color: #999999;
}
.butt {
cursor: pointer;
width: 100%;
border: none;
text-align: left;
}
.rainbow {
background: linear-gradient( 92deg, #ff0000, #00ffff);
background: -webkit-linear-gradient( 92deg, #ff0000, #00ffff);
background-size:600vw 600vw;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: textAnimate 4s linear infinite alternate;
}
@keyframes textAnimate {
from {
filter: hue-rotate(0deg);
background-position-x: 0%;
}
to {
filter: hue-rotate(360deg);
background-position-x: 600vw;
}
}
</style>
</head>
<center>
<h1 class="rainbow">
<div>
Hi <%= user.name %> c:
</div>
<div>
gyerekkori videók <%=dirname%>
</div>
</h1>
</center>
<h2>
<a href="<%= url + prevDir%>" >Back</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"
onmouseenter='mouseEnter(this, <%= i %>)'
onmouseleave='mouseLeave(this, <%= i %>)'
>
<table class="subtable <%= folders[i].watched ? 'watched' : '' %>">
<tr height="62">
<td style='width:85%;'>
<%=folders[i].name %>
</td>
<td style='width:15%;'>
<%
if (folders[i].isDir) {
%> <%= "Mappa" %> <%
} else {
if (folders[i].size === 0) {
%> <%= "~0 MB" %> <%
} else {
%> <%= folders[i].size + ' MB' %> <%
}
}
%>
</td>
</tr>
</table>
</button>
</a>
</td>
</tr>
<% } %>
</table>
<a href='/logout'>logout</a>
</body>
<script>
console.log('hi')
function mouseEnter (e, i) {
e.className += ' rainbow'
}
function mouseLeave (e, i) {
e.className = e.className.replace(/ rainbow/g, '')
}
</script>
</html>

View file

@ -0,0 +1,63 @@
<html>
<body bgcolor="#212127">
<head>
<title>login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6" />
<style>
video {
width: 100%
}
.rainbow {
background: linear-gradient( 92deg, #ff0000, #00ffff);
background: -webkit-linear-gradient( 92deg, #ff0000, #00ffff);
background-size:600vw 600vw;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: textAnimate 4s linear infinite alternate;
}
@keyframes textAnimate {
from {
filter: hue-rotate(0deg);
background-position-x: 0%;
}
to {
filter: hue-rotate(360deg);
background-position-x: 600vw;
}
}
.text {
color: white;
}
.title {
font: normal 28px Verdana;
font-weight: bold;
color: white;
}
</style>
</head>
<center>
<h2 class='title'>
Login to Porn Vids
</h2>
<div class='text'>
Jelszó:
</div>
<input type='text' id='pw' />
<button onclick='login()'>
Login
</button>
</center>
</body>
<script>
function login () {
const pw = document.getElementById('pw').value
location.href = '/login/?pw=' + pw
}
</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,57 @@
<html>
<body bgcolor="#ffeeee">
<head>
<title><%= fname %></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6" />
<style>
video {
width: 100%
}
.rainbow {
background: linear-gradient( 92deg, #ff0000, #00ffff);
background: -webkit-linear-gradient( 92deg, #ff0000, #00ffff);
background-size:600vw 600vw;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: textAnimate 4s linear infinite alternate;
}
@keyframes textAnimate {
from {
filter: hue-rotate(0deg);
background-position-x: 0%;
}
to {
filter: hue-rotate(360deg);
background-position-x: 600vw;
}
}
.title {
font: normal 28px Verdana;
font-weight: bold;
}
</style>
</head>
<center>
<h2 class='rainbow title'>
<%= 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>