Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- *
- * Controller component
- * Handles communication with server and login
- * Three main areas of the controller: Authentication, Messages to server, Messages from server
- *
- */
- /*
- *
- * Main variables used for website
- *
- */
- var ws;
- var http = "http:%2F%2F";
- var hostname = "ec2-122-248-200-91.ap-southeast-1.compute.amazonaws.com";
- //var hostname = "localhost";
- var port = "80";
- var VM;
- var pingVariable; // To be able to stop ping messages on disconnect
- var pingFunction = function(x){ // Looping function to send ping to server
- pingVariable = setTimeout(function(){
- sendping();
- pingFunction(x);
- },x)
- };
- var pingPeriod = 120*1000;
- /*
- *
- * Authentication
- *
- */
- // Initialisation of webpage
- $(document).ready(function () {
- // Create VM
- initUI();
- VM = new HangoutViewModel();
- ko.applyBindings(VM);
- // Try get token
- var token = getParameterByName("token");
- if (token != undefined){
- setCookie("token",token,365);
- setCookie("tokenvalid","1",365);
- window.location.replace("chat.html");
- }
- // Try get cookie
- else {
- token = getCookie("token");
- tokenvalid = getCookie("tokenvalid");
- if (token != undefined && tokenvalid != "0"){
- auth("auth", token);
- }
- }
- });
- // Function to get query GET parameter for ivle token
- function getParameterByName(name){
- name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
- var regexS = "[\\?&]" + name + "=([^&#]*)";
- var regex = new RegExp(regexS);
- var results = regex.exec(window.location.search);
- if(results == null)
- return undefined;
- else
- return decodeURIComponent(results[1].replace(/\+/g, " "));
- }
- // To store cookie, used for ivle token
- function getCookie(cookiename){
- var i,x,y,ARRcookies=document.cookie.split(";");
- for (i=0;i<ARRcookies.length;i++)
- {
- x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
- y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
- x=x.replace(/^\s+|\s+$/g,"");
- if (x==cookiename){
- return unescape(y);
- }
- }
- return undefined;
- }
- // To set cookie, used for ivle token
- function setCookie(cookiename,value,exdays){
- var exdate=new Date();
- exdate.setDate(exdate.getDate() + exdays);
- var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
- document.cookie=cookiename + "=" + c_value;
- }
- function initSize(){
- // Set viewport
- var userWidth = $(window).width();
- var userHeight = $(window).height();
- document.getElementById("document-area").style.height = (userHeight - 260)+"px";
- document.getElementById("channels-bar-area").style.width = (userWidth - 680)+"px";
- document.getElementById("chat-area").style.width = (userWidth - 680-20)+"px";
- document.getElementById("chat-area").style.height = (userHeight - 165)+"px";
- document.getElementById("chatbox-input").style.width = (userWidth - 680-20)+"px";
- document.getElementById("joined-area").style.height = (userHeight - 380)+"px";
- document.getElementById("channels-bar-items-id").style.width = (userWidth - 680-100)+"px";
- }
- // Any UI initialisation needed
- function initUI(){
- // Dimensions based on screen
- window.onresize = function(event) {
- initSize();
- };
- initSize();
- // Set enter to send message
- $('#chatbox-input').keydown(function(e){
- if (e.keyCode == 13) {
- sendchat();
- }});
- // Right click to close channel search window
- $('#search-channel-popup').bind('contextmenu', function(e){
- e.preventDefault();
- document.getElementById('search-channel-popup').style.display = 'none';
- });
- // Enter to search channels
- $('#search-channel-input').keydown(function(e){
- if (e.keyCode == 13) {
- searchchannel($("#search-channel-input").val());
- }});
- // Right click to close user search window
- $('#search-user-popup').bind('contextmenu', function(e){
- e.preventDefault();
- document.getElementById('search-user-popup').style.display = 'none';
- });
- // Enter to search users
- $('#search-user-input').keydown(function(e){
- if (e.keyCode == 13) {
- searchuser($("#search-user-input").val());
- }
- });
- // Enter to create/join channels
- $('#create-channel-input').keydown(function(e){
- if (e.keyCode == 13) {
- requestjoin($("#create-channel-input").val());
- closeSearchChannelPopup();
- }
- });
- // Enter to create/join channels
- $('#nickname-input').keydown(function(e){
- if (e.keyCode == 13) {
- var newnickname = $("#nickname-input").val();
- //$("#nickname-input").val(VM.selfnickname());
- document.getElementById("nickname-input").blur();
- changenickname(newnickname);
- }
- });
- // Right click to close channel options
- $('#channel-options-popup').bind('contextmenu', function(e){
- e.preventDefault();
- document.getElementById('channel-options-popup').style.display = 'none';
- });
- }
- /*
- *
- * Messages to server
- *
- */
- // Send chat, privchat to server (Deprecated, pelase remove soon)
- function sendchat() {
- var text = $("#chatbox-input").val();
- if (text[0] == '/')
- ws.send(text.substring(1));
- else if (VM.selectedPrivateChat() != undefined)
- ws.send("user,sendprivchat,"+VM.selectedPrivateChat().user().ivleid+","+text);
- else if (VM.selectedChannel != undefined)
- ws.send("channel,sendchat,"+VM.selectedChannel.name+","+text);
- else
- alert("Invalid command. Please prefix with \"/\".");
- $("#chatbox-input").val("");
- }
- // Send raw command to server
- function sendcommand(command){
- ws.send(command);
- }
- // Request to send a chat to a channel
- function sendchattrial(channame, text){
- ws.send("channel,sendchat,"+channame+","+text);
- }
- // Request to register a channel
- function registerchannel(channame){
- ws.send("channel,registerchannel,"+channame);
- }
- // Request to deregister a channel
- function deregisterchannel(channame){
- ws.send("channel,deregisterchannel,"+channame);
- }
- // Request to join a channel
- function requestjoin(channame){
- ws.send("channel,requestjoin,"+channame);
- }
- // Request to leave a channel
- function requestleave(channame){
- ws.send("channel,requestleave,"+channame);
- }
- // Request to invite a user to a channel
- function requestinvite(channame, ivleid){
- ws.send("channel,requestinvite,"+channame+","+ivleid);
- }
- // Request to kick a user in a channel
- function requestkick(channame, ivleid){
- ws.send("channel,requestkick,"+channame+","+ivleid);
- }
- // Request to change topic of a channel
- function changetopic(channame, topic){
- ws.send("channel,changetopic,"+channame+","+topic);
- }
- // Request to set a channel's privacy
- function setprivacy(channame, publicBit){
- if (publicBit)
- ws.send("channel,setprivacy,"+channame+",public");
- else
- ws.send("channel,setprivacy,"+channame+",private");
- }
- // Request to set access of a user of a channel
- function setaccess(channame, ivleid, level){
- ws.send("channel,setaccess,"+channame+","+ivleid+","+level);
- }
- // Set permissions of a channel
- function setpermissions(channame, permissions){
- ws.send("channel,setpermissions,"+channame+","+JSON.stringify(permissions));
- }
- // Search a channel with a query string
- function searchchannel(query){
- ws.send("channel,searchchannel,"+query);
- }
- // Change user's nickname
- function changenickname(nickname){
- ws.send("user,changenickname,"+nickname);
- }
- // Mute a user
- function addmute(ivleid){
- ws.send("user,addmute,"+ivleid);
- }
- // Unmute a user
- function unmute(ivleid){
- ws.send("user,removemute,"+ivleid);
- }
- // Request to send a private chat to a user
- function sendprivchat(ivleid, text){
- ws.send("user,sendprivchat,"+ivleid+","+text);
- }
- // Adds a channel to autojoin list
- function addautojoin(channame){
- ws.send("user,addautojoin,"+channame);
- }
- // Deletes a channel from autojoin list
- function deleteautojoin(channame){
- ws.send("user,deleteautojoin,"+channame);
- }
- // Logout
- function logout(){
- ws.send("user,sessionclose");
- }
- // Search for a user by nickname
- function searchuser(query){
- ws.send("user,searchuser,"+query);
- }
- // Request for specific user's info
- function getuserinfo(ivleid){
- ws.send("user,getuserinfo,"+ivleid);
- }
- // Send raw command to server
- function sendping(){
- ws.send("ping");
- }
- // Send auth command to server
- function auth(type, key){
- ws = new WebSocket("ws://"+ hostname +":8888/socket");
- ws.onopen = function() {
- ws.send("auth,"+type+","+key);
- };
- ws.onmessage = function(event) {
- handleMessage(event.data);
- };
- ws.onclose = function(event) {
- handleMessage(event.data);
- };
- }
- /*
- *
- * Messages from server
- * Most of them are used to edit the ViewModel's data
- *
- */
- function handleMessage(message){
- try{
- // Handle invalid login
- if (message == "Invalid login."){
- setCookie("token","",365);
- setCookie("tokenvalid","0",365);
- alert(message);
- return;
- }
- // Log all messages
- console.log(message);
- // Prepare message with standard format
- comma = message.indexOf(",");
- var commandType = message.substring(0, comma);
- message = message.substring(comma+1, message.length);
- comma2 = message.indexOf(",");
- if (comma2 == -1)
- comma2 = message.length;
- var command = message.substring(0, comma2);
- var args;
- if (comma2+1 < message.length)
- args = message.substring(comma2+1, message.length);
- else
- args = "";
- // Case of user type
- if (commandType == "user"){
- switch (command)
- {
- case "userinfo":
- var user = JSON.parse(args);
- VM.updateUserInfo(user);
- break;
- case "changednickname":
- args = args.split(",");
- VM.updateUserNickname(args[0],args[1],true);
- break;
- case "addedautojoin":
- VM.addedAutojoin(args);
- break;
- case "deletedautojoin":
- VM.deletedAutojoin(args);
- break;
- case "muted":
- VM.addedMute(args);
- break;
- case "removedmute":
- VM.removedMute(args);
- break;
- case "privchat":
- args = args.split(",");
- VM.addPrivateChat(args[0], args[1], args[2]);
- break;
- case "searcheduser":
- args = JSON.parse(args);
- VM.receiveSearchedUser(args);
- break;
- case "sessionclose":
- setCookie("token","",365);
- location.reload(true);
- break;
- default:
- break;
- }
- }
- // Case of channel type
- else if (commandType == "channel"){
- switch (command)
- {
- case "chat":
- var split = args.indexOf(",");
- var channame = args.substring(0,split);
- args = args.substring(split+1);
- var split2 = args.indexOf(",");
- var ivleid = args.substring(0,split2);
- if (channame == "drawsomething" && ivleid != VM.selfivleid()){
- var draw = JSON.parse(args.substring(split2+1));
- receiveArrays(draw.x, draw.y);
- }
- else
- VM.addChannelMessage(channame, ivleid, args.substring(split2+1));
- break;
- case "join":
- var split = args.indexOf(",");
- var channame = args.substring(0,split);
- var user = JSON.parse(args.substring(split+1,args.length));
- VM.updateUserInfo(user);
- VM.addJoined(channame, user.ivleid);
- break;
- case "leave":
- args = args.split(",");
- if (args[2] == "undefined")
- args[2] = "leave";
- VM.removeJoined(args[0], args[1], args[2]);
- break;
- case "joinedchannel":
- joinedchannel = JSON.parse(args);
- VM.addChannel(joinedchannel);
- break;
- case "topic":
- var split = args.indexOf(",");
- var channame = args.substring(0,split);
- args = args.substring(split+1,args.length);
- var split2 = args.indexOf(",");
- var ivleid = args.substring(0,split2);
- VM.setTopic(channame, ivleid, args.substring(split2+1,args.length));
- break;
- case "permissions":
- var split = args.indexOf(",");
- var channame = args.substring(0,split);
- var permissions = JSON.parse(args.substring(split+1,args.length));
- VM.setPermissions(channame, permissions);
- break;
- case "setaccess":
- args = args.split(",");
- VM.setACL(args[0], args[1], args[2]);
- break;
- case "registered":
- VM.setRegistered(args);
- break;
- case "deregistered":
- VM.setDeregistered(args);
- break;
- case "privacy":
- args = args.split(",");
- VM.setPrivacy(args[0], args[1]);
- break;
- case "invite":
- args = args.split(",");
- VM.receiveInvited(args[0], args[1], args[2], args[3]);
- break;
- case "invited":
- args = args.split(",");
- VM.receiveInvite(args[0], args[1], args[2]);
- break;
- case "kicked":
- args = args.split(",");
- VM.receiveKicked(args[0], args[1], args[2]);
- break;
- case "searchedchannel":
- args = JSON.parse(args);
- VM.receiveSearchedChannel(args);
- break;
- default:
- break;
- }
- }
- // Case of notices (Needs to change according to UI)
- else if (commandType == "notice"){
- alert(args);
- }
- // First login message (Needs to change according to UI)
- else if (commandType == "welcome"){
- switch (command)
- {
- case "userinfo":
- $("#pre-login").css('display','none');
- setCookie("tokenvalid","0",365);
- pingFunction(pingPeriod);
- args = JSON.parse(args);
- VM.updateUserInfo(args);
- VM.selfivleid(args.ivleid);
- VM.selfnickname(args.nickname);
- VM.selffullname(args.fullname);
- VM.selfemail(args.email);
- break;
- case "userpreference":
- args = JSON.parse(args);
- VM.myMute = args.mute;
- VM.myAutojoin = args.autojoin;
- break;
- case "availablelevels":
- VM.availablerolesMap = JSON.parse(args);
- for (var p in VM.availablerolesMap){
- VM.availablelevels.push(p);
- VM.availablelevelsMap[VM.availablerolesMap[p]] = p;
- }
- break;
- case "availablepermissions":
- var arr = JSON.parse(args);
- for (var p in arr)
- VM.availablepermissions.push(p);
- break;
- default:
- break;
- }
- }
- } catch (err) {
- // Exception
- alert(err+"\n"+message+"\n"+"Connection ended.");
- clearTimeout(pingVariable);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement