Merge branch 'f0ckdev' into 'master'

new configsystem

See merge request !31
This commit is contained in:
Flummi 2016-11-07 01:30:03 +00:00
commit 4fab49e884
3 changed files with 354 additions and 319 deletions

View File

@ -5,25 +5,9 @@ var exec = require('child_process').exec;
var crypto = require('crypto'); var crypto = require('crypto');
var request = require('request'); var request = require('request');
var mysql = require('mysql'); var mysql = require('mysql');
var irccfg = require('../cfg/irc.json');
var self = Lib.prototype; var self = Lib.prototype;
self.bot = require('coffea')(); self.bot = require('coffea')();
irccfg.forEach(e => {
self.bot.add({
"name": e.name,
"host": e.host,
"port": e.port,
"ssl": e.ssl,
"ssl_allow_invalid": e.ssl_allow_invalid,
"pass": e.pass,
"nick": e.nick,
"username": e.username,
"realname": e.realname,
"throttling": e.throttling
});
console.log("Server "+e.name+" wurde geladen");
});
self.admins = []; self.admins = [];
self.debug = false; self.debug = false;
@ -53,18 +37,21 @@ haDC();
module.exports = Lib; module.exports = Lib;
function Lib() { function Lib() {
self.cfg = require('../cfg/main.json'); self.cfg = {};
self.debug = self.cfg.debug; self.getcfg('main', cfg => {
self.loadUser((cb) => console.log((cb)?"Admins wurden geladen":"Admins konnten nicht geladen werden")); self.cfg.main = cfg;
self.loadTrigger(); self.debug = self.cfg.main.debug;
self.loadEvents(); self.loadIRC();
self.loadUser((cb) => console.log((cb)?"Admins wurden geladen":"Admins konnten nicht geladen werden"));
self.loadTrigger();
self.loadEvents();
});
} }
self.getUserlevel = (user, network, channel, cb) => { self.getUserlevel = (user, network, channel, cb) => {
self.bot.whois(user, network, (err, data) => { self.bot.whois(user, network, (err, data) => {
self.bot.names(channel, network, (names) => { self.bot.names(channel, network, (names) => {
var lvl_channel = (data.nick in names)? self.cfg.level[ names[data.nick] ] : 0; var lvl_channel = (data.nick in names)? self.cfg.main.level[ names[data.nick] ] : 0;
var lvl_db = 0; var lvl_db = 0;
if(data.account in self.admins) if(data.account in self.admins)
lvl_db = (self.admins[data.account].network === network)? self.admins[data.account].level : 0; lvl_db = (self.admins[data.account].network === network)? self.admins[data.account].level : 0;
@ -161,7 +148,7 @@ self.generateThumbs = () => {
}; };
self.log = (msg) => { self.log = (msg) => {
if(self.debug) if(self.debug)
self.bot.send(self.cfg.debugchannel, msg, 'n0xy'); self.bot.send(self.cfg.main.debugchannel, msg, 'n0xy');
}; };
self.loadTrigger = () => { self.loadTrigger = () => {
var files = fs.readdirSync(__dirname+'/trigger/'); var files = fs.readdirSync(__dirname+'/trigger/');
@ -238,3 +225,50 @@ self.levelToModes = level => {
return "v"; return "v";
return ""; return "";
}; };
self.getcfg = (kat, cb) => {
// main, websrv, irc
var out = {};
self.sql.query("select * from `f0ck`.`cfg` where `class` = ?", kat, (err, rows) => {
rows.forEach(e => {
out[e.key] = ((type, value) => {
switch(type) {
case 'string':
return value;
break;
case 'int':
return parseInt(value);
break;
case 'bool':
return (value === 'true')?true:false;
break;
case 'json':
return JSON.parse(value);
break;
}
})(e.type, e.value);
});
if(cb) cb(out);
});
};
self.loadIRC = () => {
self.getcfg('irc', cfg => {
self.cfg.irc = cfg;
self.cfg.irc.irccfg.forEach(e => {
self.bot.add({
"name": e.name,
"host": e.host,
"port": e.port,
"ssl": e.ssl,
"ssl_allow_invalid": e.ssl_allow_invalid,
"pass": e.pass,
"nick": e.nick,
"username": e.username,
"realname": e.realname,
"throttling": e.throttling
});
console.log("Server "+e.name+" wurde geladen");
});
});
};

View File

@ -7,7 +7,6 @@ var fileType = require('file-type');
var request = require('request'); var request = require('request');
var ytdl = require('ytdl-core'); var ytdl = require('ytdl-core');
var Readable = require('stream').Readable; var Readable = require('stream').Readable;
var cfg = require('../../cfg/main.json');
module.exports = (lib) => { module.exports = (lib) => {
lib.trigger.add({ lib.trigger.add({
@ -40,7 +39,7 @@ module.exports = (lib) => {
(cb.info.thumb !== null)?cb.info.thumb:'' (cb.info.thumb !== null)?cb.info.thumb:''
]).on('result', (result) => { ]).on('result', (result) => {
lib.generateThumbs(); lib.generateThumbs();
e.reply(cfg.url+"/"+result.insertId+" - "+cb.info.title+" ("+cb.info.mime+", ~"+lib.formatSize(cb.size)+") from "+cbgu['nick']+" ("+cbgu['username']+"@"+cbgu['hostname']+")"); e.reply(lib.cfg.main.url+"/"+result.insertId+" - "+cb.info.title+" ("+cb.info.mime+", ~"+lib.formatSize(cb.size)+") from "+cbgu['nick']+" ("+cbgu['username']+"@"+cbgu['hostname']+")");
}).on('error', (msg) => { }).on('error', (msg) => {
e.reply(msg); e.reply(msg);
}); });
@ -82,10 +81,10 @@ module.exports = (lib) => {
try { try {
ytdl.downloadFromInfo(inf, { filter: (format) => { return format.container === 'webm'; } }) ytdl.downloadFromInfo(inf, { filter: (format) => { return format.container === 'webm'; } })
.on('response', (res) => { .on('response', (res) => {
if(res.headers['content-length'] > cfg.maxFileSize) { if(res.headers['content-length'] > lib.cfg.main.maxFileSize) {
res.destroy(); res.destroy();
dat.end(); dat.end();
cb({ success: false, file: tmpdest, msg: 'f0ck! your file is too big (~'+lib.formatSize(res.headers['content-length'])+'), max '+lib.formatSize(cfg.maxFileSize)+' allowed' }); cb({ success: false, file: tmpdest, msg: 'f0ck! your file is too big (~'+lib.formatSize(res.headers['content-length'])+'), max '+lib.formatSize(lib.cfg.main.maxFileSize)+' allowed' });
} }
else { else {
info = { info = {
@ -111,10 +110,10 @@ module.exports = (lib) => {
}); });
} }
else if(url.match(sc)) { // scdl else if(url.match(sc)) { // scdl
request('https://api.soundcloud.com/resolve.json?client_id=' + cfg.scclientid + '&url=' + url, (err, res, body) => { request('https://api.soundcloud.com/resolve.json?client_id=' + lib.cfg.main.scclientid + '&url=' + url, (err, res, body) => {
if(!err && res.statusCode === 200) { if(!err && res.statusCode === 200) {
var data = JSON.parse(body); var data = JSON.parse(body);
request(data.stream_url + ((data.stream_url.indexOf('?') === -1)?'?':'&') + 'client_id=' + cfg.scclientid) request(data.stream_url + ((data.stream_url.indexOf('?') === -1)?'?':'&') + 'client_id=' + lib.cfg.main.scclientid)
.pipe(dat); .pipe(dat);
info = { info = {
type: 'soundcloud', type: 'soundcloud',
@ -141,8 +140,8 @@ module.exports = (lib) => {
var type = res.headers['content-type']; var type = res.headers['content-type'];
lib.log('MimeType: '+type); lib.log('MimeType: '+type);
var length = res.headers['content-length']; var length = res.headers['content-length'];
if(cfg.allowedMimes.hasOwnProperty(type)) { if(lib.cfg.main.allowedMimes.hasOwnProperty(type)) {
if(data.length <= cfg.maxFileSize) { if(data.length <= lib.cfg.main.maxFileSize) {
var s = new Readable var s = new Readable
s.push(data); s.push(data);
s.push(null); s.push(null);
@ -151,13 +150,13 @@ module.exports = (lib) => {
type: 'other', type: 'other',
title: path.parse(url).base, title: path.parse(url).base,
mime: type, mime: type,
ext: cfg.allowedMimes[type], ext: lib.cfg.main.allowedMimes[type],
thumb: null thumb: null
}; };
} }
else { else {
dat.end(); dat.end();
cb({ success: false, file: tmpdest, msg: 'f0ck! your file is too big (~'+lib.formatSize(data.length)+'), max '+lib.formatSize(cfg.maxFileSize)+' allowed' }); cb({ success: false, file: tmpdest, msg: 'f0ck! your file is too big (~'+lib.formatSize(data.length)+'), max '+lib.formatSize(lib.cfg.main.maxFileSize)+' allowed' });
} }
} }
else { else {
@ -176,8 +175,8 @@ module.exports = (lib) => {
.on('finish', () => { .on('finish', () => {
var size = dat.bytesWritten; var size = dat.bytesWritten;
dat.end(); dat.end();
if(size > cfg.maxFileSize) if(size > lib.cfg.main.maxFileSize)
cb({ success: false, file: tmpdest, msg: 'f0ck! your file is too big (~'+lib.formatSize(size)+'), max '+lib.formatSize(cfg.maxFileSize)+' allowed' }); cb({ success: false, file: tmpdest, msg: 'f0ck! your file is too big (~'+lib.formatSize(size)+'), max '+lib.formatSize(lib.cfg.main.maxFileSize)+' allowed' });
else { else {
fs.stat('./b/' + tmpdest, (err, stat) => { fs.stat('./b/' + tmpdest, (err, stat) => {
if(!err && stat.isFile() && stat.size > 300) { if(!err && stat.isFile() && stat.size > 300) {
@ -186,13 +185,13 @@ module.exports = (lib) => {
lib.checkRepostCheckSum(cbcs, (cbcrcs) => { lib.checkRepostCheckSum(cbcs, (cbcrcs) => {
if(cbcrcs === true) { if(cbcrcs === true) {
var mime = fileType(readChunk.sync('./b/' + tmpdest, 0, 262)); var mime = fileType(readChunk.sync('./b/' + tmpdest, 0, 262));
if(cfg.allowedMimes.hasOwnProperty(mime.mime) || info.type === 'soundcloud') if(lib.cfg.main.allowedMimes.hasOwnProperty(mime.mime) || info.type === 'soundcloud')
cb({ success: true, info: info, size: size, file: './b/' + tmpdest, checksum: cbcs }); cb({ success: true, info: info, size: size, file: './b/' + tmpdest, checksum: cbcs });
else else
cb({ success: false, file: tmpdest, msg: 'lol, go f0ck yourself ('+mime+')' }); cb({ success: false, file: tmpdest, msg: 'lol, go f0ck yourself ('+mime+')' });
} }
else else
cb({ success: false, file: tmpdest, msg: 'repost motherf0cker: '+cfg.url+'/'+cbcrcs }); cb({ success: false, file: tmpdest, msg: 'repost motherf0cker: '+lib.cfg.main.url+'/'+cbcrcs });
}); });
}); });
} }
@ -204,7 +203,7 @@ module.exports = (lib) => {
}); });
} }
else else
cb({ success: false, file: tmpdest, msg: 'repost motherf0cker: '+cfg.url+'/'+cbcr }); cb({ success: false, file: tmpdest, msg: 'repost motherf0cker: '+lib.cfg.main.url+'/'+cbcr });
}); });
}; };
}; };

View File

@ -3,7 +3,6 @@ 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 cfg = require('../cfg/websrv.json');
var exec = require('child_process').exec; var exec = require('child_process').exec;
var templates = {}; var templates = {};
@ -13,309 +12,312 @@ module.exports = Websrv;
function Websrv(tlib) { function Websrv(tlib) {
this.lib = lib = tlib; this.lib = lib = tlib;
Websrv.prototype.getTpls(); lib.getcfg('websrv', cfg => {
lib.cfg.websrv = cfg;
Websrv.prototype.getTpls();
http.createServer((req, res) => { http.createServer((req, res) => {
if(cfg.wlip.hasOwnProperty(req.connection.remoteAddress)) { if(lib.cfg.websrv.wlip.hasOwnProperty(req.connection.remoteAddress)) {
var filePath = '.' + req.url; var filePath = '.' + req.url;
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'] == cfg.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) {
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' );
if( lib.cfg.main.debugchannel === '#f0ck' ) {
exec('cd ../ & git pull', (error, stdout) => {
if(error === null) {
if(!lib.debug)
lib.bot.send(lib.cfg.main.debugchannel, 'git pull suxxessfully.', 'n0xy');
else
lib.log(stdout);
}
});
}
} }
catch(ex) { });
commit = body.commits[body.commits.length-2].message.replace('\n','').trim(); res.writeHead(200, { 'Content-Type': 'text/html' });
} res.end('muh', 'utf-8');
lib.bot.send( lib.cfg.debugchannel, eventname + ' from ' + autor + ' ('+commit+') in branch '+branch, 'n0xy' ); }
if( lib.cfg.debugchannel === '#f0ck' ) { else {
exec('cd ../ & git pull', (error, stdout) => { res.writeHead(403);
if(error === null) { }
if(!lib.debug)
lib.bot.send(lib.cfg.debugchannel, 'git pull suxxessfully.', 'n0xy');
else
lib.log(stdout);
}
});
}
}
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('muh', 'utf-8');
} }
else { else {
res.writeHead(403); var extname = String(path.extname(filePath)).toLowerCase();
} var contentType = 'text/html';
} var mimeTypes = {
else { '.html': 'text/html',
var extname = String(path.extname(filePath)).toLowerCase(); '.js': 'text/javascript',
var contentType = 'text/html'; '.css': 'text/css',
var mimeTypes = { '.png': 'image/png',
'.html': 'text/html', '.jpg': 'image/jpg',
'.js': 'text/javascript', '.gif': 'image/gif',
'.css': 'text/css', '.mp3': 'audio/mpeg',
'.png': 'image/png', '.mp4': 'video/mp4',
'.jpg': 'image/jpg', '.webm': 'video/webm',
'.gif': 'image/gif', '.ogg': 'audio/ogg'
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.ogg': 'audio/ogg'
};
if(filePath == "./index.html") { // mainpage
var tpl = swig.compile(templates.index);
var data = {
items: [],
last: 10000
}; };
lib.sql.query("select `id`,`mime` from `f0ck`.`items` order by `id` desc limit 100", (err, rows, fields) => { if(filePath == "./index.html") { // mainpage
rows.forEach((e,i,a) => { var tpl = swig.compile(templates.index);
data.items.push({ "id": e.id, "mime": e.mime });
data.last = e.id;
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(data), 'utf-8');
});
}
else if(Number.isInteger(parseInt(url))) { // itempage
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 max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item
lib.sql.query(query, [url, url, url], (err, rows, fields) => {
var tpl = swig.compile(templates.item);
var data = { var data = {
id: '', items: [],
username: '', last: 10000
item: '',
src: '',
dest: '',
mime: '',
size: '',
userchannel: '',
usernetwork: '',
thumb: null,
next: null,
prev: null
}; };
if(rows[0].length) { lib.sql.query("select `id`,`mime` from `f0ck`.`items` order by `id` desc limit 100", (err, rows, fields) => {
var e = rows[0][0];
switch(e.mime) {
case "image/png":
case "image/jpeg":
case "image/gif":
data.item = 'image';
break;
case "video/webm":
case "video/mp4":
data.item = 'video';
break;
case "audio/mpeg":
case "audio/ogg":
data.item = 'audio';
break;
}
data.id = e.id;
data.username = e.username;
data.srcurl = e.src;
data.src = urlm.parse(e.src).hostname;
data.thumb = (e.thumb != '' && e.thumb.match(/sndcdn\.com/i))?e.thumb:null;
data.dest = e.dest;
data.mime = e.mime;
data.size = lib.formatSize(e.size);
data.userchannel = e.userchannel;
data.usernetwork = e.usernetwork;
data.timestamp = new Date(e.stamp * 1000).toString();
if(rows[1].length)
data.next = rows[1][0].id;
if(rows[2].length)
data.prev = rows[2][0].id;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(data), 'utf-8');
});
}
else if(filePath == "./random") {
lib.sql.query("select `id` from `f0ck`.`items` order by rand() limit 1", (err, rows, fields) => {
res.writeHead(301, {
'Cache-Control': 'no-cache, public',
'Location': '/' + rows[0].id
});
res.end();
});
}
else if(filePath == "./how") {
var tpl = swig.compile(templates.how);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8');
}
else if(filePath == "./contact") {
var tpl = swig.compile(templates.contact);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8');
}
else if(filePath == "./scripts") {
var tpl = swig.compile(templates.scripts);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8');
}
else if(filePath.match(/^\.\/(b|s|t)\/.*/)) { // file
contentType = mimeTypes[extname];
switch(contentType) {
case "video/webm":
case "video/mp4":
case "audio/mpeg":
case "audio/ogg":
var start = 0;
var end = 0;
var range = req.headers['range'];
var stat = fs.statSync(filePath);
if(range != null) {
start = parseInt(range.slice(range.indexOf('bytes=')+6, range.indexOf('-')));
end = parseInt(range.slice(range.indexOf('-')+1, range.length));
}
if(isNaN(end) || end == 0) end = stat.size-1;
if(start > end) return;
res.writeHead(206, {
'Connection':'close',
'Content-Type':contentType,
'Content-Length':end - start,
'Content-Range':'bytes '+start+'-'+end+'/'+stat.size,
'Transfer-Encoding':'chunked'
});
var stream = fs.createReadStream(filePath, { flags: 'r', start: start, end: end});
stream.pipe(res);
break;
default:
fs.readFile(filePath, (error, content) => {
if(error) {
if(error.code == 'ENOENT') {
res.writeHead(200, { 'Content-Type': contentType });
res.end('404 - f0ck you', 'utf-8');
}
else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
res.end();
}
}
else {
res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': content.length, 'Cache-Control': 'max-age=2592000, public' });
res.end(content, 'utf-8');
}
});
break;
}
fs.readFile(filePath, (error, content) => {
if(error) {
if(error.code == 'ENOENT') {
res.writeHead(200, { 'Content-Type': contentType });
res.end('404 - f0ck you', 'utf-8');
}
else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
res.end();
}
}
});
}
else if(filePath.match(/^\.\/api/i)) { // api
var url = filePath.split('/');
if(url[2] === undefined) { // Mainpage
var query = "select * from `f0ck`.`items`";
lib.sql.query(query, (err, rows, fields) => {
var items = [];
rows.forEach((e,i,a) => { rows.forEach((e,i,a) => {
items.push({ data.items.push({ "id": e.id, "mime": e.mime });
'id': e.id, data.last = e.id;
'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(tpl(data), 'utf-8');
}); });
} }
else if(url[2] == "p" && Number.isInteger(parseInt(url[3]))) { // pagination else if(Number.isInteger(parseInt(url))) { // itempage
var eps = 50;
var id = url[3];
lib.sql.query("select * from `f0ck`.`items` where `id` < ? order by `id` desc limit ?", [id, eps], (err, rows, fields) => {
var items = {
"items": [],
"last": id
};
rows.forEach((e,i,a) => {
items.items.push({
'id': e.id,
'mime': e.mime
});
items.last = e.id;
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(items), 'utf-8');
});
}
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, url, url], (err, rows, fields) => {
var data; var tpl = swig.compile(templates.item);
var data = {
id: '',
username: '',
item: '',
src: '',
dest: '',
mime: '',
size: '',
userchannel: '',
usernetwork: '',
thumb: null,
next: null,
prev: null
};
if(rows[0].length) { if(rows[0].length) {
var e = rows[0][0]; var e = rows[0][0];
data = { switch(e.mime) {
id: e.id, case "image/png":
username: e.username, case "image/jpeg":
src: e.src, case "image/gif":
dest: e.dest, data.item = 'image';
mime: e.mime, break;
size: e.size, case "video/webm":
userchannel: e.userchannel, case "video/mp4":
usernetwork: e.usernetwork, data.item = 'video';
next: null, break;
prev: null case "audio/mpeg":
}; case "audio/ogg":
data.item = 'audio';
break;
}
data.id = e.id;
data.username = e.username;
data.srcurl = e.src;
data.src = urlm.parse(e.src).hostname;
data.thumb = (e.thumb != '' && e.thumb.match(/sndcdn\.com/i))?e.thumb:null;
data.dest = e.dest;
data.mime = e.mime;
data.size = lib.formatSize(e.size);
data.userchannel = e.userchannel;
data.usernetwork = e.usernetwork;
data.timestamp = new Date(e.stamp * 1000).toString();
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
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(tpl(data), 'utf-8');
}); });
} }
} else if(filePath == "./random") {
else { // errorpage lib.sql.query("select `id` from `f0ck`.`items` order by rand() limit 1", (err, rows, fields) => {
res.writeHead(404); res.writeHead(301, {
res.end('404 - f0ck you', 'utf-8'); 'Cache-Control': 'no-cache, public',
'Location': '/' + rows[0].id
});
res.end();
});
}
else if(filePath == "./how") {
var tpl = swig.compile(templates.how);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8');
}
else if(filePath == "./contact") {
var tpl = swig.compile(templates.contact);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8');
}
else if(filePath == "./scripts") {
var tpl = swig.compile(templates.scripts);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(), 'utf-8');
}
else if(filePath.match(/^\.\/(b|s|t)\/.*/)) { // file
contentType = mimeTypes[extname];
switch(contentType) {
case "video/webm":
case "video/mp4":
case "audio/mpeg":
case "audio/ogg":
var start = 0;
var end = 0;
var range = req.headers['range'];
var stat = fs.statSync(filePath);
if(range != null) {
start = parseInt(range.slice(range.indexOf('bytes=')+6, range.indexOf('-')));
end = parseInt(range.slice(range.indexOf('-')+1, range.length));
}
if(isNaN(end) || end == 0) end = stat.size-1;
if(start > end) return;
res.writeHead(206, {
'Connection':'close',
'Content-Type':contentType,
'Content-Length':end - start,
'Content-Range':'bytes '+start+'-'+end+'/'+stat.size,
'Transfer-Encoding':'chunked'
});
var stream = fs.createReadStream(filePath, { flags: 'r', start: start, end: end});
stream.pipe(res);
break;
default:
fs.readFile(filePath, (error, content) => {
if(error) {
if(error.code == 'ENOENT') {
res.writeHead(200, { 'Content-Type': contentType });
res.end('404 - f0ck you', 'utf-8');
}
else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
res.end();
}
}
else {
res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': content.length, 'Cache-Control': 'max-age=2592000, public' });
res.end(content, 'utf-8');
}
});
break;
}
fs.readFile(filePath, (error, content) => {
if(error) {
if(error.code == 'ENOENT') {
res.writeHead(200, { 'Content-Type': contentType });
res.end('404 - f0ck you', 'utf-8');
}
else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
res.end();
}
}
});
}
else if(filePath.match(/^\.\/api/i)) { // api
var url = filePath.split('/');
if(url[2] === undefined) { // Mainpage
var query = "select * from `f0ck`.`items`";
lib.sql.query(query, (err, rows, fields) => {
var items = [];
rows.forEach((e,i,a) => {
items.push({
'id': e.id,
'mime': e.mime
});
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(items), 'utf-8');
});
}
else if(url[2] == "p" && Number.isInteger(parseInt(url[3]))) { // pagination
var eps = 50;
var id = url[3];
lib.sql.query("select * from `f0ck`.`items` where `id` < ? order by `id` desc limit ?", [id, eps], (err, rows, fields) => {
var items = {
"items": [],
"last": id
};
rows.forEach((e,i,a) => {
items.items.push({
'id': e.id,
'mime': e.mime
});
items.last = e.id;
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(items), 'utf-8');
});
}
else if(Number.isInteger(parseInt(url[2]))) { // 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 max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item
lib.sql.query(query, [url[2], url[2], url[2]], (err, rows, fields) => {
var data;
if(rows[0].length) {
var e = rows[0][0];
data = {
id: e.id,
username: e.username,
src: e.src,
dest: e.dest,
mime: e.mime,
size: e.size,
userchannel: e.userchannel,
usernetwork: e.usernetwork,
next: null,
prev: null
};
if(rows[1].length)
data.next = rows[1][0].id;
if(rows[2].length)
data.prev = rows[2][0].id;
}
else
data = { error: 'nope' };
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(JSON.stringify(data), 'utf-8');
});
}
}
else { // errorpage
res.writeHead(404);
res.end('404 - f0ck you', 'utf-8');
}
} }
} }
} else {
else { res.writeHead(403);
res.writeHead(403); res.end('403 - forbidden');
res.end('403 - forbidden'); }
} }).listen(lib.cfg.websrv.port);
}).listen(cfg.port); });
} }
Websrv.prototype.getTpls = () => { Websrv.prototype.getTpls = () => {