Advertisement
Guest User

Untitled

a guest
Dec 16th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.83 KB | None | 0 0
  1. function startApp(){
  2. //App constants stay here
  3. const kinveyBaseUrl = "https://baas.kinvey.com/";
  4. const kinveyAppKey = "kid_rytDhd9Xl";
  5. const kinveyAppSecret =
  6. "f5e77fe7369145f5978d7a5a5f3c2029";
  7. const kinveyAppAuthHeaders = {
  8. 'Authorization': "Basic " +
  9. btoa(kinveyAppKey + ":" + kinveyAppSecret),
  10. };
  11.  
  12. sessionStorage.clear();
  13. showHideMenuLinks();
  14. showAppHomeView();
  15.  
  16. $('#infoBox, #errorBox').click(function () { $(this).fadeOut(); });
  17. $(document).on({
  18. ajaxStart: function() { $("#loadingBox").show() },
  19. ajaxStop: function() { $("#loadingBox").hide() }
  20. });
  21.  
  22. //If AJAX query doesn't work, error will be generated from here.
  23. function handleAjaxError(response) {
  24. let errorMsg = JSON.stringify(response);
  25. if (response.readyState === 0)
  26. errorMsg = "Cannot connect due to network error.";
  27. if (response.responseJSON && response.responseJSON.description)
  28. errorMsg = response.responseJSON.description;
  29. showError(errorMsg);
  30. }
  31. //Function to show green info box with a message
  32. function showInfoBox(message) {
  33. $('#infoBox').text(message);
  34. $('#infoBox').show();
  35. setTimeout(function() {
  36. $('#infoBox').fadeOut();
  37. }, 3000);
  38.  
  39. }
  40. //Function to show red error box with a message
  41. function showError(errorMsg) {
  42. $('#errorBox').text("Error: " + errorMsg);
  43. $('#errorBox').show();
  44. setTimeout(function () {
  45. $('#errorBox').fadeOut();
  46. },2000)
  47. }
  48. //set session info when user is logged in
  49. function setSessionInfo(userInfo){
  50. sessionStorage.setItem('authToken', userInfo._kmd.authtoken);
  51. sessionStorage.setItem('userId', userInfo._id);
  52. sessionStorage.setItem('username', userInfo.username);
  53. sessionStorage.setItem('name', userInfo.name);
  54.  
  55.  
  56. $('#spanMenuLoggedInUser').text('Welcome, ' + sessionStorage.getItem('username') +'!');
  57. $('#viewUserHomeHeading').text('Welcome, ' + sessionStorage.getItem('username') +'!');
  58. }
  59.  
  60. $("#linkMenuAppHome").click(showAppHomeView);
  61. $("#linkMenuLogin").click(showLoginView);
  62. $("#linkMenuRegister").click(showRegisterView);
  63. $("#linkMenuUserHome").click(showUserHomeView);
  64. $("#linkMenuMyMessages").click(listMsgs);
  65. $("#linkMenuArchiveSent").click(showMsgArchiveView);
  66. $("#linkMenuSendMessage").click(showSendMsgView);
  67. //buttons in the homeview when logged in
  68. $("#linkUserHomeMyMessages").click(listMsgs);
  69. $("#linkUserHomeArchiveSent").click(showMsgArchiveView);
  70. $("#linkUserHomeSendMessage").click(showSendMsgView);
  71. $("#linkMenuLogout").click(logoutUser);
  72.  
  73. //form submit actions start from here
  74. $('#formLogin').submit(function () {
  75. loginUser();
  76. return false;
  77. });
  78. $('#formRegister').submit(function(){
  79. registerUser();
  80. return false;
  81. });
  82. $('#formSendMessage').submit(function(){
  83. messageUser();
  84. return false;
  85. });
  86.  
  87. //what to show if you are logged in/not logged in
  88. function showHideMenuLinks() {
  89. $("#menu a").hide();
  90. if(sessionStorage.getItem("authToken")){
  91. $("#linkMenuUserHome").show();
  92. $("#linkMenuMyMessages").show();
  93. $("#linkMenuArchiveSent").show();
  94. $("#linkMenuSendMessage").show();
  95. $("#linkMenuLogout").show();
  96.  
  97. }else{
  98. $("#linkMenuAppHome").show();
  99. $("#linkMenuLogin").show();
  100. $("#linkMenuRegister").show();
  101. }
  102. }
  103. //show views
  104. function showView(viewName){
  105. $('main > section').hide();
  106. $('#'+viewName).show();
  107. }
  108. function showAppHomeView(){
  109. showView('viewAppHome')
  110. }
  111. function showLoginView(){
  112. showView('viewLogin')
  113. }
  114. function showRegisterView(){
  115. showView('viewRegister')
  116. }
  117. function showUserHomeView(){
  118. showView('viewUserHome')
  119. }
  120.  
  121. //operations
  122. //do not touch login/logout. THEY WORK /delete this later/
  123. function loginUser(){
  124.  
  125. let userData = {
  126. username: $('#formLogin input[name=username]').val(),
  127. password:$('#formLogin input[name=password]').val()
  128. };
  129.  
  130. $.ajax({
  131. method: "POST",
  132. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  133. headers: kinveyAppAuthHeaders,
  134. data: userData,
  135. success: loginSuccess,
  136. error:handleAjaxError
  137. });
  138.  
  139. function loginSuccess(userInfo){
  140. setSessionInfo(userInfo);
  141. showHideMenuLinks();
  142. showUserHomeView();
  143. showInfoBox('Login successful.')
  144. }
  145. }
  146. function logoutUser(){
  147.  
  148. $.ajax({
  149. method: "POST",
  150. url: kinveyBaseUrl + "user/" + kinveyAppKey + "/_logout",
  151. headers: getKinveyHeader(),
  152. })
  153. .then(
  154. sessionStorage.clear(),
  155. showInfoBox('Logout successful'),
  156. showHideMenuLinks(),
  157. $('#spanMenuLoggedInUser').text(''),
  158. showAppHomeView()
  159. );
  160.  
  161.  
  162. }
  163. function registerUser(){
  164.  
  165. let userData = {
  166. username: $('#formRegister input[name=username]').val(),
  167. password:$('#formRegister input[name=password]').val(),
  168. name: $('#formRegister input[name=name]').val()
  169. };
  170.  
  171. $.ajax({
  172. method: "POST",
  173. url: kinveyBaseUrl + "user/" + kinveyAppKey,
  174. headers: kinveyAppAuthHeaders,
  175. data: userData,
  176. success: registerSuccess,
  177. error:handleAjaxError
  178. });
  179.  
  180. function registerSuccess(userInfo){
  181. setSessionInfo(userInfo);
  182. showHideMenuLinks();
  183. showUserHomeView();
  184. showInfoBox('User registration successful.')
  185. }
  186. }
  187. function listMsgs(){
  188. let currentUser = sessionStorage.getItem('username');
  189. $('#myMessages').empty();
  190. showView('viewMyMessages')
  191.  
  192. $.ajax({
  193. async: true,
  194. crossDomain: true,
  195. method: "GET",
  196. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages?query=%7B%22recipient_username%22%3A%22"+currentUser+"%22%7D",
  197. headers: getKinveyHeader(),
  198. success: listSuccess,
  199. error: handleAjaxError
  200. });
  201.  
  202. function listSuccess(msgs){
  203. let table = $('<table>')
  204. .append($('<thead>'))
  205. .append(`<tr>
  206. <th>From</th>
  207. <th>Message</th>
  208. <th>Date Received</th>
  209. </tr>`);
  210.  
  211. for(let msg of msgs){
  212. addMsgInfoInTable(msg, table)
  213. }
  214.  
  215. function addMsgInfoInTable(msg, table){
  216. let row = $('<tbody>')
  217. .append(`
  218. <tr>
  219. <td>`+formatSender(msg.sender_name, msg.sender_username) +`</td>
  220. <td>`+msg.text+`</td>
  221. <td>`+formatDate(msg._kmd.lmt)+`</td>
  222. </tr>`);
  223. table.append(row);
  224. }
  225. $('#myMessages').append(table);
  226.  
  227. }
  228. }
  229. function showMsgArchiveView(){
  230. showView('viewArchiveSent');
  231. $('#sentMessages').empty();
  232. let currentUser = sessionStorage.getItem('username');
  233.  
  234. $.ajax({
  235. async: true,
  236. crossDomain: true,
  237. method: "GET",
  238. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages?query=%7B%22sender_username%22%3A%22"+currentUser+"%22%7D",
  239. headers: getKinveyHeader(),
  240. success: listArchiveSuccess,
  241. error: handleAjaxError
  242. });
  243.  
  244. function listArchiveSuccess(msgs){
  245. let archiveTable = $('<table>')
  246. .append($('<thead>'))
  247. .append(`<tr>
  248. <th>To</th>
  249. <th>Message</th>
  250. <th>Date Sent</th>
  251. <th>Actions</th>
  252. </tr>`);
  253.  
  254. for(let msg of msgs){
  255. addSentMsg(msg, archiveTable);
  256. }
  257.  
  258. $('#sentMessages').append(archiveTable);
  259.  
  260. function addSentMsg(msg, table){
  261.  
  262. let deleteButton = $('<button>Delete</button>').click(deleteMsg.bind(this, msg));
  263. let row = $('<tbody>')
  264. .append('<tr>').append(
  265. $('<td>').text(msg.recipient_username),
  266. $('<td>').text(msg.text),
  267. $('<td>').text(formatDate(msg._kmd.lmt)),
  268. $('<td>').append(deleteButton)
  269. )
  270. table.append(row);
  271. function deleteMsg(msg){
  272. $.ajax({
  273. method: "DELETE",
  274. url: kinveyBaseUrl +"appdata/"+ kinveyAppKey + "/messages/"+ msg._id,
  275. headers: getKinveyHeader(),
  276. success: successfullyDeleted,
  277. error: handleAjaxError
  278. });
  279.  
  280. function successfullyDeleted(response){
  281. row.fadeOut(() => {row.remove();});
  282. showInfoBox('Deleted')
  283. }
  284. }
  285.  
  286.  
  287. }
  288.  
  289. }
  290.  
  291. }
  292.  
  293. //load available users from here
  294. function showSendMsgView(){
  295. showView('viewSendMessage');
  296. $('#msgRecipientUsername').empty();
  297. loadUsers();
  298. function loadUsers(){
  299. $.ajax({
  300. method: "GET",
  301. url: kinveyBaseUrl + "user/" + kinveyAppKey,
  302. headers: getKinveyHeader(),
  303. success: listUserOptions,
  304. error: handleAjaxError
  305. });
  306.  
  307. function listUserOptions(users){
  308. for(let user of users){
  309. $('#msgRecipientUsername')
  310. .append($('<option>').text(formatSender(user.name, user.username)).val(user.username))
  311. }
  312. }
  313. }
  314. }
  315. //message a user from here
  316. function messageUser(){
  317. let msgData = {
  318. sender_username: sessionStorage.getItem('username'),
  319. sender_name: sessionStorage.getItem('name'),
  320. recipient_username: $('#formSendMessage [name=recipient]').val(),
  321. text: $('#formSendMessage input[name=text]').val()
  322.  
  323. };
  324.  
  325. $.ajax({
  326. method: "POST",
  327. url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/messages",
  328. headers: getKinveyHeader(),
  329. data: msgData,
  330. success: msgSent,
  331. error:handleAjaxError
  332. });
  333.  
  334. function msgSent(){
  335. showInfoBox('Message sent.');
  336. showMsgArchiveView();
  337. }
  338. }
  339.  
  340.  
  341. function formatSender(name, username) {
  342. if (!name)
  343. return username;
  344. else
  345. return username + ' (' + name + ')';
  346. }
  347. function formatDate(dateISO8601) {
  348. let date = new Date(dateISO8601);
  349. if (Number.isNaN(date.getDate()))
  350. return '';
  351. return date.getDate() + '.' + padZeros(date.getMonth() + 1) +
  352. "." + date.getFullYear() + ' ' + date.getHours() + ':' +
  353. padZeros(date.getMinutes()) + ':' + padZeros(date.getSeconds());
  354.  
  355. function padZeros(num) {
  356. return ('0' + num).slice(-2);
  357. }
  358. }
  359. function getKinveyHeader(){
  360. return{
  361. 'Authorization': "Kinvey " +
  362. sessionStorage.getItem("authToken"),
  363. }
  364. }
  365. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement