repl.it
Nodejs

No description

fork
loading
Files
  • index.js
  • static
  • templates
  • Packager files
  • package-lock.json
  • package.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const express = require("express");
const nunjucks = require("nunjucks");
const multer = require("multer")
const currentYear = new Date().getFullYear();
const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const dbname = "my_db";
const dbcollection = "Data";
const dateTime = new Date();
const sharp = require("sharp");
// const path = require('path');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 8080

let upload = multer({
  fileFilter: (req, file, cb) => {
    if(!(file.originalname.endsWith(".webp"))) {
      return cb("only .webp are allowed!!")
    }

    cb(null, true)
  },
  limits:{
    files: 1
  }
});

const app = express();
const mongodb = new MongoClient(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });

app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json());

app.use(express.static("static"));

// nunjucks init
nunjucks.configure("./templates", {
  autoescape: true,
  express: app
});


const generateId = () => {
  let asciiLetterDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";

  let randomId = "";
  while(randomId.length < 8){
    randomId += asciiLetterDigits[Math.floor(Math.random() * asciiLetterDigits.length)];
  }

  return randomId
}


app.get('/', (req, res) => {
  let tempData = {
    year: currentYear
  }
  res.render("index.html", tempData);
});


app.post("/upload", upload.single("webp_thevillainer"), (req, res) => {
  // res.send("Hello im ")
  console.log("Lol Im working")
  let id = generateId()

  let data = {
    _id: id,
    originalname: req.file.originalname,
    created: `${dateTime.getMonth()+1}/${dateTime.getDate()}/${dateTime.getFullYear()}  ${dateTime.getHours()}:${dateTime.getMinutes()}:${dateTime.getSeconds()}`,
    filedata: req.file.buffer
  }
  
  mongodb.connect((err, dbb) => {
    assert.equal(null, err);

    const db = mongodb.db(dbname).collection(dbcollection);

    db.insertOne(data)
    dbb.close()
    res.redirect(`/${id}`)
  })
})

app.post("/api/v1/upload", upload.single("webp_thevillainer"), (req, res) => {
  console.log("lol im working!!")
  let id = generateId()

  let data = {
    _id: id,
    originalname: req.file.originalname,
    created: `${dateTime.getMonth()+1}/${dateTime.getDate()}/${dateTime.getFullYear()}  ${dateTime.getHours()}:${dateTime.getMinutes()}:${dateTime.getSeconds()}`,
    filedata: req.file.buffer
  }
  
  mongodb.connect((err, bb) => {
    assert.equal(null, err);

    const db = mongodb.db(dbname).collection(dbcollection);

    db.insertOne(data)

    // console.log(`https://webp.thevillainer.com/${id}`)
    bb.close();
    res.send(`https://webp.thevillainer.com/${id}`)
  })
})





let getHeight = (file) => {
  sharp(file).metadata((err, meta) => {
    return meta.height
  })
}

let getWidth = (file) => {
  sharp(file).metadata((err, meta) => {
    return meta.width
  })
}

let isDigit = (v) => {
  return (v.match(/^[0-9]+$/) ? true : false)
}




app.get("/:id", (req, res) => {
  mongodb.connect((err, bb) => {
    assert.equal(null, err);

    const db = mongodb.db(dbname).collection(dbcollection);

    db.findOne({_id: req.params.id}, (err, data) => {

      
      try {
        // let img = Buffer.from(data.filedata.toString("base64"), "base64")
        let img = data.filedata.buffer;
        let h = req.query.h
        let w = req.query.w
        
        if((h != undefined && isDigit(h)) && (w != undefined && isDigit(w))) {
          
          sharp(img).resize(parseInt(w), parseInt(h)).toBuffer((err, b, info) => {
            
            res.writeHead(200, {
              'Content-Type': 'image/webp',
              'Content-Length': b.length
            });

            res.end(b);
            return
          })
          return
        } else {
          res.writeHead(200, {
            'Content-Type': 'image/webp',
            'Content-Length': img.length
          });

          res.end(img);
          return
        }
      } catch(e) {
        res.send("Invalid ID")
      }

      bb.close();
    })

  })
})



app.get("/s/uptimerobot", (req, res) => {
  res.send("Hello UptimeRobot")
})


app.listen(PORT, () => {
  console.log('server started');
});
?