diff options
-rwxr-xr-x | server/serverstore.js | 49 |
1 files changed, 26 insertions, 23 deletions
diff --git a/server/serverstore.js b/server/serverstore.js index 1d04530..3d1c401 100755 --- a/server/serverstore.js +++ b/server/serverstore.js @@ -23,25 +23,14 @@ function renewChallenge(){ setInterval(renewChallenge,8000); renewChallenge(); -var gencode=(function(){ - const startn=42424242; - const alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - var lastn=Persist.getItemSync("gencode_lastn"); - if(lastn==null)lastn=startn; - return function gencode(){ - var code="",coden=lastn; - while(coden){ - code+=alphabet[coden%alphabet.length]; - coden=~~(coden/alphabet.length); - } - if(lastn==0x7fffffff)lastn=0; //maximum value of a 32-bit int - else lastn++; - Persist.setItemSync("gencode_lastn",lastn); - if(lastn==startn)throw new Error("RUN OUT OF INDICES PANIC PANIC"); - while(code.length<6)code+="a"; - return code; - }; -})(); +function gencode(){ + var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + var code = ""; + for(var i = 0; i < 6; i++) { + code += alphabet[~~(Math.random() * alphabet.length)]; + } + return code; +} app.use(bodyParser.raw({ @@ -82,8 +71,7 @@ app.param("authhash",function(req,res,next,authhash){ next(); }); app.param("fname",function(req,res,next,fname){ - req.sscode=gencode(); - req.ssfname=req.sscode+"_"+fname.replace(/[\x00-\x1F\/]/g,"").replace(/^\.+/,""); + req.ssfname = fname.replace(/[\x00-\x1F\/]/g,"").replace(/^\.+/,""); next(); }); app.post("/ss/image/:userid/:authhash/:fname",function(req,res){ @@ -96,8 +84,23 @@ app.post("/ss/image/:userid/:authhash/:fname",function(req,res){ if(!fs.existsSync("images/"+req.ssuser[0])){ fs.mkdirSync("images/"+req.ssuser[0]); } - fs.writeFileSync("images/"+req.ssuser[0]+"/"+req.ssfname,req.body); - res.end("https://"+HOSTNAME+"/ss/get/"+req.ssuser[0]+"/"+req.sscode); + + // Try until we get a unique code (enforced by "wx"), or we've failed 10 times + for (var i = 0; i < 10; i++) { + var code = gencode(); + var path = "images/" + req.ssuser[0] + "/" + code + "_" + req.ssfname; + try { + fs.writeFileSync(path, req.body, {flag: "wx"}); + res.end("https://" + HOSTNAME + "/ss/get/" + req.ssuser[0] + "/" + code); + return; + } catch(e) { + if (i == 10) console.log(e); + continue; + } + } + + res.sendStatus(500); + res.end(); }); |