-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.js
executable file
·491 lines (440 loc) · 14.7 KB
/
web.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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
if(process.env.NODETIME_ACCOUNT_KEY) {
require('nodetime').profile({
accountKey: process.env.NODETIME_ACCOUNT_KEY,
appName: 'My Application Name' // optional
});
}
var express = require('express'),
app = module.exports = express(),
request = require('request'),
// RedisStore = require('connect-redis')(express),
util = require('util'),
mu = require('mu2'),
debug = require('debug')('photoflux:web'),
auth = require('connect-auth')
async = require('async');
var storage = require('./lib/storage'),
fb = require('./lib/facebook');
var updateInterval = 5 * 60 * 1000; // min * second * milisecond
var imagesPerPage = 5;
// Session configuration
var cookieSecret = process.env.SECRET || "afv932uvrnjqi4rh9";
app.engine('mustache', mu2proxy);// rendu mustache. @see:mu2proxy
app.param('fid', loadFlux);
app.use(express.logger('dev'));
app.use(express.favicon());
//app.use(express.compress());
app.use("/static", express.static(__dirname + '/static/'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({
secret: cookieSecret,
// store: new RedisStore(redisOptions)
}));
app.use(auth({
strategies: auth.Facebook({
appId : process.env.FACEBOOK_APP_ID || 0,
appSecret: process.env.FACEBOOK_SECRET || "abcd1234",
scope: "user_photos,manage_pages",
// callback: process.env.FACEBOOK_CALLBACK || "http://photoflux.tarnet.ch/imback"}),
// callback doit être ça, car hard-codé dans la strategie facebook
// TODO: réécrire la strategie, pour être un peu plus modulable.
callback: process.env.FACEBOOK_CALLBACK || "http://photoflux.tarnet.ch/auth/facebook_callback"}),
trace: true}));
app.use(app.router);
///////////////////////////////////////////////////////
// Routes
app.get("/", render("index.mustache", {title: "PhotoFlux | Page d'accueil"}));
app.get("/letsgo", function(req, res) { res.render("letsgo.mustache", defaultData(req)); });
app.get("/loginWithFacebook", fbConnected, loginWithFacebook);
app.get("/albumsSelection", fbConnected, albumsSelectionGet);
app.get("/albumsSelection/:pid", fbConnected, albumsSelectionGet);
app.post("/albumsSelection", fbConnected, albumsSelectionPost);
app.post("/albumsSelection/:pid", fbConnected, albumsSelectionPost);
app.get("/fluxValidation", fbConnected, validation, renderFlux);
app.get("/fluxValidation/:page", fbConnected, validation, renderFlux);
app.get("/fluxCreation", fbConnected, saveFlux);
app.get("/login", fbConnected, login);
app.get("/logout", logout);
app.get("/f/:fid", updateFluxIfNeeded, renderFlux);
app.get("/f/:fid/:page", renderFlux);
app.get("/confidentiality", render('confidentiality.mustache'));
app.get("/eula", render('eula.mustache'));
app.get("/support", render('support.mustache'));
app.get("/robots.txt", function(req, res) {
res.sendfile("views/robots.txt", {root: __dirname});
});
// development stuff
if(process.env.NODE_ENV == "development") {
app.get("/test", dummy);
app.get("/_session", function(req, res) { res.set('Content-Type', "application/json"); res.end(JSON.stringify(req.session, null, 2));});
}
///////////////////////////////////////////////////////
// listen to the PORT given to us in the environment
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("PhotoFlux listening on " + port);
});
///////////////////////////////////////////////////////
// route functions
function loginWithFacebook(req, res, next) {
var auth = req.getAuthDetails();
var fid = auth.user.username || auth.user.id;
var pages, albums;
async.parallel([
// tente de charger le flux depuis le storage
function(callback) {
storage.getFlux(fid, function(err, data) {
if(err && !data) return callback(err);
if(data.error) {
debug("storage return an error", data);
// une soft erreur, la galerie n'existe juste pas.
if(data.error === "not_found") {
return callback();
}
// si c'est une autre erreur, on la propage.
else {
return callback(new Error(data.error + ": " + data.reason));
}
}
// tout va bien, on poursuit la route.
req.session.flux = data;
callback();
});
},
// récupère la liste des albums sur facebook
function(callback) {
debug("Fetching facebook pages and albums list");
fb.get(req.session.access_token, auth.user.id, "accounts.fields(id,access_token,link,username,name,albums.fields(name,cover_photo,privacy)),albums.fields(name,cover_photo,privacy)", function(err, data) {
if(err) return next(err);
albums = data.albums.data;
if(data.accounts) {
pages = data.accounts.data;
for(var i = 0; i < pages.length; i++) {
pages[i].pid = pages[i].username || pages[i].id;
}
}
//récupère les images de couvertures
debug("Fetching cover photos");
var covers = [];
for(var i = 0; i < albums.length; i++) {
covers.push(albums[i].cover_photo);
}
fb.get(req.session.access_token, covers, "picture", function(err, data) {
if(err) return next(err);
for(var i = 0; i < albums.length; i++) {
var picture = data[albums[i].cover_photo];
albums[i].cover_photo = picture;
}
callback();
});
});
}
], function() {
// merge les albums fb avec le flux ou crée un nouveau flux
var flux = req.session.flux = req.session.flux || {};
flux._id = flux._id || "flux-" + fid;
flux.type = "flux";
// merge user
flux.user = req.session.flux.user || {};
flux.user.id = auth.user.id;
flux.user.name = auth.user.name;
flux.user.link = auth.user.link;
flux.user.username = auth.user.username;
flux.user.locale = auth.user.locale;
flux.user.token = req.session.access_token;
// merge albums
flux.albums = flux.albums || [];
for(var i = 0; i < flux.albums.length; i++) {
if(flux.albums[i].selected) {
for(var j = 0; j < albums.length; j++) {
if(flux.albums[i].id == albums[j].id) {
albums[j].selected = true;
}
}
}
}
flux.albums = albums;
flux.pages = pages;
// redirect vers albumsSelection
res.redirect('/albumsSelection');
});
}
function albumsSelectionGet(req, res, next) {
var flux = req.session.flux;
// les albums d'une page sont demandés
if(req.params.pid) {
debug("albumsSelection for a page");
var pid = req.params.pid;
var page;
for(var i = 0; i < flux.pages.length; i++) {
if(pid == flux.pages[i].pid) {
page = flux.pages[i];
}
}
debug("page is", page, page.albums.data);
storage.getFlux(pid, function(err, pageFlux) {
if(err && !pageFlux) return next(err);
debug("getFlux just return", pageFlux);
if(pageFlux.error) {
debug("storage return an error", pageFlux);
// une soft erreur, la galerie n'existe juste pas.
if(pageFlux.error === "not_found") {
req.session.pageFlux = pageFlux = {};
}
// si c'est une autre erreur, on la propage.
else {
return next(new Error(pageFlux.error + ": " + pageFlux.reason));
}
}
else {
req.session.pageFlux = pageFlux;
}
var albums = page.albums.data;
// merge pageFlux
pageFlux.type = "flux";
pageFlux._id = pageFlux._id || "flux-" + pid;
pageFlux.user = pageFlux.user || {};
pageFlux.user.id = page.id;
pageFlux.user.username = page.username;
pageFlux.user.name = page.name;
pageFlux.user.link = page.link;
pageFlux.user.token = page.access_token;
pageFlux.albums = pageFlux.albums || [];
debug("mergin pageFlux", pageFlux.albums, albums);
for(var i = 0; i < pageFlux.albums.length; i++) {
if(pageFlux.albums[i].selected) {
for(var j = 0; j < albums.length; j++) {
if(flux.albums[i].id == albums[j].id) {
debug("Go here...............................");
albums[j].selected = true;
}
}
}
}
pageFlux.albums = albums;
debug("pageFlux merged", pageFlux);
var covers = [];
for(var i = 0; i < albums.length; i++) {
covers.push(albums[i].cover_photo);
}
fb.get(page.access_token, covers, "picture", function(err, photos) {
if(err) return next(err);
for(var i = 0; i < albums.length; i++) {
var photo = photos[albums[i].cover_photo];
albums[i].cover_photo = photo;
}
debug("render albums", albums);
res.render("albumSelection.mustache", defaultData(req, {
albums: albums
}));
});
});
}
else {
debug("albumsSelection for user album", req.session.flux.pages);
res.render("albumSelection.mustache", defaultData(req, {
albums: flux.albums,
pages: {list: flux.pages}
}));
}
}
function albumsSelectionPost(req, res, next) {
if(!req.body) return next(new Error("Nothing in body"));
if(typeof req.body !== "object") return next(new Error("Body not an object"));
if(!req.body.album) return next(new Error("No album in body"));
var flux;
// l'album concerne une page
if(req.params.pid) {
var pid = req.params.pid;
flux = req.session.pageFlux;
}
else {
flux = req.session.flux;
}
var albums = flux.albums;
var selectedAlbums = typeof req.body.album === "string" ? [req.body.album] : req.body.album;
for(var i = 0; i < albums.length; i++) {
albums[i].selected = (selectedAlbums.indexOf(albums[i].id) > -1);
}
debug("get facebook photos for selected albums");
fb.getPhotos(flux.user.token, selectedAlbums, function(err, photos) {
if(err) return next(err);
flux.photos = photos;
flux.lastUpdate = Date.now();
req.session.flux = flux;
res.redirect("/fluxValidation");
});
}
function saveFlux(req, res, next) {
var flux = req.session.flux;
var fid = flux.user.username || flux.user.id;
storage.saveFlux(fid, flux, function(err) {
if(err) return next(err);
res.redirect("/f/" + fid);
});
}
function login(req, res, next) {
var redir = req.query.redir || req.rootUrl;
res.redirect(redir);
}
function logout(req, res, next) {
req.logout(function() {
req.session.destroy(function(err) {
if(err) return next(err);
res.redirect("/");
});
});
}
////////////////////////////////////////////////////////
// helper functions
// MiddleWare pour s'assurer que l'utilisateur est connecté à facebook
function fbConnected(req, res, next) {
// if(req.isAuthenticated()) {
// next();
// }
// else {
req.authenticate('facebook', function(err, authenticated) {
if(err) return next(err);
if(authenticated == true) {
next();
}
else if(authenticated == false) {
res.redirect(req.rootUrl);
}
else {}
});
// }
}
function validation(req, res, next) {
req.validate = true;
next();
}
// Affichage du flux avec gestion du paging
function renderFlux(req, res, next) {
if(!req.session.flux) return next(new Error("No flux loaded"));
var photos = req.session.flux.photos;
var ipp = imagesPerPage;
var page = req.params.page || 1;
if((page-1)*ipp >= photos.length) return res.send(404);
var homeUrl = req.route.path.replace(":fid", req.session.flux._id.substring("flux-".length)).replace("/:page", "") + "/";
var haveNext = page*ipp < photos.length;
var data = defaultData(req, {
photos: photos.slice(ipp*(page-1), ipp*page),
infiniteScroll: true,
validate: req.validate,
pager: {
current: page,
prev: page < 2 ? false : homeUrl + (page-1),
home: homeUrl,
next: haveNext ? homeUrl + (page+1) : false
}
});
res.render("galerie.mustache", data);
}
function render(template, data) {
return function(req, res) {
res.render(template, defaultData(req, data));
};
}
// Mise-à-jour du flux auprès de facebook, si l'interval de mise-à-jour est passée
function updateFluxIfNeeded(req, res, next) {
// on passe si aucun flux
if(!req.session.flux) return next();
// si le flux est à jour, on passe
var flux = req.session.flux;
if(flux.lastUpdate && flux.lastUpdate + updateInterval > Date.now()) return next();
// si on a pas de token on passe avec un warning
if(!flux.user.token) {
debug("Aucun token disponible pour mettre à jour ce flux.");
return next();
}
// mise-à-jour très simple, on remplace seulement les données qu'on a
// part celles fournies par facebook.
debug("updating flux");
var albums = flux.albums;
var selectedAlbums = [];
for(var i = 0; i < albums.length; i++) {
if(albums[i].selected) { selectedAlbums.push(albums[i].id); }
}
fb.getPhotos(flux.user.token, selectedAlbums, function(err, photos) {
if(err) return next(err);
flux.photos = photos;
flux.lastUpdate = Date.now();
var fid = flux.user.username || flux.user.id;
storage.saveFlux(fid, flux, function(err) {
if(err) return next(err);
return next();
});
});
}
// Charge un flux depuis le storage
function loadFlux(req, res, next, fid) {
debug("loadFlux with fid=" + fid);
// si le flux de la session est déjà le bon, passe à la suite.
if(req.session.flux && req.session.flux._id == "flux-"+fid) {
debug("flux ok, next");
return next();
}
// sinon, on charge le flux depuis la base de donnée et le stock dans la session
storage.getFlux(fid, function(err, data) {
debug("storage return");
if(err && !data) return next(err);
if(data.error) {
debug("storage return an error", data);
// une soft erreur, la galerie n'existe juste pas.
if(data.error === "not_found") {
return res.render("fluxNotFound.mustache");
}
// si c'est une autre erreur, on la propage.
else {
return next(new Error(data.error + ": " + data.reason));
}
}
// tout va bien, on poursuit la route.
req.session.flux = data;
return next();
});
}
// Renseigne les données pour mustache communes à toutes les pages.
function defaultData(req, data) {
console.log(req.headers);
data = data || {};
data.staticUrl = data.staticUrl || "/static";
data.originalUrl = data.originalUrl || req.originalUrl;
data.user = data.user || req.getAuthDetails().user;
data.development = process.env.NODE_ENV == 'development';
data.title = data.title || "PhotoFlux | " + req.url.substring(1);
return data;
}
// On utilise mu2 https://github.com/raycmorgan/Mu plutôt que
// mustache disponible avec consolidate. mustache ne semble
// pas gérer le chargement automatique des parials.
function mu2proxy(path, options, callback) {
mu.root = 'views';
// bric-à-brac pour gérer mon pseudo proxy
if(app.get('views') == "../PhotoFlux/views/") {
mu.root = app.get('views');
path = path.substr(mu.root.length);
}
// on recompile les templates à chaque fois durant le development
if (app.get('env') == 'development') {
debug("clearing mustache cache");
mu.clearCache();
}
var stream = mu.compileAndRender(path, options);
var html = "";
stream.on('data', function(data) {
html += data;
});
stream.on('end', function() {
callback(null, html);
});
stream.on('error', function(err) {
callback(err, null);
});
}
function dummy(req, res) {
res.set('Content_type', 'text/html');
res.send('<html><body><h1>Dummy page</h1><p>'+req.headers.host+req.originalUrl+'</p><h3>params</h3><pre>'+util.inspect(req.params)+'</pre><h3>session</h3><pre>'+util.inspect(req.session)+'</pre></body></html>');
}