forked from joemccann/dillinger
/
routes.js
432 lines (356 loc) · 12.2 KB
/
routes.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
var dbox = require('./utils/dropbox').dropbox,
appConfig = require('./config'),
fs = require('fs'),
md = require('./utils/md').md,
githubProxy = require('./utils/github'),
dropboxProxy = require('./utils/dropbox')(appConfig.dropbox.consumer_key, appConfig.dropbox.consumer_secret),
request = require('request'),
qs = require('querystring');
// Routes
function initRoutes (app) {
app.get('/', function(req, res, next){
if (!req.session) {
return next('Session not initialized');
}
// if(typeof req.session.dropbox !== 'undefined' && typeof req.session.dropbox.access_token !== 'undefined'){
// // Create a new request token on every request
// dbox.forceNewRequestToken(function(err, data){
// if (err) {
// next(err);
// } else{
// res.local('dropbox',{
// sync : true,
// request_token: dbox.getRequestToken(),
// oauth_callback: dbox.getOauthCallback()
// });
// dbox.setAccessToken(req.session.dropbox.access_token);
// dbox.setAccessTokenSecret(req.session.dropbox.access_token_secret);
// dbox.getAccountInfo(function(err, data){
// if(err){
// // If this fails, the token is old or something else is
// // wrong so let's delete it and redirect, thus trying agin.
// delete req.session.dropbox;
// return res.redirect('/');
// } else {
// // If there's no error, let's now check Github's oauth setting.
// res.local('dropbox', {
// sync : true,
// request_token: dbox.getRequestToken(),
// oauth_callback: dbox.getOauthCallback()
// });
// return checkGithubOauth(req, res, next);
// }
// });
// }
// });
// } else{
// // Create a new request token on every request
// dbox.forceNewRequestToken(function(err, data){
// if(err) {
// next(err);
// } else{
// res.local('dropbox',{
// sync : null,
// request_token: dbox.getRequestToken(),
// oauth_callback: dbox.getOauthCallback()
// });
// checkGithubOauth(req, res, next);
// }
// });
// }
res.render('dillinger', {
title: 'Dillinger, the last Markdown editor, ever.',
version: appConfig.VERSION,
debugging: appConfig.debug,
layout: 'dillinger-layout',
loggedIn: false,
github: !!req.session.github ? req.session.github : false,
dropbox: !!req.session.dropbox ? req.session.dropbox : false
});
});
app.get('/github/authorizeApp', function (req, res, next) {
var url = "https://github.com/login/oauth/authorize?" +
"client_id=" + appConfig.github.client_id +
"&scope=repo" +
"&redirect_uri=" + appConfig.github.callback_url;
res.redirect(url);
});
/*
* OAuth callback
*/
app.get('/oauth/github', function(req, res, next) {
if (!req.query.code) {
next();
} else {
var paramsObj = {
code: req.query.code,
client_id: appConfig.github.client_id,
redirect_url: appConfig.github.redirect_uri,
client_secret: appConfig.github.client_secret
};
var opts = {
uri: 'https://github.com/login/oauth/access_token?' + qs.stringify(paramsObj)
};
request.post(opts, function(err, resp, body){
req.session.github = req.session.github || {};
if(err) {
res.send(err.message);
} else {
req.session.github.access_token = qs.decode(body).access_token;
githubProxy.getCurrentUserInfo(req.session.github.access_token, function (err, data) {
console.log('HOP', req.session);
if (err) {
res.send(err);
} else {
var d = JSON.parse(data);
req.session.github.username = d.login;
res.redirect('/');
}
});
}
});
}
});
function _defaultHandler (res) {
return function _defaultHandlerReal (err, data) {
if (err) {
res.send({
error: 'Request error.',
data: err
});
} else {
res.json(data);
}
};
}
/* Github Actions */
app.post('/github/repo/fetch_all', function (req, res) {
githubProxy.fetchUserRepos(req.session.github.access_token, _defaultHandler(res));
});
app.post('/github/repo/fetch_branches', function(req,res){
githubProxy.fetchUserRepositoryBranches(
req.session.github.access_token,
req.session.github.username,
req.body.repo,
_defaultHandler(res)
);
});
app.post('/github/repo/fetch_tree_files', function (req,res){
githubProxy.fetchUserRepositoryTreeFiles(
req.session.github.access_token,
req.session.github.username,
req.body.repo,
req.body.sha,
_defaultHandler(res)
);
});
app.post('/github/repo/fetch_markdown_file', function (req,res){
githubProxy.fetchFileFromURL(req.session.github.access_token, req.body.mdFile, function (err, data) {
if (err) {
res.send({
error: 'Request error.',
data: err
});
} else {
res.json({data: data});
}
});
});
app.get('/dropbox/authorizeApp', function (req, res, next) {
dropboxProxy.getRequestToken(function (err, data) {
req.session.dropbox = data;
var url = "https://www.dropbox.com/1/oauth/authorize?" +
"oauth_token=" + data.oauth_token +
"&oauth_callback=" + appConfig.dropbox.oauth_callback;
res.redirect(url);
});
});
/* Dropbox OAuth */
app.get('/oauth/dropbox', function (req, res, next) {
if(!req.query.oauth_token) {
next();
} else {
req.session.dropbox.oauth_token = req.query.oauth_token;
req.session.dropbox.uid = req.query.uid;
dropboxProxy.getAccessToken(req.session.dropbox.oauth_token, req.session.dropbox.oauth_token_secret, function (err, data) {
if (err) {
res.send('Error while fetching access token: ' + err);
} else {
delete req.session.dropbox.oauth_token;
delete req.session.dropbox.oauth_token_secret;
req.session.dropbox.access_token_secret = data.oauth_token_secret;
req.session.dropbox.access_token = data.oauth_token;
res.redirect('/');
}
});
}
});
/* Dropbox Actions */
// Search for all .md files.
app.get('/dropbox/search', function (req, res){
if(typeof req.session.dropbox === 'undefined') {
return res.json( { "data": "Not authorized with Dropbox."} );
}
dropboxProxy.searchForMdFiles(
req.session.dropbox.access_token,
req.session.dropbox.access_token_secret,
function (err, data) {
res.json(err);
});
});
app.get('/dropbox/account/info', function (req,res) {
if (typeof req.session.dropbox === 'undefined') {
return res.json({
"data": "You must authorize Dropbox first before using this action."
});
}
dropboxProxy.getAccountInfo(
req.session.oauth_token,
req.session.oauth_token_secret,
function (err,data) {
if (err) {
res.json(err);
} else {
res.send(data);
}
}
);
});
// Basically your directory listing with 'dropbox' as the root.
app.get('/dropbox/metadata', function(req,res){
if(typeof req.session.dropbox === 'undefined') return res.json( { "data": "Not authorized with Dropbox."} );
dbox.getMetadata( function(err,data){
if(err){
console.error(err);
res.json(err);
}
else{
res.json(JSON.parse(data));
}
}); // end getMetadata()
});
// Fetch a .md file's contents.
app.post('/dropbox/files/get', function(req,res){
if(typeof req.session.dropbox === 'undefined') return res.json( { "data": "Not authorized with Dropbox."} )
var pathToMdFile = req.body.mdFile
// For some reason dropbox needs me to do this...
// Otherwise, spaces and shit get fuct up
// TODO: DRY THIS UP
var name = pathToMdFile.split('/').pop()
var encodedName = encodeURIComponent(name)
pathToMdFile = pathToMdFile.replace(name, encodedName)
dbox.getMdFile(pathToMdFile, function(err,filedata){
if(err){
console.error(err)
res.json(err)
}
else{
res.json({data: filedata})
}
}) // end getMdFile()
})
app.post('/dropbox/files/put', function(req,res){
if(typeof req.session.dropbox === 'undefined') return res.json( { "data": "Not authorized with Dropbox."} )
var pathToMdFile = req.body.pathToMdFile || '/Dillinger/' + md.generateRandomMdFilename('md')
var contents = req.body.fileContents || 'Test Data from Dillinger.'
// For some reason dropbox needs me to do this...
// Otherwise, spaces and shit get fuct up
var name = pathToMdFile.split('/').pop()
var encodedName = encodeURIComponent(name)
pathToMdFile = pathToMdFile.replace(name, encodedName)
dbox.putMdFile(pathToMdFile, contents, function(err,filedata){
if(err){
console.error(err)
res.json(err)
}
else{
res.json({data: filedata})
}
}) // end getMdFile()
})
/* Dillinger Actions */
// save a markdown file and send header to download it directly as response
app.post('/factory/fetch_markdown', function(req,res){
var unmd = req.body.unmd
, json_response =
{
data: ''
, error: false
}
// TODO: maybe change this to user submitted filename or name of repo imported file?
var name = md.generateRandomMdFilename('md')
var filename = ( __dirname + '/public/files/md/' + name )
// TODO: THIS CAN BE OPTIMIZED WITH PIPING INSTEAD OF WRITING TO DISK
fs.writeFile( filename, unmd, 'utf8', function(err, data){
if(err){
json_response.error = true
json_response.data = "Something wrong with the markdown conversion."
res.send( JSON.stringify( json_response) );
if(debug) throw err
}
else{
json_response.data = name
res.send( JSON.stringify( json_response) );
}
}) // end writeFile
}) // end post
// save a html file and send header to download it directly as response
app.post('/factory/fetch_html', function(req,res){
var unmd = req.body.unmd
, json_response =
{
data: ''
, error: false
}
var html = md.getHtml(req.body.unmd)
var name = md.generateRandomMdFilename('html')
var filename = ( __dirname + '/public/files/html/' + name )
fs.writeFile( filename, html, 'utf8', function(err, data){
if(err){
json_response.error = true
json_response.data = "Something wrong with the markdown conversion."
res.send( JSON.stringify( json_response) );
if(debug) throw err
}
else{
json_response.data = name
res.send( JSON.stringify( json_response) );
}
}) // end writeFile
}) // end post
// route to handle download of md file
app.get('/files/md/:mdid', function(req, res){
var fileId = req.params.mdid
var filename = __dirname + '/public/files/md/' + fileId
res.attachment(filename)
res.download(filename, function(err){
if(err) console.error(err)
else{
// Delete the file after download
fs.unlink(filename, function(err, data){
if(err) console.error(err)
})
}
})
})
// route to handle download of html file
app.get('/files/html/:html', function(req, res){
var fileId = req.params.html
var filename = __dirname + '/public/files/html/' + fileId
res.attachment(filename)
res.download(filename, function(err){
if(err) console.error(err)
else{
// Delete the file after download
fs.unlink(filename, function(err, data){
if(err) console.error(err)
})
}
})
})
}
exports = module.exports = {
add: function (app) {
initRoutes(app);
}
}