UNPKG

molly-file

Version:
75 lines (56 loc) 2.98 kB
/*--────────────────────────────────────────────────────────────────────────────────────────────--*/ const file = require('./file_handler'); const crypto = require('crypto-js'); const {Buffer} = require('buffer'); const stream = require('stream'); const rdl = require('readline'); const path = require('path'); const os = require('os'); /*--────────────────────────────────────────────────────────────────────────────────────────────--*/ function parseFile(obj,cli){ return new Promise((response,reject)=>{ try { // obj const st = !obj.headers.range ? 0 : +obj.headers.range.match(/\d+/i)[0]; const ch = +obj.headers['chunk-size'] || Math.pow(10,6) * 10; const trg =`${obj.url}|${Math.floor(st/ch)*ch}|${obj.method}`; obj.hash = obj.headers.hash || crypto.SHA256(trg).toString(); obj.path = path.join( os.tmpdir(), obj.hash ); setTimeout(()=>{ cli.end() },1000*60); // obj file( obj,cli ); } catch(e) { cli.end() } }); } /*--────────────────────────────────────────────────────────────────────────────────────────────--*/ function parseProtocol( line,obj ){ const arg = line.split(/ /gi); obj.method = arg[0]; obj.ptr = arg[2]; obj.url = Buffer.from( arg[1].slice(1),'base64' ).toString(); return 1; } function parseHeaders( line,obj ){ const arg = line.split(/: /i); if( !arg[0].length ) return 1; obj.headers[arg[0]] = arg[1]; return 1; } /*--────────────────────────────────────────────────────────────────────────────────────────────--*/ module.exports = (cli)=>{ const obj = { headers:{}, decode:false, responseType:'stream' }; const itf = rdl.createInterface({ input: cli }); let i=0; obj.body = stream.PassThrough(); itf.on('line',(line)=>{ if( line.length<=1 && i!=2 && obj.method == 'POST' ){ i = 2; return 0; } else if( line.length<=1 ) { obj.body.end(); itf.close(); } else if( i==2 ){ obj.body.write(line); } if( i==0 ) return i=parseProtocol(line,obj); if( i==1 ) return i=parseHeaders(line,obj); }) itf.on('close',()=>{ parseFile(obj,cli) }) };