Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function startApp(){
- //App constants stay here
- const kinveyBaseUrl = "https://baas.kinvey.com/";
- const kinveyAppKey = "kid_rytDhd9Xl";
- const kinveyAppSecret =
- "f5e77fe7369145f5978d7a5a5f3c2029";
- const kinveyAppAuthHeaders = {
- 'Authorization': "Basic " +
- btoa(kinveyAppKey + ":" + kinveyAppSecret),
- };
- sessionStorage.clear();
- showHideMenuLinks();
- showAppHomeView();
- $('#infoBox, #errorBox').click(function () { $(this).fadeOut(); });
- $(document).on({
- ajaxStart: function() { $("#loadingBox").show() },
- ajaxStop: function() { $("#loadingBox").hide() }
- });
- //If AJAX query doesn't work, error will be generated from here.
- function handleAjaxError(response) {
- let errorMsg = JSON.stringify(response);
- if (response.readyState === 0)
- errorMsg = "Cannot connect due to network error.";
- if (response.responseJSON && response.responseJSON.description)
- errorMsg = response.responseJSON.description;
- showError(errorMsg);
- }
- //Function to show green info box with a message
- function showInfoBox(message) {
- $('#infoBox').text(message);
- $('#infoBox').show();
- setTimeout(function() {
- $('#infoBox').fadeOut();
- }, 3000);
- }
- //Function to show red error box with a message
- function showError(errorMsg) {
- $('#errorBox').text("Error: " + errorMsg);
- $('#errorBox').show();
- setTimeout(function () {
- $('#errorBox').fadeOut();
- },2000)
- }
- //set session info when user is logged in
- function setSessionInfo(userInfo){
- sessionStorage.setItem('authToken', userInfo._kmd.authtoken);
- sessionStorage.setItem('userId', userInfo._id);
- sessionStorage.setItem('username', userInfo.username);
- sessionStorage.setItem('name', userInfo.name);
- $('#spanMenuLoggedInUser').text('Welcome, ' + sessionStorage.getItem('username') +'!');
- $('#viewUserHomeHeading').text('Welcome, ' + sessionStorage.getItem('username') +'!');
- }
- $("#linkMenuAppHome").click(showAppHomeView);
- $("#linkMenuLogin").click(showLoginView);
- $("#linkMenuRegister").click(showRegisterView);
- $("#linkMenuUserHome").click(showUserHomeView);
- $("#linkMenuMyMessages").click(listMsgs);
- $("#linkMenuArchiveSent").click(showMsgArchiveView);
- $("#linkMenuSendMessage").click(showSendMsgView);
- //buttons in the homeview when logged in
- $("#linkUserHomeMyMessages").click(listMsgs);
- $("#linkUserHomeArchiveSent").click(showMsgArchiveView);
- $("#linkUserHomeSendMessage").click(showSendMsgView);
- $("#linkMenuLogout").click(logoutUser);
- //form submit actions start from here
- $('#formLogin').submit(function () {
- loginUser();
- return false;
- });
- $('#formRegister').submit(function(){
- registerUser();
- return false;
- });
- $('#formSendMessage').submit(function(){
- messageUser();
- return false;
- });
- //what to show if you are logged in/not logged in
- function showHideMenuLinks() {
- $("#menu a").hide();
- if(sessionStorage.getItem("authToken")){
- $("#linkMenuUserHome").show();
- $("#linkMenuMyMessages").show();
- $("#linkMenuArchiveSent").show();
- $("#linkMenuSendMessage").show();
- $("#linkMenuLogout").show();
- }else{
- $("#linkMenuAppHome").show();
- $("#linkMenuLogin").show();
- $("#linkMenuRegister").show();
- }
- }
- //show views
- function showView(viewName){
- $('main > section').hide();
- $('#'+viewName).show();
- }
- function showAppHomeView(){
- showView('viewAppHome')
- }
- function showLoginView(){
- showView('viewLogin')
- }
- function showRegisterView(){
- showView('viewRegister')
- }
- function showUserHomeView(){
- showView('viewUserHome')
- }
- //operations
- //do not touch login/logout. THEY WORK /delete this later/
- function loginUser(){
- let userData = {
- username: $('#formLogin input[name=username]').val(),
- password:$('#formLogin input[name=password]').val()
- };
- $.ajax({
- method: "POST",
- url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
- headers: kinveyAppAuthHeaders,
- data: userData,
- success: loginSuccess,
- error:handleAjaxError
- });
- function loginSuccess(userInfo){
- setSessionInfo(userInfo);
- showHideMenuLinks();
- showUserHomeView();
- showInfoBox('Login successful.')
- }
- }
- function logoutUser(){
- $.ajax({
- method: "POST",
- url: kinveyBaseUrl + "user/" + kinveyAppKey + "/_logout",
- headers: getKinveyHeader(),
- })
- .then(
- sessionStorage.clear(),
- showInfoBox('Logout successful'),
- showHideMenuLinks(),
- $('#spanMenuLoggedInUser').text(''),
- showAppHomeView()
- );
- }
- function registerUser(){
- let userData = {
- username: $('#formRegister input[name=username]').val(),
- password:$('#formRegister input[name=password]').val(),
- name: $('#formRegister input[name=name]').val()
- };
- $.ajax({
- method: "POST",
- url: kinveyBaseUrl + "user/" + kinveyAppKey,
- headers: kinveyAppAuthHeaders,
- data: userData,
- success: registerSuccess,
- error:handleAjaxError
- });
- function registerSuccess(userInfo){
- setSessionInfo(userInfo);
- showHideMenuLinks();
- showUserHomeView();
- showInfoBox('User registration successful.')
- }
- }
- function listMsgs(){
- let currentUser = sessionStorage.getItem('username');
- $('#myMessages').empty();
- showView('viewMyMessages')
- $.ajax({
- async: true,
- crossDomain: true,
- method: "GET",
- url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages?query=%7B%22recipient_username%22%3A%22"+currentUser+"%22%7D",
- headers: getKinveyHeader(),
- success: listSuccess,
- error: handleAjaxError
- });
- function listSuccess(msgs){
- let table = $('<table>')
- .append($('<thead>'))
- .append(`<tr>
- <th>From</th>
- <th>Message</th>
- <th>Date Received</th>
- </tr>`);
- for(let msg of msgs){
- addMsgInfoInTable(msg, table)
- }
- function addMsgInfoInTable(msg, table){
- let row = $('<tbody>')
- .append(`
- <tr>
- <td>`+formatSender(msg.sender_name, msg.sender_username) +`</td>
- <td>`+msg.text+`</td>
- <td>`+formatDate(msg._kmd.lmt)+`</td>
- </tr>`);
- table.append(row);
- }
- $('#myMessages').append(table);
- }
- }
- function showMsgArchiveView(){
- showView('viewArchiveSent');
- $('#sentMessages').empty();
- let currentUser = sessionStorage.getItem('username');
- $.ajax({
- async: true,
- crossDomain: true,
- method: "GET",
- url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages?query=%7B%22sender_username%22%3A%22"+currentUser+"%22%7D",
- headers: getKinveyHeader(),
- success: listArchiveSuccess,
- error: handleAjaxError
- });
- function listArchiveSuccess(msgs){
- let archiveTable = $('<table>')
- .append($('<thead>'))
- .append(`<tr>
- <th>To</th>
- <th>Message</th>
- <th>Date Sent</th>
- <th>Actions</th>
- </tr>`);
- for(let msg of msgs){
- addSentMsg(msg, archiveTable);
- }
- $('#sentMessages').append(archiveTable);
- function addSentMsg(msg, table){
- let deleteButton = $('<button>Delete</button>').click(deleteMsg.bind(this, msg));
- let row = $('<tbody>')
- .append('<tr>').append(
- $('<td>').text(msg.recipient_username),
- $('<td>').text(msg.text),
- $('<td>').text(formatDate(msg._kmd.lmt)),
- $('<td>').append(deleteButton)
- )
- table.append(row);
- function deleteMsg(msg){
- $.ajax({
- method: "DELETE",
- url: kinveyBaseUrl +"appdata/"+ kinveyAppKey + "/messages/"+ msg._id,
- headers: getKinveyHeader(),
- success: successfullyDeleted,
- error: handleAjaxError
- });
- function successfullyDeleted(response){
- row.fadeOut(() => {row.remove();});
- showInfoBox('Deleted')
- }
- }
- }
- }
- }
- //load available users from here
- function showSendMsgView(){
- showView('viewSendMessage');
- $('#msgRecipientUsername').empty();
- loadUsers();
- function loadUsers(){
- $.ajax({
- method: "GET",
- url: kinveyBaseUrl + "user/" + kinveyAppKey,
- headers: getKinveyHeader(),
- success: listUserOptions,
- error: handleAjaxError
- });
- function listUserOptions(users){
- for(let user of users){
- $('#msgRecipientUsername')
- .append($('<option>').text(formatSender(user.name, user.username)).val(user.username))
- }
- }
- }
- }
- //message a user from here
- function messageUser(){
- let msgData = {
- sender_username: sessionStorage.getItem('username'),
- sender_name: sessionStorage.getItem('name'),
- recipient_username: $('#formSendMessage [name=recipient]').val(),
- text: $('#formSendMessage input[name=text]').val()
- };
- $.ajax({
- method: "POST",
- url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages",
- headers: getKinveyHeader(),
- data: msgData,
- success: msgSent,
- error:handleAjaxError
- });
- function msgSent(){
- showInfoBox('Message sent.');
- showMsgArchiveView();
- }
- }
- function formatSender(name, username) {
- if (!name)
- return username;
- else
- return username + ' (' + name + ')';
- }
- function formatDate(dateISO8601) {
- let date = new Date(dateISO8601);
- if (Number.isNaN(date.getDate()))
- return '';
- return date.getDate() + '.' + padZeros(date.getMonth() + 1) +
- "." + date.getFullYear() + ' ' + date.getHours() + ':' +
- padZeros(date.getMinutes()) + ':' + padZeros(date.getSeconds());
- function padZeros(num) {
- return ('0' + num).slice(-2);
- }
- }
- function getKinveyHeader(){
- return{
- 'Authorization': "Kinvey " +
- sessionStorage.getItem("authToken"),
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement