-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
106 lines (91 loc) · 2.71 KB
/
server.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
/*Require Modules*/
var express = require('express')
var fs = require('fs')
var path = require('path')
var shortid = require('shortid')
var http = require('http')
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
// var S3FS = require('s3fs')
var multiparty = require('connect-multiparty')
var multipartyMiddleware = multiparty()
/*Global Variables*/
AWS.config.loadFromPath('./s3_config.json')
var s3 = new AWS.S3( {
endpoint: 's3-ap-south-1.amazonaws.com',
signatureVersion: 'v4',
region: 'ap-south-1'
} );
var bucketName ='sketch.arjun.ninja'
var app = express()
app.use(multipartyMiddleware)
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res) {
res.sendFile('static/index.html' , { root : __dirname});
})
app.get('/static/:file', function(req, res) {
res.sendFile(path.join(__dirname, '/static/', req.params['file']));
})
app.get('/:sketch_id', function (req, res) {
var sketchID = `${req.params["sketch_id"]}.png`
var params = {
Bucket: bucketName,
Key: sketchID
}
s3.headObject(params, function(err, data) {
if(err) {
console.log(err)
res.redirect('/')
}
else {
res.send(`
<html>
<head>
<link rel="stylesheet" href="./static/sketch.css">
</head>
<body>
<a href="https://sketch.arjun.ninja"><img src="" alt="logo" class="logo"></a>
<img class="sketch" src="https://s3.ap-south-1.amazonaws.com/sketch.arjun.ninja/${sketchID}" alt="Sketch">
<script src="./static/sketch.js"></script>
</body>
</html>
`)
}
})
})
app.post('/', function (req, res) {
var newID = `${shortid.generate()}.png`
function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)
var response = {}
if (matches.length !== 3) {
return new Error('Invalid input string')
}
response.type = matches[1]
response.data = new Buffer(matches[2], 'base64')
return response
}
// res.send(req.body.imageBinary)
var imageBuffer = decodeBase64Image(req.body.imageBinary)
fs.writeFile('./files/image.png', imageBuffer.data)
var stream = fs.createReadStream('./files/image.png')
res.statusMessage = 200;
var data = {
Bucket: bucketName,
Key: newID,
Body: imageBuffer.data,
ContentEncoding: 'base64',
ContentType: 'image/png',
}
s3.putObject(data, function(err, data){
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
console.log('succesfully uploaded the image!');
res.send(newID)
}
})
})
app.listen(app.get('port'));
// console.log('magic happens on '+port)