From 30a77f4086c4b8b673176444271411bb3990b7ec Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 10:38:28 -0400 Subject: [PATCH 01/32] started setting up redis wrapper --- .gitignore | 2 ++ index.js | 9 +++++++++ lib/redisWrapper.js | 22 ++++++++++++++++++++++ package.json | 27 +++++++++++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 .gitignore create mode 100644 index.js create mode 100644 lib/redisWrapper.js create mode 100644 package.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d43c3ac --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +data-structure.txt \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..1ceaf52 --- /dev/null +++ b/index.js @@ -0,0 +1,9 @@ +const http = require("http"); +const express = require("express"); +const app = express(); +const hbs = require("express-handlebars"); +const bodyParser = require("body-parser"); +const redisClient = require("redis"); + +const server = http.createServer(app); +const io = require("socket.io")(server); \ No newline at end of file diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js new file mode 100644 index 0000000..c4d9030 --- /dev/null +++ b/lib/redisWrapper.js @@ -0,0 +1,22 @@ +const redisClient = require("redis"); + +var wrapperStuff = { + saveMessage: (body, author, room) => { + // messageID = generate a unique id + redisClient.hmset(messageID, "body", body) + }, + + loadMessage: () => { + + }, + + addRoom: () => { + + }, + + addUser: () => { + + } +} + +module.exports = wrapperStuff \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..c301f70 --- /dev/null +++ b/package.json @@ -0,0 +1,27 @@ +{ + "name": "project_superchat", + "version": "1.0.0", + "description": "Super Simple Chat Client", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Avonyel/project_superchat.git" + }, + "author": "Stephanie and Greg", + "license": "ISC", + "bugs": { + "url": "https://github.com/Avonyel/project_superchat/issues" + }, + "homepage": "https://github.com/Avonyel/project_superchat#readme", + "dependencies": { + "body-parser": "^1.17.2", + "express": "^4.15.3", + "express-handlebars": "^3.0.0", + "redis": "^2.7.1", + "socket.io": "^2.0.3", + "socket.io-client": "^2.0.3" + } +} From 467126cef15e31933550141367102c089302bcd1 Mon Sep 17 00:00:00 2001 From: Greg Filipczak Date: Wed, 26 Jul 2017 15:06:04 +0000 Subject: [PATCH 02/32] working on redis wrapper --- index.js | 8 +++++-- lib/redisWrapper.js | 55 ++++++++++++++++++++++++++++----------------- 2 files changed, 41 insertions(+), 22 deletions(-) diff --git a/index.js b/index.js index 1ceaf52..8537f7f 100644 --- a/index.js +++ b/index.js @@ -3,7 +3,11 @@ const express = require("express"); const app = express(); const hbs = require("express-handlebars"); const bodyParser = require("body-parser"); -const redisClient = require("redis"); +const redis = require("./lib/redisWrapper.js"); const server = http.createServer(app); -const io = require("socket.io")(server); \ No newline at end of file +const io = require("socket.io")(server); + +let messageIDs = [1, 2]; + +redis.loadMessages(messageIDs); diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index c4d9030..4e3fbe9 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -1,22 +1,37 @@ -const redisClient = require("redis"); +const redisClient = require("redis").createClient(); +// client = redis.createClient(); var wrapperStuff = { - saveMessage: (body, author, room) => { - // messageID = generate a unique id - redisClient.hmset(messageID, "body", body) - }, - - loadMessage: () => { - - }, - - addRoom: () => { - - }, - - addUser: () => { - - } -} - -module.exports = wrapperStuff \ No newline at end of file + saveMessage: (body, author, room) => { + // messageID = generate a unique id + redisClient.rpushx("messages", messageID); + redisClient.hmset(messageID, [ + "body", + body, + "author", + author, + "room", + room + ]); + }, + + loadMessages: messageIDs => { + let messageIDs = redisClient.lget("messages", messages => { + messages.map(message => { + let obj = (message = {}); + }); + }); + + // messageIDs.forEach((id)=> { + // messages = redisClient.keys(`message:${i}`); + // }) + + console.log(messages); + }, + + addRoom: () => {}, + + addUser: () => {} +}; + +module.exports = wrapperStuff; From f51f73c1fec7a8fa7188a042fe74d0f8862d6411 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 12:10:35 -0400 Subject: [PATCH 03/32] can load messages! :D --- index.js | 6 +++++- lib/redisWrapper.js | 41 ++++++++++++++++++++++++++--------------- 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/index.js b/index.js index 8537f7f..547ef10 100644 --- a/index.js +++ b/index.js @@ -10,4 +10,8 @@ const io = require("socket.io")(server); let messageIDs = [1, 2]; -redis.loadMessages(messageIDs); +// redis.saveMessage("Hi there", "me", "main-room"); + +redis.loadMessages((messages) => { + console.log(messages); +}); diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 4e3fbe9..139b568 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -3,8 +3,8 @@ const redisClient = require("redis").createClient(); var wrapperStuff = { saveMessage: (body, author, room) => { - // messageID = generate a unique id - redisClient.rpushx("messages", messageID); + messageID = "message-2" + redisClient.rpush(["messages", messageID]); redisClient.hmset(messageID, [ "body", body, @@ -15,23 +15,34 @@ var wrapperStuff = { ]); }, - loadMessages: messageIDs => { - let messageIDs = redisClient.lget("messages", messages => { - messages.map(message => { - let obj = (message = {}); - }); - }); + loadMessages: (callback) => { + redisClient.lrange("messages", 0, -1, (err, messages) => { + console.log(messages); - // messageIDs.forEach((id)=> { - // messages = redisClient.keys(`message:${i}`); - // }) + messages = messages.map((message) => { + let p = new Promise((resolve, reject) => { + redisClient.hgetall(message, (err, obj) => { + let newObj = {}; + newObj[message] = { + body: obj.body, + author: obj.author, + room: obj.room + } - console.log(messages); - }, + resolve(newObj); + }); + }); - addRoom: () => {}, + return p + }); - addUser: () => {} + console.log(messages); + + Promise.all(messages).then((resolvedMessages) => { + callback(resolvedMessages); + }); + }); + } }; module.exports = wrapperStuff; From 6dd1627aa37231ab0f07e52ca0cf24f338b3f707 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 12:14:13 -0400 Subject: [PATCH 04/32] saving things --- lib/redisWrapper.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 139b568..b5a7294 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -17,7 +17,6 @@ var wrapperStuff = { loadMessages: (callback) => { redisClient.lrange("messages", 0, -1, (err, messages) => { - console.log(messages); messages = messages.map((message) => { let p = new Promise((resolve, reject) => { @@ -36,8 +35,6 @@ var wrapperStuff = { return p }); - console.log(messages); - Promise.all(messages).then((resolvedMessages) => { callback(resolvedMessages); }); From 68c3374f75bc1e1b7429ad1659d7c16b861ef31a Mon Sep 17 00:00:00 2001 From: Greg Filipczak Date: Wed, 26 Jul 2017 16:33:31 +0000 Subject: [PATCH 05/32] working on sockets --- index.js | 30 ++++++++++++++++++++++++--- lib/redisWrapper.js | 22 ++++++++------------ views/index.handlebars | 38 +++++++++++++++++++++++++++++++++++ views/layouts/main.handlebars | 1 + 4 files changed, 74 insertions(+), 17 deletions(-) create mode 100644 views/index.handlebars create mode 100644 views/layouts/main.handlebars diff --git a/index.js b/index.js index 547ef10..1b970a3 100644 --- a/index.js +++ b/index.js @@ -7,11 +7,35 @@ const redis = require("./lib/redisWrapper.js"); const server = http.createServer(app); const io = require("socket.io")(server); +app.engine("handlebars", hbs({ defaultLayout: "main" })); +app.set("view engine", "handlebars"); -let messageIDs = [1, 2]; +app.use( + "/socket-io", + express.static(__dirname + "node_modules/socket-io-client/dist/") +); + +app.get("/", (req, res) => { + redis.loadMessages(messages => { + console.log(messages); + res.render("index", { messages: messages }); + }); +}); + +// let messageIDs = [1, 2]; + +io.on("connection", ( + console.log('new connection') +) => {}); // redis.saveMessage("Hi there", "me", "main-room"); -redis.loadMessages((messages) => { - console.log(messages); +// function parseMessages = (messageArray){ +// messageArray.forEach((message)=> { +// +// } +// } + +app.listen(3000, "0.0.0.0", (req, res) => { + console.log("listening on port 3000"); }); diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 139b568..4c2a45a 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -3,8 +3,8 @@ const redisClient = require("redis").createClient(); var wrapperStuff = { saveMessage: (body, author, room) => { - messageID = "message-2" - redisClient.rpush(["messages", messageID]); + messageID = "message-1"; + redisClient.lpush(["messages", messageID]); redisClient.hmset(messageID, [ "body", body, @@ -15,30 +15,24 @@ var wrapperStuff = { ]); }, - loadMessages: (callback) => { + loadMessages: callback => { redisClient.lrange("messages", 0, -1, (err, messages) => { - console.log(messages); - - messages = messages.map((message) => { + messages = messages.map(message => { let p = new Promise((resolve, reject) => { redisClient.hgetall(message, (err, obj) => { - let newObj = {}; - newObj[message] = { + let newObj = { body: obj.body, author: obj.author, room: obj.room - } + }; resolve(newObj); }); }); - return p + return p; }); - - console.log(messages); - - Promise.all(messages).then((resolvedMessages) => { + Promise.all(messages).then(resolvedMessages => { callback(resolvedMessages); }); }); diff --git a/views/index.handlebars b/views/index.handlebars new file mode 100644 index 0000000..2c1242b --- /dev/null +++ b/views/index.handlebars @@ -0,0 +1,38 @@ + + + + + chat room + + + + +
+ + +
+ + {{#each messages as |message|}} +
+

+ {{message.body}} +

+

+ {{message.author}} +

+
+ {{/each}} + + + + + diff --git a/views/layouts/main.handlebars b/views/layouts/main.handlebars new file mode 100644 index 0000000..a0cf6b2 --- /dev/null +++ b/views/layouts/main.handlebars @@ -0,0 +1 @@ +{{{body}}} From 9e7c22aff2ca7b7513edc17a6ea293b22bff28f8 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 13:02:49 -0400 Subject: [PATCH 06/32] still working with sockets --- index.js | 14 +++++++++++--- views/index.handlebars | 42 +++++++++++++++++++++++++++++------------- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/index.js b/index.js index 1b970a3..9ef94a1 100644 --- a/index.js +++ b/index.js @@ -24,9 +24,17 @@ app.get("/", (req, res) => { // let messageIDs = [1, 2]; -io.on("connection", ( - console.log('new connection') -) => {}); +io.on("connection", (client) => { + console.log("New connection"); + + client.on("newMessage", (data) => { + var p = saveMessage(data.body, data.author, data.room); + + p.then(() => { + io.emit("updateMessages", data); + }) + }); +}); // redis.saveMessage("Hi there", "me", "main-room"); diff --git a/views/index.handlebars b/views/index.handlebars index 2c1242b..59f3a78 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -10,27 +10,43 @@ crossorigin="anonymous"> -
+ - +
- {{#each messages as |message|}} -
-

- {{message.body}} -

-

- {{message.author}} -

-
+
+ {{#each messages as |message|}} +
+

+ {{message.body}} +

+

+ {{message.author}} +

+
{{/each}} +
From 120668d2d9aa62d77f27056f2574c905f51b8078 Mon Sep 17 00:00:00 2001 From: Greg Filipczak Date: Wed, 26 Jul 2017 17:24:44 +0000 Subject: [PATCH 07/32] tomato --- index.js | 27 +++++++++++++++++---------- public/socket.io.js | 3 +++ views/index.handlebars | 29 ++++++++++++++++------------- 3 files changed, 36 insertions(+), 23 deletions(-) create mode 100644 public/socket.io.js diff --git a/index.js b/index.js index 9ef94a1..87f16ca 100644 --- a/index.js +++ b/index.js @@ -11,10 +11,17 @@ app.engine("handlebars", hbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); app.use( - "/socket-io", - express.static(__dirname + "node_modules/socket-io-client/dist/") + "/socket.io", + express.static(__dirname + "/node_modules/socket.io-client/dist/") ); +console.log(__dirname + "/node_modules/socket.io-client/dist/"); + +// app.use( +// "/socket-", +// express.static(__dirname + "node_modules/socket.io-client/dist/") +// ); + app.get("/", (req, res) => { redis.loadMessages(messages => { console.log(messages); @@ -24,16 +31,16 @@ app.get("/", (req, res) => { // let messageIDs = [1, 2]; -io.on("connection", (client) => { - console.log("New connection"); +io.on("connection", client => { + console.log("New connection"); - client.on("newMessage", (data) => { - var p = saveMessage(data.body, data.author, data.room); + client.on("newMessage", data => { + var p = saveMessage(data.body, data.author, data.room); - p.then(() => { - io.emit("updateMessages", data); - }) - }); + p.then(() => { + io.emit("updateMessages", data); + }); + }); }); // redis.saveMessage("Hi there", "me", "main-room"); diff --git a/public/socket.io.js b/public/socket.io.js new file mode 100644 index 0000000..a61d7d0 --- /dev/null +++ b/public/socket.io.js @@ -0,0 +1,3 @@ +!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";function r(t,e){"object"===("undefined"==typeof t?"undefined":o(t))&&(e=t,t=void 0),e=e||{};var n,r=i(t),s=r.source,u=r.id,h=r.path,f=p[u]&&h in p[u].nsps,l=e.forceNew||e["force new connection"]||!1===e.multiplex||f;return l?(c("ignoring socket cache for %s",s),n=a(s,e)):(p[u]||(c("new io instance for %s",s),p[u]=a(s,e)),n=p[u]),r.query&&!e.query&&(e.query=r.query),n.socket(r.path,e)}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=n(1),s=n(7),a=n(13),c=n(3)("socket.io-client");t.exports=e=r;var p=e.managers={};e.protocol=s.protocol,e.connect=r,e.Manager=n(13),e.Socket=n(39)},function(t,e,n){(function(e){"use strict";function r(t,n){var r=t;n=n||e.location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(i("protocol-less url %s",t),t="undefined"!=typeof n?n.protocol+"//"+t:"https://"+t),i("parse %s",t),r=o(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var s=r.host.indexOf(":")!==-1,a=s?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+a+":"+r.port,r.href=r.protocol+"://"+a+(n&&n.port===r.port?"":":"+r.port),r}var o=n(2),i=n(3)("socket.io-client:url");t.exports=r}).call(e,function(){return this}())},function(t,e){var n=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");o!=-1&&i!=-1&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s=n.exec(t||""),a={},c=14;c--;)a[r[c]]=s[c]||"";return o!=-1&&i!=-1&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a}},function(t,e,n){(function(r){function o(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(t){var n=this.useColors;if(t[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+t[0]+(n?"%c ":" ")+"+"+e.humanize(this.diff),n){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))}),t.splice(i,0,r)}}function s(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(n){}}function c(){var t;try{t=e.storage.debug}catch(n){}return!t&&"undefined"!=typeof r&&"env"in r&&(t=r.env.DEBUG),t}function p(){try{return window.localStorage}catch(t){}}e=t.exports=n(5),e.log=s,e.formatArgs=i,e.save=a,e.load=c,e.useColors=o,e.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:p(),e.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},e.enable(c())}).call(e,n(4))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(t){if(u===setTimeout)return setTimeout(t,0);if((u===n||!u)&&setTimeout)return u=setTimeout,setTimeout(t,0);try{return u(t,0)}catch(e){try{return u.call(null,t,0)}catch(e){return u.call(this,t,0)}}}function i(t){if(h===clearTimeout)return clearTimeout(t);if((h===r||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(t);try{return h(t)}catch(e){try{return h.call(null,t)}catch(e){return h.call(this,t)}}}function s(){y&&l&&(y=!1,l.length?d=l.concat(d):m=-1,d.length&&a())}function a(){if(!y){var t=o(s);y=!0;for(var e=d.length;e;){for(l=d,d=[];++m1)for(var n=1;n100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*u;case"days":case"day":case"d":return n*p;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function r(t){return t>=p?Math.round(t/p)+"d":t>=c?Math.round(t/c)+"h":t>=a?Math.round(t/a)+"m":t>=s?Math.round(t/s)+"s":t+"ms"}function o(t){return i(t,p,"day")||i(t,c,"hour")||i(t,a,"minute")||i(t,s,"second")||t+" ms"}function i(t,e,n){if(!(t0)return n(t);if("number"===i&&isNaN(t)===!1)return e["long"]?o(t):r(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,n){function r(){}function o(t){var n=""+t.type;return e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(n+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(n+=t.nsp+","),null!=t.id&&(n+=t.id),null!=t.data&&(n+=JSON.stringify(t.data)),h("encoded %j as %s",t,n),n}function i(t,e){function n(t){var n=d.deconstructPacket(t),r=o(n.packet),i=n.buffers;i.unshift(r),e(i)}d.removeBlobs(t,n)}function s(){this.reconstructor=null}function a(t){var n=0,r={type:Number(t.charAt(0))};if(null==e.types[r.type])return u();if(e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type){for(var o="";"-"!==t.charAt(++n)&&(o+=t.charAt(n),n!=t.length););if(o!=Number(o)||"-"!==t.charAt(n))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(n+1))for(r.nsp="";++n;){var i=t.charAt(n);if(","===i)break;if(r.nsp+=i,n===t.length)break}else r.nsp="/";var s=t.charAt(n+1);if(""!==s&&Number(s)==s){for(r.id="";++n;){var i=t.charAt(n);if(null==i||Number(i)!=i){--n;break}if(r.id+=t.charAt(n),n===t.length)break}r.id=Number(r.id)}return t.charAt(++n)&&(r=c(r,t.substr(n))),h("decoded %s as %j",t,r),r}function c(t,e){try{t.data=JSON.parse(e)}catch(n){return u()}return t}function p(t){this.reconPack=t,this.buffers=[]}function u(){return{type:e.ERROR,data:"parser error"}}var h=n(3)("socket.io-parser"),f=n(8),l=n(9),d=n(11),y=n(12);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=r,e.Decoder=s,r.prototype.encode=function(t,n){if(t.type!==e.EVENT&&t.type!==e.ACK||!l(t.data)||(t.type=t.type===e.EVENT?e.BINARY_EVENT:e.BINARY_ACK),h("encoding packet %j",t),e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)i(t,n);else{var r=o(t);n([r])}},f(s.prototype),s.prototype.add=function(t){var n;if("string"==typeof t)n=a(t),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new p(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!y(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,this.emit("decoded",n))}},s.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},p.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=d.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},p.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,n){function r(t){if(t)return o(t)}function o(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r,o=0;o0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},r.prototype.cleanup=function(){h("cleanup");for(var t=this.subs.length,e=0;e=this._reconnectionAttempts)h("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();h("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var n=setTimeout(function(){t.skipReconnect||(h("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open(function(e){e?(h("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(h("reconnect success"),t.onreconnect())}))},e);this.subs.push({destroy:function(){clearTimeout(n)}})}},r.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,n){t.exports=n(15)},function(t,e,n){t.exports=n(16),t.exports.parser=n(23)},function(t,e,n){(function(e){function r(t,n){if(!(this instanceof r))return new r(t,n);n=n||{},t&&"object"==typeof t&&(n=t,t=null),t?(t=u(t),n.hostname=t.host,n.secure="https"===t.protocol||"wss"===t.protocol,n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=u(n.host).host),this.secure=null!=n.secure?n.secure:e.location&&"https:"===location.protocol,n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.agent=n.agent||!1,this.hostname=n.hostname||(e.location?location.hostname:"localhost"),this.port=n.port||(e.location&&location.port?location.port:this.secure?443:80),this.query=n.query||{},"string"==typeof this.query&&(this.query=f.decode(this.query)),this.upgrade=!1!==n.upgrade,this.path=(n.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!n.forceJSONP,this.jsonp=!1!==n.jsonp,this.forceBase64=!!n.forceBase64,this.enablesXDR=!!n.enablesXDR,this.timestampParam=n.timestampParam||"t",this.timestampRequests=n.timestampRequests,this.transports=n.transports||["polling","websocket"],this.transportOptions=n.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=n.policyPort||843,this.rememberUpgrade=n.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=n.onlyBinaryUpgrades,this.perMessageDeflate=!1!==n.perMessageDeflate&&(n.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=n.pfx||null,this.key=n.key||null,this.passphrase=n.passphrase||null,this.cert=n.cert||null,this.ca=n.ca||null,this.ciphers=n.ciphers||null,this.rejectUnauthorized=void 0===n.rejectUnauthorized||n.rejectUnauthorized,this.forceNode=!!n.forceNode;var o="object"==typeof e&&e;o.global===o&&(n.extraHeaders&&Object.keys(n.extraHeaders).length>0&&(this.extraHeaders=n.extraHeaders),n.localAddress&&(this.localAddress=n.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}function o(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}var i=n(17),s=n(8),a=n(3)("engine.io-client:socket"),c=n(37),p=n(23),u=n(2),h=n(38),f=n(31);t.exports=r,r.priorWebsocketSuccess=!1,s(r.prototype),r.protocol=p.protocol,r.Socket=r,r.Transport=n(22),r.transports=n(17),r.parser=n(23),r.prototype.createTransport=function(t){a('creating transport "%s"',t);var e=o(this.query);e.EIO=p.protocol,e.transport=t;var n=this.transportOptions[t]||{};this.id&&(e.sid=this.id);var r=new i[t]({query:e,socket:this,agent:n.agent||this.agent,hostname:n.hostname||this.hostname,port:n.port||this.port,secure:n.secure||this.secure,path:n.path||this.path,forceJSONP:n.forceJSONP||this.forceJSONP,jsonp:n.jsonp||this.jsonp,forceBase64:n.forceBase64||this.forceBase64,enablesXDR:n.enablesXDR||this.enablesXDR,timestampRequests:n.timestampRequests||this.timestampRequests,timestampParam:n.timestampParam||this.timestampParam,policyPort:n.policyPort||this.policyPort,pfx:n.pfx||this.pfx,key:n.key||this.key,passphrase:n.passphrase||this.passphrase,cert:n.cert||this.cert,ca:n.ca||this.ca,ciphers:n.ciphers||this.ciphers,rejectUnauthorized:n.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:n.perMessageDeflate||this.perMessageDeflate,extraHeaders:n.extraHeaders||this.extraHeaders,forceNode:n.forceNode||this.forceNode,localAddress:n.localAddress||this.localAddress,requestTimeout:n.requestTimeout||this.requestTimeout,protocols:n.protocols||void 0});return r},r.prototype.open=function(){var t;if(this.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout(function(){e.emit("error","No transports available")},0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(n){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},r.prototype.setTransport=function(t){a("setting transport %s",t.name);var e=this;this.transport&&(a("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",function(){e.onDrain()}).on("packet",function(t){e.onPacket(t)}).on("error",function(t){e.onError(t)}).on("close",function(){e.onClose("transport close")})},r.prototype.probe=function(t){function e(){if(f.onlyBinaryUpgrades){var e=!this.supportsBinary&&f.transport.supportsBinary;h=h||e}h||(a('probe transport "%s" opened',t),u.send([{type:"ping",data:"probe"}]),u.once("packet",function(e){if(!h)if("pong"===e.type&&"probe"===e.data){if(a('probe transport "%s" pong',t),f.upgrading=!0,f.emit("upgrading",u),!u)return;r.priorWebsocketSuccess="websocket"===u.name,a('pausing current transport "%s"',f.transport.name),f.transport.pause(function(){h||"closed"!==f.readyState&&(a("changing transport and sending upgrade packet"),p(),f.setTransport(u),u.send([{type:"upgrade"}]),f.emit("upgrade",u),u=null,f.upgrading=!1,f.flush())})}else{a('probe transport "%s" failed',t);var n=new Error("probe error");n.transport=u.name,f.emit("upgradeError",n)}}))}function n(){h||(h=!0,p(),u.close(),u=null)}function o(e){var r=new Error("probe error: "+e);r.transport=u.name,n(),a('probe transport "%s" failed because of error: %s',t,e),f.emit("upgradeError",r)}function i(){o("transport closed")}function s(){o("socket closed")}function c(t){u&&t.name!==u.name&&(a('"%s" works - aborting "%s"',t.name,u.name),n())}function p(){u.removeListener("open",e),u.removeListener("error",o),u.removeListener("close",i),f.removeListener("close",s),f.removeListener("upgrading",c)}a('probing transport "%s"',t);var u=this.createTransport(t,{probe:1}),h=!1,f=this;r.priorWebsocketSuccess=!1,u.once("open",e),u.once("error",o),u.once("close",i),this.once("close",s),this.once("upgrading",c),u.open()},r.prototype.onOpen=function(){if(a("socket open"),this.readyState="open",r.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){a("starting upgrade probes");for(var t=0,e=this.upgrades.length;t1?{type:b[o],data:t.substring(1)}:{type:b[o]}:w}var i=new Uint8Array(t),o=i[0],s=f(t,1);return k&&"blob"===n&&(s=new k([s])),{type:b[o],data:s}},e.decodeBase64Packet=function(t,e){var n=b[t.charAt(0)];if(!p)return{type:n,data:{base64:!0,data:t.substr(1)}};var r=p.decode(t.substr(1));return"blob"===e&&k&&(r=new k([r])),{type:n,data:r}},e.encodePayload=function(t,n,r){function o(t){return t.length+":"+t}function i(t,r){e.encodePacket(t,!!s&&n,!1,function(t){r(null,o(t))})}"function"==typeof n&&(r=n,n=null);var s=h(t);return n&&s?k&&!g?e.encodePayloadAsBlob(t,r):e.encodePayloadAsArrayBuffer(t,r):t.length?void c(t,i,function(t,e){return r(e.join(""))}):r("0:")},e.decodePayload=function(t,n,r){if("string"!=typeof t)return e.decodePayloadAsBinary(t,n,r);"function"==typeof n&&(r=n,n=null);var o;if(""===t)return r(w,0,1);for(var i,s,a="",c=0,p=t.length;c0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return r(w,0,1);c+=s[p]}o=f(o,2+c.length),c=parseInt(c);var u=f(o,0,c);if(a)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(h){var l=new Uint8Array(u);u="";for(var p=0;pr&&(n=r),e>=r||e>=n||0===r)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(n-e),s=e,a=0;s=55296&&e<=56319&&o65535&&(e-=65536,o+=w(e>>>10&1023|55296),e=56320|1023&e),o+=w(e);return o}function c(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function p(t,e){return w(t>>e&63|128)}function u(t,e){if(0==(4294967168&t))return w(t);var n="";return 0==(4294965248&t)?n=w(t>>6&31|192):0==(4294901760&t)?(c(t,e)||(t=65533),n=w(t>>12&15|224),n+=p(t,6)):0==(4292870144&t)&&(n=w(t>>18&7|240),n+=p(t,12),n+=p(t,6)),n+=w(63&t|128)}function h(t,e){e=e||{};for(var n,r=!1!==e.strict,o=s(t),i=o.length,a=-1,c="";++a=v)throw Error("Invalid byte index");var t=255&g[b];if(b++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function l(t){var e,n,r,o,i;if(b>v)throw Error("Invalid byte index");if(b==v)return!1;if(e=255&g[b],b++,0==(128&e))return e;if(192==(224&e)){if(n=f(),i=(31&e)<<6|n,i>=128)return i;throw Error("Invalid continuation byte")}if(224==(240&e)){if(n=f(),r=f(),i=(15&e)<<12|n<<6|r,i>=2048)return c(i,t)?i:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(n=f(),r=f(),o=f(),i=(7&e)<<18|n<<12|r<<6|o,i>=65536&&i<=1114111))return i;throw Error("Invalid UTF-8 detected")}function d(t,e){e=e||{};var n=!1!==e.strict;g=s(t),v=g.length,b=0;for(var r,o=[];(r=l(n))!==!1;)o.push(r);return a(o)}var y="object"==typeof e&&e,m=("object"==typeof t&&t&&t.exports==y&&t,"object"==typeof o&&o);m.global!==m&&m.window!==m||(i=m);var g,v,b,w=String.fromCharCode,k={version:"2.1.2",encode:h,decode:d};r=function(){return k}.call(e,n,e,t),!(void 0!==r&&(t.exports=r))}(this)}).call(e,n(28)(t),function(){return this}())},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}},function(t,e){!function(){"use strict";for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(256),r=0;r>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3===2?i=i.substring(0,i.length-1)+"=":o%3===1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(t){var e,r,o,i,s,a=.75*t.length,c=t.length,p=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);var u=new ArrayBuffer(a),h=new Uint8Array(u);for(e=0;e>4,h[p++]=(15&o)<<4|i>>2,h[p++]=(3&i)<<6|63&s;return u}}()},function(t,e){(function(e){function n(t){for(var e=0;e0);return e}function r(t){var e=0;for(u=0;u';i=document.createElement(e)}catch(t){i=document.createElement("iframe"),i.name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),u=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=u,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),r(),t=t.replace(p,"\\\n"),this.area.value=t.replace(c,"\\n");try{this.form.submit()}catch(h){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&n()}:this.iframe.onload=n}}).call(e,function(){return this}())},function(t,e,n){(function(e){function r(t){var e=t&&t.forceBase64;e&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=h&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(l=o),i.call(this,t)}var o,i=n(22),s=n(23),a=n(31),c=n(32),p=n(33),u=n(3)("engine.io-client:websocket"),h=e.WebSocket||e.MozWebSocket;if("undefined"==typeof window)try{o=n(36)}catch(f){}var l=h;l||"undefined"!=typeof window||(l=o),t.exports=r,c(r,i),r.prototype.name="websocket",r.prototype.supportsBinary=!0,r.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,n={agent:this.agent,perMessageDeflate:this.perMessageDeflate};n.pfx=this.pfx,n.key=this.key,n.passphrase=this.passphrase,n.cert=this.cert,n.ca=this.ca,n.ciphers=this.ciphers,n.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(n.headers=this.extraHeaders),this.localAddress&&(n.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket?e?new l(t,e):new l(t):new l(t,e,n)}catch(r){return this.emit("error",r)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},r.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},r.prototype.write=function(t){function n(){r.emit("flush"),setTimeout(function(){r.writable=!0,r.emit("drain")},0)}var r=this;this.writable=!1;for(var o=t.length,i=0,a=o;i0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(t){this.ms=t},n.prototype.setMax=function(t){this.max=t},n.prototype.setJitter=function(t){this.jitter=t}}])}); +//# sourceMappingURL=socket.io.js.map \ No newline at end of file diff --git a/views/index.handlebars b/views/index.handlebars index 59f3a78..b55c744 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -30,23 +30,26 @@ From 9bd564ea6bc7240dbfcfb15ca51de724e09f04e4 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 15:00:02 -0400 Subject: [PATCH 08/32] working sockets! --- index.js | 16 ++++++----- lib/redisWrapper.js | 28 +++++++++++-------- package.json | 1 + views/index.handlebars | 62 ++++++++++++++++++++++-------------------- 4 files changed, 60 insertions(+), 47 deletions(-) diff --git a/index.js b/index.js index 87f16ca..ad52993 100644 --- a/index.js +++ b/index.js @@ -15,7 +15,7 @@ app.use( express.static(__dirname + "/node_modules/socket.io-client/dist/") ); -console.log(__dirname + "/node_modules/socket.io-client/dist/"); +// server.listen(3000) // app.use( // "/socket-", @@ -24,7 +24,6 @@ console.log(__dirname + "/node_modules/socket.io-client/dist/"); app.get("/", (req, res) => { redis.loadMessages(messages => { - console.log(messages); res.render("index", { messages: messages }); }); }); @@ -35,14 +34,16 @@ io.on("connection", client => { console.log("New connection"); client.on("newMessage", data => { - var p = saveMessage(data.body, data.author, data.room); + var p = redis.saveMessage(data.body, data.author, data.room); p.then(() => { - io.emit("updateMessages", data); + console.log("Promise found!"); + io.emit("updateMessages", data); }); }); }); + // redis.saveMessage("Hi there", "me", "main-room"); // function parseMessages = (messageArray){ @@ -51,6 +52,7 @@ io.on("connection", client => { // } // } -app.listen(3000, "0.0.0.0", (req, res) => { - console.log("listening on port 3000"); -}); +// app.listen(3000, (req, res) => { +// console.log("listening on port 3000"); +// }); +server.listen(3000); \ No newline at end of file diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 7d81506..2ded926 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -1,18 +1,24 @@ const redisClient = require("redis").createClient(); -// client = redis.createClient(); +const shortid = require("shortid"); var wrapperStuff = { saveMessage: (body, author, room) => { - messageID = "message-1"; - redisClient.lpush(["messages", messageID]); - redisClient.hmset(messageID, [ - "body", - body, - "author", - author, - "room", - room - ]); + var p = new Promise((res, rej) => { + var messageID = "message-" + shortid.generate(); + redisClient.lpush(["messages", messageID]); + redisClient.hmset(messageID, [ + "body", + body, + "author", + author, + "room", + room + ]); + + res(true); + }); + + return p; }, loadMessages: callback => { diff --git a/package.json b/package.json index c301f70..7573be9 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "express": "^4.15.3", "express-handlebars": "^3.0.0", "redis": "^2.7.1", + "shortid": "^2.2.8", "socket.io": "^2.0.3", "socket.io-client": "^2.0.3" } diff --git a/views/index.handlebars b/views/index.handlebars index b55c744..6f02b98 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -8,50 +8,54 @@ src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"> + + + -
- - -
+
+
+ + +
+
-
+
{{#each messages as |message|}} -
-

- {{message.body}} -

-

- {{message.author}} -

+
+
+

+ {{message.body}} +

+

+ {{message.author}} +

+
{{/each}}
- + From aace93f54a6d11107793786ede56e7cf9594c45c Mon Sep 17 00:00:00 2001 From: Greg Filipczak Date: Wed, 26 Jul 2017 20:29:49 +0000 Subject: [PATCH 09/32] finished log out --- index.js | 53 ++++++++++++++++++----------------- lib/redisWrapper.js | 4 +++ package.json | 1 + views/index.handlebars | 11 ++++++-- views/layouts/main.handlebars | 21 +++++++++++++- views/login.handlebars | 6 ++++ 6 files changed, 66 insertions(+), 30 deletions(-) create mode 100644 views/login.handlebars diff --git a/index.js b/index.js index ad52993..8568d99 100644 --- a/index.js +++ b/index.js @@ -4,31 +4,44 @@ const app = express(); const hbs = require("express-handlebars"); const bodyParser = require("body-parser"); const redis = require("./lib/redisWrapper.js"); - +const cookieParser = require("cookie-parser"); const server = http.createServer(app); const io = require("socket.io")(server); app.engine("handlebars", hbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); +app.use(cookieParser()); +app.use(bodyParser.urlencoded({ extended: false })); app.use( "/socket.io", express.static(__dirname + "/node_modules/socket.io-client/dist/") ); -// server.listen(3000) +app.get("/", (req, res) => { + if (!req.cookies.user) { + res.render("login"); + } else { + redis.loadMessages(messages => { + res.render("index", { + messages: messages, + user: req.cookies.user + }); + }); + } +}); -// app.use( -// "/socket-", -// express.static(__dirname + "node_modules/socket.io-client/dist/") -// ); +app.post("/", (req, res) => { + let user = req.body.user; + redis.saveUser(user); + res.cookie("user", user); -app.get("/", (req, res) => { - redis.loadMessages(messages => { - res.render("index", { messages: messages }); - }); + res.redirect("/"); }); -// let messageIDs = [1, 2]; +app.post("/logout", (req, res) => { + res.clearCookie("user"); + res.redirect("/"); +}); io.on("connection", client => { console.log("New connection"); @@ -37,22 +50,10 @@ io.on("connection", client => { var p = redis.saveMessage(data.body, data.author, data.room); p.then(() => { - console.log("Promise found!"); - io.emit("updateMessages", data); + console.log("Promise found!"); + io.emit("updateMessages", data); }); }); }); - -// redis.saveMessage("Hi there", "me", "main-room"); - -// function parseMessages = (messageArray){ -// messageArray.forEach((message)=> { -// -// } -// } - -// app.listen(3000, (req, res) => { -// console.log("listening on port 3000"); -// }); -server.listen(3000); \ No newline at end of file +server.listen(3000); diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 2ded926..44f91ea 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -43,6 +43,10 @@ var wrapperStuff = { callback(resolvedMessages); }); }); + }, + + saveUser: user => { + redisClient.hsetnx("users", user, user); } }; diff --git a/package.json b/package.json index 7573be9..1236092 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "homepage": "https://github.com/Avonyel/project_superchat#readme", "dependencies": { "body-parser": "^1.17.2", + "cookie-parser": "^1.4.3", "express": "^4.15.3", "express-handlebars": "^3.0.0", "redis": "^2.7.1", diff --git a/views/index.handlebars b/views/index.handlebars index 6f02b98..5f6eaf9 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -9,10 +9,15 @@ integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"> - + + +

Welcome {{user}}!

+
+ +
@@ -37,14 +42,14 @@ + + + + + + + {{{body}}} + + + + diff --git a/views/login.handlebars b/views/login.handlebars new file mode 100644 index 0000000..9313e4b --- /dev/null +++ b/views/login.handlebars @@ -0,0 +1,6 @@ +
+ + + + +
From b1e00eb9dcf9c62d6e6bd8eb0d37a4ba1f098442 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 16:56:16 -0400 Subject: [PATCH 10/32] working on multiple chat rooms --- lib/redisWrapper.js | 44 +++++++++++++++++++++++++++++++++++++++--- views/index.handlebars | 13 +++++++++++-- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 44f91ea..67ddda0 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -3,9 +3,9 @@ const shortid = require("shortid"); var wrapperStuff = { saveMessage: (body, author, room) => { - var p = new Promise((res, rej) => { + var p = new Promise((resolve, reject) => { var messageID = "message-" + shortid.generate(); - redisClient.lpush(["messages", messageID]); + redisClient.lpush([room, messageID]); redisClient.hmset(messageID, [ "body", body, @@ -15,7 +15,7 @@ var wrapperStuff = { room ]); - res(true); + resolve(true); }); return p; @@ -45,8 +45,46 @@ var wrapperStuff = { }); }, + loadRoomMessages: (roomName, callback) => { + redisClient.lrange(roomName, 0, -1, (err, messages) => { + messages = messages.map(message => { + let p = new Promise((resolve, reject) => { + redisClient.hgetall(message, (err, obj) => { + let newObj = { + body: obj.body, + author: obj.author, + room: obj.room + }; + + resolve(newObj); + }); + }); + + return p; + }); + + Promise.all(messages).then(resolvedMessages => { + callback(resolvedMessages); + }); + }); + }, + saveUser: user => { redisClient.hsetnx("users", user, user); + }, + + addRoom: (roomName) => { + + }, + + getRooms: () => { + let p = new Promise((resolve, reject) => { + redisClient.lrange("rooms", 0, -1, (err, rooms) => { + resolve(rooms); + }); + }); + + return p; } }; diff --git a/views/index.handlebars b/views/index.handlebars index 5f6eaf9..095fc95 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -18,6 +18,15 @@
+ +
+ {{#each rooms as |room|}} +
+

{{room}}

+
+ {{/each}} +
+
@@ -42,14 +51,14 @@ diff --git a/views/partials/message_form.js b/views/partials/message_form.js new file mode 100644 index 0000000..0a9617f --- /dev/null +++ b/views/partials/message_form.js @@ -0,0 +1,21 @@ +
+ + + + +
+ +
+ {{#each messages as |message|}} +
+
+

+ {{message.body}} +

+

+ {{message.author}} +

+
+
+ {{/each}} +
From 10db5fb3ed6555cf5919a8817c07c8a61bd9f16f Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 18:06:11 -0400 Subject: [PATCH 12/32] working on displaying rooms --- index.js | 12 +++++++++++- views/index.handlebars | 39 ++++++++++++++++++++++++++++----------- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index c0e0a2e..8d2cf73 100644 --- a/index.js +++ b/index.js @@ -56,7 +56,6 @@ io.on("connection", client => { var p = redis.saveMessage(data.body, data.author, data.room); p.then(() => { - console.log("Promise found!"); io.emit("updateMessages", data); }); }); @@ -68,6 +67,17 @@ io.on("connection", client => { io.emit("updateRooms", data); }); }); + + client.on("showRoom", data => { + redis.loadRoomMessages(data, (messages) => { + let output = { + messages: messages, + roomName: data + } + + client.emit("roomLoaded", output); + }); + }); }); server.listen(3000); diff --git a/views/index.handlebars b/views/index.handlebars index 10b5c43..77b79e6 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -31,23 +31,37 @@ -
- - +
+ +
+ {{#each messages as |message|}} +
+
+

+ {{message.body}} +

+

+ {{message.author}} +

+
+
+ {{/each}} +
+
- + From e927c19229f300b0c59c3f47017b80c9607a1e8f Mon Sep 17 00:00:00 2001 From: Greg Filipczak Date: Wed, 26 Jul 2017 22:46:25 +0000 Subject: [PATCH 13/32] working! with bugs :( --- index.js | 20 +++++++++---------- lib/redisWrapper.js | 2 ++ views/index.handlebars | 44 ++++++++++++++++++++++-------------------- 3 files changed, 35 insertions(+), 31 deletions(-) diff --git a/index.js b/index.js index 8d2cf73..952a700 100644 --- a/index.js +++ b/index.js @@ -27,7 +27,6 @@ app.get("/", (req, res) => { // user: req.cookies.user // }); redis.getRooms().then(rooms => { - console.log(rooms); res.render("index", { rooms: rooms, user: req.cookies.user @@ -39,6 +38,7 @@ app.get("/", (req, res) => { app.post("/", (req, res) => { let user = req.body.user; redis.saveUser(user); + console.log(user); res.cookie("user", user); res.redirect("/"); @@ -46,7 +46,7 @@ app.post("/", (req, res) => { app.post("/logout", (req, res) => { res.clearCookie("user"); - res.redirect("/ "); + res.redirect("/"); }); io.on("connection", client => { @@ -69,14 +69,14 @@ io.on("connection", client => { }); client.on("showRoom", data => { - redis.loadRoomMessages(data, (messages) => { - let output = { - messages: messages, - roomName: data - } - - client.emit("roomLoaded", output); - }); + redis.loadRoomMessages(data, messages => { + let output = { + messages: messages, + roomName: data + }; + + client.emit("roomLoaded", output); + }); }); }); diff --git a/lib/redisWrapper.js b/lib/redisWrapper.js index 73d0331..f5ad2f0 100644 --- a/lib/redisWrapper.js +++ b/lib/redisWrapper.js @@ -46,7 +46,9 @@ var wrapperStuff = { }, loadRoomMessages: (roomName, callback) => { + console.log(roomName); redisClient.lrange(roomName, 0, -1, (err, messages) => { + console.log(messages); messages = messages.map(message => { let p = new Promise((resolve, reject) => { redisClient.hgetall(message, (err, obj) => { diff --git a/views/index.handlebars b/views/index.handlebars index 77b79e6..05a0269 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -21,7 +21,7 @@
{{#each rooms as |room|}} -
+

{{room}}

{{/each}} @@ -34,36 +34,26 @@
- -
- {{#each messages as |message|}} -
-
-

- {{message.body}} -

-

- {{message.author}} -

-
-
- {{/each}} -
From 773ce1e645b05f393130a4cd63e4ad9ab6823886 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Wed, 26 Jul 2017 19:29:43 -0400 Subject: [PATCH 14/32] fixed weird message appending issue --- index.js | 2 +- views/index.handlebars | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 952a700..57cf64e 100644 --- a/index.js +++ b/index.js @@ -39,7 +39,7 @@ app.post("/", (req, res) => { let user = req.body.user; redis.saveUser(user); console.log(user); - res.cookie("user", user); + res.cookie("user", user, {httpOnly: false}); res.redirect("/"); }); diff --git a/views/index.handlebars b/views/index.handlebars index 05a0269..ce12053 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -39,7 +39,7 @@ diff --git a/views/partials/message_form.handlebars b/views/partials/message_form.handlebars new file mode 100644 index 0000000..b7cf112 --- /dev/null +++ b/views/partials/message_form.handlebars @@ -0,0 +1,19 @@ +
+
+ + +
+
+ +
+ {{#each messages as |message|}} +
+
+

+ {{message.author}}: + {{message.body}} +

+
+
+ {{/each}} +
From b04c1006bcf1cd71465c3138ae34698c033d6c16 Mon Sep 17 00:00:00 2001 From: Stephanie Barker Date: Thu, 27 Jul 2017 12:30:59 -0400 Subject: [PATCH 16/32] moved ugly jquery stuff to handlebars template --- index.js | 4 ++++ package.json | 1 + public/javascripts/message_form_compiled.js | 23 +++++++++++++++++++++ public/javascripts/script.js | 4 ++-- views/index.handlebars | 4 ++-- views/partials/dummy.js | 1 + views/partials/message_form.handlebars | 2 +- views/partials/message_form.js | 21 ------------------- 8 files changed, 34 insertions(+), 26 deletions(-) create mode 100644 public/javascripts/message_form_compiled.js create mode 100644 views/partials/dummy.js delete mode 100644 views/partials/message_form.js diff --git a/index.js b/index.js index 5c4bb5b..721a1a6 100644 --- a/index.js +++ b/index.js @@ -18,6 +18,10 @@ app.use( ); app.use("/", express.static(__dirname + "/public")); +app.use( + "/handlebars", + express.static(__dirname + "/node_modules/handlebars/dist/") +); app.get("/", (req, res) => { if (!req.cookies.user) { diff --git a/package.json b/package.json index 1236092..74c2764 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "cookie-parser": "^1.4.3", "express": "^4.15.3", "express-handlebars": "^3.0.0", + "handlebars": "^4.0.10", "redis": "^2.7.1", "shortid": "^2.2.8", "socket.io": "^2.0.3", diff --git a/public/javascripts/message_form_compiled.js b/public/javascripts/message_form_compiled.js new file mode 100644 index 0000000..e392535 --- /dev/null +++ b/public/javascripts/message_form_compiled.js @@ -0,0 +1,23 @@ +(function() { + var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; +templates['message_form_compiled.js'] = template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { + return "message_form_compiled"; +},"useData":true}); +templates['message_form'] = template({"1":function(container,depth0,helpers,partials,data,blockParams) { + var stack1, alias1=container.lambda, alias2=container.escapeExpression; + + return "
\r\n
\r\n

\r\n " + + alias2(alias1(((stack1 = blockParams[0][0]) != null ? stack1.author : stack1), depth0)) + + ": \r\n " + + alias2(alias1(((stack1 = blockParams[0][0]) != null ? stack1.body : stack1), depth0)) + + "\r\n

\r\n
\r\n
\r\n"; +},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams) { + var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}); + + return "
\r\n
\r\n \r\n \r\n
\r\n
\r\n\r\n
\r\n" + + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.messages : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 1, blockParams),"inverse":container.noop,"data":data,"blockParams":blockParams})) != null ? stack1 : "") + + "
\r\n"; +},"useData":true,"useBlockParams":true}); +})(); diff --git a/public/javascripts/script.js b/public/javascripts/script.js index 0908952..29af54f 100644 --- a/public/javascripts/script.js +++ b/public/javascripts/script.js @@ -1,4 +1,4 @@ -var socket = io.connect("http://localhost:3030"); +var socket = io.connect("http://localhost:3000"); let formHandler = function() { $(".messageForm").on("submit", e => { @@ -45,7 +45,7 @@ $(document).ready(function() { }); socket.on("roomLoaded", output => { - let messageFormHBS = Handlebars.partials["message_form"](output); + let messageFormHBS = Handlebars.templates["message_form"](output); // let messageForm = `
`; $("#messageContainer").empty(); $("#messageContainer").append(messageFormHBS); diff --git a/views/index.handlebars b/views/index.handlebars index 15208d3..d795861 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -36,8 +36,8 @@
- - + + diff --git a/views/partials/dummy.js b/views/partials/dummy.js new file mode 100644 index 0000000..2995a4d --- /dev/null +++ b/views/partials/dummy.js @@ -0,0 +1 @@ +dummy \ No newline at end of file diff --git a/views/partials/message_form.handlebars b/views/partials/message_form.handlebars index b7cf112..6a070a9 100644 --- a/views/partials/message_form.handlebars +++ b/views/partials/message_form.handlebars @@ -1,5 +1,5 @@
-
+
diff --git a/views/partials/message_form.js b/views/partials/message_form.js deleted file mode 100644 index 0a9617f..0000000 --- a/views/partials/message_form.js +++ /dev/null @@ -1,21 +0,0 @@ -
-
- - -
-
- -
- {{#each messages as |message|}} -
-
-

- {{message.body}} -

-

- {{message.author}} -

-
-
- {{/each}} -
From 14c012f27612c150d65a819ef1fcd0c228ebdcd1 Mon Sep 17 00:00:00 2001 From: Greg Filipczak Date: Thu, 27 Jul 2017 17:00:58 +0000 Subject: [PATCH 17/32] styling :( --- index.js | 6 - public/javascripts/message_form_compiled.js | 117 ++++++++++++++++---- public/javascripts/script.js | 15 +-- views/index.handlebars | 54 ++++++--- views/partials/message_form.handlebars | 2 +- views/partials/message_form_compiled.js | 0 6 files changed, 140 insertions(+), 54 deletions(-) create mode 100644 views/partials/message_form_compiled.js diff --git a/index.js b/index.js index 721a1a6..9cc0f2b 100644 --- a/index.js +++ b/index.js @@ -27,11 +27,6 @@ app.get("/", (req, res) => { if (!req.cookies.user) { res.render("login"); } else { - // redis.loadMessages(messages => { - // res.render("index", { - // messages: messages, - // user: req.cookies.user - // }); redis.getRooms().then(rooms => { res.render("index", { rooms: rooms, @@ -44,7 +39,6 @@ app.get("/", (req, res) => { app.post("/", (req, res) => { let user = req.body.user; redis.saveUser(user); - console.log(user); res.cookie("user", user, { httpOnly: false }); res.redirect("/"); diff --git a/public/javascripts/message_form_compiled.js b/public/javascripts/message_form_compiled.js index e392535..99abfbc 100644 --- a/public/javascripts/message_form_compiled.js +++ b/public/javascripts/message_form_compiled.js @@ -1,23 +1,102 @@ (function() { - var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; -templates['message_form_compiled.js'] = template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - return "message_form_compiled"; -},"useData":true}); -templates['message_form'] = template({"1":function(container,depth0,helpers,partials,data,blockParams) { - var stack1, alias1=container.lambda, alias2=container.escapeExpression; + var template = Handlebars.template, + templates = (Handlebars.templates = Handlebars.templates || {}); + templates["message_form_compiled.js"] = template({ + compiler: [7, ">= 4.0.0"], + main: function(container, depth0, helpers, partials, data) { + return ""; + }, + useData: true + }); + templates["message_form"] = template({ + "1": function(container, depth0, helpers, partials, data, blockParams) { + var stack1, + alias1 = container.lambda, + alias2 = container.escapeExpression; - return "
\r\n
\r\n

\r\n " - + alias2(alias1(((stack1 = blockParams[0][0]) != null ? stack1.author : stack1), depth0)) - + ": \r\n " - + alias2(alias1(((stack1 = blockParams[0][0]) != null ? stack1.body : stack1), depth0)) - + "\r\n

\r\n
\r\n
\r\n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data,blockParams) { - var stack1, helper, alias1=depth0 != null ? depth0 : (container.nullContext || {}); + return ( + '
\r\n
\r\n

\r\n ' + + alias2( + alias1( + (stack1 = blockParams[0][0]) != null ? stack1.author : stack1, + depth0 + ) + ) + + ": \r\n " + + alias2( + alias1( + (stack1 = blockParams[0][0]) != null ? stack1.body : stack1, + depth0 + ) + ) + + "\r\n

\r\n
\r\n
\r\n" + ); + }, + compiler: [7, ">= 4.0.0"], + main: function(container, depth0, helpers, partials, data, blockParams) { + var stack1, + helper, + alias1 = depth0 != null ? depth0 : container.nullContext || {}, + alias2 = helpers.helperMissing, + alias3 = "function", + alias4 = container.escapeExpression; - return "
\r\n
\r\n \r\n \r\n
\r\n
\r\n\r\n
\r\n" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.messages : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 1, blockParams),"inverse":container.noop,"data":data,"blockParams":blockParams})) != null ? stack1 : "") - + "
\r\n"; -},"useData":true,"useBlockParams":true}); + return ( + '
\r\n
\r\n \r\n \r\n
\r\n
\r\n\r\n
\r\n' + + ((stack1 = helpers.each.call( + alias1, + depth0 != null ? depth0.messages : depth0, + { + name: "each", + hash: {}, + fn: container.program(1, data, 1, blockParams), + inverse: container.noop, + data: data, + blockParams: blockParams + } + )) != null + ? stack1 + : "") + + "
\r\n" + ); + }, + useData: true, + useBlockParams: true + }); })(); diff --git a/public/javascripts/script.js b/public/javascripts/script.js index 29af54f..2c45cd5 100644 --- a/public/javascripts/script.js +++ b/public/javascripts/script.js @@ -1,10 +1,11 @@ -var socket = io.connect("http://localhost:3000"); +var socket = io.connect("http://localhost:3030"); let formHandler = function() { $(".messageForm").on("submit", e => { e.preventDefault(); var data = {}; data.body = $("input[name='message']").val(); + $("input").val(""); data.author = document.cookie.replace( /(?:(?:^|.*;\s*)user\s*\=\s*([^;]*).*$)|^.*$/, "$1" @@ -12,6 +13,7 @@ let formHandler = function() { data.author = data.author.replace("%20", " "); data.room = $(".messageForm").attr("id"); + console.log(data); socket.emit("newMessage", data); }); }; @@ -46,19 +48,8 @@ $(document).ready(function() { socket.on("roomLoaded", output => { let messageFormHBS = Handlebars.templates["message_form"](output); - // let messageForm = `
`; $("#messageContainer").empty(); $("#messageContainer").append(messageFormHBS); - // let allMessages = ""; - // let messageDiv = $( - // `
` - // ); - // output.messages.forEach(message => { - // let thisMessage = `

${message.author}: ${message.body}

`; - // allMessages += thisMessage; - // }); - // messageDiv.append(allMessages); - // $("#messageContainer").append(messageDiv); formHandler(); }); }); diff --git a/views/index.handlebars b/views/index.handlebars index d795861..b888152 100644 --- a/views/index.handlebars +++ b/views/index.handlebars @@ -14,28 +14,50 @@ -

Welcome {{user}}!

-
- -
- -
- {{#each rooms as |room|}} -
-

{{room}}

+ +
+ +
+
+

Welcome {{user}}!

+
+
+
+ +
- {{/each}} +
+
-
- - -
-
+ -
+
+
+
+
+ {{#each rooms as |room|}} +
+

{{room}}

+
+ {{/each}} + +
+ + +
+
+
+ +
+
+
+
+
+ + + + -
+
+
+