-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
761 lines (655 loc) · 23.1 KB
/
index.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
// NOTE: COOKIES DON'T WORKING USING LOCALHOST, MUST USE 127.0.0.1.
// node node_modules/gibber.server 8080 '/www/gibber.libraries/'
var request = require( 'request' ),
connect = require( 'connect' ),
url = require( 'url' ),
fs = require( 'fs' ),
passport = require( 'passport' ),
express = require( 'express' ),
sharejs = require( 'share' ),
shareCodeMirror = require( 'share-codemirror'),
app = express(),
RedisStore = require( 'connect-redis' )( express ),
server = require( 'http' ).createServer( app ),
util = require( 'util' ),
LocalStrategy = require( 'passport-local' ).Strategy,
queryString = require( 'querystring' ),
rtc = require( './gibber_rtc.js' )( server, process.argv[4] ),
nodemailer = require( 'nodemailer' ),
transporter = nodemailer.createTransport(),
webServerPort = process.argv[2] || 80, //second argument passed to command
serverRoot = process.argv[3] || __dirname + '/../../',
users = [],
_url = 'http://127.0.0.1:5984/gibber',
designURI = 'http://127.0.0.1:5984/gibber/_design/gibber/',
searchURL = 'http://127.0.0.1:5984/_fti/local/gibber/_design/fti/';
function findById(id, fn) {
var idx = id;
if (users[idx]) {
fn(null, users[idx]);
} else {
fn( null, null )
//fn(new Error('User ' + id + ' does not exist'));
}
}
function findByUsername(username, fn) {
request(
{ uri:designURI + '_view/password?key="'+username+'"', json: true },
function(e,r,b) {
//console.log(b.rows)
if(b.rows && b.rows.length === 1) {
var user = { username:b.rows[ 0 ].key, password: b.rows[ 0 ].value, id:users.length } // MUST GIVE A USER ID FOR SESSION MAINTENANCE
users.push( user )
return fn( null, user );
}else{
return fn( null, null );
}
}
)
}
function findByTag( tag, fn ) {
request(
{ uri:designURI + '_view/tagged', json: true },
function(e,r,b) {
// console.log(b.rows)
var results = []
if(b.rows && b.rows.length > 0) {
for( var i = 0; i < b.rows.length; i++ ) {
var row = b.rows[ i ]
if( row.value.indexOf( tag ) > -1 ) results.push( row.key )
}
}
return results
}
)
}
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser( function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(
function(username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
})
});
}
));
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', ["http://127.0.0.1:8080"]);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
// res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials', 'false')
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept')
next();
}
var checkForREST = function( req, res, next ) {
var arr = req.url.split('/');
if( arr[1] === 'gibber' ) {
arr.shift(); arr.shift(); // get rid of first two elements, the first / and gibber/
var url = escapeString( arr.join('/') )
request('http://127.0.0.1:5984/gibber/'+ url, function(err, response, body) {
res.send( body )
// res.redirect( 'http://gibber.mat.ucsb.edu/?url='+url, { loadFile: body } )
})
}else{
next()
}
}
var checkForVersion = function( req, res, next ) {
var version = null,
search = /\/(v(\d+))/.exec( req.originalUrl )
if( search && search.length !== 0 ) {
version = search[2]
remove = search[1]
req.url = req.url.slice( remove.length + 1 ) // remove version string from URL
}
req.gibberVersion = version
next()
}
var entityMap = { "&": "%26", "'": '%27', "/": '%2F' };
function escapeString( string ) {
return String( string ).replace(/[&<>"'\/]/g, function ( s ) {
return entityMap[ s ];
});
}
// var app = express();
var oneDay = 86400000;
app.engine('htm', require('ejs').renderFile);
app.configure( function() {
app.set('views', serverRoot + 'snippets/')
app.set('view engine', 'ejs')
//app.use(express.logger())
app.use( express.cookieParser() )
//app.use(express.methodOverride())
app.use( express.session({ secret:'gibber gibberish gibbering' }) )// store:new RedisStore() }) )
//{ /* */ secret: 'gibber gibberish gibbering', expires:false, maxAge:10000000000 }) )
app.use( express.bodyParser() )
app.use( passport.initialize() )
app.use( passport.session() )
app.use( allowCrossDomain )
app.use( checkForVersion )
app.use( app.router )
app.use( checkForREST )
app.use( express.static( sharejs.scriptsDir ) )
// serve share codemirror plugin
app.use( express.static( shareCodeMirror.scriptsDir ) )
app.use( express.static( serverRoot/*, { maxAge:oneDay } */ ) )
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
})
app.get( '/', function(req, res){
var path, version = null
if( req.query ) {
if( req.query.path || req.query.p ) {
path = req.query.path || req.query.p
if( path.indexOf('/publications') === -1 ) { // shorthand to leave publications out of url
var arr = path.split( '/' )
path = arr[0] + '/publications/' + arr[1]
}
request('http://127.0.0.1:5984/gibber/' + escapeString( path ), function(err, response, body) {
var _body = JSON.parse( body )
if( body && typeof body.error === 'undefined' ) {
res.render( 'index', { loadFile:body, isInstrument:_body.isInstrument || 'false', gibberVersion: req.gibberVersion } )
}else{
res.render( 'index', { loadFile: JSON.stringify({ error:'path not found' }) })
}
})
}else if( req.query.i ) {
path = req.query.i
if( path.indexOf('/publications') === -1 ) { // shorthand to leave publications out of url
var arr = path.split( '/' )
path = arr[0] + '/publications/' + arr[1]
}
request('http://127.0.0.1:5984/gibber/' + escapeString( path ), function(err, response, body) {
var _body = JSON.parse( body )
if( body && typeof body.error === 'undefined' ) {
res.render( 'index', { loadFile:body, isInstrument:true, gibberVersion: req.gibberVersion } )
}else{
res.render( 'index', { loadFile: JSON.stringify({ error:'path not found' }) })
}
})
}else if( req.query.u || req.query.user ) {
path = req.query.u || req.query.user
request( designURI + '_view/publications?key=%22'+path+'%22', function(e,r,_b) {
res.render( 'instrumentBrowser', {
user: path,
userfiles:(JSON.parse(_b)).rows,
});
})
}else{
res.render( 'index', { loadFile:'null', isInstrument:'false', gibberVersion: req.gibberVersion } )
}
}
// fs.readFile(serverRoot + "index.htm", function (err, data) {
// if (err) {
// next(err);
// return;
// }
// res.writeHead( 200, {
// 'Content-Type': 'text/html',
// 'Content-Length': data.length
// })
// res.end( data )
// })
})
app.get( '/tag', function( req, res ) {
if( req.query.tag ) {
request(
{ uri:designURI + '_view/tagged', json: true },
function(e,r,b) {
var results = []
if(b.rows && b.rows.length > 0) {
for( var i = 0; i < b.rows.length; i++ ) {
var row = b.rows[ i ]
if( row.value.indexOf( req.query.tag ) > -1 ) results.push( row.key )
}
}
res.send({ results: results })
}
)
}
})
app.get( '/recent', function( req, res ) {
request(
{ uri:designURI + '_view/recent?descending=true&limit=20', json: true },
function(e,r,b) {
res.send({ results: b.rows })
}
)
})
app.get( '/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
})
app.post( '/requestPassword', function(req, res){
request( 'http://127.0.0.1:5984/gibber/' + req.body.username, function(e,r,_b) {
var data = JSON.parse( _b ),
password = data.password,
email = data.email
if( typeof email === 'undefined' || email === '' ) {
res.send({ result:'fail', msg:'You did not specify an email account for password reminders. Please contact an administrator if you need access to this account.'})
}else{
transporter.sendMail({
from: '[email protected]',
to: email,
subject:'gibber password reminder',
text:'As requested, your gibber password is ' + password + '.'
})
res.send({ result:'success', msg:'An email with your password been sent to ' + email })
}
})
})
app.get( '/login', function(req, res){
// console.log(" LOGIN? ")
res.render( 'login_start', { user: req.user, message:'login' /*req.flash('error')*/ });
})
app.get( '/loginStatus', function( req, res ) {
if( req.isAuthenticated() ) {
res.send({ username: req.user.username })
}else{
res.send({ username: null })
}
})
// app.post( '/test', function(req, res, next){
// console.log("TESTING", req.user, req.isAuthenticated() )
// next()
// res.render( 'login_start', { user: req.user, message: req.flash('error') });
// })
app.post( '/retrieve', function( req, res, next ) {
// console.log( req.body )
var suffix = req.body.address.replace(/\//g, '%2F'),
_url = 'http://127.0.0.1:5984/gibber/' + suffix
if( _url.indexOf('%2Fpublications') === -1 ) { // shorthand to leave publications out of url
var arr = _url.split( '/' )
_url = arr[0] + '%2Fpublications%2F' + arr[1]
}
_url += suffix.indexOf('?') > -1 ? "&revs_info=true" : "?revs_info=true"
request( _url, function(e,r,b) {
//console.log( e, b )
res.send( b )
})
})
app.get( '/create_publication', function( req, res, next ) {
//console.log( req.user )
res.render( 'create_publication', { user: req.user, message:'publication' } );
})
app.post( '/publish', function( req, res, next ) {
var date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
time = date.toLocaleTimeString()
//console.log( "USERNAME", req.body.username )
request.post({
url:'http://127.0.0.1:5984/gibber/',
json:{
_id: req.body.username + '/publications/' + req.body.name,
name: req.body.name,
author: req.body.username,
language: req.body.language,
type: 'publication',
publicationDate: [year, month, day, time],
text: req.body.code,
tags: req.body.tags,
permissions : req.body.permissions === 'true' ? true : false,
isInstrument: false, //req.body.instrument,
notes: req.body.notes
}
},
function ( error, response, body ) {
if( error ) {
res.send({ error:"unable to publish; most likely you used some reserved characters such as ? & or /" })
}else{
console.log( "Attempted to publish", body, req.body )
if( body.error ) {
res.send({ error:'could not publish to database. ' + body.reason })
}else{
body.url = req.body.username + '/publications/' + req.body.name
//res.send( body )
var suffix = body.url.replace(/\//g, '%2F'),
_url = 'http://127.0.0.1:5984/gibber/' + suffix
if( _url.indexOf('%2Fpublications') === -1 ) { // shorthand to leave publications out of url
var arr = _url.split( '/' )
_url = arr[0] + '%2Fpublications%2F' + arr[1]
}
_url += suffix.indexOf('?') > -1 ? "&revs_info=true" : "?revs_info=true"
request( _url, function(e,r,b) {
console.log( e, b )
res.send( b )
})
}
}
}
)
})
app.post( '/update', function( req, res, next ) {
//console.log( req.body._rev, req.body._id )
if( typeof req.user === 'undefined' ) {
res.send({ error:'you are not currently logged in.' })
return
}
//console.log(req.body)
if( req.body.__proto__ ) delete req.body.__proto__
var docName = req.body._id.split('/')
request.put({
url:'http://127.0.0.1:5984/gibber/' + req.user.username + '%2Fpublications%2F' + docName[2], // must use username explicitly for security
json: req.body
},
function ( error, response, body ) {
if( error ) {
res.send({ error:"unable to publish; most likely you used some reserved characters such as ? & or /" })
}else{
// console.log( "Attempted to publish", body, req.body )
if( body.error ) {
console.log( 'fail', body.reason )
res.send({ error:'could not publish to database. ' + body.reason })
}else{
res.send({ _rev: body.rev })
}
}
}
)
})
app.post( '/createNewUser', function( req, res, next ) {
request.post({url:'http://127.0.0.1:5984/gibber/', json:req.body},
function (error, response, body) {
if( error ) {
console.log( error )
res.send({ msg: 'The server was unable to create your account' })
} else {
res.send({ msg:'User account ' + req.body._id + ' created' })
}
}
)
})
app.get( '/welcome', function( req, res, next ) {
res.render( 'welcome', {
user:req.user
})
})
app.get( '/preferences', function( req, res, next ) {
res.render( 'preferences', {
user:req.user
})
})
app.get( '/documentation', function( req, res, next ) {
res.render( 'docs', {
user:req.user
})
})
app.get( '/help', function( req, res, next ) {
res.render( 'help', {
user:req.user
})
})
app.get( '/docs/', function( req,res,next ) {
res.render( '../docs/output/'+req.query.group+'/'+req.query.file+'.htm' )
})
app.get( '/credits', function( req,res,next ) {
res.render( 'credits' )
})
// adds inspect function to .ejs templates, used in browser .ejs to dynamically inject js
app.locals.inspect = require('util').inspect;
app.get( '/browser', function( req, res, next ) {
var demos = {}
request( designURI + '_view/demos', function(e,r,b) {
var audio = [], visual = [], audiovisual = [], demoRows = JSON.parse( b ).rows
for( var i =0; i < demoRows.length; i++ ) {
var cat, row = demoRows[ i ]
cat = row.value.category || 'audiovisual'
switch( cat ) {
case 'Visual': visual.push( row ); break;
case 'Audio' : audio.push( row ); break;
default: audiovisual.push( row ); break;
}
}
demos.visual = visual; demos.audio = audio; demos.audiovisual = audiovisual;
request( { uri:designURI + '_view/recent?descending=true&limit=20', json: true },
function(__e,__r,__b) {
var recent = []
for( var i = 0; i < __b.rows.length; i++ ){
console.log( __b.rows[i] )
recent.push( __b.rows[i].value )
}
request( designURI + '_view/tutorials', function(e,r,b) {
// console.log( (JSON.parse(b)).rows )
var _audio = [], _3d = [], _2d = [], _misc=[], demoRows = JSON.parse( b ).rows
for( var i =0; i < demoRows.length; i++ ) {
var cat = 'misc', row = demoRows[ i ]
//console.log( row )
if( row.key.split('*').length > 0 ) {
cat = row.key.split('*')[1]
switch( cat ) {
case '2d' :
_2d.push( row ); break;
case '3d' : _3d.push( row ); break;
case 'audio' : _audio.push( row ); break;
default:
_misc.push( row ); break;
}
}
}
if( req.user ) {
//console.log("USER ACCOUNT")
request({
uri:designURI + '_view/publications?key=%22'+req.user.username+'%22',
json:true
},
function(e,r,_b) {
//console.log(_b)
res.render( 'browser', {
user: req.user,
demos:demos,
audio:_audio,
_2d:_2d,
_3d:_3d,
misc:_misc,
userfiles:_b.rows,
recent: recent,
});
})
}else{
//console.log("NO USER ACCOUNT")
res.render( 'browser', {
user: null,
demos: demos,
audio: _audio,
_2d: _2d,
_3d: _3d,
misc: _misc,
userfiles:[],
recent:recent,
});
}
});
})
})
})
app.post( '/userfiles', function( req,res,next ) {
if( req.user && req.user.username ) {
request({
uri:designURI + '_view/publications?key=%22'+req.user.username+'%22',
json:true
},
function(e,r,_b) {
res.send({
files:_b.rows,
});
})
}else{
res.send({ msg:'No user is logged in. Cannot retrieve userfiles.' })
}
})
app.get( '/chat', function( req, res, next ) {
var result = {}
if( !req.user ) {
result.error = "You must log in (create an account if necessary) before using chat."
res.send( result )
}else{
res.render( 'chat' )
}
})
app.get( '/demos', function( req, res, next ) {
request( designURI + '_view/demos', function(e,r,b) {
var audio = [], visual = [], audiovisual = [], demoRows = JSON.parse( b ).rows
for( var i =0; i < demoRows.length; i++ ) {
var cat, row = demoRows[ i ]
cat = row.demoCategory || 'audiovisual'
switch( cat ) {
case 'visual': visual.push( row ); break;
case 'audio' : audio.push( row ); break;
default: audiovisual.push( row ); break;
}
}
res.render( 'demos', { audio:audio, visual:visual, audiovisual:audiovisual})
})
})
app.post( '/deleteUserFile', function( req, res, next ) {
var fileInfo = req.body
console.log( fileInfo )
})
app.post( '/search', function( req, res, next) {
var result = {},
query = queryString.escape(req.body.query), filter = req.body.filter,
url = searchURL + filter + "?q="+query
console.log( "SEARCH REQUEST", url )
if( typeof query === 'undefined' || typeof filter === 'undefined') {
result.error = 'Search query or search type is undefined.'
res.send( result )
return
}
var pubs = [], count = 0
request({ 'url':url }, function(e,r,b) {
//console.log( b )
b = JSON.parse( b )
if( b && b.rows && b.rows.length > 0 ) {
//result.rows = b.rows
//res.send( result )
for( var i = 0; i < b.rows.length; i++ ) {
!function() {
var num = i,
pubID = b.rows[ i ].id,
suffix = pubID.replace(/\//g, '%2F'),
_url = 'http://127.0.0.1:5984/gibber/' + suffix
_url += suffix.indexOf('?') > -1 ? "&revs_info=false" : "?revs_info=false"
request( _url, function(e,r,_b) {
_b = JSON.parse( _b )
delete _b.text
pubs[ num ] = JSON.stringify( _b )
if( ++count === b.rows.length ) sendResults()
})
}()
}
function sendResults() {
res.send({ rows: pubs, totalRows:b.total_rows })
}
}else{
if( b.reason ) {
res.send({ error:b.reason })
}else{
res.send({ rows:[] })
}
}
})
//request({ url:searchURL, json:})
/*request({ url: esUrl , json:{
"query": {
"filtered" : {
"query" : {
"query_string" : {
"query" : req.body.query
}
}
}
},
}}, function(e,r,b) {
console.log("SEARCH RESULTS:", b )
var result = {}
if(b) {
if( b.hits ) {
for(var i = 0; i < b.hits.hits. length; i++ ) {
console.log( b.hits.hits[i] )
if( b.hits.hits[i]._id )
result[ b.hits.hits[i]._id ] = b.hits.hits[i]._source.text
//console.log("RESULT " + i + ":", b.hits.hits[i]._id, b.hits.hits[i]._source.text )
}
}else{
result.noresults = "No matches were found for your query."
}
}else{
if( b ) {
result.error = b.indexOf('error') > -1 ? "The gibber database appears to be down. Please contact an administrator" : "No hits were found"
}else{
result.error = "The search database is offline. Please, please, please report this to [email protected]"
console.log(e, r)
}
}
res.send(result)
})*/
})
app.post( '/login', function( req, res, next ) {
passport.authenticate( 'local', function( err, user, info ) {
var data = {}
//console.log( "LOGGING IN... ", user, err, info )
if (err) { return next( err ) }
if (!user) {
res.send({ error:'Your username or password is incorrect. Please try again.' })
}else{
req.logIn( user, function() {
res.send({ username: user.username })
});
}
})( req, res, next );
})
app.get('/logout', function(req, res, next){
if( req.user ) {
req.logout();
res.send({ msg:'logout complete' })
}else{
//console.log( "There wasn't any user... " )
res.send({ msg:'you aren\t logged in... how did you even try to logout?' })
}
//res.redirect('/');
});
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
nodemailer.sendmail = true
server.listen( webServerPort )
rtc.init()