Skip to content

Instantly share code, notes, and snippets.

@luizs81
Last active December 4, 2017 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luizs81/ce8c3b81abff7e83fe1e96007f7c221f to your computer and use it in GitHub Desktop.
Save luizs81/ce8c3b81abff7e83fe1e96007f7c221f to your computer and use it in GitHub Desktop.
SignalR Client - JavaScript Implementation
$('#bid-area').hide();
loadJavascript('scripts/jquery.signalR-2.2.2.min.js', () => {
loadJavascript('signalr/hubs', () => {
fetchProduct();
getActivePoints();
getNumberOfBids();
getBidRanking();
});
});
var cookie = Cookies.getJSON('meandstars');
var productId = window.location.search.split('=')[1];
var hub = null;
var roomId = null;
if (hostUrl === undefined || hostUrl === null) {
console.log('variable hostUrl not set');
}
if (cookie === undefined) {
window.location.href = '/';
}
if (productId === undefined) {
window.location.href = '/products.html';
}
var token = cookie.access_token;
var userId = cookie.id;
var fetchProduct = () => {
var request = makeRequest(`${hostUrl}/api/v1.0/meandstars/pageId/products/${productId}`);
request.done((data) => {
$('#product-name').text(data.Name);
$('#product-description').text(data.Description);
roomId = data.ChatRoomId;
startChat();
});
request.fail((xhr, status) => { handleError(xhr, status) });
}
var getActivePoints = () => {
var request = makeRequest(`${hostUrl}/api/v1.0/meandstars/pageId/Users/Self/Points`);
request.done((data) => { refreshActivePoints(data); });
request.fail((xhr, status) => { handleError(xhr, status) });
}
var getNumberOfBids = () => {
var request = makeRequest(`${hostUrl}/api/v1.0/meandstars/pageId/product/${productId}/bids`);
request.done((data) => { refreshBids(data); });
request.fail((xhr, status) => { handleError(xhr, status) });
}
var getBidRanking = () => {
var request = makeRequest(`${hostUrl}/api/v1.0/meandstars/pageId/product/${productId}/ranking`);
request.done((data) => { refreshBidRanking(data); });
request.fail((xhr, status) => { handleError(xhr, status) });
}
var getAudience = () => {
var request = makeRequest(`${hostUrl}/api/v1.0/meandstars/pageId/Rooms/${roomId}/audience`);
request.done((data) => { $('#viewers-counter').text(data); });
request.fail((xhr, status) => { handleError(xhr, status) });
}
var startChat = () => {
$.connection.hub.url = `${hostUrl}/signalr`;
$.connection.hub.qs = { 'access_token': token };
$.connection.hub.logging = true;
hub = $.connection.signalRHub;
hub.client.addChatMessage = addChatMessage;
hub.client.addReaction = addReaction;
hub.client.refreshActivePoints = refreshActivePoints;
hub.client.refreshAudience = refreshAudience;
hub.client.refreshBids = refreshBids;
hub.client.refreshBidRanking = refreshBidRanking;
var startConnection = $.connection.hub.start();
startConnection.done((response) => {
$('#chat-form').submit(addComment);
$('#bid-form').submit(addBid);
joinRoom();
getAudience();
var messageInput = $('#message-input');
messageInput.keyup(updateCount);
messageInput.keydown(updateCount);
window.addEventListener('beforeunload', (e) => {
hub.server.leaveRoom(roomId);
(e || window.event).returnValue = null;
return null;
});
});
startConnection.fail((xhr, status) => {
var errorAlert = $('#error');
errorAlert.removeClass('hidden');
errorAlert.text(`${status}: ${xhr.responseJSON.Message}`);
});
startConnection.always(() => {
$('#loading').addClass('hidden');
});
};
var addChatMessage = (message, user) => {
if (user !== undefined)
$('#chat-messages').append(formatMessage(message, user));
else
$('#chat-messages').append(`<p>${message}</p>`);
var chatMessages = $('#chat-messages');
chatMessages.scrollTop(chatMessages.prop("scrollHeight"));
}
var addReaction = () => {
var hearts = $('#hearts');
hearts.removeClass('hidden');
hearts.animate({
opacity: 0,
bottom: '+=150px',
}, 'slow', () => {
hearts.addClass('hidden');
hearts.css('bottom', 6);
hearts.css('left', 18);
hearts.css('opacity', 1);
});
}
var refreshActivePoints = (data) => {
$('#points-counter').text(data.TotalPoints);
}
var refreshAudience = (participants) => {
$('#viewers-counter').text(participants);
}
var refreshBids = (bidCount) => {
$('#bids-counter').text(bidCount.Bids);
}
var refreshBidRanking = (ranking) => {
if (ranking.PriceCurrency.length <= 0)
return;
$('#top-rank').text(ranking.PriceCurrency[0].toLocaleString());
if (ranking.length > 1) {
$('#low-position').text(`${ranking.length}&nbsp;位`)
$('#low-rank').text(data[ranking.PriceCurrency.length - 1].toLocaleString());
}
}
var joinRoom = () => {
var joinRoom = hub.server.joinRoom(roomId);
joinRoom.fail((xhr, status) => {
var errorAlert = $('#error');
errorAlert.removeClass('hidden');
errorAlert.text(xhr);
});
}
var addComment = (e) => {
e.stopPropagation();
e.preventDefault();
var messageInput = $('#message-input');
var message = messageInput.val();
if (message === '')
return;
var request = $.ajax({
type: 'POST',
url: `${hostUrl}/api/v1.0/meandstars/pageId/Rooms/${roomId}/comments`,
beforeSend: (request) => {
request.setRequestHeader('Authorization', 'Bearer ' + token);
request.setRequestHeader('client_version', '0.1');
},
data: {
'text': message,
},
});
request.done((data) => {
messageInput.val('');
messageInput.focus();
});
request.fail((xhr, status) => { handleError(xhr, status) });
}
var addBid = (e) => {
e.stopPropagation();
e.preventDefault();
var bidPrice = $('#total-value').text().replace(',', '');
var amount = $($('#qty option:selected')[0]).val();
var request = $.ajax({
type: 'POST',
url: `${hostUrl}/api/v1.0/meandstars/{pageId}/product/${productId}/bidaction`,
beforeSend: (request) => {
request.setRequestHeader('Authorization', 'Bearer ' + token);
request.setRequestHeader('client_version', '0.1');
},
data: {
'Amount': amount,
'BidPrice': bidPrice,
},
});
request.done((data) => {
$('#bid-area').hide();
$('#chat-area').show();
var chatMessages = $('#chat-messages');
chatMessages.scrollTop(chatMessages.prop("scrollHeight"));
});
request.fail((xhr, status) => { handleError(xhr, status) });
}
var formatMessage = (message, user) => {
var css = user.Identifier === userId ? 'message-highlight' : '';
var container = `
<div class="comment ${css}">
<img src="${user.ProfilePhotoUrl}" class="img-circle avatar" width="40" height="40">
<p class="message-body">${message}</p>
<p class="message-sender">${user.NickName}</p>
</div>
`;
return container
}
var updateCount = () => {
var cs = $('#message-input').val().length;
$('#message-counter').text(100 - cs);
}
$('#bid').click(() => {
$('#chat-area').hide();
$('#bid-area').show();
});
$('#comment').click(() => {
$('#bid-area').hide();
$('#chat-area').show();
});
$('#qty').change(() => {
var qty = $($('#qty option:selected')[0]).val();
var value = qty * 100;
$('#total-value').text(value.toLocaleString());
});
$('#like').click(() => {
var request = $.ajax({
type: 'POST',
url: `${hostUrl}/api/v1.0/meandstars/pageId/product/${productId}/reaction`,
beforeSend: (request) => {
request.setRequestHeader('Authorization', 'Bearer ' + token);
request.setRequestHeader('client_version', '0.1');
},
data: {
'ReactionId': 'meandstars.liveauction.BasicHeart',
},
});
request.fail((xhr, status) => { handleError(xhr, status) });
});
var makeRequest = (url) => {
return $.ajax({
type: 'GET',
url: url,
beforeSend: (request) => {
request.setRequestHeader('Authorization', 'Bearer ' + token);
request.setRequestHeader('client_version', '0.1');
}
});
}
var handleError = (xhr, status) => {
var errorAlert = $('#error');
errorAlert.removeClass('hidden');
if (xhr.responseJSON === undefined)
errorAlert.text(`${status}: Could not connect to server`);
else
errorAlert.text(`${status}: ${xhr.responseJSON.Message}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment