api: add src

This commit is contained in:
Flummi 2018-06-04 13:20:44 +00:00
parent 45a35eb5f9
commit c4bd1d6553

View File

@ -1,360 +1,360 @@
var fs = require('fs-extra'); var fs = require('fs-extra');
var http = require('http'); var http = require('http');
var path = require('path'); var path = require('path');
var swig = require('swig'); var swig = require('swig');
var urlm = require('url'); var urlm = require('url');
var exec = require('child_process').exec; var exec = require('child_process').exec;
var templates = {}; var templates = {};
var lib; var lib;
module.exports = Websrv; module.exports = Websrv;
function Websrv(tlib) { function Websrv(tlib) {
this.lib = lib = tlib; this.lib = lib = tlib;
Websrv.prototype.getTpls(); Websrv.prototype.getTpls();
http.createServer((req, res) => { http.createServer((req, res) => {
if(lib.cfg.websrv.wlip.hasOwnProperty(req.connection.remoteAddress)) { if(lib.cfg.websrv.wlip.hasOwnProperty(req.connection.remoteAddress)) {
var filePath = '.' + req.url.split('?')[0]; var filePath = '.' + req.url.split('?')[0];
var url = req.url.split("/")[1]; var url = req.url.split("/")[1];
if(filePath == './') if(filePath == './')
filePath = './index.html'; filePath = './index.html';
if(req.method == 'POST') { if(req.method == 'POST') {
if(filePath == './git' && req.headers['x-gitlab-token'] == lib.cfg.websrv.gittoken) { if(filePath == './git' && req.headers['x-gitlab-token'] == lib.cfg.websrv.gittoken) {
var body = ''; var body = '';
req.on('data', (data) => { req.on('data', (data) => {
body += data; body += data;
if(body.length > 1e6) if(body.length > 1e6)
req.connection.destroy(); req.connection.destroy();
}); });
req.on('end', () => { req.on('end', () => {
body = JSON.parse(body); body = JSON.parse(body);
var eventname = body.event_name; var eventname = body.event_name;
var autor = body.user_name; var autor = body.user_name;
var branch = body.ref.split('/')[2]; var branch = body.ref.split('/')[2];
if(branch === "master") { if(branch === "master") {
var commit = ""; var commit = "";
try { try {
commit = body.commits[body.commits.length-1].message.replace('\n','').trim(); commit = body.commits[body.commits.length-1].message.replace('\n','').trim();
} }
catch(ex) { catch(ex) {
commit = body.commits[body.commits.length-2].message.replace('\n','').trim(); commit = body.commits[body.commits.length-2].message.replace('\n','').trim();
} }
lib.bot.send( lib.cfg.main.debugchannel, eventname + ' from ' + autor + ' ('+commit+') in branch '+branch, 'n0xy' ); lib.bot.send( lib.cfg.main.debugchannel, eventname + ' from ' + autor + ' ('+commit+') in branch '+branch, 'n0xy' );
if( lib.cfg.main.debugchannel === '#f0ck' ) { if( lib.cfg.main.debugchannel === '#f0ck' ) {
exec('cd ../ & git pull', (error, stdout) => { exec('cd ../ & git pull', (error, stdout) => {
if(error === null) { if(error === null) {
if(!lib.debug) if(!lib.debug)
lib.bot.send(lib.cfg.main.debugchannel, 'git pull suxxessfully.', 'n0xy'); lib.bot.send(lib.cfg.main.debugchannel, 'git pull suxxessfully.', 'n0xy');
else else
lib.log(stdout); lib.log(stdout);
} }
}); });
} }
} }
}); });
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('muh', 'utf-8'); res.end('muh', 'utf-8');
} }
else else
res.writeHead(403); res.writeHead(403);
} }
else { else {
var extname = String(path.extname(filePath)).toLowerCase(); var extname = String(path.extname(filePath)).toLowerCase();
var contentType = 'text/html'; var contentType = 'text/html';
var mimeTypes = { var mimeTypes = {
'.html': 'text/html', '.html': 'text/html',
'.js': 'text/javascript', '.js': 'text/javascript',
'.css': 'text/css', '.css': 'text/css',
'.png': 'image/png', '.png': 'image/png',
'.jpg': 'image/jpg', '.jpg': 'image/jpg',
'.gif': 'image/gif', '.gif': 'image/gif',
'.mp3': 'audio/mpeg', '.mp3': 'audio/mpeg',
'.flac': 'audio/x-flac', '.flac': 'audio/x-flac',
'.mp4': 'video/mp4', '.mp4': 'video/mp4',
'.webm': 'video/webm', '.webm': 'video/webm',
'.ogg': 'audio/ogg', '.ogg': 'audio/ogg',
'.mov': 'video/quicktime', '.mov': 'video/quicktime',
'.woff': 'application/font-woff', '.woff': 'application/font-woff',
'.woff2': 'font/woff2', '.woff2': 'font/woff2',
'.eot': 'application/vnd.ms-fontobject', '.eot': 'application/vnd.ms-fontobject',
'.svg': 'image/svg+xml', '.svg': 'image/svg+xml',
'.ttf': 'application/octet-stream' '.ttf': 'application/octet-stream'
}; // Todo: hat hier nichts zu suchen! }; // Todo: hat hier nichts zu suchen!
if(filePath == "./index.html") { // mainpage if(filePath == "./index.html") { // mainpage
var tpl = swig.compile(templates.index); var tpl = swig.compile(templates.index);
var data = { var data = {
items: [], items: [],
last: 10000 last: 10000
}; };
lib.sql.query("select `id`,`mime` from `f0ck`.`items` order by `id` desc limit 100", (err, rows, fields) => { lib.sql.query("select `id`,`mime` from `f0ck`.`items` order by `id` desc limit 100", (err, rows, fields) => {
rows.forEach((e,i,a) => { rows.forEach((e,i,a) => {
data.items.push({ "id": e.id, "mime": e.mime }); data.items.push({ "id": e.id, "mime": e.mime });
data.last = e.id; data.last = e.id;
}); });
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(data), 'utf-8'); res.end(tpl(data), 'utf-8');
}); });
} }
else if(Number.isInteger(parseInt(url))) { // itempage else if(Number.isInteger(parseInt(url))) { // itempage
var query = "select * from `f0ck`.`items` where `id` = ? limit 1; " // get item var query = "select * from `f0ck`.`items` where `id` = ? limit 1; " // get item
+ "select `id` from `f0ck`.`items` where `id` = (select min(`id`) from `f0ck`.`items` where `id` > ?); " // get previous item + "select `id` from `f0ck`.`items` where `id` = (select min(`id`) from `f0ck`.`items` where `id` > ?); " // get previous item
+ "select `id` from `f0ck`.`items` where `id` = (select max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item + "select `id` from `f0ck`.`items` where `id` = (select max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item
lib.sql.query(query, [url, url, url], (err, rows, fields) => { lib.sql.query(query, [url, url, url], (err, rows, fields) => {
var tpl = swig.compile(templates.item); var tpl = swig.compile(templates.item);
var data = { var data = {
id: '', id: '',
username: '', username: '',
item: '', item: '',
src: '', src: '',
dest: '', dest: '',
mime: '', mime: '',
size: '', size: '',
userchannel: '', userchannel: '',
usernetwork: '', usernetwork: '',
thumb: null, thumb: null,
thumbnail: null, thumbnail: null,
next: null, next: null,
prev: null prev: null
}; };
if(rows[0].length) { if(rows[0].length) {
var e = rows[0][0]; var e = rows[0][0];
switch(e.mime) { switch(e.mime) {
case "image/png": case "image/png":
case "image/jpeg": case "image/jpeg":
case "image/gif": case "image/gif":
data.item = 'image'; data.item = 'image';
break; break;
case "video/webm": case "video/webm":
case "video/mp4": case "video/mp4":
case "video/quicktime": case "video/quicktime":
data.item = 'video'; data.item = 'video';
break; break;
case "audio/mpeg": case "audio/mpeg":
case "audio/ogg": case "audio/ogg":
case "audio/flac": case "audio/flac":
case "audio/x-flac": case "audio/x-flac":
data.item = 'audio'; data.item = 'audio';
break; break;
} }
data.id = e.id; data.id = e.id;
data.username = e.username; data.username = e.username;
data.srcurl = e.src; data.srcurl = e.src;
data.src = urlm.parse(e.src).hostname; data.src = urlm.parse(e.src).hostname;
data.thumb = (e.thumb != '' && e.thumb.match(/sndcdn\.com/i))?e.thumb:null; data.thumb = (e.thumb != '' && e.thumb.match(/sndcdn\.com/i))?e.thumb:null;
data.thumbnail = `${lib.cfg.main.url}/t/${e.id}.png`; data.thumbnail = `${lib.cfg.main.url}/t/${e.id}.png`;
data.dest = e.dest; data.dest = e.dest;
data.mime = e.mime; data.mime = e.mime;
data.size = lib.formatSize(e.size); data.size = lib.formatSize(e.size);
data.userchannel = e.userchannel; data.userchannel = e.userchannel;
data.usernetwork = e.usernetwork; data.usernetwork = e.usernetwork;
data.timestamp = new Date(e.stamp * 1000).toISOString(); data.timestamp = new Date(e.stamp * 1000).toISOString();
if(rows[1].length) if(rows[1].length)
data.next = rows[1][0].id; data.next = rows[1][0].id;
if(rows[2].length) if(rows[2].length)
data.prev = rows[2][0].id; data.prev = rows[2][0].id;
} }
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(data), 'utf-8'); res.end(tpl(data), 'utf-8');
}); });
} }
else if(filePath == "./random") { else if(filePath == "./random") {
lib.sql.query("select `id` from `f0ck`.`items` order by rand() limit 1", (err, rows, fields) => { lib.sql.query("select `id` from `f0ck`.`items` order by rand() limit 1", (err, rows, fields) => {
res.writeHead(301, { res.writeHead(301, {
'Cache-Control': 'no-cache, public', 'Cache-Control': 'no-cache, public',
'Location': '/' + rows[0].id 'Location': '/' + rows[0].id
}); });
res.end(); res.end();
}); });
} }
else if(filePath == "./how") { else if(filePath == "./how") {
var tpl = swig.compile(templates.how); var tpl = swig.compile(templates.how);
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8'); res.end(tpl(), 'utf-8');
} }
else if(filePath == "./contact") { else if(filePath == "./contact") {
var tpl = swig.compile(templates.contact); var tpl = swig.compile(templates.contact);
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8'); res.end(tpl(), 'utf-8');
} }
else if(filePath == "./scripts") { else if(filePath == "./scripts") {
var tpl = swig.compile(templates.scripts); var tpl = swig.compile(templates.scripts);
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8'); res.end(tpl(), 'utf-8');
} }
else if(filePath.match(/^\.\/(b|s|t)\/.*/)) { // file else if(filePath.match(/^\.\/(b|s|t)\/.*/)) { // file
contentType = mimeTypes[extname]; contentType = mimeTypes[extname];
if(( contentType === "video/webm" if(( contentType === "video/webm"
|| contentType === "video/mp4" || contentType === "video/mp4"
|| contentType === "video/quicktime" || contentType === "video/quicktime"
|| contentType === "audio/mpeg" || contentType === "audio/mpeg"
|| contentType === "audio/flac" || contentType === "audio/flac"
|| contentType === "audio/x-flac" || contentType === "audio/x-flac"
|| contentType === "audio/ogg") && req.headers['range']) { || contentType === "audio/ogg") && req.headers['range']) {
fs.readFile(filePath, "binary", function(err, file) { fs.readFile(filePath, "binary", function(err, file) {
if(typeof req.headers.range !== 'undefined') { if(typeof req.headers.range !== 'undefined') {
var range = req.headers.range; var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-"); var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0]; var partialstart = parts[0];
var partialend = parts[1]; var partialend = parts[1];
var total = file.length; var total = file.length;
var start = parseInt(partialstart, 10); var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1; var end = partialend ? parseInt(partialend, 10) : total-1;
res.writeHead(206, { res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + (total), "Content-Range": "bytes " + start + "-" + end + "/" + (total),
"Accept-Ranges": "bytes", "Accept-Ranges": "bytes",
"Content-Length": (end-start)+1, "Content-Length": (end-start)+1,
"Transfer-Encoding": "chunked", "Transfer-Encoding": "chunked",
"Connection": "close" "Connection": "close"
}); });
res.write(file.slice(start, end)+'0', "binary"); res.write(file.slice(start, end)+'0', "binary");
} }
else { else {
res.writeHead(200); res.writeHead(200);
res.write(file, "binary"); res.write(file, "binary");
} }
res.end(); res.end();
}); });
} }
else { else {
fs.readFile(filePath, (error, content) => { fs.readFile(filePath, (error, content) => {
if(error) { if(error) {
if(error.code == 'ENOENT') { if(error.code == 'ENOENT') {
res.writeHead(404); res.writeHead(404);
res.end('404 - f0ck you', 'utf-8'); res.end('404 - f0ck you', 'utf-8');
} }
else { else {
res.writeHead(500); res.writeHead(500);
res.end('Sorry, check with the site admin for error: '+error.code+' ..\n'); res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
res.end(); res.end();
} }
} }
else { else {
//res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': content.length, 'Cache-Control': 'max-age=2592000, public' }); //res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': content.length, 'Cache-Control': 'max-age=2592000, public' });
res.writeHead(200); res.writeHead(200);
res.end(content, 'utf-8'); res.end(content, 'utf-8');
} }
}); });
} }
} }
else if(filePath.match(/^\.\/api/i)) { // api else if(filePath.match(/^\.\/api/i)) { // api
var url = filePath.split('/'); var url = filePath.split('/');
if(url[2] === undefined) { // Mainpage if(url[2] === undefined) { // Mainpage
/*var query = "select * from `f0ck`.`items`"; /*var query = "select * from `f0ck`.`items`";
lib.sql.query(query, (err, rows, fields) => { lib.sql.query(query, (err, rows, fields) => {
var items = []; var items = [];
rows.forEach((e,i,a) => { rows.forEach((e,i,a) => {
items.push({ items.push({
'id': e.id, 'id': e.id,
'mime': e.mime 'mime': e.mime
}); });
}); });
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(items), 'utf-8'); res.end(JSON.stringify(items), 'utf-8');
});*/ });*/
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('nope', 'utf-8'); res.end('nope', 'utf-8');
} }
else if(url[2] == "p" && Number.isInteger(parseInt(url[3]))) { // pagination else if(url[2] == "p" && Number.isInteger(parseInt(url[3]))) { // pagination
var eps = 50; var eps = 50;
var id = url[3]; var id = url[3];
lib.sql.query("select * from `f0ck`.`items` where `id` < ? order by `id` desc limit ?", [id, eps], (err, rows, fields) => { lib.sql.query("select * from `f0ck`.`items` where `id` < ? order by `id` desc limit ?", [id, eps], (err, rows, fields) => {
var items = { var items = {
"items": [], "items": [],
"last": id "last": id
}; };
rows.forEach((e,i,a) => { rows.forEach((e,i,a) => {
items.items.push({ items.items.push({
'id': e.id, 'id': e.id,
'mime': e.mime 'mime': e.mime
}); });
items.last = e.id; items.last = e.id;
}); });
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(items), 'utf-8'); res.end(JSON.stringify(items), 'utf-8');
}); });
} }
else if(Number.isInteger(parseInt(url[2]))) { // Item else if(Number.isInteger(parseInt(url[2]))) { // Item
var query = "select * from `f0ck`.`items` where `id` = ? limit 1; " // get item var query = "select * from `f0ck`.`items` where `id` = ? limit 1; " // get item
+ "select `id` from `f0ck`.`items` where `id` = (select min(`id`) from `f0ck`.`items` where `id` > ?); " // get previous item + "select `id` from `f0ck`.`items` where `id` = (select min(`id`) from `f0ck`.`items` where `id` > ?); " // get previous item
+ "select `id` from `f0ck`.`items` where `id` = (select max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item + "select `id` from `f0ck`.`items` where `id` = (select max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item
lib.sql.query(query, [url[2], url[2], url[2]], (err, rows, fields) => { lib.sql.query(query, [url[2], url[2], url[2]], (err, rows, fields) => {
var data; var data;
if(rows[0].length) { if(rows[0].length) {
var e = rows[0][0]; var e = rows[0][0];
data = { data = {
id: e.id, id: e.id,
username: e.username, username: e.username,
src: e.src, src: e.src,
dest: e.dest, dest: e.dest,
mime: e.mime, mime: e.mime,
size: e.size, size: e.size,
userchannel: e.userchannel, userchannel: e.userchannel,
usernetwork: e.usernetwork, usernetwork: e.usernetwork,
thumb: lib.cfg.main.url + "/t/" + e.id + ".png", thumb: lib.cfg.main.url + "/t/" + e.id + ".png",
next: null, next: null,
prev: null prev: null
}; };
if(rows[1].length) if(rows[1].length)
data.next = rows[1][0].id; data.next = rows[1][0].id;
if(rows[2].length) if(rows[2].length)
data.prev = rows[2][0].id; data.prev = rows[2][0].id;
} }
else else
data = { error: 'nope' }; data = { error: 'nope' };
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(data), 'utf-8'); res.end(JSON.stringify(data), 'utf-8');
}); });
} }
else if(url[2] === "random") { else if(url[2] === "random") {
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
let mimes = []; let mimes = [];
let query = ""; let query = "";
switch(url[3]) { switch(url[3]) {
case "image": case "image":
mimes = ["image/png", "image/gif", "image/jpeg"]; mimes = ["image/png", "image/gif", "image/jpeg"];
query = "where "+mimes.map(mime => "`mime` = '"+mime+"'").join(" or ")+" order by rand() limit 1"; query = "where "+mimes.map(mime => "`mime` = '"+mime+"'").join(" or ")+" order by rand() limit 1";
break; break;
case "video": case "video":
mimes = ["video/webm", "video/mp4", "video/quicktime"]; mimes = ["video/webm", "video/mp4", "video/quicktime"];
query = "where "+mimes.map(mime => "`mime` = '"+mime+"'").join(" or ")+" order by rand() limit 1"; query = "where "+mimes.map(mime => "`mime` = '"+mime+"'").join(" or ")+" order by rand() limit 1";
break; break;
case "audio": case "audio":
mimes = ["audio/mpeg", "audio/flac", "audio/x-flac", "audio/ogg"]; mimes = ["audio/mpeg", "audio/flac", "audio/x-flac", "audio/ogg"];
query = "where "+mimes.map(mime => "`mime` = '"+mime+"'").join(" or ")+" order by rand() limit 1"; query = "where "+mimes.map(mime => "`mime` = '"+mime+"'").join(" or ")+" order by rand() limit 1";
break; break;
default: default:
query = "order by rand() limit 1"; query = "order by rand() limit 1";
break; break;
} }
if(query.length === 0) if(query.length === 0)
return res.end('type not found', 'utf-8'); return res.end('type not found', 'utf-8');
lib.sql.query("select `id`, `mime`, `size`, `username`, `userchannel`, `usernetwork`, `stamp`, `dest` from `f0ck`.`items` " + query, (err, rows, fields) => { lib.sql.query("select `id`, `mime`, `size`, `username`, `userchannel`, `usernetwork`, `stamp`, `dest`, `src` from `f0ck`.`items` " + query, (err, rows, fields) => {
if(err || rows.length === 0) if(err || rows.length === 0)
return res.end('no results', 'utf-8'); return res.end('no results', 'utf-8');
res.end(JSON.stringify( rows[0] ), 'utf-8'); res.end(JSON.stringify( rows[0] ), 'utf-8');
}); });
} }
} }
else { // errorpage else { // errorpage
res.writeHead(404); res.writeHead(404);
res.end('404 - f0ck you', 'utf-8'); res.end('404 - f0ck you', 'utf-8');
} }
} }
} }
else { else {
res.writeHead(403); res.writeHead(403);
res.end('403 - forbidden'); res.end('403 - forbidden');
console.log(req.connection.remoteAddress); console.log(req.connection.remoteAddress);
} }
}).listen(lib.cfg.websrv.port); }).listen(lib.cfg.websrv.port);
} }
Websrv.prototype.getTpls = () => { Websrv.prototype.getTpls = () => {
templates = { templates = {
"index": fs.readFileSync("./s/index.tpl.html", "utf-8"), "index": fs.readFileSync("./s/index.tpl.html", "utf-8"),
"item": fs.readFileSync("./s/item.tpl.html", "utf-8"), "item": fs.readFileSync("./s/item.tpl.html", "utf-8"),
"how": fs.readFileSync("./s/how.tpl.html", "utf-8"), "how": fs.readFileSync("./s/how.tpl.html", "utf-8"),
"contact": fs.readFileSync("./s/contact.tpl.html", "utf-8") "contact": fs.readFileSync("./s/contact.tpl.html", "utf-8")
}; };
}; };