index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2020 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of gostfix project https://git.semlanik.org/semlanik/gostfix
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. var currentFolder = '';
  26. var currentPage = 0;
  27. var currentMail = '';
  28. var mailbox = '';
  29. var pageMax = 10;
  30. const mailboxRegex = /^(\/m\d+)/g;
  31. const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  32. const emailEndRegex = /[;,\s]/g;
  33. var folders = new Array();
  34. var notifierSocket = null;
  35. var toEmailList = new Array();
  36. var toEmailIndex = 0;
  37. var toEmailPreviousSelectionPosition = 0;
  38. $(window).click(function(e){
  39. var target = $(e.target);
  40. var isDropDown = false;
  41. for (var i = 0; i < target.parents().length; i++) {
  42. isDropDown = target.parents()[i].classList.contains('dropbtn');
  43. if (isDropDown) {
  44. break;
  45. }
  46. }
  47. if (!e.target.matches('.dropbtn') && !isDropDown) {
  48. $('.dropdown-content').hide();
  49. }
  50. })
  51. $(document).ready(function(){
  52. $.ajaxSetup({
  53. global: false,
  54. type: 'POST'
  55. });
  56. urlPaths = mailboxRegex.exec($(location).attr('pathname'));
  57. if (urlPaths != null && urlPaths.length === 2) {
  58. mailbox = urlPaths[0];
  59. } else {
  60. mailbox = '';
  61. }
  62. $(window).bind('hashchange', onHashChanged);
  63. onHashChanged();
  64. loadFolders();
  65. loadStatusLine();
  66. $('#mailNewButton').click(mailNew);
  67. connectNotifier();
  68. $('#toEmailField').on('input', toEmailFieldChanged);
  69. $('#toEmailField').keydown(function(e){
  70. var actualText = $('#toEmailField').val();
  71. const selectionPosition = e.target.selectionStart;
  72. switch(e.keyCode) {
  73. case 8:
  74. if (toEmailPreviousSelectionPosition == 0 && e.target.selectionStart == 0
  75. && toEmailList.length > 0 && $('#toEmailList').children().length > 1) {
  76. removeToEmail($('#toEmailList').children()[$('#toEmailList').children().length - 2].id, toEmailList[toEmailList.length - 1]);
  77. }
  78. break;
  79. case 13:
  80. case 9:
  81. addToEmail(actualText.slice(0, selectionPosition));
  82. $('#toEmailField').val(actualText.slice(selectionPosition + 1, actualText.length));
  83. break;
  84. }
  85. toEmailPreviousSelectionPosition = e.target.selectionStart;
  86. })
  87. resetSelectionList();
  88. })
  89. function toEmailFieldChanged(e) {
  90. const selectionPosition = e.target.selectionStart - 1;
  91. var actualText = $('#toEmailField').val();
  92. if (actualText.length <= 0 || selectionPosition < 0) {
  93. return;
  94. }
  95. var lastChar = actualText[selectionPosition];
  96. if (emailEndRegex.test(lastChar)) {
  97. addToEmail(actualText.slice(0, selectionPosition));
  98. $('#toEmailField').val(actualText.slice(selectionPosition + 1, actualText.length));
  99. }
  100. }
  101. function addToEmail(toEmail) {
  102. if (toEmail.length <= 0) {
  103. return;
  104. }
  105. var style = emailRegex.test(toEmail) ? 'valid' : 'invalid';
  106. $('<div class="'+ style + ' toEmail" id="toEmail' + toEmailIndex + '">' + toEmail + '<img class="iconBtn" style="height: 12px; margin-left:10px; margin: auto;" onclick="removeToEmail(\'toEmail' + toEmailIndex + '\', \'' + toEmail + '\');" src="/assets/cross.svg"/></div>').insertBefore('#toEmailField');
  107. toEmailIndex++;
  108. toEmailList.push(toEmail);
  109. checkSendDisabled();
  110. }
  111. function removeToEmail(id, email) {
  112. const index = toEmailList.indexOf(email);
  113. if (index >= 0) {
  114. toEmailList.splice(index, 1);
  115. checkSendDisabled();
  116. }
  117. $('#' + id).remove();
  118. }
  119. function checkSendDisabled() {
  120. if (toEmailList.length > 0) {
  121. $('#sendButton').removeClass('disabled');
  122. } else {
  123. $('#sendButton').addClass('disabled');
  124. }
  125. }
  126. function mailNew(e) {
  127. window.location.hash = currentFolder + currentPage + '/mailNew';
  128. }
  129. function mailOpen(id) {
  130. window.location.hash = currentFolder + currentPage + '/' + id;
  131. }
  132. function openFolder(folder) {
  133. resetSelectionList();
  134. window.location.hash = folder;
  135. }
  136. function onHashChanged() {
  137. var hashLocation = window.location.hash;
  138. if (hashLocation == '') {
  139. setDetailsVisible(false);
  140. openFolder('Inbox');
  141. return;
  142. }
  143. hashRegex = /^#([a-zA-Z]+)(\d*)\/?([A-Fa-f\d]*)/g;
  144. hashParts = hashRegex.exec(hashLocation);
  145. page = 0;
  146. if (hashParts.length >= 3 && hashParts[2] != '') {
  147. page = parseInt(hashParts[2]);
  148. if (typeof page != 'number' || page > pageMax || page < 0) {
  149. page = 0;
  150. }
  151. }
  152. if (hashParts.length >= 2 && (hashParts[1] != currentFolder || currentPage != page) && hashParts[1] != '') {
  153. updateMailList(hashParts[1], page);
  154. }
  155. if (hashParts.length >= 4 && hashParts[3] != "" && hashParts[3] != '/mailNew') {
  156. if (currentMail != hashParts[3]) {
  157. requestMail(hashParts[3]);
  158. }
  159. } else {
  160. setDetailsVisible(false);
  161. }
  162. hashParts = hashLocation.split('/');
  163. if (hashParts.length == 2 && hashParts[1] == 'mailNew') {
  164. setMailNewVisible(true);
  165. } else {
  166. setMailNewVisible(false);
  167. }
  168. }
  169. function requestMail(mailId) {
  170. if (mailId != "") {
  171. $.ajax({
  172. url: '/mail',
  173. data: {
  174. mailId: mailId
  175. },
  176. success: function(result) {
  177. currentMail = mailId;
  178. if ($('#readListIcon'+mailId)) {
  179. $('#readListIcon'+mailId).attr('src', '/assets/read.svg');
  180. }
  181. $('#mail'+mailId).removeClass('unread');
  182. $('#mail'+mailId).addClass('read');
  183. $('#mailDetails').html(result);
  184. setDetailsVisible(true);
  185. folderStat(currentFolder);//TODO: receive statistic from websocket
  186. checkMailUnread();
  187. },
  188. error: function(jqXHR, textStatus, errorThrown) {
  189. $('#mailDetails').html(textStatus);
  190. setDetailsVisible(true);
  191. showToast(Severity.Critical, 'Unable to open mail: ' + errorThrown + ' ' + textStatus);
  192. }
  193. });
  194. }
  195. }
  196. function loadFolders() {
  197. if (mailbox == '') {
  198. $('#folders').html('Unable to load folder list');
  199. return;
  200. }
  201. $.ajax({
  202. url: mailbox + '/folders',
  203. success: function(result) {
  204. folderList = jQuery.parseJSON(result);
  205. for(var i = 0; i < folderList.folders.length; i++) {
  206. folders.push(folderList.folders[i].name);
  207. folderStat(folderList.folders[i].name);
  208. }
  209. $('#folders').html(folderList.html);
  210. },
  211. error: function(jqXHR, textStatus, errorThrown) {
  212. showToast(Severity.Critical, 'Unable to update folder list: ' + errorThrown + ' ' + textStatus);
  213. }
  214. });
  215. }
  216. function folderStat(folder) {
  217. $.ajax({
  218. url: mailbox + '/folderStat',
  219. data: {
  220. folder: folder
  221. },
  222. success: function(result) {
  223. var stats = jQuery.parseJSON(result);
  224. if (stats.unread > 0) {
  225. $('#folderStats'+folder).text(stats.unread);
  226. $('#folder'+folder).addClass('unread');
  227. } else {
  228. $('#folder'+folder).removeClass('unread');
  229. $('#folderStats'+folder).text("");
  230. }
  231. },
  232. error: function(jqXHR, textStatus, errorThrown) {
  233. showToast(Severity.Critical, 'Unable to update folder list: ' + errorThrown + ' ' + textStatus);
  234. }
  235. });
  236. }
  237. function closeDetails() {
  238. window.location.hash = currentFolder + currentPage;
  239. }
  240. function closeMailNew() {
  241. window.location.hash = currentFolder + currentPage;
  242. }
  243. function loadStatusLine() {
  244. $.ajax({
  245. url: mailbox + '/statusLine',
  246. success: function(result) {
  247. $('#statusLine').html(result);
  248. },
  249. error: function(jqXHR, textStatus, errorThrown) {
  250. showToast(Severity.Critical, 'Unable to load status line: ' + errorThrown + ' ' + textStatus);
  251. }
  252. });
  253. }
  254. function localDate(elementToChange, timestamp) {
  255. var today = new Date();
  256. var date = new Date(timestamp * 1000);
  257. dateString = '';
  258. if (today.getDay() == date.getDay()
  259. && today.getMonth() == date.getMonth()
  260. && today.getFullYear() == date.getFullYear()) {
  261. dateString = date.toLocaleTimeString('en-US');
  262. } else if (today.getFullYear() == date.getFullYear()) {
  263. const options = { day: 'numeric', month: 'short' };
  264. dateString = date.toLocaleDateString('en-US', options);
  265. } else {
  266. dateString = date.toLocaleDateString('en-US');
  267. }
  268. $('#'+elementToChange).text(dateString);
  269. }
  270. function setRead(mailId, read) {
  271. $.ajax({
  272. url: '/setRead',
  273. data: {mailId: mailId,
  274. read: read},
  275. success: function(result) {
  276. if (read) {
  277. if ($('#readIcon'+mailId)) {
  278. $('#readIcon'+mailId).attr('src', '/assets/read.svg');
  279. }
  280. if ($('#readListIcon'+mailId)) {
  281. $('#readListIcon'+mailId).attr('src', '/assets/read.svg');
  282. }
  283. $('#mail'+mailId).removeClass('unread');
  284. $('#mail'+mailId).addClass('read');
  285. } else {
  286. if ($('#readIcon'+mailId)) {
  287. $('#readIcon'+mailId).attr('src', '/assets/unread.svg');
  288. }
  289. if ($('#readListIcon'+mailId)) {
  290. $('#readListIcon'+mailId).attr('src', '/assets/unread.svg');
  291. }
  292. $('#mail'+mailId).removeClass('read');
  293. $('#mail'+mailId).addClass('unread');
  294. }
  295. folderStat(currentFolder);//TODO: receive statistic from websocket
  296. checkMailUnread();
  297. },
  298. error: function(jqXHR, textStatus, errorThrown) {
  299. }
  300. });
  301. }
  302. function toggleRead(mailId) {
  303. var read = $('#mail'+mailId).hasClass('read');
  304. setRead(mailId, !read);
  305. }
  306. function removeMail(mailId, callback) {
  307. var url = currentFolder != 'Trash' ? '/remove' : '/delete';
  308. $.ajax({
  309. url: url,
  310. data: {mailId: mailId},
  311. success: function() {
  312. removeFromSelectionList(mailId);
  313. $('#mail'+mailId).remove();
  314. if (callback) {
  315. callback(mailId);
  316. }
  317. folderStat(currentFolder);//TODO: receive statistic from websocket
  318. folderStat('Trash');//TODO: receive statistic from websocket
  319. },
  320. error: function(jqXHR, textStatus, errorThrown) {
  321. }
  322. });
  323. }
  324. function restoreMail(mailId, callback) {
  325. $.ajax({
  326. url: '/restore',
  327. data: {mailId: mailId},
  328. success: function() {
  329. if (currentFolder == 'Trash') {
  330. $('#mail'+mailId).remove();
  331. removeFromSelectionList(mailId);
  332. }
  333. if (callback) {
  334. callback();
  335. }
  336. for (var i = 0; i < folders.length; i++) {
  337. folderStat(folders[i]);
  338. }
  339. },
  340. error: function(jqXHR, textStatus, errorThrown) {
  341. }
  342. });
  343. }
  344. function downloadAttachment(attachmentId, filename) {
  345. $.ajax({
  346. url: '/attachment/' + attachmentId,
  347. xhrFields: {
  348. responseType: 'blob'
  349. },
  350. success: function (data) {
  351. // Ah-ha-ha-ha html and web is piece of shit full of hacks...
  352. var a = document.createElement('a');
  353. var url = window.URL.createObjectURL(data);
  354. a.href = url;
  355. a.download = filename;
  356. document.body.append(a);
  357. a.click();
  358. a.remove();
  359. window.URL.revokeObjectURL(url);
  360. },
  361. error: function(jqXHR, textStatus, errorThrown) {
  362. showToast(Severity.Critical, 'Unable to download attachment: ' + errorThrown + ' ' + textStatus);
  363. }
  364. });
  365. }
  366. function setDetailsVisible(visible) {
  367. if (visible) {
  368. $('#mailDetails').show();
  369. $('#mailList').css({pointerEvents: 'none'});
  370. } else {
  371. currentMail = '';
  372. $('#mailDetails').hide();
  373. $('#mailDetails').html('');
  374. $('#mailList').css({pointerEvents: 'auto'});
  375. }
  376. }
  377. function setMailNewVisible(visible) {
  378. if (visible) {
  379. $('#mailNew').show();
  380. $('#mailList').css({pointerEvents: 'none'});
  381. } else {
  382. currentMail = '';
  383. $('#mailNew').hide();
  384. $('#mailList').css({pointerEvents: 'auto'});
  385. }
  386. while (toEmailList.length > 0 && $('#toEmailList').children().length > 1) {
  387. removeToEmail($('#toEmailList').children()[$('#toEmailList').children().length - 2].id, toEmailList[toEmailList.length - 1]);
  388. }
  389. toEmailList = new Array();
  390. $('#newMailEditor').val('');
  391. $('#newMailSubject').val('');
  392. $('#newMailTo').val('');
  393. $('#toEmailField').val('');
  394. }
  395. function updateMailList(folder, page) {
  396. if (mailbox == '' || folder == '') {
  397. if ($('#mailList')) {
  398. $('#mailList').html('Unable to load message list');
  399. }
  400. return;
  401. }
  402. $.ajax({
  403. url: mailbox + '/mailList',
  404. data: {
  405. folder: folder,
  406. page: page
  407. },
  408. success: function(result) {
  409. var data = jQuery.parseJSON(result);
  410. pageMax = Math.floor(data.total/50);
  411. if ($('#mailList')) {
  412. $('#mailList').html(data.html);
  413. }
  414. currentFolder = folder;
  415. enableRestoreFunctionality();
  416. currentPage = page;
  417. if ($('#currentPageIndex')) {
  418. $('#currentPageIndex').text(currentPage + 1);
  419. }
  420. if ($('#totalPageCount')) {
  421. $('#totalPageCount').text(pageMax + 1);
  422. }
  423. },
  424. error: function(jqXHR, textStatus, errorThrown) {
  425. if ($('#mailList')) {
  426. $('#mailList').html('Unable to load message list');
  427. }
  428. }
  429. });
  430. }
  431. function nextPage() {
  432. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax;
  433. window.location.hash = currentFolder + newPage;
  434. }
  435. function prevPage() {
  436. var newPage = currentPage > 0 ? currentPage - 1 : 0;
  437. window.location.hash = currentFolder + newPage;
  438. }
  439. function toggleDropDown(dd) {
  440. $('#'+dd).toggle();
  441. }
  442. function sendNewMail(force) {
  443. if (toEmailList.length <= 0) {
  444. return;
  445. }
  446. if (!force) {
  447. //TODO: Check if subject or body empty and display popup here
  448. // return
  449. }
  450. var composedEmailString = toEmailList[0];
  451. for (var i = 1; i < toEmailList.length; i++) {
  452. composedEmailString += "," + toEmailList[i];
  453. }
  454. $('#newMailTo').val(composedEmailString);
  455. var formValue = $('#mailNewForm').serialize();
  456. $.ajax({
  457. url: mailbox + '/sendNewMail',
  458. data: formValue,
  459. success: function() {
  460. $('#newMailEditor').val('');
  461. $('#newMailSubject').val('');
  462. $('#newMailTo').val('');
  463. closeMailNew();
  464. showToast(Severity.Normal, 'Email succesfully send');
  465. },
  466. error: function(jqXHR, textStatus, errorThrown) {
  467. showToast(Severity.Critical, 'Unable to send email: ' + errorThrown + ' ' + textStatus);
  468. }
  469. });
  470. }
  471. function logout() {
  472. window.location.href = '/logout';
  473. }
  474. function settings() {
  475. window.location.href = '/settings';
  476. }
  477. function connectNotifier() {
  478. if (notifierSocket != null) {
  479. return;
  480. }
  481. var protocol = 'wss://';
  482. if (window.location.protocol !== 'https:') {
  483. protocol = 'ws://';
  484. }
  485. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + '/notifierSubscribe');
  486. notifierSocket.onmessage = function (e) {
  487. for (var i = 0; i < folders.length; i++) {
  488. folderStat(folders[i]);
  489. }
  490. updateMailList(currentFolder, currentPage);
  491. }
  492. }
  493. $(window).on('beforeunload', function(){
  494. if (notifierSocket != null) {
  495. notifierSocket.close();
  496. notifierSocket = null;
  497. }
  498. });
  499. function toggleMailSelection(id) {
  500. var currentState = $('#mailCheckbox'+id).prop('checked')
  501. if (currentState) {
  502. addToSelectionList(id);
  503. } else {
  504. removeFromSelectionList(id);
  505. }
  506. }
  507. function toogleMailSelection() {
  508. var currentState = $('#selectAllCheckbox').prop('checked');
  509. currentState = !currentState;
  510. resetSelectionList();
  511. if (!currentState) {
  512. $('[id^="mailCheckbox"]').each(function() {
  513. addToSelectionList(this.id.replace('mailCheckbox', ''));
  514. })
  515. }
  516. }
  517. function removeSelection() {
  518. for (var i = 0; i < selectionList.length; ++i) {
  519. removeMail(selectionList[i], function(){});
  520. }
  521. }
  522. function restoreSelection() {
  523. for (var i = 0; i < selectionList.length; ++i) {
  524. restoreMail(selectionList[i], function(){});
  525. }
  526. }
  527. function toggleSelectionRead() {
  528. var read = checkMailUnread();
  529. for (var i = 0; i < selectionList.length; ++i) {
  530. setRead(selectionList[i], read);
  531. }
  532. }
  533. function checkMailUnread() {
  534. for (var i = 0; i < selectionList.length; ++i) {
  535. if ($('#mail'+selectionList[i]).hasClass('unread')) {
  536. $('#multiActionsRead').attr('src', '/assets/unread.svg');
  537. return true;
  538. }
  539. }
  540. $('#multiActionsRead').attr('src', '/assets/read.svg');
  541. return false;
  542. }
  543. //Mail selection list operations
  544. var selectionList = new Array();
  545. function addToSelectionList(mailId) {
  546. const i = selectionList.indexOf(mailId);
  547. if (i >= 0) {
  548. return;
  549. }
  550. selectionList.push(mailId);
  551. $('#mailCheckbox'+mailId).prop('checked', true);
  552. $('#multiActionsControls').css('display', 'flex');
  553. $('#selectAllCheckbox').prop('checked', true);
  554. checkMailUnread();
  555. }
  556. function removeFromSelectionList(mailId) {
  557. const i = selectionList.indexOf(mailId);
  558. if (i < 0) {
  559. console.log('Mail with id ' + mailId + ' is not in list');
  560. return;
  561. }
  562. selectionList.splice(i, 1);
  563. $('#'+mailId).prop('checked', false);
  564. if (selectionList.length <= 0) {
  565. $('#multiActionsControls').css('display', 'none');
  566. $('#selectAllCheckbox').prop('checked', false);
  567. }
  568. checkMailUnread();
  569. }
  570. function resetSelectionList() {
  571. for (var i = 0; i < selectionList.length; ++i) {
  572. $('#mailCheckbox'+selectionList[i]).prop('checked', false);
  573. }
  574. selectionList = new Array();
  575. $('#selectAllCheckbox').prop('checked', false);
  576. $('#multiActionsControls').css('display', 'none');
  577. }
  578. function enableRestoreFunctionality() {
  579. if (currentFolder == 'Trash') {
  580. $('#multiActionsRestore').css('display', 'block');
  581. $('[id^="restoreListIcon"]').css('display', 'block');
  582. } else {
  583. $('#multiActionsRestore').css('display', 'none');
  584. $('[id^="restoreListIcon"]').css('display', 'none');
  585. }
  586. }