index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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/' + mailId,
  173. type: 'GET',
  174. success: function(result) {
  175. currentMail = mailId;
  176. if ($('#readListIcon'+mailId)) {
  177. $('#readListIcon'+mailId).attr('src', '/assets/read.svg');
  178. }
  179. $('#mail'+mailId).removeClass('unread');
  180. $('#mail'+mailId).addClass('read');
  181. $('#mailDetails').html(result);
  182. setDetailsVisible(true);
  183. folderStat(currentFolder);//TODO: receive statistic from websocket
  184. checkMailUnread();
  185. },
  186. error: function(jqXHR, textStatus, errorThrown) {
  187. $('#mailDetails').html(textStatus);
  188. setDetailsVisible(true);
  189. showToast(Severity.Critical, 'Unable to open mail: ' + errorThrown + ' ' + textStatus);
  190. }
  191. });
  192. }
  193. }
  194. function loadFolders() {
  195. if (mailbox == '') {
  196. $('#folders').html('Unable to load folder list');
  197. return;
  198. }
  199. $.ajax({
  200. url: mailbox + '/folders',
  201. success: function(result) {
  202. folderList = jQuery.parseJSON(result);
  203. for(var i = 0; i < folderList.folders.length; i++) {
  204. folders.push(folderList.folders[i].name);
  205. folderStat(folderList.folders[i].name);
  206. }
  207. $('#folders').html(folderList.html);
  208. },
  209. error: function(jqXHR, textStatus, errorThrown) {
  210. showToast(Severity.Critical, 'Unable to update folder list: ' + errorThrown + ' ' + textStatus);
  211. }
  212. });
  213. }
  214. function folderStat(folder) {
  215. $.ajax({
  216. url: mailbox + '/folderStat',
  217. data: {
  218. folder: folder
  219. },
  220. success: function(result) {
  221. var stats = jQuery.parseJSON(result);
  222. if (stats.unread > 0) {
  223. $('#folderStats'+folder).text(stats.unread);
  224. $('#folder'+folder).addClass('unread');
  225. } else {
  226. $('#folder'+folder).removeClass('unread');
  227. $('#folderStats'+folder).text("");
  228. }
  229. },
  230. error: function(jqXHR, textStatus, errorThrown) {
  231. showToast(Severity.Critical, 'Unable to update folder list: ' + errorThrown + ' ' + textStatus);
  232. }
  233. });
  234. }
  235. function closeDetails() {
  236. window.location.hash = currentFolder + currentPage;
  237. }
  238. function closeMailNew() {
  239. window.location.hash = currentFolder + currentPage;
  240. }
  241. function loadStatusLine() {
  242. $.ajax({
  243. url: mailbox + '/statusLine',
  244. success: function(result) {
  245. $('#statusLine').html(result);
  246. },
  247. error: function(jqXHR, textStatus, errorThrown) {
  248. showToast(Severity.Critical, 'Unable to load status line: ' + errorThrown + ' ' + textStatus);
  249. }
  250. });
  251. }
  252. function localDate(elementToChange, timestamp) {
  253. var today = new Date();
  254. var date = new Date(timestamp * 1000);
  255. dateString = '';
  256. if (today.getDay() == date.getDay()
  257. && today.getMonth() == date.getMonth()
  258. && today.getFullYear() == date.getFullYear()) {
  259. dateString = date.toLocaleTimeString('en-US');
  260. } else if (today.getFullYear() == date.getFullYear()) {
  261. const options = { day: 'numeric', month: 'short' };
  262. dateString = date.toLocaleDateString('en-US', options);
  263. } else {
  264. dateString = date.toLocaleDateString('en-US');
  265. }
  266. $('#'+elementToChange).text(dateString);
  267. }
  268. function setRead(mailId, read) {
  269. $.ajax({
  270. url: '/mail/'+mailId,
  271. type: 'PATCH',
  272. data: {read: read},
  273. success: function(result) {
  274. if (read) {
  275. if ($('#readIcon'+mailId)) {
  276. $('#readIcon'+mailId).attr('src', '/assets/read.svg');
  277. }
  278. if ($('#readListIcon'+mailId)) {
  279. $('#readListIcon'+mailId).attr('src', '/assets/read.svg');
  280. }
  281. $('#mail'+mailId).removeClass('unread');
  282. $('#mail'+mailId).addClass('read');
  283. } else {
  284. if ($('#readIcon'+mailId)) {
  285. $('#readIcon'+mailId).attr('src', '/assets/unread.svg');
  286. }
  287. if ($('#readListIcon'+mailId)) {
  288. $('#readListIcon'+mailId).attr('src', '/assets/unread.svg');
  289. }
  290. $('#mail'+mailId).removeClass('read');
  291. $('#mail'+mailId).addClass('unread');
  292. }
  293. folderStat(currentFolder);//TODO: receive statistic from websocket
  294. checkMailUnread();
  295. },
  296. error: function(jqXHR, textStatus, errorThrown) {
  297. }
  298. });
  299. }
  300. function toggleRead(mailId) {
  301. var read = $('#mail'+mailId).hasClass('read');
  302. setRead(mailId, !read);
  303. }
  304. function removeMail(mailId, callback) {
  305. var method = 'PATCH';
  306. var data = { trash: 'true' };
  307. if (currentFolder == 'Trash') {
  308. method = 'DELETE';
  309. data = null;
  310. }
  311. $.ajax({
  312. url: '/mail/'+mailId,
  313. type: method,
  314. data: data,
  315. success: function() {
  316. removeFromSelectionList(mailId);
  317. $('#mail'+mailId).remove();
  318. if (callback) {
  319. callback(mailId);
  320. }
  321. folderStat(currentFolder);//TODO: receive statistic from websocket
  322. folderStat('Trash');//TODO: receive statistic from websocket
  323. },
  324. error: function(jqXHR, textStatus, errorThrown) {
  325. showToast(Severity.Critical, 'Unable to remove mail: ' + errorThrown + ' ' + textStatus);
  326. }
  327. });
  328. }
  329. function restoreMail(mailId, callback) {
  330. $.ajax({
  331. url: '/mail/'+mailId,
  332. type: 'PATCH',
  333. data: {trash: 'false'},
  334. success: function() {
  335. if (currentFolder == 'Trash') {
  336. $('#mail'+mailId).remove();
  337. removeFromSelectionList(mailId);
  338. }
  339. if (callback) {
  340. callback();
  341. }
  342. for (var i = 0; i < folders.length; i++) {
  343. folderStat(folders[i]);
  344. }
  345. },
  346. error: function(jqXHR, textStatus, errorThrown) {
  347. showToast(Severity.Critical, 'Unable to restore mail: ' + errorThrown + ' ' + textStatus);
  348. }
  349. });
  350. }
  351. function downloadAttachment(attachmentId, filename) {
  352. $.ajax({
  353. url: '/attachment/' + attachmentId,
  354. type: 'GET',
  355. xhrFields: {
  356. responseType: 'blob'
  357. },
  358. success: function (data) {
  359. // Ah-ha-ha-ha html and web is piece of shit full of hacks...
  360. var a = document.createElement('a');
  361. var url = window.URL.createObjectURL(data);
  362. a.href = url;
  363. a.download = filename;
  364. document.body.append(a);
  365. a.click();
  366. a.remove();
  367. window.URL.revokeObjectURL(url);
  368. },
  369. error: function(jqXHR, textStatus, errorThrown) {
  370. showToast(Severity.Critical, 'Unable to download attachment: ' + errorThrown + ' ' + textStatus);
  371. }
  372. });
  373. }
  374. function setDetailsVisible(visible) {
  375. if (visible) {
  376. $('#mailDetails').show();
  377. $('#mailList').css({pointerEvents: 'none'});
  378. } else {
  379. currentMail = '';
  380. $('#mailDetails').hide();
  381. $('#mailDetails').html('');
  382. $('#mailList').css({pointerEvents: 'auto'});
  383. }
  384. }
  385. function setMailNewVisible(visible) {
  386. if (visible) {
  387. $('#mailNew').show();
  388. $('#mailList').css({pointerEvents: 'none'});
  389. } else {
  390. currentMail = '';
  391. $('#mailNew').hide();
  392. $('#mailList').css({pointerEvents: 'auto'});
  393. }
  394. while (toEmailList.length > 0 && $('#toEmailList').children().length > 1) {
  395. removeToEmail($('#toEmailList').children()[$('#toEmailList').children().length - 2].id, toEmailList[toEmailList.length - 1]);
  396. }
  397. toEmailList = new Array();
  398. $('#newMailEditor').val('');
  399. $('#newMailSubject').val('');
  400. $('#newMailTo').val('');
  401. $('#toEmailField').val('');
  402. }
  403. function updateMailList(folder, page) {
  404. if (mailbox == '' || folder == '') {
  405. if ($('#mailList')) {
  406. $('#mailList').html('Unable to load message list');
  407. }
  408. return;
  409. }
  410. $.ajax({
  411. url: mailbox + '/mailList',
  412. data: {
  413. folder: folder,
  414. page: page
  415. },
  416. success: function(result) {
  417. var data = jQuery.parseJSON(result);
  418. pageMax = Math.floor(data.total/50);
  419. if ($('#mailList')) {
  420. $('#mailList').html(data.html);
  421. }
  422. currentFolder = folder;
  423. enableRestoreFunctionality();
  424. currentPage = page;
  425. resetSelectionList();
  426. if ($('#currentPageIndex')) {
  427. $('#currentPageIndex').text(currentPage + 1);
  428. }
  429. if ($('#totalPageCount')) {
  430. $('#totalPageCount').text(pageMax + 1);
  431. }
  432. },
  433. error: function(jqXHR, textStatus, errorThrown) {
  434. if ($('#mailList')) {
  435. $('#mailList').html('Unable to load message list');
  436. }
  437. }
  438. });
  439. }
  440. function nextPage() {
  441. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax;
  442. window.location.hash = currentFolder + newPage;
  443. }
  444. function prevPage() {
  445. var newPage = currentPage > 0 ? currentPage - 1 : 0;
  446. window.location.hash = currentFolder + newPage;
  447. }
  448. function toggleDropDown(dd) {
  449. $('#'+dd).toggle();
  450. }
  451. function sendNewMail(force) {
  452. if (toEmailList.length <= 0) {
  453. return;
  454. }
  455. if (!force) {
  456. //TODO: Check if subject or body empty and display popup here
  457. // return
  458. }
  459. var composedEmailString = toEmailList[0];
  460. for (var i = 1; i < toEmailList.length; i++) {
  461. composedEmailString += "," + toEmailList[i];
  462. }
  463. $('#newMailTo').val(composedEmailString);
  464. var formValue = $('#mailNewForm').serialize();
  465. $.ajax({
  466. url: mailbox + '/sendNewMail',
  467. data: formValue,
  468. success: function() {
  469. $('#newMailEditor').val('');
  470. $('#newMailSubject').val('');
  471. $('#newMailTo').val('');
  472. closeMailNew();
  473. showToast(Severity.Normal, 'Email succesfully send');
  474. },
  475. error: function(jqXHR, textStatus, errorThrown) {
  476. showToast(Severity.Critical, 'Unable to send email: ' + errorThrown + ' ' + textStatus);
  477. }
  478. });
  479. }
  480. function logout() {
  481. window.location.href = '/logout';
  482. }
  483. function settings() {
  484. window.location.href = '/settings';
  485. }
  486. function connectNotifier() {
  487. if (notifierSocket != null) {
  488. return;
  489. }
  490. var protocol = 'wss://';
  491. if (window.location.protocol !== 'https:') {
  492. protocol = 'ws://';
  493. }
  494. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + '/notifierSubscribe');
  495. notifierSocket.onmessage = function (e) {
  496. for (var i = 0; i < folders.length; i++) {
  497. folderStat(folders[i]);
  498. }
  499. updateMailList(currentFolder, currentPage);
  500. }
  501. }
  502. $(window).on('beforeunload', function(){
  503. if (notifierSocket != null) {
  504. notifierSocket.close();
  505. notifierSocket = null;
  506. }
  507. });
  508. function toggleMailSelection(id) {
  509. var currentState = $('#mailCheckbox'+id).prop('checked')
  510. if (currentState) {
  511. addToSelectionList(id);
  512. } else {
  513. removeFromSelectionList(id);
  514. }
  515. }
  516. function toogleMailSelection() {
  517. var currentState = $('#selectAllCheckbox').prop('checked');
  518. currentState = !currentState;
  519. resetSelectionList();
  520. if (!currentState) {
  521. $('[id^="mailCheckbox"]').each(function() {
  522. addToSelectionList(this.id.replace('mailCheckbox', ''));
  523. })
  524. }
  525. }
  526. function removeSelection() {
  527. for (var i = 0; i < selectionList.length; ++i) {
  528. removeMail(selectionList[i], function(){});
  529. }
  530. }
  531. function restoreSelection() {
  532. for (var i = 0; i < selectionList.length; ++i) {
  533. restoreMail(selectionList[i], function(){});
  534. }
  535. }
  536. function toggleSelectionRead() {
  537. var read = checkMailUnread();
  538. for (var i = 0; i < selectionList.length; ++i) {
  539. setRead(selectionList[i], read);
  540. }
  541. }
  542. function checkMailUnread() {
  543. for (var i = 0; i < selectionList.length; ++i) {
  544. if ($('#mail'+selectionList[i]).hasClass('unread')) {
  545. $('#multiActionsRead').attr('src', '/assets/unread.svg');
  546. return true;
  547. }
  548. }
  549. $('#multiActionsRead').attr('src', '/assets/read.svg');
  550. return false;
  551. }
  552. //Mail selection list operations
  553. var selectionList = new Array();
  554. function addToSelectionList(mailId) {
  555. const i = selectionList.indexOf(mailId);
  556. if (i >= 0) {
  557. return;
  558. }
  559. selectionList.push(mailId);
  560. $('#mailCheckbox'+mailId).prop('checked', true);
  561. $('#multiActionsControls').css('display', 'flex');
  562. $('#selectAllCheckbox').prop('checked', true);
  563. checkMailUnread();
  564. }
  565. function removeFromSelectionList(mailId) {
  566. const i = selectionList.indexOf(mailId);
  567. if (i < 0) {
  568. console.log('Mail with id ' + mailId + ' is not in list');
  569. return;
  570. }
  571. selectionList.splice(i, 1);
  572. $('#'+mailId).prop('checked', false);
  573. if (selectionList.length <= 0) {
  574. $('#multiActionsControls').css('display', 'none');
  575. $('#selectAllCheckbox').prop('checked', false);
  576. }
  577. checkMailUnread();
  578. }
  579. function resetSelectionList() {
  580. for (var i = 0; i < selectionList.length; ++i) {
  581. $('#mailCheckbox'+selectionList[i]).prop('checked', false);
  582. }
  583. selectionList = new Array();
  584. $('#selectAllCheckbox').prop('checked', false);
  585. $('#multiActionsControls').css('display', 'none');
  586. }
  587. function enableRestoreFunctionality() {
  588. if (currentFolder == 'Trash') {
  589. $('#multiActionsRestore').css('display', 'block');
  590. $('[id^="restoreListIcon"]').css('display', 'block');
  591. } else {
  592. $('#multiActionsRestore').css('display', 'none');
  593. $('[id^="restoreListIcon"]').css('display', 'none');
  594. }
  595. }