Advertisement
Rikonardo

ZakShare Source Old Version

Jun 5th, 2021
1,522
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const bodyParser = require('body-parser');
  3. const fileType = require('file-type');
  4. const fs = require('fs');
  5. const shortid = require('shortid');
  6. const cfg = require('./config.json')
  7. const app = express();
  8. app.use(bodyParser.raw({
  9.     type: 'image/png',
  10.     limit: '20mb'
  11. }));
  12. app.use(bodyParser.raw({
  13.     type: 'image/jpeg',
  14.     limit: '20mb'
  15. }));
  16. app.use(bodyParser.raw({
  17.     type: 'image/gif',
  18.     limit: '20mb'
  19. }));
  20.  
  21. const getTimestamp = () => {
  22.     const dt = new Date;
  23.     return `[${
  24.         dt.getDate().toString().padStart(2, '0')}.${
  25.         (dt.getMonth()+1).toString().padStart(2, '0')}.${
  26.         dt.getFullYear().toString().padStart(4, '0')} ${
  27.         dt.getHours().toString().padStart(2, '0')}:${
  28.         dt.getMinutes().toString().padStart(2, '0')}:${
  29.         dt.getSeconds().toString().padStart(2, '0')}]`
  30. }
  31.  
  32. const cd = new Set();
  33. app.post('/push', async (req, res) => {
  34.     const ip = req.headers['x-forwarded-for'] || req.ip;
  35.     if(cd.has(ip)){
  36.         return res.status(429).json({ok: false, error: 'Вы отправляете слишком много запросов'})
  37.     }
  38.     cd.add(ip);
  39.     setTimeout(() => {
  40.         cd.delete(ip);
  41.     }, 5000);
  42.  
  43.     try{
  44.         const buf = Buffer.from(req.body);
  45.         const mimeInfo = await fileType.fromBuffer(buf);
  46.         if(['image/png', 'image/jpeg', 'image/gif'].includes(mimeInfo.mime)){
  47.             const id = shortid.generate();
  48.             fs.writeFileSync('./storage/' + id, but);
  49.             console.log(getTimestamp(), 'Uploaded new image -> ' + id);
  50.             res.json({ok: true, data: {id}});
  51.         }
  52.         else{
  53.             res.status(400).json({ok: false, error: 'Неверный тип файла'})
  54.         }
  55.     }
  56.     catch(err){
  57.         res.status(500).json({ok: false, error: 'В процессе загрузки произошла неизвестная ошибка'})
  58.         console.error(getTimestamp(), err);
  59.     }
  60. })
  61.  
  62. app.get('/:id', async (req, res) => {
  63.     if(fs.existsSync('./storage/' + req.params.id)){
  64.         res.sendFile('./storage/' + req.params.id);
  65.     }
  66.     else res.status(404).send();
  67. })
  68.  
  69. app.listen(cfg.port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement