-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_two.js
More file actions
282 lines (254 loc) · 8.35 KB
/
Copy pathnode_two.js
File metadata and controls
282 lines (254 loc) · 8.35 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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
var fs = require('fs');
var Web3 = require('web3');
var Mustache = require('mustache');
var express = require('express');
var app = express();
var gm = require('gm').subClass({imageMagick: true});
var smartcrop = require('smartcrop-gm');
var qs = require('querystring');
var bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
var global_images = [];
const file_folder = __dirname+'/files/'
app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
var GoogleMapsAPI = require('googlemaps');
var publicConfig = {
key: ' AIzaSyB9vsjYH5PeNWEUOo_NGLqRLSn7zmPqKQA ',
stagger_time: 1000, // for elevationPath
encode_polylines: false,
secure: true, // use https
};
var gmAPI = new GoogleMapsAPI(publicConfig);
if (typeof window !== 'undefined' && typeof window.Web3 === 'undefined') {
window.Web3 = Web3;
}
/*
* This function creates a thumbnail out of a given image
* and uploads both original image and the thumbnail to
* IPFS. Also, updates the ethereum blockchain with changes
*/
function applySmartCrop(body, dest, width, height, req, res) {
smartcrop.crop(body, {width: width, height: height}).then(function(result) {
var crop = result.topCrop;
gm(body)
.crop(crop.width, crop.height, crop.x, crop.y)
.resize(width, height)
.write(dest, function(error){
if (error) return console.error(error);
large_hash = saveToIPFS(body);
small_hash = saveToIPFS(dest);
myContract.uploadImage.sendTransaction(small_hash, large_hash, req.body.topics, req.body.lat, req.body.lon, {gas:2000000});
res.redirect('/');
});
});
}
/*
* Saves file to IPFS
*/
function saveToIPFS(path_to_file) {
var exec = require('child_process').execSync;
var cmd = 'ipfs add "' + path_to_file + '"';
console.log(cmd);
stdout = exec(cmd).toString();
hash = stdout.split(" ")[1];
console.log('Hash', hash)
return hash;
}
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var data = fs.readFileSync('contract/EthImage.sol', 'utf-8')
var compiled = web3.eth.compile.solidity(data);
var code = compiled.code;
var abi = compiled.info.abiDefinition;
var contractAbi = web3.eth.contract(abi);
address = fs.readFileSync('contract/address', 'utf-8');
var myContract = contractAbi.at(address);
web3.eth.defaultAccount = web3.eth.accounts[2];
console.log(web3.eth.coinbase)
/*
* This endpoint serves the data.js file.
*/
app.get('/data', function(req, res) {
res.sendFile(__dirname + '/files/data.js')
})
/*
* Serves homepage of the webUI
*/
app.get('/', function(req, res) {
var username = myContract.getUsernameByAdd.call();
var imgs = [];
/*
* This event is used to get logs of all
* image uploads to the blockchain. This is
* useful to create a list of all uploaded
* images in the blockchain.
*/
var event = myContract.Addition({}, {
fromBlock: 0,
toBlock: 'latest'
});
event.get(function(error, result) {
for (var j = 0; j < result.length; j++) {
hash = result[j]['args']['image_hash'];
if (!myContract.imagePresent.call(hash)) {
continue;
}
var temp = {};
var lat = myContract.getLat.call(hash);
var lon = myContract.getLon.call(hash);
temp["hash"] = hash;
temp["location"] = [lat, lon];
temp["thumbnail"] = myContract.getThumb.call(hash);
imgs.push(temp);
}
global_images = imgs;
datajs = JSON.stringify(imgs);
fs.writeFileSync(__dirname + '/files/data.js', 'var content =' + datajs);
ins = {
username: username
};
var view = Mustache.render(fs.readFileSync(__dirname + '/templates/home.html', 'utf-8'), ins);
res.send(view);
});
});
/*
* This endpoint serves the map with images of search topic.
* Gets data from the blockchain using web3 api.
* Takes topic as parameter.
*/
app.get('/topic_search', function(req, res) {
new_list = []
search = req.query.topic;
search_terms = search.replace(',', ' ').split(' ');
console.log(search_terms);
for (var k = 0; k < search_terms.length; k++) {
for (var i = 0; i < global_images.length; i++) {
topics = myContract.getTopics.call(global_images[i]["hash"]);
topics = topics.replace(',', ' ').split(' ');
console.log(topics)
for (var j = 0; j < topics.length; j++) {
if (topics[j].trim() == search_terms[k].trim()) {
new_list.push(global_images[i]);
}
}
}
}
datajs = JSON.stringify(new_list);
fs.writeFileSync(__dirname + '/files/data.js', 'var content =' + datajs);
ins = {
username: myContract.getUsernameByAdd.call()
};
var view = Mustache.render(fs.readFileSync(__dirname + '/templates/home.html', 'utf-8'), ins);
res.send(view);
})
/*
* Endpoint returns page for viewing images
* including user who uploaded the image and
* topics associated with it.
* Takes image hash as parameter.
*/
app.get('/view_image', function(req, res) {
var ins = {
hash: req.query.hash,
topics: myContract.getTopics.call(req.query.hash),
username: myContract.getUsername.call(req.query.hash),
location: myContract.getLat.call(req.query.hash)+', '+myContract.getLon.call(req.query.hash),
username_add: myContract.getUsernameByAdd.call()
};
var view = Mustache.render(fs.readFileSync(__dirname+'/templates/view_image.html', 'utf-8'), ins);
res.send(view);
})
/*
* Allows user to change his username (UI)
*/
app.get('/change_username', function(req, res) {
ins = {
username: myContract.getUsernameByAdd.call()
};
var view = Mustache.render(fs.readFileSync(__dirname+'/templates/change_username.html', 'utf-8'), ins);
res.send(view);
})
/*
* API endpoint for affecting username change in the
* blockchain. Takes new username as parameter.
*/
app.get('/set_username', function(req, res) {
myContract.setUsername.sendTransaction(req.query.username);
res.redirect('/');
})
/*
* This endpoint handles the upload image task.
* It takes an image and sends it to applySmartCrop
* which creates a thumbnail, adds the original and
* thumbnail image to IPFS and adds info to blockchain.
* Takes path to image, topic and lat&lng as parameters.
*/
app.post('/upload_image', function(req, res, next) {
var img = req.files.upload;
var large_path = file_folder + img.name;
var small_path = file_folder + 'thumb_' + img.name;
img.mv(large_path, function(err) {
applySmartCrop(large_path, small_path, 180, 180, req, res);
});
})
/*
* Cute page for displaying success/failure messages.
* Takes situation as parameter to decided message.
*/
app.get('/done', function(req, res) {
sit = req.query.situation;
if (sit == 'del_failure')
var ins = {
message: 'No permission to delete.'
};
else if (sit == 'success')
var ins = {
message: 'Success!'
};
else var ins = {
message: 'Done!'
};
var view = Mustache.render(fs.readFileSync(__dirname + '/templates/done.html', 'utf-8'), ins)
res.send(view);
})
/*
* End point takes image hash as parameter and
* deletes it from the blockchain.
*/
app.get('/delete_picture', function(req, res) {
hash_img = req.query.hash;
console.log('data', hash_img, myContract.getUsernameByAdd.call(), myContract.canDelete.call(hash_img));
if (myContract.canDelete.call(hash_img)) {
console.log('Deleting', hash_img)
myContract.deleteImage.sendTransaction(hash_img);
res.redirect('/');
}
else {
res.redirect('/done?situation=del_failure');
}
})
/*
* Returns the coordinates of an address using
* googlemaps API.
*/
app.post('/coordinates', function(req, res, next) {
var geocodeParams = {
"address": req.body.location
};
gmAPI.geocode(geocodeParams, function(err, result)
{
console.log(result);
if (err) {
res.send('');
}
if(result['status']=='OK') {
loc = result['results'][0]['geometry']['location'];
res.send(loc['lat']+','+loc['lng'])
}
});
})
app.listen(3051, function () {
console.log('Example app listening on port 3051!')
})