-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathuploads.js
More file actions
377 lines (335 loc) · 9.36 KB
/
uploads.js
File metadata and controls
377 lines (335 loc) · 9.36 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
'use strict';
/**
* Module Dependencies
*/
var knox = require('knox'),
uuid = require('node-uuid'),
geo = require('mapbox-geocoding'),
async = require('async'),
stream = require('getstream'),
streamUtils = require('../lib/stream_utils'),
algoliaSearch = require('algoliasearch');
/**
* Get uploads based on query
* URL: /uploads
* Method: GET
* Auth Required: Yes
* @param {string} user_id This required param specifies the user id to filter by
* @param {string} type This optional param specifies the type to filter by
* @param {string} query This optional param specifies the query to filter by
* @returns {object} Returns a 200 status code with an array of upload objects
*/
server.get('/uploads', function(req, res, next) {
// extract query params
var params = req.params || {};
// default sql
var sql = '';
// if the params type and query are defined, build query for 'type'
if (params.type && params.query) {
// check type and build query
switch (params.type) {
case 'hashtags':
sql = `
SELECT *
FROM uploads
WHERE hashtags LIKE '%${params.query.substring(1)}%'
`;
break;
case 'location':
sql = `
SELECT *
FROM uploads
WHERE location LIKE '%${params.query}%'
`;
break;
case 'user':
const userName = params.query.split(' ');
sql = `
SELECT *
FROM uploads
LEFT JOIN users
ON uploads.user_id = users.id
WHERE users.first_name = ${db.escape(userName[0])}
AND CONCAT(SUBSTR(users.last_name, 1, 1), '.') = ${db.escape(
userName[1],
)}
`;
break;
}
// execute sql query
db.query(sql, function(err, result) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err.message));
}
// send response to client
res.send(200, result);
return next();
});
// otherwise default to normal query
} else {
// async waterfall (see: https://github.com/caolan/async)
async.waterfall(
[
// connect to stream
function(cb) {
// instantiate a new client (server side)
var streamClient = stream.connect(
config.stream.key,
config.stream.secret,
);
// instantiate a feed using feed class 'timeline_flat' and user id from params
var timelineFlatFeed = streamClient.feed(
'timeline_flat',
params.user_id,
);
cb(null, timelineFlatFeed);
},
// get and loop through activities
function(timelineFlatFeed, cb) {
// build query params for stream (id_lt is preferred)
var uploadGetParams = { limit: 5 };
if (params.last_id) uploadGetParams.id_lt = params.last_id;
// get activities from stream
timelineFlatFeed
.get(uploadGetParams)
.then(function(stream) {
// length of activity results
var ln = stream.results.length;
// exit if length is zero
if (!ln) {
res.send(204);
return next();
}
// enrich the activities
var references = streamUtils.referencesFromActivities(
stream.results,
);
streamUtils.loadReferencedObjects(
references,
params.user_id,
function(referencedObjects) {
streamUtils.enrichActivities(
stream.results,
referencedObjects,
);
cb(null, stream.results);
},
);
})
.catch(function(error) {
cb(error);
});
},
// final cb callback
],
function(err, result) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err));
}
// send response to client
res.send(200, result);
return next();
},
);
}
});
/**
* Get uploads based on query
* URL: /uploads
* Method: GET
* Auth Required: Yes
* @param {string} user_id This required param specifies the user id to filter by
* @param {string} id This required param specifies the upload id to filter by
* @returns {object} Returns a 200 status code with the upload object
*/
server.get('/upload', function(req, res, next) {
// extract query params
var params = req.params || {};
// build sql statement
var sql = `
SELECT
uploads.*,
users.id AS user_id,
MD5(users.email) AS email_md5,
users.first_name AS first_name,
users.last_name AS last_name,
users.fb_uid AS fb_uid,
IF((SELECT 1 AS liked FROM likes WHERE user_id = ? AND upload_id = uploads.id), true, false) AS liked
FROM uploads
LEFT JOIN users
ON users.id = uploads.user_id
WHERE uploads.id = ?
ORDER BY uploads.created_at DESC
`;
// execute sql query
db.query(sql, [params.user_id, params.id], function(err, result) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err.message));
}
// send response to client
res.send(200, result[0]);
return next();
});
});
/**
* Upload an image
* URL: /uploads
* Method: POST
* Auth Required: Yes
* @param {string} user_id This required param specifies the user id to associate the upload with
* @param {string} caption Caption to associate with the uploaded image
* @param {string} hashtags Hashtags to associate with the uploaded image
* @param {string} location Location to associate with the uploaded image
* @param {object} file This required param specifies the image to upload
* @returns {object} Returns a 201 status code with the upload object
*/
server.post('/uploads', function(req, res, next) {
// extract params from body and file from uploaded files
var data = req.body || {},
file = req.files || {};
// generate unique filename using uuid and assign to object
data.filename = uuid.v4();
data['created_at'] = new Date();
// async waterfall (see: https://github.com/caolan/async)
async.waterfall(
[
// upload file to amazon s3
function(cb) {
// initialize knox client
var knoxClient = knox.createClient({
key: config.s3.key,
secret: config.s3.secret,
bucket: config.s3.bucket,
});
// send put via knox
knoxClient.putFile(
file.image.path,
'uploads/' + data.filename,
{
'Content-Type': file.image.type,
'x-amz-acl': 'public-read',
},
function(err, result) {
if (err || result.statusCode != 200) {
cb(err);
} else {
cb(null);
}
},
);
},
// use mapbox to get latitude and longitude
function(cb) {
// initialize mapbox client
geo.setAccessToken(config.mapbox.accessToken);
// get location data
geo.geocode('mapbox.places', data.location, function(
err,
location,
) {
if (err) {
cb(err);
} else {
// if the location was found
if (location.features.length) {
// extract coorindates
var coords =
location.features[0].geometry.coordinates;
if (coords.length) {
// assign to latitude and longitude in data object
data.longitude = coords[0];
data.latitude = coords[1];
}
}
cb(null);
}
});
},
// insert record into database
function(cb) {
// run query using node mysql, passing the data object as params
db.query('INSERT INTO uploads SET ?', data, function(
err,
result,
) {
if (err) {
cb(err);
} else {
// use object assign to merge the object id
result = Object.assign(
{},
{ id: result.insertId },
data,
);
cb(null, result);
}
});
},
// submit to algolia for indexing
function(result, cb) {
// initialize algolia
var algolia = algoliaSearch(
config.algolia.appId,
config.algolia.apiKey,
);
// initialize algoia index
var index = algolia.initIndex('cabin');
// add returned database object for indexing
index.addObject(result);
cb(null, result);
},
// submit to stream
function(result, cb) {
// instantiate a new client (server side)
var streamClient = stream.connect(
config.stream.key,
config.stream.secret,
);
// build activity object for stream feed
var activity = {
actor: `user:${data.user_id}`,
verb: 'add',
object: `upload:${result.id}`,
foreign_id: `upload:${result.id}`,
time: data['created_at'],
};
// instantiate a feed using feed class 'user_posts' and the user id from the database
var userFeed = streamClient.feed('user_posts', data.user_id);
// add activity to the feed
userFeed
.addActivity(activity)
.then(function(response) {
cb(null, result);
})
.catch(function(err) {
cb(err);
});
},
// final cb function
],
function(err, result) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err));
}
// respond to client with result from database
res.send(201, result);
return next();
},
);
});