Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Polished chat #38

Merged
merged 3 commits into from
May 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .DS_Store
Binary file not shown.
3 changes: 3 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ var handlebars = hbs.create({
ifEquals: function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
},
ifNotEquals: function(arg1, arg2, options) {
return (arg1 != arg2) ? options.fn(this) : options.inverse(this);
}
},
extname: 'hbs',
defaultLayout:'layout.hbs',
Expand Down
70 changes: 43 additions & 27 deletions routes/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ router.use(bodyParser.urlencoded({ extended: false }))


/* GET home page. */
router.get('/', checkAuthentication, setupSocketListeners, function(req, res, next) {
router.get('/', (req, res, next) => {
req.session.authorigin = 'chat?' + querystring.stringify(req.query);
next();
}, checkAuthentication, setupSocketListeners, function(req, res, next) {
// Setup chat data and render chat page
preselectedThread = req.query.preselectedThread ? req.query.preselectedThread : '';
chatData.find({allParticipants:
Expand Down Expand Up @@ -95,40 +98,53 @@ function setupSocketListeners(req, res, next) {
next();
}

router.post('/openThread', checkAuthentication, function(req,res){
chatData.findOne({item: req.body.itemId, interestedBuyer:req.session.passport.user._json.email}).then(doc => {
if (!doc) {
// Start a new thread
var current_millies = new Date().getTime();
var current_timestamp = Long.fromNumber(current_millies);
var date = new Date(current_millies);
var dateReadable = date.toString();
var chat = {
item: mongoose.Types.ObjectId(req.body.itemId),
seller: req.body.seller,
interestedBuyer: req.session.passport.user._json.email,
allParticipants:[ {email: req.session.passport.user._json.email}, {email: req.body.seller} ],
dateChatCreated: current_timestamp,
dateChatCreatedComputed: dateReadable
router.get('/openThread', (req, res, next) => {
req.session.authorigin = 'chat/openThread?' + querystring.stringify(req.query);
next();
}, checkAuthentication, function(req,res) {
var {itemId, seller} = req.query;
var currentUser = req.session.passport.user._json.email;
// Ensure the seller is not opening a thread on their own listing
itemData.findOne({_id: itemId, postedBy:currentUser}).then(doc => {
if (!doc) {
// The seller ≠ the buyer
// Create a new thread or open the existing one
chatData.findOne({item: itemId, interestedBuyer:currentUser}).then(doc => {
if (!doc) {
// Start a new thread
var current_millies = new Date().getTime();
var current_timestamp = Long.fromNumber(current_millies);
var date = new Date(current_millies);
var dateReadable = date.toString();
var chat = {
item: mongoose.Types.ObjectId(itemId),
seller: seller,
interestedBuyer: req.session.passport.user._json.email,
allParticipants:[ {email: currentUser}, {email: seller} ],
dateChatCreated: current_timestamp,
dateChatCreatedComputed: dateReadable
}
var data = new chatData(chat);
data.save((err, doc) => {
res.redirect('/chat?' + querystring.stringify({'preselectedThread':doc.id}));
});
} else {
// Open the existing thread
res.redirect('/chat?' + querystring.stringify({'preselectedThread':doc.id}));
}
});
} else {
// The seller = the buyer
res.redirect('/?' + querystring.stringify({'alert':"You own this listing! You cannot buy your own listing!"}));
}
var data = new chatData(chat);
data.save((err, doc) => {
res.redirect('/chat?' + querystring.stringify({'preselectedThread':doc.id}));
});
} else {
// Open the existing thread
res.redirect('/chat?' + querystring.stringify({'preselectedThread':doc.id}));
}
})
});
});

//authenticate a user is logged in
function checkAuthentication(req,res,next){
if(req.isAuthenticated()){
//req.isAuthenticated() will return true if user is logged in
next();
} else{
req.session.authorigin = 'chat';
res.redirect('/auth/google/callback')
}
}
Expand Down
2 changes: 1 addition & 1 deletion routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ router.get('/' ,function(req, res, next) {
}
results.find({sold:false}).sort( { datePosted: -1 } )
.then(function(doc) {
res.render('index', { title: 'DrewUse', items:doc, currentSession: req.session, filters:filters});
res.render('index', { title: 'DrewUse', items:doc, currentSession: req.session, filters:filters, queryParams:req.query});
});
});

Expand Down
17 changes: 6 additions & 11 deletions views/chat.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ img{ max-width:100%;}
</div>
<div id="input_zone" class="type_msg">
<div class="input_msg_write">
<input id="message" type="text" class="write_msg" placeholder="Type a message" />
<input id="message" type="text" class="write_msg" placeholder="Type a message..." />
<button id="send_message" class="msg_send_btn" type="button"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>
</div>
</div>
Expand All @@ -225,16 +225,15 @@ img{ max-width:100%;}
</div>

<script>
// Add current user to session
window.sessionStorage.setItem('currentUser', '{{currentSession.passport.user._json.email}}');
window.sessionStorage.setItem('currentUsername', window.sessionStorage.getItem('currentUser').match(/[^@]+/)[0]);
// Setup socket.io client
var socket = io.connect(`/${window.sessionStorage.getItem('currentUsername')}`);

// Add listeners
socket.on('newMessage', appendMessage)
socket.on('displayThread', displayThread)

// Add current user to session
window.sessionStorage.setItem('currentUser', '{{currentSession.passport.user._json.email}}');
window.sessionStorage.setItem('currentUsername', window.sessionStorage.getItem('currentUser').match(/[^@]+/)[0]);

// Setup listener for clicking the send-message button
$("#send_message").click(() => {
Expand All @@ -249,8 +248,7 @@ img{ max-width:100%;}
});

// Handle selection of a specific thread
$('.chat_people').click(function(){
console.log('Thread Clicked');
$('.chat_people').click(function() {
var threadId = $(this).attr('threadId'); // Get thread id
selectThread(threadId);
});
Expand All @@ -274,7 +272,6 @@ img{ max-width:100%;}
// xs.emit('hey');

function selectThread(threadId) {
console.log('Thread Selected');
// Save thread id to session storage
window.sessionStorage.setItem('currentThread', threadId); // set thread id in session
$("#chatroom").empty();
Expand Down Expand Up @@ -304,7 +301,7 @@ img{ max-width:100%;}
function appendMessage(message){
// Add new message to chat room
$("#chatroom").append(`<p class='message'>${message.byWho}: ${message.message}</p>`)
$("#message").val(" ");
$("#message").val("");
}

function displayThread(thread){
Expand All @@ -320,8 +317,6 @@ img{ max-width:100%;}
for (var i in thread.messages) {
appendMessage(thread.messages[i]);
}

$("#message").val(" ");
}

</script>
48 changes: 13 additions & 35 deletions views/index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@
</div>
</div>
<!-- LISTING CARDS -->
{{#if currentSession.passport}}
<div class="row">
{{# each items }}
<div class="row">
{{# each items }}
{{#ifNotEquals this.postedBy ../currentSession.passport.user._json.email}}
<div class="col-sm-3" style="margin-top:20px">
<div class="card" >
<img class="card-img-top" src="{{ this.image_url }}" alt="Card image cap" style="height:10vw;">
Expand All @@ -127,45 +127,23 @@
<p class="card-text" name="description">{{ this.description }}</p>
<p name="condition">A <strong>{{ this.booktype }}</strong> in <strong>{{ this.condition }}</strong> condition.</strong></p>
<hr/>
{{#if listingIsSameAsUser}}

{{else}}
<form action="/chat/openThread" method="POST">
<form action="/chat/openThread">
<input class="card-text" name="itemId" value="{{this._id}}" style="display:none;"></input>
<input class="card-text" name="seller" value="{{this.postedBy}}" style="display:none;"></input>
<center><button type="submit" class="btn btn-success">I'm Interested</button></center>
</form>
{{/if}}
</div>
<div class="card-footer">
<small class="text-muted">{{ this.datePostedComputed }}</small>
</div>
</div>
</div>
{{/each}}
</div>
{{else}}
<div class="row">
{{# each items }}
<div class="col-sm-3" style="margin-top:20px">
<div class="card" >
<img class="card-img-top" src="{{ this.image_url }}" alt="Card image cap" style="height:10vw;">
<div class="card-body">
<h5 class="card-title" name="title">{{ this.title }}</h5>
<p name="price">Price: ${{ this.price }}</p>
<p class="card-text" name="description">{{ this.description }}</p>
<p name="condition">A <strong>{{ this.booktype }}</strong> in <strong>{{ this.condition }}</strong> condition.</strong></p>
<hr/>
<form>
<center><button class="btn btn-success disabled">I'm Interested</button></center>
</form>
</div>
<div class="card-footer">
<small class="text-muted">{{ this.datePostedComputed }}</small>
</div>
</div>
</div>
{{/each}}
</div>
{{/if}}
<br>
{{/ifNotEquals}}
{{/each}}
</div>

{{#if queryParams.alert}}
<script>
alert('{{queryParams.alert}}');
</script>
{{/if}}