-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsockets.js
More file actions
96 lines (69 loc) · 1.97 KB
/
Copy pathsockets.js
File metadata and controls
96 lines (69 loc) · 1.97 KB
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
// Handles sockets
var io = require('socket.io');
var fs = require('fs-extra');
var crypto = require('crypto');
var path = require('path');
var haiku = require('./haiku');
var tagger = require('./tagger');
function genId() {
var currDate = (new Date()).valueOf().toString();
var random = Math.random().toString();
var hmac = crypto.createHmac('sha256', 'asdasd');
hmac.update(currDate + random);
return hmac.digest('hex');
}
function genPath(fileName) {
fs.ensureDirSync(__dirname + '/public/img/static');
return path.resolve(__dirname + '/public/img/static/'+fileName);
}
module.exports = function(io) {
io.on('connection', function(socket) {
socket.emit('testConnect', {
message: 'hello'
});
socket.on('imageUpload', function(data) {
// TODO check image size
// check image type
var typeSection = data.imageData.substring(0, 30);
var re = /^data:image\/((png)|(jpeg)|(gif));base64,/;
if(!typeSection.match(re)) {
// bad file
console.log('Bad', typeSection);
return;
}
var ext = '.' + typeSection.substring(11, typeSection.indexOf(';'));
var buffer = new Buffer(data.imageData.replace(re, ''), 'base64');
console.log('uploading...');
// TODO grab extention from buffer
var fileName = genId() + ext;
var imgPath = genPath(fileName);
// console.log(imgPath);
// run through clarifai
var testURL = 'http://5bbe1c9c.ngrok.io/img/static/'+fileName;
fs.writeFile(imgPath, buffer, function(err) {
if(err) {
console.log(err);
return;
}
// image has been saved to server
socket.emit('imageSaved', {
url: '/img/static/' + fileName
});
// make haiku
tagger(testURL, fileName)
.then(function(terms) {
console.log('jared');
socket.emit('haiku', {
message: haiku(terms)
});
}, function(err) {
console.log(err);
})
.fail(function(err){
console.log(err);
});
console.log('upload complete', fileName);
});
});
});
};