const http = require('http'); const url = require('url'); const fs = require('fs'); const ws = require('ws'); const redis = require('redis') //redis client const redis_cli = redis.createClient() redis_cli.on("error", function (error) { console.error(error) }) const outpath = ['sym', ''] //HTTP server http.createServer(function (req, res) { const q = url.parse(req.url, true); let filename = "./public" + q.pathname; if (filename === "./public/") filename = "./public/index.html"; //q.pathname.split("/", 2)[1] === "sym" || ) if (function valid_path(){ for (let i = 0; i < outpath.length; i++) if (q.pathname.split("/", 2)[1] === outpath[i]) return true return false }() === true){ fs.readFile(filename, function(err, data) { if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); } res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }) }else{ let url = redis_cli.hget("surl;"+q.pathname.split("/", 2)[1], "url") res.writeHead(302, {'Location': 'http://adb.sh'}); //res.write(data); return res.end(); } }).listen(8080); //WS server const wss = new ws.Server({ port: 8081, perMessageDeflate: { zlibDeflateOptions: { // See zlib defaults. chunkSize: 1024, memLevel: 7, level: 3 }, zlibInflateOptions: { chunkSize: 10 * 1024 }, // Other options settable: clientNoContextTakeover: true, // Defaults to negotiated value. serverNoContextTakeover: true, // Defaults to negotiated value. serverMaxWindowBits: 10, // Defaults to negotiated value. // Below options specified as default values. concurrencyLimit: 10, // Limits zlib concurrency for perf. threshold: 1024 // Size (in bytes) below which messages // should not be compressed. } }); //WS handler wss.on('connection', ws => { ws.on('message', message => { console.log(`Received message => ${message}`) let msg = `${message}`.split(";", 2) if (msg[0] === 'long_url') { if (function valid_url(){ if (msg[1] === ''){ws.send('error;url is empty'); return false} else if (msg[1].length > 2000){ws.send('error;your url is too long'); return false} else return true }() === true){ let ran_key = get_key(8) //redis_client.set("key", "value", redis.print) redis_cli.hmset("surl;"+ran_key, "url", msg[1], "time", Date.now()) ws.send('short_url;http://127.0.0.1/'+ran_key) } } //ws.send('got your request: '+msg) console.log(msg[0]) }) ws.send('websocket connected') }) //random key const forbidden_array = ['sym', 'admin', 'stats'] function get_key(length) { let forbidden = false; let output = '' let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' do{ for (let i = 0; i < length; i++ ) output += characters.charAt(Math.floor(Math.random() * characters.length)) for (let i = 0; i < forbidden_array.length; i++) if (output === forbidden_array[i]) forbidden = true } while (forbidden) return output }