-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat-default.bsh
669 lines (522 loc) · 19.8 KB
/
chat-default.bsh
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
#! /bin/bash
## chat-default.bsh last update: 2019-02-13
## Bash-shell script to create the Github-feathers chat application entirely from scratch.
## Script is written entirely from https://docs.feathersjs.com/guides/chat/readme.html
## Note: expect-tcl is used to run the six feathers-cli steps.
## Also, there is a bit of a debate if sudo is required for the feathers installation. I
## am using sudo to make the command global in nature.
## Be sure to run the gist build feathers first!
echo -n 'node version: ' ; node --version ; ## 8.15 at the time of this writing
if [ $? -ne 0 ]; then
echo 'Node has not yet been installed!';
exit 1;
fi
echo -n 'npm version: ' ; npm --version ; ## 6.7.0 at the time of this writing
if [ $? -ne 0 ]; then
echo 'NPM has not yet been installed!';
exit 1;
fi
echo -n 'feathers version: ' ; feathers --version ; ## 3.9.0 at the time of this writing
if [ $? -ne 0 ]; then
echo 'Feathers has not yet been installed!';
exit 1;
fi
THIS_IPADDR=$(dig +short myip.opendns.com @resolver1.opendns.com. ;);
FileNameWithExtension=${0##*/} ;
FileNameWithoutExtension=${FileNameWithExtension%.*} ;
TimeStamp=$(date "+%Y-%m-%d %r") ;
commonPath="$(readlink -f $0 | xargs dirname)"/common;
rm -Rf ./${FileNameWithoutExtension}/ ; ## just in case one already exists.
mkdir ./${FileNameWithoutExtension}/ && cd ./${FileNameWithoutExtension}/ ;
. ${commonPath}/createApp.bsh
## ## feathers generate app; ## taking all the defaults, except for the description
## export FileNameWithExtension;
## export TimeStamp;
## expect <(cat <<'END_OF_GENERATE_APP'
## # generates an application, taking ALL the defaults
##
## # written from https://docs.feathersjs.com/guides/chat/creating.html
##
## set timeout -1
##
## set UPARROW \x1B\[A;
## set DOWNARROW \x1B\[B;
## set SPACE \x20;
## set RETURN \x0d;
##
## spawn feathers generate app;
##
## expect -re ".*Do you want to use JavaScript or TypeScript.*"
## send -- "${RETURN}"
## ## new in Crow 2019-07-01
##
## expect -re ".*Project name.*"
## send -- "${RETURN}"
## ## defaults to the name of the directory
##
## expect -re ".*Description.*"
## send -- "This app created with expect and $env(FileNameWithExtension) $env(TimeStamp)!${RETURN}"
## ## optional description
##
## expect -re ".*What folder should the source files live in\?.*\\\(src\\\).*"
## send -- "${RETURN}"
## ## defaults to 'src'
##
## expect -re ".*Which package manager are you using \\\(has to be installed globally\\\)\?.*"
## send -- "${RETURN}"
## ## defaults to 'npm'
##
## expect -re ".*What type of API are you making.*"
## send -- "${RETURN}"
## ## defaults to REST & Realtime via Socket.io
##
## expect -re ".*Which testing framework do you prefer?.*"
## send -- "${RETURN}"
## ## defaults to Mocha + assert
##
## expect -re ".*This app uses authentication.*"
## send -- "n${RETURN}"
## ## defaults to Y
##
## expect eof
##END_OF_GENERATE_APP
##) ## end of feathers generate app
## feathers generate service; ## all defaults except for the service name - "messages"
expect <(cat <<'END_OF_GENERATE_SERVICE'
## creates a service: messages (all the defaults)
## written from: https://docs.feathersjs.com/guides/chat/service.html
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate service;
expect -re ".*What kind of service is it\?.*"
send -- "${RETURN}"
## defaults to NeDB
expect -re ".*What is the name of the service\?.*"
send -- "messages${RETURN}"
## messages
expect -re ".*Which path should the service be registered on\?.*"
send -- "${RETURN}"
## defaults to /messages
expect -re ".*What is the database connection string\?.*"
send -- "${RETURN}"
## defaults to nedb://../data
expect eof
END_OF_GENERATE_SERVICE
) ## end of feathers genereate service
## feathers generate authentication; ## all defaults
expect <(cat <<'END_OF_GENERATE_AUTH'
# generates an authentication for Github
# written from https://docs.feathersjs.com/guides/chat/authentication.html
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate authentication ;
expect -re ".*What authentication strategies do you want to use\?.*"
send -- "${RETURN}"
## return defaults to Local Storage
expect -re ".*What is the name of the user \\\(entity\\\) service.*"
send -- "${RETURN}"
## default answer is 'users'
expect -re ".*What kind of service is it\?.*"
send -- "${RETURN}"
## default answer is NeDB
expect eof
END_OF_GENERATE_AUTH
) ## end of feathers generate authentication
## feathers generate hook;
## hook name: process-message
## type of hook: before
## which service: messages
## which method: create
expect <(cat <<'END_OF_GENERATE_PROCESS_MESSAGE_HOOK'
# creates the first "BEFORE--CREATE" hook named "process-message" for the "messages" service
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate hook;
expect -re ".*What is the name of the hook\?.*"
send -- "process-message${RETURN}"
## hook is "process-message"
expect -re ".*What kind of hook should it be\?.*"
send -- "${DOWNARROW}${RETURN}"
## DOWNARROW & return selects "before"
expect -re ".*What service\\\(s\\\) should this hook be for .*"
send -- "${DOWNARROW}${SPACE}${RETURN}"
## DOWNARROW, space, & return selects "messages"
expect -re ".*What methods should the hook be for .*"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${SPACE}${RETURN}"
## DOWNARROW three times, space, and return to select "create"
expect eof
END_OF_GENERATE_PROCESS_MESSAGE_HOOK
) ## end of feathers generate hook process-message (first hook)
## feathers generate hook;
## hook name: gravatar
## type of hook: before
## which service: messages
## which method: create
expect <(cat <<'END_OF_GENERATE_GRAVATAR_HOOK'
## creates second "BEFORE--CREATE" hook named "gravatar" for the "user" service
## written from https://docs.feathersjs.com/guides/chat/authentication.html
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate hook;
expect -re ".*What is the name of the hook\?.*"
send -- "gravatar${RETURN}"
## name the hook "gravatar"
expect -re ".*What kind of hook should it be\?.*"
send -- "${DOWNARROW}${RETURN}"
## DOWNARROW & return selects "before"
expect -re ".*What service\\\(s\\\) should this hook be for .*"
send -- "${DOWNARROW}${DOWNARROW}${SPACE}${RETURN}"
## DOWNARROW twice, space, & return selects "users"
expect -re ".*What methods should the hook be for .*"
send -- "${DOWNARROW}${DOWNARROW}${DOWNARROW}${SPACE}${RETURN}"
## DOWNARROW three times, space and return to select "create"
expect eof
END_OF_GENERATE_GRAVATAR_HOOK
) ## end of feathers generate hook gravatar (second hook)
## feathers generate hook;
## hook name: populate-user
## type of hook: after
## which service: messages
## which method: all
expect <(cat <<'END_OF_GENERATE_POPULATE_USER_HOOK'
# creates a third and final "AFTER-ALL" hook named "populate-user" for the "messages" service
# written from: https://docs.feathersjs.com/guides/chat/authentication.html
set timeout -1
set UPARROW \x1B\[A;
set DOWNARROW \x1B\[B;
set SPACE \x20;
set RETURN \x0d;
spawn feathers generate hook;
expect -re ".*What is the name of the hook\?.*"
send -- "populate-user${RETURN}"
expect -re ".*What kind of hook should it be\?.*"
send -- "${DOWNARROW}${DOWNARROW}${RETURN}"
## DOWNARROW & return selects "after"
expect -re ".*What service\\\(s\\\) should this hook be for .*"
send -- "${DOWNARROW}${SPACE}${RETURN}"
## DOWNARROW, space, & return selects "messages"
expect -re ".*What methods should the hook be for .*"
send -- "${SPACE}${RETURN}"
## space & return to select "all"
expect eof
END_OF_GENERATE_POPULATE_USER_HOOK
) ## end of feathers generate hook populate-user (third and final hook)
## authenticate code as per: https://docs.feathersjs.com/guides/chat/authentication.html
sed --in-place --file=- ./src/services/messages/messages.hooks.js <<END_OF_SED_MESSAGE_HOOK ;
1s/^/const { authenticate } = require('@feathersjs\/authentication').hooks;/;
/^ before: {/N; s/all: \[]/all:[authenticate('jwt')]/;
END_OF_SED_MESSAGE_HOOK
## hook code in three files from https://docs.feathersjs.com/guides/chat/processing.html
sed --in-place --file=- ./src/hooks/process-message.js << END_OF_SED_PROCESS_MESSAGE_HOOK ;
/^ return async context => {$/a\
const { data } = context;\\
\\
\/\/ Throw an error if we didn't get a text\\
if(!data.text) {\\
throw new Error('A message must have a text');\\
}\\
\\
\/\/ The authenticated user\\
const user = context.params.user;\\
\/\/ The actual message text\\
const text = context.data.text\\
\/\/ Messages can't be longer than 400 characters\\
.substring(0, 400);\\
\\
\/\/ Override the original data (so that people can't submit additional stuff)\\
context.data = {\\
text,\\
\/\/ Set the user id\\
userId: user._id,\\
\/\/ Add the current date\\
createdAt: new Date().getTime()\\
};\\
\\
\/\/ Best practise, hooks should always return the context
END_OF_SED_PROCESS_MESSAGE_HOOK
## several changes to gravatar.js, so we are using cat instead of sed
cat <<END_OF_GRAVATAR_HOOK > ./src/hooks/gravatar.js ;
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/api/hooks.html
// We need this to create the MD5 hash
const crypto = require('crypto');
// The Gravatar image service
const gravatarUrl = 'https://s.gravatar.com/avatar';
// The size query. Our chat needs 60px images
const query = 's=60';
module.exports = function (options = {}) { // eslint-disable-line no-unused-vars
return async context => {
// The user email
const { email } = context.data;
// Gravatar uses MD5 hashes from an email address to get the image
const hash = crypto.createHash('md5').update(email).digest('hex');
context.data.avatar = \`\${gravatarUrl}/\${hash}?\${query}\`;
// Best practise, hooks should always return the context
return context;
};
};
END_OF_GRAVATAR_HOOK
sed --in-place --file=- ./src/hooks/populate-user.js << END_OF_SED_POPULATE_USER ;
/^ return async context => {$/a\
\/\/ Get \`app\`, \`method\`, \`params\` and \`result\` from the hook context\\
const { app, method, result, params } = context;\\
\\
\/\/ Make sure that we always have a list of messages either by wrapping\\
\/\/ a single message into an array or by getting the \`data\` from the \`find\` method's result\\
const messages = method === 'find' ? result.data : \[ result ];\\
\\
\/\/ Asynchronously get user object from each message's \`userId\`\\
\/\/ and add it to the message\\
await Promise.all(messages.map(async message => {\\
\/\/ Also pass the original \`params\` to the service call\\
\/\/ so that it has the same information available (e.g. who is requesting it)\\
const user = await app.service('users').get(message.userId, params);\\
\\
message.user = user;\\
}));\\
\\
\/\/ Best practise, hooks should always return the context\\
END_OF_SED_POPULATE_USER
## html&js code from https://docs.feathersjs.com/guides/chat/frontend.html
cat <<END_OF_INDEX_HTML > ./public/index.html ;
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=0" />
<title>Vanilla JavaScript Feathers Chat</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="//cdn.rawgit.com/feathersjs/feathers-chat/v0.2.0/public/base.css">
<link rel="stylesheet" href="//cdn.rawgit.com/feathersjs/feathers-chat/v0.2.0/public/chat.css">
</head>
<body>
<div id="app" class="flex flex-column"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>
<script src="//unpkg.com/@feathersjs/client@^3.0.0/dist/feathers.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="app.js"></script>
</body>
</html>
END_OF_INDEX_HTML
cat <<END_OF_APP_JS > ./public/app.js ;
// Establish a Socket.io connection
const socket = io();
// Initialize our Feathers client application through Socket.io
// with hooks and authentication.
const client = feathers();
client.configure(feathers.socketio(socket));
// Use localStorage to store our login token
client.configure(feathers.authentication({
storage: window.localStorage
}));
// Login screen
const loginHTML = \`<main class="login container">
<div class="row">
<div class="col-12 col-6-tablet push-3-tablet text-center heading">
<h1 class="font-100">Log in or signup</h1>
</div>
</div>
<div class="row">
<div class="col-12 col-6-tablet push-3-tablet col-4-desktop push-4-desktop">
<form class="form">
<fieldset>
<input class="block" type="email" name="email" placeholder="email">
</fieldset>
<fieldset>
<input class="block" type="password" name="password" placeholder="password">
</fieldset>
<button type="button" id="login" class="button button-primary block signup">
Log in
</button>
<button type="button" id="signup" class="button button-primary block signup">
Sign up and log in
</button>
</form>
</div>
</div>
</main>\`;
// Chat base HTML (without user list and messages)
const chatHTML = \`<main class="flex flex-column">
<header class="title-bar flex flex-row flex-center">
<div class="title-wrapper block center-element">
<img class="logo" src="http://feathersjs.com/img/feathers-logo-wide.png"
alt="Feathers Logo">
<span class="title">Chat</span>
</div>
</header>
<div class="flex flex-row flex-1 clear">
<aside class="sidebar col col-3 flex flex-column flex-space-between">
<header class="flex flex-row flex-center">
<h4 class="font-300 text-center">
<span class="font-600 online-count">0</span> users
</h4>
</header>
<ul class="flex flex-column flex-1 list-unstyled user-list"></ul>
<footer class="flex flex-row flex-center">
<a href="#" id="logout" class="button button-primary">
Sign Out
</a>
</footer>
</aside>
<div class="flex flex-column col col-9">
<main class="chat flex flex-column flex-1 clear"></main>
<form class="flex flex-row flex-space-between" id="send-message">
<input type="text" name="text" class="flex flex-1">
<button class="button-primary" type="submit">Send</button>
</form>
</div>
</div>
</main>\`;
// Add a new user to the list
const addUser = user => {
const userList = document.querySelector('.user-list');
if(userList) {
// Add the user to the list
userList.insertAdjacentHTML('beforeend', \`<li>
<a class="block relative" href="#">
<img src="\${user.avatar}" alt="" class="avatar">
<span class="absolute username">\${user.email}</span>
</a>
</li>\`);
// Update the number of users
const userCount = document.querySelectorAll('.user-list li').length;
document.querySelector('.online-count').innerHTML = userCount;
}
};
// Renders a new message and finds the user that belongs to the message
const addMessage = message => {
// Find the user belonging to this message or use the anonymous user if not found
const { user = {} } = message;
const chat = document.querySelector('.chat');
// Escape HTML
const text = message.text
.replace(/&/g, '&')
.replace(/</g, '<').replace(/>/g, '>');
if(chat) {
chat.insertAdjacentHTML( 'beforeend', \`<div class="message flex flex-row">
<img src="\${user.avatar}" alt="\${user.email}" class="avatar">
<div class="message-wrapper">
<p class="message-header">
<span class="username font-600">\${user.email}</span>
<span class="sent-date font-300">\${moment(message.createdAt).format('MMM Do, hh:mm:ss')}</span>
</p>
<p class="message-content font-300">\${text}</p>
</div>
</div>\`);
chat.scrollTop = chat.scrollHeight - chat.clientHeight;
}
};
// Show the login page
const showLogin = (error = {}) => {
if(document.querySelectorAll('.login').length) {
document.querySelector('.heading').insertAdjacentHTML('beforeend', \`<p>There was an error: \${error.message}</p>\`);
} else {
document.getElementById('app').innerHTML = loginHTML;
}
};
// Shows the chat page
const showChat = async () => {
document.getElementById('app').innerHTML = chatHTML;
// Find the latest 25 messages. They will come with the newest first
// which is why we have to reverse before adding them
const messages = await client.service('messages').find({
query: {
\$sort: { createdAt: -1 },
\$limit: 25
}
});
// We want to show the newest message last
messages.data.reverse().forEach(addMessage);
// Find all users
const users = await client.service('users').find();
users.data.forEach(addUser);
};
// Retrieve email/password object from the login/signup page
const getCredentials = () => {
const user = {
email: document.querySelector('[name="email"]').value,
password: document.querySelector('[name="password"]').value
};
return user;
};
// Log in either using the given email/password or the token from storage
const login = async credentials => {
try {
if(!credentials) {
// Try to authenticate using the JWT from localStorage
await client.authenticate();
} else {
// If we get login information, add the strategy we want to use for login
const payload = Object.assign({ strategy: 'local' }, credentials);
await client.authenticate(payload);
}
// If successful, show the chat page
showChat();
} catch(error) {
// If we got an error, show the login page
showLogin(error);
}
};
document.addEventListener('click', async ev => {
switch(ev.target.id) {
case 'signup': {
// For signup, create a new user and then log them in
const credentials = getCredentials();
// First create the user
await client.service('users').create(credentials);
// If successful log them in
await login(credentials);
break;
}
case 'login': {
const user = getCredentials();
await login(user);
break;
}
case 'logout': {
await client.logout();
document.getElementById('app').innerHTML = loginHTML;
break;
}
}
});
document.addEventListener('submit', async ev => {
if(ev.target.id === 'send-message') {
// This is the message text input field
const input = document.querySelector('[name="text"]');
ev.preventDefault();
// Create a new message and then clear the input field
await client.service('messages').create({
text: input.value
});
input.value = '';
}
});
// Listen to created events and add the new message in real-time
client.service('messages').on('created', addMessage);
// We will also see when new users get created in real-time
client.service('users').on('created', addUser);
login();
END_OF_APP_JS
## optionally, modify the default.json file (you will have to change these values !)
sed --in-place --file=- ./config/default.json << END_OF_CONFIG_DEFAULT ;
s/"host": "localhost",/"host": "${THIS_IPADDR}",/;
END_OF_CONFIG_DEFAULT
cat <<END_OF_SCRIPT;
Feathers chat app from scratch should now be built.
Now run ' cd ./${FileNameWithoutExtension}/ ; npm start; ' to try it out.
END_OF_SCRIPT
#
#