-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
257 lines (231 loc) · 6.68 KB
/
Copy pathapp.js
File metadata and controls
257 lines (231 loc) · 6.68 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
/* This is an ExpressJS app that responds to page requests by rendering Jade templates and responds to asynchronous JSON HTTP requests with info from the picpost database. */
function fetch_images(callback) {
// TODO: Add range selection and ordering functionality.
var query = 'SELECT * FROM images';
var images = [];
var connection = mysql.createConnection(db_info);
connection.connect();
connection.query(query)
.on('result', function(row) {
images.push(row);
})
.on('end', function() {
connection.end();
callback(images);
});
}
var express = require('express'),
http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs'),
mysql = require('mysql'),
vsprintf = require('sprintf').vsprintf;
var db_info;
if(process.env.VCAP_SERVICES) {
var services = JSON.parse(process.env.VCAP_SERVICES)['mysql-5.1'];
for(var i = 0; i < services.length; i++) {
if(services[i].name == 'picpost') {
credentials = services[i].credentials;
db_info = {
host: credentials.hostname,
database: credentials.name,
user: credentials.username,
password: credentials.password
};
}
}
} else {
db_info = {
'host': 'localhost',
'database': 'picpost',
'user': 'picpost',
'password': 'ULSM8NpFNFTvUGrT'
};
}
var app = express();
app.configure(function(){
app.set('port', process.env.VCAP_APP_PORT || process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
// Routes
app.get('/', function(req, res) {
fetch_images(function(images) {
res.render('index', {
title: 'gallery',
images: images
});
});
});
app.get('/fetch-images', function(req, res) { // Returns info on selected images as JSON.
var params = url.parse(req.url, true).query;
var image_batch_size = params.image_batch_size !== undefined? params.image_batch_size: 1;
var offset = params.offset !== undefined? params.offset: 0;
var direction = params.direction !== undefined && (params.direction === 'ASC' || params.direction === 'DESC')? params.direction: null;
var settings = JSON.parse(fs.readFile(path.join(__dirname, '/settings.json')));
var max_image_batch_size = settings.max_image_batch_size !== undefined? settings.max_image_batch_size: 100;
var batch_size = Math.max(0, Math.min(image_batch_size, max_image_batch_size));
var query = vsprintf(
'SELECT * FROM images LIMIT %(start), %(end) ORDER BY %(order) %(direction)',
{
start: mysql.escape(offset),
end: mysql.escape(offset + batch_size),
order: mysql.escape(order),
direction: direction? mysql.escape(direction): ''
}
);
var image_list = [];
var connection = mysql.createConnection(db_info);
connection.connect();
connection.query(query)
.on('result', function(row) {
image_info.push(row);
})
.on('end', function() {
connection.end();
response.writeHead(200, {'Content-Type': 'application/json'});
response.write(JSON.stringify(image_list));
});
});
app.post('/hit/:id', function(req, res) {
// Increment the popularity of the identified image, if it exists.
function respond() {
connection.query(
'SELECT * FROM images WHERE ?',
{id: req.params.id},
function(error, results) {
//console.log(res.json(results[0].popularity));
res.json(results[0].popularity);
res.send();
connection.end();
}
);
}
function handle_result(result) {
if(result.affectedRows === 1) respond();
else if (result.affectedRows === 0) {
res.writeHead(404);
res.send();
connection.end();
} else {
res.writeHead(500);
res.send();
connection.end();
}
}
var connection = mysql.createConnection(db_info);
connection.connect();
connection.query(
'UPDATE images SET popularity = popularity + 1 WHERE ?',
{id: req.params.id},
function(error, result) {
if(!error) {
handle_result(result);
} else {
res.writeHead(500);
res.send();
connection.end();
throw error;
}
}
);
});
app.get('/upload', function(req, res) {
res.render('upload', {
title: 'upload'
});
});
app.post('/upload', function(req, res) {
var errors = [];
// Thumbnailer
function thumbnail(source, destination) {
//var gm = require('gm');
var im = require('imagemagick');
im.resize(
{
srcPath: source,
dstPath: destination,
width: 200
},
function(error, stdout, stderr) {
//if(error) errors.push(error);
if(error) console.log('ImageMagick error: ' + error);
else console.log('Resized ' + source + ' to a width of 200px.');
}
);
}
// Insert the image info in a record.
var connection = mysql.createConnection(db_info);
connection.connect();
connection.query(
'INSERT INTO images SET ?',
{
title: req.body.title,
description: req.body.description
},
function(error, result) {
if(!error) {
// Make a file name based on the record id, with the extension from the uploaded image.
var filename = String(result.insertId);
var extension = req.files.image.name.split('.').pop().toLowerCase();
var gallery_dir = path.join('public', 'images', 'gallery');
var thumb_dir = path.join('public', 'images', 'thumbs');
var gallery_path = path.join(gallery_dir, filename + '.' + extension);
var thumb_path = path.join(thumb_dir, filename + '.' + extension);
var gallery_src = ['images', 'gallery', filename + '.' + extension].join('/');
var thumb_src = ['images', 'thumbs', filename + '.' + extension].join('/');
// Set the image filename in the new record.
connection.query(
'UPDATE images SET ? WHERE id=' + result.insertId,
{
filename: gallery_src,
thumb: thumb_src
}
);
connection.end()
// Save uploaded image to public/images/gallery
fs.readFile(req.files.image.path, function(error, data) {
if(!error) {
console.log('Uploading ' + gallery_path + ' and thumbnailing to ' + thumb_path);
fs.writeFile(gallery_path, data, function(error) {
if(!error) {
thumbnail(gallery_path, thumb_path);
} else {
errors.push(error);
}
});
} else {
errors.push(error);
}
});
} else {
errors.push(error);
}
}
);
if(!errors.length) {
res.render('upload', {
title: 'upload',
status: req.files.image.name + ' was uploaded.'
});
} else {
console.log(errors);
res.render('upload', {
title: 'upload',
status: String(errors)
});
}
});