Merge branch 'f0ckdev' into 'master'

gitfap pls -.-

See merge request !46
This commit is contained in:
Flummi 2016-11-22 16:32:39 +00:00
commit 720a27c0be
8 changed files with 492 additions and 423 deletions

74
src/cfg.js Normal file
View File

@ -0,0 +1,74 @@
var mysql = require('mysql');
var self = Cfg.prototype;
var haDC = () => {
self.sql = mysql.createConnection(require('../cfg/mysql.json'));
self.sql.connect((err) => {
if(err) setTimeout(haDC, 2000);
});
self.sql.on('error', (err) => {
if(err.code === 'PROTOCOL_CONNECTION_LOST') haDC();
});
};
haDC();
module.exports = Cfg;
function Cfg() {
self.cfg;
}
self.read = (cb, kat, key) => {
// main, websrv, irc
var out = {
irc: {},
main: {},
websrv: {},
trigger: {}
};
self.sql.query("select * from `f0ck`.`cfg`" + (kat?" where `class` = '"+kat+"'"+(key?" && `key` = '"+key+"'":""):""), (err, rows) => {
if(err || rows.length < 1)
cb(err);
else {
rows.forEach(e => {
out[e.class][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( key?out[kat][key]:out );
else
if(!kat && !key)
self.cfg = out;
}
});
};
self.write = (kat, key, value, type, cb) => {
self.sql.query("select * from `f0ck`.`cfg` where `class` = ? && `key` = ? limit 1", [kat, key], (err, rows) => {
if(rows.length > 0) {
self.sql.query("update `f0ck`.`cfg` set `value` = ? where `class` = ? && `key` = ?", [value, kat, key], (err) => {
self.read();
if(cb) cb(err);
});
}
else {
self.sql.query("insert into `f0ck`.`cfg` (`class`,`key`,`value`,`type`) values (?,?,?,?)", [kat, key, value, type], (err) => {
self.read();
if(cb) cb(err);
});
}
});
};

View File

@ -3,8 +3,8 @@ module.exports = (lib) => {
lib.trigger.trigger.forEach((entry,i,a) => { lib.trigger.trigger.forEach((entry,i,a) => {
if(e.message.match(entry.call)) { if(e.message.match(entry.call)) {
let active = false; let active = false;
if(lib.trigger.chans[e.network+e.channel.getName()] !== undefined) { if(lib.cfg.trigger[e.network+e.channel.getName()] !== undefined) {
if(lib.trigger.chans[e.network+e.channel.getName()][entry.name]) if(lib.cfg.trigger[e.network+e.channel.getName()][entry.name])
active = true; active = true;
} }
else else

View File

@ -4,7 +4,6 @@ var https = require('https');
var exec = require('child_process').exec; 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 self = Lib.prototype; var self = Lib.prototype;
self.bot = require('coffea')(); self.bot = require('coffea')();
@ -25,29 +24,17 @@ self.trigger = {
}); });
} }
}; };
var haDC = () => {
self.sql = mysql.createConnection(require('../cfg/mysql.json'));
self.sql.connect((err) => {
if(err) setTimeout(haDC, 2000);
});
self.sql.on('error', (err) => {
if(err.code === 'PROTOCOL_CONNECTION_LOST') haDC();
});
};
haDC();
module.exports = Lib; module.exports = Lib;
function Lib() { function Lib(config) {
self.cfg = {}; self.config = config;
self.getcfg('main', cfg => { self.sql = config.sql;
self.cfg.main = cfg; self.cfg = config.cfg;
self.debug = self.cfg.main.debug; self.debug = self.cfg.main.debug;
self.loadIRC(); self.loadIRC();
self.loadUser((cb) => console.log((cb)?"Admins wurden geladen":"Admins konnten nicht geladen werden")); self.loadUser((cb) => console.log((cb)?"Admins wurden geladen":"Admins konnten nicht geladen werden"));
self.loadTrigger(); self.loadTrigger();
self.loadEvents(); self.loadEvents();
self.getChanTrigger();
});
} }
self.getUserlevel = (user, network, channel, cb) => { self.getUserlevel = (user, network, channel, cb) => {
@ -229,63 +216,21 @@ self.levelToModes = level => {
return ""; return "";
}; };
self.getcfg = (kat, cb, key) => {
// main, websrv, irc
var out = {};
self.sql.query("select * from `f0ck`.`cfg` where `class` = ?"+(key?" && `key` = '"+key+"'":""), kat, (err, rows) => {
if(err || rows.length < 1)
cb(err);
else {
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( key?out[key]:out );
}
});
};
self.loadIRC = () => { self.loadIRC = () => {
self.getcfg('irc', cfg => { self.cfg.irc.irccfg.forEach(e => {
self.cfg.irc = cfg; self.bot.add({
self.cfg.irc.irccfg.forEach(e => { "name": e.name,
self.bot.add({ "host": e.host,
"name": e.name, "port": e.port,
"host": e.host, "ssl": e.ssl,
"port": e.port, "ssl_allow_invalid": e.ssl_allow_invalid,
"ssl": e.ssl, "pass": e.pass,
"ssl_allow_invalid": e.ssl_allow_invalid, "nick": e.nick,
"pass": e.pass, "username": e.username,
"nick": e.nick, "realname": e.realname,
"username": e.username, "throttling": e.throttling
"realname": e.realname,
"throttling": e.throttling
});
console.log("Server "+e.name+" wurde geladen");
}); });
}); console.log("Server "+e.name+" wurde geladen");
};
self.getChanTrigger = () => {
self.trigger.chans = {};
self.getcfg('trigger', cb => {
for(let tmp in cb)
self.trigger.chans[tmp] = cb[tmp];
}); });
}; };

View File

@ -1,5 +1,14 @@
var Cfg = require('./cfg.js');
var Lib = require('./lib.js'); var Lib = require('./lib.js');
var Websrv = require('./websrv.js'); var Websrv = require('./websrv.js');
var lib = new Lib(); var cfg = new Cfg();
var websrv = new Websrv(lib); cfg.read(config => {
if(config) {
cfg.cfg = config;
var lib = new Lib(cfg);
var websrv = new Websrv(lib);
}
else
console.log(config);
});

64
src/trigger/cfg.js Normal file
View File

@ -0,0 +1,64 @@
module.exports = (lib) => {
var kats = {
main: [
"allowedMimes",
"debugchannel",
"disallowedHosts",
"maxFileSize"
]
};
lib.trigger.add({
name: 'cfg',
call: /^!cfg/i,
level: 100,
active: 1,
func: (e) => {
// irc, main, websrv, trigger
var msg = e.message.replace('!cfg.','');
if(msg.match(/=/)) {
var tmp = e.message.split('=');
var value = tmp[1].trim();
var cmd = tmp[0].trim().split('.');
if(cmd.length == 2) {
var kat = cmd[0];
if(kat in kats) {
var key = cmd[1];
if(kats[kat].indexOf(key) !== -1) {
e.reply("kat: "+kat+" ; key: "+key+" ; val: "+value);
}
else {
e.reply("key not found");
}
}
else {
e.reply("kat not found");
}
}
else {
e.reply("nope");
}
}
else {
var cmd = msg.trim().split('.');
var kat = cmd[0];
if(kat in kats) {
var key = cmd[1];
if(kats[kat].indexOf(key) !== -1) {
lib.getcfg(kat, (cb) => {
e.reply(kat+"."+key+" = "+JSON.stringify(cb));
}, key);
}
else {
e.reply("key not found");
}
}
else {
e.reply("kat not found");
}
}
},
desc: 'cfg'
});
};

View File

@ -2,24 +2,30 @@ var fs = require('fs-extra');
module.exports = (lib) => { module.exports = (lib) => {
lib.trigger.add({ lib.trigger.add({
name: 'delete', name: 'del',
call: /^\!(del|rm) (\d+)$/i, call: /^\!(del|rm)/i,
level: 100, level: 100,
active: 0, active: 0,
func: (e) => { func: (e) => {
var id = e.message.split(' ')[1]; var ids = e.message.split(' ');
lib.sql.query("select `dest` from `f0ck`.`items` where `id` = ?", id, (err, rows, fields) => { ids.shift();
if(rows[0]) { ids.forEach(id => {
lib.sql.query("delete from `f0ck`.`items` where `id` = ?", id).on('end', () => { if(Number.isInteger(parseInt(id))) {
fs.unlink(rows[0].dest); lib.sql.query("select `dest` from `f0ck`.`items` where `id` = ? limit 1", id, (err, rows) => {
fs.unlink("./t/"+id+".png"); if(rows[0]) {
e.reply("f0ck "+id+" deleted"); lib.sql.query("delete from `f0ck`.`items` where `id` = ? limit 1", id, err => {
if(!err) {
fs.unlink(rows[0].dest, err => {});
fs.unlink("./t/"+id+".png", err => {});
}
else
e.reply(err);
});
}
}); });
} }
else {
e.reply("404 - f0ck not found");
}
}); });
e.reply("f0ck"+(ids.length>1?"s":"")+" deleted");
}, },
desc: 'delete f0ck' desc: 'delete f0ck'
}); });

View File

@ -6,35 +6,31 @@ module.exports = (lib) => {
active: 1, active: 1,
func: (e) => { func: (e) => {
var args = e.message.split(' '); var args = e.message.split(' ');
lib.getcfg('trigger', cb => { if(!lib.cfg.trigger[e.network+e.channel])
if(!cb) lib.cfg.trigger[e.network+e.channel] = lib.genStdTrigger();
cb = lib.genStdTrigger(); switch(args[1]) {
switch(args[1]) { case "std":
case "std": e.reply(JSON.stringify(lib.genStdTrigger()));
e.reply(JSON.stringify(lib.genStdTrigger())); break;
break; case "toggle":
case "toggle": if(trigger = args[2].toLowerCase()) {
if(trigger = args[2].toLowerCase()) { lib.cfg.trigger[e.network+e.channel] = triggertoggle(lib.cfg.trigger[e.network+e.channel], trigger);
cb = triggertoggle(cb, trigger); lib.config.write('trigger', e.network+e.channel, JSON.stringify(lib.cfg.trigger[e.network+e.channel]), 'json', cbwc => {
writecfg('trigger', e.network+e.channel, JSON.stringify(cb), cbwc => { if(!cbwc)
if(!cbwc) { e.reply("trigger "+ trigger +" in channel "+e.channel.getName() + lib.bot.format.get(lib.cfg.trigger[e.network+e.channel][trigger]?'green':'red')+" "+(lib.cfg.trigger[e.network+e.channel][trigger]?'activated':'deactivated'));
e.reply("trigger "+ trigger +" in channel "+e.channel.getName() + lib.bot.format.get(cb[trigger]?'green':'red')+" "+(cb[trigger]?"activated":"deactivated")); else
lib.getChanTrigger(); e.reply(cbwc);
} });
else }
e.reply(cbwc); break;
}); default:
} var output = "";
break; e.reply("Trigger in "+e.channel.getName()+" (green: activated, red: deactivated):");
default: for(var key in lib.cfg.trigger[e.network+e.channel])
var output = ""; output += lib.bot.format.get(lib.cfg.trigger[e.network+e.channel][key]?'green':'red')+" "+key;
e.reply("Trigger in "+e.channel.getName()+" (green: activated, red: deactivated):"); e.reply(output);
for(var key in cb) break;
output += lib.bot.format.get(cb[key]?'green':'red')+" "+key; }
e.reply(output);
break;
}
}, e.network+e.channel);
}, },
desc: 'muh' desc: 'muh'
}); });
@ -44,19 +40,4 @@ module.exports = (lib) => {
trigger[key] = !trigger[key]; trigger[key] = !trigger[key];
return trigger; return trigger;
}; };
var writecfg = (kat, key, value, cb) => {
lib.sql.query("select * from `f0ck`.`cfg` where `class` = ? && `key` = ? limit 1", [kat, key], (err, rows) => {
if(rows.length > 0) {
lib.sql.query("update `f0ck`.`cfg` set `value` = ? where `class` = ? && `key` = ?", [value, kat, key], (err) => {
if(cb) cb(err);
});
}
else {
lib.sql.query("insert into `f0ck`.`cfg` (`class`,`key`,`value`,`type`) values (?,?,?,?)", [kat, key, value, 'json'], (err) => {
if(cb) cb(err);
});
}
});
};
}; };

View File

@ -11,316 +11,306 @@ 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();
lib.getcfg('websrv', cfg => { http.createServer((req, res) => {
lib.cfg.websrv = cfg; if(lib.cfg.websrv.wlip.hasOwnProperty(req.connection.remoteAddress)) {
Websrv.prototype.getTpls(); var filePath = '.' + req.url;
var url = req.url.split("/")[1];
http.createServer((req, res) => { if(filePath == './')
if(lib.cfg.websrv.wlip.hasOwnProperty(req.connection.remoteAddress)) { filePath = './index.html';
var filePath = '.' + req.url; if(req.method == 'POST') {
var url = req.url.split("/")[1]; if(filePath == './git' && req.headers['x-gitlab-token'] == lib.cfg.websrv.gittoken) {
if(filePath == './') var body = '';
filePath = './index.html'; req.on('data', (data) => {
if(req.method == 'POST') { body += data;
if(filePath == './git' && req.headers['x-gitlab-token'] == lib.cfg.websrv.gittoken) { if(body.length > 1e6)
var body = ''; req.connection.destroy();
req.on('data', (data) => { });
body += data; req.on('end', () => {
if(body.length > 1e6) body = JSON.parse(body);
req.connection.destroy(); var eventname = body.event_name;
}); var autor = body.user_name;
req.on('end', () => { var branch = body.ref.split('/')[2];
body = JSON.parse(body); if(branch === "master") {
var eventname = body.event_name; var commit = "";
var autor = body.user_name; try {
var branch = body.ref.split('/')[2]; commit = body.commits[body.commits.length-1].message.replace('\n','').trim();
if(branch === "master") {
var commit = "";
try {
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();
}
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);
}
});
}
}
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('muh', 'utf-8');
}
else
res.writeHead(403);
}
else {
var extname = String(path.extname(filePath)).toLowerCase();
var contentType = 'text/html';
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.ogg': 'audio/ogg',
'.mov': 'video/quicktime'
}; // Todo: hat hier nichts zu suchen!
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) => {
rows.forEach((e,i,a) => {
data.items.push({ "id": e.id, "mime": e.mime });
data.last = e.id;
}); });
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('muh', 'utf-8'); res.end(tpl(data), 'utf-8');
} });
else {
res.writeHead(403);
}
} }
else { else if(Number.isInteger(parseInt(url))) { // itempage
var extname = String(path.extname(filePath)).toLowerCase(); var query = "select * from `f0ck`.`items` where `id` = ? limit 1; " // get item
var contentType = 'text/html'; + "select `id` from `f0ck`.`items` where `id` = (select min(`id`) from `f0ck`.`items` where `id` > ?); " // get previous item
var mimeTypes = { + "select `id` from `f0ck`.`items` where `id` = (select max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item
'.html': 'text/html', lib.sql.query(query, [url, url, url], (err, rows, fields) => {
'.js': 'text/javascript', var tpl = swig.compile(templates.item);
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.ogg': 'audio/ogg',
'.mov': 'video/quicktime'
};
if(filePath == "./index.html") { // mainpage
var tpl = swig.compile(templates.index);
var data = { var data = {
items: [], id: '',
last: 10000 username: '',
item: '',
src: '',
dest: '',
mime: '',
size: '',
userchannel: '',
usernetwork: '',
thumb: null,
next: null,
prev: null
}; };
lib.sql.query("select `id`,`mime` from `f0ck`.`items` order by `id` desc limit 100", (err, rows, fields) => { if(rows[0].length) {
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":
case "video/quicktime":
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 "video/quicktime":
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) => {
data.items.push({ "id": e.id, "mime": e.mime }); items.push({
data.last = e.id; 'id': e.id,
'mime': e.mime
});
}); });
res.writeHead(200, { 'Content-Type': 'text/html' }); res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(tpl(data), 'utf-8'); res.end(JSON.stringify(items), 'utf-8');
}); });
} }
else if(Number.isInteger(parseInt(url))) { // itempage else if(url[2] == "p" && Number.isInteger(parseInt(url[3]))) { // pagination
var query = "select * from `f0ck`.`items` where `id` = ? limit 1; " // get item var eps = 50;
+ "select `id` from `f0ck`.`items` where `id` = (select min(`id`) from `f0ck`.`items` where `id` > ?); " // get previous item var id = url[3];
+ "select `id` from `f0ck`.`items` where `id` = (select max(`id`) from `f0ck`.`items` where `id` < ?)"; // get next item lib.sql.query("select * from `f0ck`.`items` where `id` < ? order by `id` desc limit ?", [id, eps], (err, rows, fields) => {
lib.sql.query(query, [url, url, url], (err, rows, fields) => { var items = {
var tpl = swig.compile(templates.item); "items": [],
var data = { "last": id
id: '',
username: '',
item: '',
src: '',
dest: '',
mime: '',
size: '',
userchannel: '',
usernetwork: '',
thumb: null,
next: null,
prev: null
}; };
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) { if(rows[0].length) {
var e = rows[0][0]; var e = rows[0][0];
switch(e.mime) { data = {
case "image/png": id: e.id,
case "image/jpeg": username: e.username,
case "image/gif": src: e.src,
data.item = 'image'; dest: e.dest,
break; mime: e.mime,
case "video/webm": size: e.size,
case "video/mp4": userchannel: e.userchannel,
case "video/quicktime": 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(tpl(data), 'utf-8'); res.end(JSON.stringify(data), 'utf-8');
}); });
} }
else if(filePath == "./random") { }
lib.sql.query("select `id` from `f0ck`.`items` order by rand() limit 1", (err, rows, fields) => { else { // errorpage
res.writeHead(301, { res.writeHead(404);
'Cache-Control': 'no-cache, public', res.end('404 - f0ck you', 'utf-8');
'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 "video/quicktime":
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 { }
res.writeHead(403); else {
res.end('403 - forbidden'); res.writeHead(403);
} res.end('403 - forbidden');
}).listen(lib.cfg.websrv.port); }
}); }).listen(lib.cfg.websrv.port);
} }
Websrv.prototype.getTpls = () => { Websrv.prototype.getTpls = () => {