Advertisement
Guest User

Untitled

a guest
Dec 11th, 2016
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const kinveyAppKey = 'kid_rkm22_5Xg';
  2. const kinveyAppSecret = '28605befe77c4072930e3dbaa58f0b53';
  3. const kinveyBaseUrl = 'https://baas.kinvey.com/';
  4.  
  5. $(function(){
  6.     showHideNavigationLinks();
  7.     $("section").hide();
  8.     showView("AppHome");
  9.     $("#infoBox").hide().on('click', function(){
  10.         $('#infoBox').hide();
  11.     });
  12.     $("#errorBox").hide().on('click', function(){
  13.         $("#errorBox").hide();
  14.     });
  15.     $("#loadingBox").hide();
  16.     $("#linkMenuAppHome").on('click', function(){
  17.         showView("AppHome");
  18.     });
  19.     $("#linkMenuLogin").on('click', function(){
  20.         showView("Login");
  21.     });
  22.     $("#linkMenuRegister").on('click', function(){
  23.         showView("Register");
  24.     });
  25.     $("#linkMenuUserHome").on('click', function(){
  26.         showView("UserHome");
  27.         $("#homeScreenUsername").text(sessionStorage.name);
  28.     });
  29.     $("#linkMenuMyMessages").on('click', function(){
  30.         showView("MyMessages");
  31.         loadMessages();
  32.     });
  33.     $("#linkMenuArchiveSent").on('click', function(){
  34.         showView("ArchiveSent");
  35.         loadSentMessages();
  36.     });
  37.     $("#linkMenuSendMessage").on('click', function(){
  38.         showView("SendMessage");
  39.         loadUsers();
  40.     });
  41.     $("#linkMenuLogout").on('click', function(){
  42.         logout();
  43.     });
  44.     $("#formLogin").on('submit', function(e){
  45.         e.preventDefault();
  46.         login();
  47.     });
  48.     $("#formRegister").on('submit', function(e){
  49.         e.preventDefault();
  50.         register();
  51.     });
  52.     $("#formSendMessage").on('submit', function(e){
  53.         e.preventDefault();
  54.         sendMessage();
  55.     });
  56.     $("#linkUserHomeMyMessages").on('click', function(){
  57.         showView("MyMessages");
  58.         loadMessages();
  59.     });
  60.     $("#linkUserHomeSendMessage").on('click', function(){
  61.         showView('SendMessage');
  62.     });
  63.     $("#linkUserHomeArchiveSent").on('click', function(){
  64.         showView('ArchiveSent');
  65.         loadSentMessages();
  66.     });
  67.  
  68. }).on('click', ".buttonDeleteMessage", function(){
  69.     deleteMessage($(this).parent().parent().attr('data-id'));
  70. });
  71.  
  72.  
  73. function showView(view) {
  74.     $("section").hide();
  75.     $("#view" + view).show();
  76. }
  77.  
  78. function showHideNavigationLinks() {
  79.     let loggedIn = sessionStorage.authToken;
  80.     if (loggedIn == null) {
  81.         $(".useronly").hide();
  82.         $(".anonymous").show();
  83.         $("#spanMenuLoggedInUser").hide();
  84.     } else {
  85.         $(".useronly").show();
  86.         $(".anonymous").hide();
  87.         $("#spanMenuLoggedInUser").show();
  88.         $("#spanNavUsername").text(sessionStorage.name);
  89.  
  90.     }
  91. }
  92.  
  93. function login() {
  94.     let authBase64 = btoa(kinveyAppKey + ":" + kinveyAppSecret);
  95.     let loginUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/login";
  96.     let loginData = ({
  97.         username: $("#loginUsername").val(),
  98.         password: $("#loginPasswd").val()
  99.     });
  100.     $.ajax({
  101.         method: "POST",
  102.         url: loginUrl,
  103.         data: loginData,
  104.         headers: {"Authorization" : "Basic " + authBase64},
  105.         success: loginSuccess,
  106.         error: showAjaxError
  107.     });
  108.     function loginSuccess(data, status) {
  109.         sessionStorage.authToken = data._kmd.authtoken;
  110.         sessionStorage.username = data.username;
  111.         sessionStorage.name = data.name;
  112.         sessionStorage.uid = data._id;
  113.         showInfo("Login successful.");
  114.         showHideNavigationLinks();
  115.     }
  116. }
  117.  
  118. function logout() {
  119.     let logoutUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/_logout";
  120.     $.ajax({
  121.         method: "POST",
  122.         url: logoutUrl,
  123.         headers: {"Authorization" : "Kinvey " + sessionStorage.authToken},
  124.         success: logoutSuccess,
  125.         error: showAjaxError
  126.     });
  127.  
  128.     function logoutSuccess() {
  129.         sessionStorage.clear();
  130.         showHideNavigationLinks();
  131.         showView("AppHome");
  132.         showInfo("Logout successful.");
  133.     }
  134. }
  135.  
  136. function register() {
  137.         let authBase64 = btoa(kinveyAppKey + ":" + kinveyAppSecret);
  138.         let registerUrl = kinveyBaseUrl + "user/" + kinveyAppKey + "/";
  139.         let registerData = ({
  140.             username: $('#registerUsername').val(),
  141.             password: $('#registerPasswd').val(),
  142.             name: $('#registerName').val()
  143.         });
  144.         $.ajax({
  145.             method: "POST",
  146.             url: registerUrl,
  147.             data: registerData,
  148.             headers: {"Authorization": "Basic " + authBase64},
  149.             success: registerSuccess,
  150.             error: showAjaxError
  151.         });
  152.         function registerSuccess(data, status) {
  153.             sessionStorage.authToken = data._kmd.authtoken;
  154.             sessionStorage.username = data.username;
  155.             sessionStorage.name = data.name;
  156.             sessionStorage.uid = data._id;
  157.             showInfo("User registration successful.");
  158.             showHideNavigationLinks();
  159.             showView("UserHome");
  160.         }
  161. }
  162.  
  163. function loadSentMessages() {
  164.     let messagesUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/messages?query={"sender_username":"${sessionStorage.username}"}`;
  165.     $.ajax({
  166.         method: "GET",
  167.         url: messagesUrl,
  168.         headers: {"Authorization" : "Kinvey " + sessionStorage.authToken},
  169.         success: drawSentMessages,
  170.         error: showAjaxError
  171.     });
  172.     function drawSentMessages(data) {
  173.         let table = $("<table>");
  174.         let tableHeadings = $("<thead>");
  175.         let tableRow = $("<tr>");
  176.         tableRow.append($("<th>To</th>"));
  177.         tableRow.append($("<th>Message</th>"));
  178.         tableRow.append($("<th>Date Received</th>"));
  179.         tableRow.append($("<th>Actions</th>"));
  180.         tableHeadings.append(tableRow);
  181.  
  182.         let tableBody = $("<tbody>");
  183.  
  184.         for (let message of data) {
  185.             let row = $("<tr data-id=>").attr('data-id', message._id);
  186.             row.append($(`<td>`).text(message.recipient_username));
  187.             row.append($(`<td>`).text(message.text));
  188.             row.append($(`<td>${formatDate(message._kmd.ect)}</td>`));
  189.             row.append($(`<td><input type="button" class="buttonDeleteMessage" value="Delete"></td>`));
  190.             row.appendTo(tableBody);
  191.         }
  192.         table.append(tableHeadings);
  193.         table.append(tableBody);
  194.         $("#sentMessages").empty().append(table);
  195.     }
  196. }
  197.  
  198.  
  199. function loadMessages() {
  200.     let messagesUrl = kinveyBaseUrl + "appdata/" + kinveyAppKey + `/messages?query={"recipient_username":"${sessionStorage.username}"}`;
  201.     $.ajax({
  202.         method: "GET",
  203.         url: messagesUrl,
  204.         headers: {"Authorization" : "Kinvey " + sessionStorage.authToken},
  205.         success: drawMessages,
  206.         error: showAjaxError
  207.     });
  208.     function drawMessages(data) {
  209.         let table = $("<table>");
  210.         let tableHeadings = $("<thead>");
  211.         let tableRow = $("<tr>");
  212.         tableRow.append($("<th>From</th>"));
  213.         tableRow.append($("<th>Message</th>"));
  214.         tableRow.append($("<th>Date Received</th>"));
  215.         tableHeadings.append(tableRow);
  216.  
  217.         let tableBody = $("<tbody>");
  218.  
  219.         for (let message of data) {
  220.             let row = $("<tr data-id=>").attr('data-id', message._id);
  221.             row.append($(`<td>`).text(formatSender(message.sender_name, message.sender_username)));
  222.             row.append($(`<td>`).text(message.text));
  223.             row.append($(`<td>${formatDate(message._kmd.ect)}</td>`));
  224.             row.appendTo(tableBody);
  225.         }
  226.         table.append(tableHeadings);
  227.         table.append(tableBody);
  228.         $("#myMessages").empty().append(table);
  229.     }
  230. }
  231.  
  232.  
  233. function deleteMessage(messageId) {
  234.     let url = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages/" + messageId;
  235.     $.ajax({
  236.         method: "DELETE",
  237.         url: url,
  238.         headers: {"Authorization" : "Kinvey " + sessionStorage.authToken},
  239.         success: completeDeletion,
  240.         error: showAjaxError
  241.     });
  242.     function completeDeletion() {
  243.         showInfo("Message deleted.");
  244.         showView("MyMessages");
  245.         drawMessages();
  246.     }
  247. }
  248.  
  249. function sendMessage() {
  250.     let url = kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages";
  251.     let data = {
  252.         sender_username: sessionStorage.username,
  253.         sender_name: sessionStorage.name,
  254.         recipient_username: $("#msgRecipientUsername").val(),
  255.         text: $("#msgText").val()
  256.     };
  257.     let headers = {"Authorization" : "Kinvey " + sessionStorage.authToken};
  258.     $.ajax({
  259.         method: "POST",
  260.         url: url,
  261.         data: data,
  262.         headers: headers,
  263.         success: messageSent,
  264.         error: showAjaxError
  265.     });
  266.     function messageSent() {
  267.         showInfo("Message sent.");
  268.         showView("ArchiveSent");
  269.     }
  270.  
  271. }
  272.  
  273. function loadUsers() {
  274.     let url = kinveyBaseUrl + "user/" + kinveyAppKey;
  275.     $.ajax({
  276.         method: "GET",
  277.         url: url,
  278.         headers: {"Authorization": "Kinvey " + sessionStorage.authToken},
  279.         success: continueLoading,
  280.         error: showAjaxError
  281.     });
  282.  
  283.     function continueLoading(data) {
  284.         $("#msgRecipientUsername").empty();
  285.         for (let user of data) {
  286.             $("#msgRecipientUsername").append(`<option value="${user.username}">${formatSender(user.name, user.username)}</option>`);
  287.         }
  288.     }
  289. }
  290.  
  291. function formatDate(dateISO8601) {
  292.     let date = new Date(dateISO8601);
  293.     if (Number.isNaN(date.getDate()))
  294.         return '';
  295.     return date.getDate() + '.' + padZeros(date.getMonth() + 1) +
  296.         "." + date.getFullYear() + ' ' + date.getHours() + ':' +
  297.         padZeros(date.getMinutes()) + ':' + padZeros(date.getSeconds());
  298.  
  299.     function padZeros(num) {
  300.         return ('0' + num).slice(-2);
  301.     }
  302. }
  303.  
  304. function formatSender(name, username) {
  305.     if (!name)
  306.         return username;
  307.     else
  308.         return username + ' (' + name + ')';
  309. }
  310.  
  311.  
  312. function showAjaxError(data, status) {
  313.     let errorMsg = '';
  314.     if (typeof(data.readyState) != "undefined" && data.readyState == 0) {
  315.         errorMsg = "Network connection problem. Please check your connection!"
  316.     }
  317.     else if (data.responseJSON && data.responseJSON.description) {
  318.         errorMsg = data.responseJSON.description;
  319.     } else {
  320.         errorMsg = "Error: " + JSON.stringify(data)
  321.     }
  322.     $('#errorBox').text(errorMsg).fadeIn(300);
  323. }
  324.  
  325. function showInfo(messageText) {
  326.     $('#infoBox').text(messageText).fadeIn(300).delay(3000).fadeOut(300);
  327. }
  328.  
  329. $(document)
  330.     .ajaxStart(function(){
  331.     $("#loadingBox").fadeIn(300);
  332.     })
  333.     .ajaxStop(function() {
  334.         $("#loadingBox").fadeOut(300);
  335.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement