summaryrefslogtreecommitdiffstats
path: root/dist/js/chats.js
diff options
context:
space:
mode:
Diffstat (limited to 'dist/js/chats.js')
-rw-r--r--dist/js/chats.js38
1 files changed, 38 insertions, 0 deletions
diff --git a/dist/js/chats.js b/dist/js/chats.js
new file mode 100644
index 0000000..7403d0c
--- /dev/null
+++ b/dist/js/chats.js
@@ -0,0 +1,38 @@
+
+const DIRECTORY_URL="/directory.json";const CHATS_BEGIN_TAG="<!-- ba-ctlmsg-chat-begin -->";const CHATS_END_TAG="<!-- ba-ctlmsg-chat-end -->";const CHAT_REGEX=/<!-- ba-ctlmsg-chat-begin -->([\S\s]+)<!-- ba-ctlmsg-chat-end -->/g;const CHATS_SUBJECT_PREFIX="ba-ctlmsg-chat-";let directory=null;let currentlyChattingWith=null;let sogovornik=null;let firstPageOfMessages=null;async function checkLogin(){localforage.getItem("logged_in").then(function(value){if(value!==true){window.location.replace("/index.html");}}).catch(function(err){console.log(err);});}
+function getKeyByValue(object,value){return Object.keys(object).find(key=>object[key]===value);}
+function htmlEncode(value){return $("<textarea/>").text(value).html();}
+function htmlDecode(value){return $("<textarea/>").html(value).text();}
+function loadDirectory(){$.ajax({url:DIRECTORY_URL,crossDomain:true,dataType:"json",cache:false,type:"GET",success:(data)=>{localforage.setItem("directory",data);directory=data;populateAutocomplete();},error:()=>{localforage.getItem("directory").then((storedDirectory)=>{if(storedDirectory===null){UIAlert(D("nameDirectoryNotSet"),"loadDirectory(): stored_directory === null");directory=null;$("#msg-send").prop("disabled",true);}else{directory=storedDirectory;populateAutocomplete();}});}});}
+function populateAutocomplete(){let elems=document.querySelectorAll('.autocomplete-fullname');let autocompleteEntries=Object.assign({},directory);for(const[key]of Object.entries(autocompleteEntries)){autocompleteEntries[key]=null;}
+M.Autocomplete.init(elems,{data:autocompleteEntries,onAutocomplete:validateName,minLength:0});if(window.location.hash.length>1){$("#full-name").val(decodeURIComponent(window.location.hash.substring(1)));}else{$("#full-name").val(getUrlParameter("m"));}
+M.updateTextFields();validateName();}
+function setLoading(state){if(state){$("#loading-bar").removeClass("hidden");}else{$("#loading-bar").addClass("hidden");}}
+async function sendMessage(recipientNumber=null,body=null){if(recipientNumber==null){recipientNumber=directory[sogovornik];}
+if(body==null){body=$("#msg-body").val();}
+if(body.length>180){throw new RangeError("sendMessage(): message is longer than 180 characters.");}
+let promisesToRun=[localforage.getItem("username").then((value)=>{username=value;}),localforage.getItem("password").then((value)=>{password=value;}),];setLoading(true);Promise.all(promisesToRun).then(()=>{try{let gsecInstance=new gsec();gsecInstance.login(username,password).then(()=>{gsecInstance.sendMessage(recipientNumber,CHATS_SUBJECT_PREFIX+body,S("chatExternalInfo")+CHATS_BEGIN_TAG+body+CHATS_END_TAG).then(()=>{addMessage(0,body);setLoading(false);}).catch((err)=>{gsecErrorHandlerUI(err);setLoading(false);});});}catch(err){gsecErrorHandlerUI(err);setLoading(false);}});}
+function addMessage(isSender,body,datePlacement=0,messageDate=null){var whos=isSender==0?"mine":"yours";var timestamp=Date.now();if(messageDate instanceof Date){timestamp=messageDate.getTime();}
+if(typeof messageDate=="number"){timestamp=messageDate;}
+var chatarea=document.getElementsByClassName("chat")[0];var alreadyMessages=chatarea.querySelectorAll(".message");var textnode=document.createTextNode(body);var bubblenode=document.createElement("div");bubblenode.setAttribute("data-date",timestamp);bubblenode.appendChild(textnode);var istaOseba;var messagesnest;if(chatarea.childElementCount==0){bubblenode.className="message last";messagesnest=document.createElement("div");istaOseba=false;}else{if(datePlacement==0||timestamp>Number(alreadyMessages[alreadyMessages.length-1].getAttribute("data-date"))){datePlacement=0;console.log(alreadyMessages[0].getAttribute("data-date"));bubblenode.className="message last";if(chatarea.children.item(chatarea.children.length-1).classList.contains(whos)){istaOseba=true;messagesnest=chatarea.children.item(chatarea.children.length-1);messagesnest.children.item(messagesnest.children.length-1).classList.remove("last");}else{istaOseba=false;messagesnest=document.createElement("div");}}else if(datePlacement==1||timestamp<Number(alreadyMessages[0].getAttribute("data-date"))){datePlacement=1;console.log(alreadyMessages[0].getAttribute("data-date"));if(chatarea.children.item(0).classList.contains(whos)){bubblenode.className="message";istaOseba=true;messagesnest=chatarea.children.item(0);}else{bubblenode.className="message last";istaOseba=false;messagesnest=document.createElement("div");}}else{console.log("if3");for(var iter=0;iter<alreadyMessages.length-2;iter++){if(Number(alreadyMessages[iter].getAttribute("data-date"))<timestamp&&Number(alreadyMessages[iter+1].getAttribute("data-date"))>timestamp){var zgornjiIsti=alreadyMessages[iter].parentElement.classList.contains(whos);var spodnjiIsti=alreadyMessages[iter+1].parentElement.classList.contains(whos);console.log([zgornjiIsti,spodnjiIsti]);if(zgornjiIsti&&spodnjiIsti){messagesnest=alreadyMessages[iter].parentElement;bubblenode.className="message";messagesnest.insertBefore(bubblenode,alreadyMessages[iter+1]);return;}
+if(zgornjiIsti&&!spodnjiIsti){messagesnest=alreadyMessages[iter].parentElement;bubblenode.className="message last";messagesnest.children.item(messagesnest.childElementCount-1).classList.remove("last");messagesnest.appendChild(bubblenode);return;}
+if(!zgornjiIsti&&spodnjiIsti){messagesnest=alreadyMessages[iter+1].parentElement;bubblenode.className="message";messagesnest.insertBefore(bubblenode,alreadyMessages[iter+1]);return;}
+throw new RangeError("This should not happen!");}}
+throw new RangeError("This should not happen!");}}
+messagesnest.className=whos+" messages";if(datePlacement==0){messagesnest.appendChild(bubblenode);}else{messagesnest.prepend(bubblenode);}
+if(!istaOseba){if(datePlacement==0){chatarea.appendChild(messagesnest);}else{chatarea.prepend(messagesnest);}}}
+async function validateName(){if(directory!==null){$("#full-name").prop("disabled",false);if($("#full-name").val()in directory){$("#full-name").addClass("valid");$("#full-name").removeClass("invalid");$("#chat-recipient-select-btn").prop("disabled",false);$("#msg-body").prop("disabled",false);}else{$("#full-name").addClass("invalid");$("#full-name").removeClass("valid");$("#chat-recipient-select-btn").prop("disabled",true);$("#msg-body").prop("disabled",true);$("#msg-body").val("");}}else{$("#chat-recipient-select-btn").prop("disabled",true);$("#full-name").val(D("nameDirectoryNotSet"));$("#full-name").prop("disabled",true);$("#msg-body").val("");}}
+async function clearMessages(){$(".chat").eq(0).html("");}
+function getUrlParameter(sParam){const url_params=new URLSearchParams(window.location.search);const found_param=url_params.get(sParam);return found_param;}
+async function updateSendButton(){if($("#msg-body").val().length==0){$("#msg-send").prop("disabled",true);}else{$("#msg-send").prop("disabled",false);}}
+async function setRecipient(name=null){if(name==null||name==false||name==undefined){name=$("#full-name").val();}else if(typeof name!="number"){throw new TypeError('Hello from setRecipient(): name can only be string or null!');}
+if(!Object.keys(directory).includes(name)){UIAlert(D("recipientNotInDirectory"));throw new RangeError("Hello from setRecipient(): name is not in directory");}
+var modal=document.querySelectorAll("#directory-side-menu")[0];var modalInstance=M.Sidenav.getInstance(modal);modalInstance.close();$(".msg-chattingWith").eq(0).html(name);sogovornik=name;currentlyChattingWith=directory[name];$("#chat-mustSelectRecipient").hide();updateSendButton();clearMessages();prepareAndStartFetchingMessages();}
+async function prepareAndStartFetchingMessages(){if(currentlyChattingWith===0||(currentlyChattingWith>=1&&currentlyChattingWith<69420)){$("#msg-body").prop("disabled",false);await clearMessages();startFetchingMessages();}else{var modal=document.querySelectorAll("#directory-side-menu")[0];var modalInstance=M.Sidenav.getInstance(modal);modalInstance.open();}}
+async function startFetchingMessages(){let promises_to_run=[localforage.getItem("username").then((value)=>{username=value;}),localforage.getItem("password").then((value)=>{password=value;}),];setLoading(true);await Promise.all(promises_to_run);try{let gsecInstance=new gsec();await gsecInstance.login(username,password);for(var category=0;category<=1;category++){let lastpage=await gsecInstance.fetchMessagesLastPageNumber(category);startLoadingMessagesForCategory(gsecInstance,category,lastpage);}}catch(err){gsecErrorHandlerUI(err);}
+setLoading(false);}
+async function startLoadingMessagesForCategory(gsecInstance,category,lastpage){for(var page=1;page<=lastpage;page++){var gsecMsgList=await gsecInstance.fetchMessagesList(category,page);if(category==0){whom=1;}else{whom=0;}
+renderMessages(gsecMsgList,whom,1);}}
+async function renderMessages(gsecMsgList,whom,order=1){for(const message of gsecMsgList){if(message.subject.startsWith(CHATS_SUBJECT_PREFIX)){console.log(message);addMessage(whom,message.subject.substring(CHATS_SUBJECT_PREFIX.length),2,message.date.getTime);}}}
+function setupEventListeners(){$("#chat-recipient-select-btn").click(()=>{setRecipient();});$("#msg-send").click(()=>{sendMessage();});$("#full-name").on("input",()=>{validateName();});$("#msg-body").on("input",()=>{updateSendButton();});}
+document.addEventListener("DOMContentLoaded",()=>{checkLogin();loadDirectory();setupEventListeners();updateSendButton();M.updateTextFields();const menus=document.querySelectorAll(".side-menu");M.Sidenav.init(menus,{edge:"right",draggable:true});let elems=document.querySelectorAll(".modal");M.Modal.init(elems,{});const modals=document.querySelectorAll(".side-modal");M.Sidenav.init(modals,{edge:"left",draggable:false});prepareAndStartFetchingMessages();}); \ No newline at end of file