index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. })
  88. function toEmailFieldChanged(e) {
  89. const selectionPosition = e.target.selectionStart - 1
  90. var actualText = $('#toEmailField').val()
  91. if (actualText.length <= 0 || selectionPosition < 0) {
  92. return
  93. }
  94. var lastChar = actualText[selectionPosition]
  95. if (emailEndRegex.test(lastChar)) {
  96. addToEmail(actualText.slice(0, selectionPosition))
  97. $('#toEmailField').val(actualText.slice(selectionPosition + 1, actualText.length))
  98. }
  99. }
  100. function addToEmail(toEmail) {
  101. if (toEmail.length <= 0) {
  102. return
  103. }
  104. var style = emailRegex.test(toEmail) ? 'valid' : 'invalid'
  105. $('<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')
  106. toEmailIndex++
  107. toEmailList.push(toEmail)
  108. checkSendDisabled()
  109. }
  110. function removeToEmail(id, email) {
  111. const index = toEmailList.indexOf(email)
  112. if (index >= 0) {
  113. toEmailList.splice(index, 1)
  114. checkSendDisabled()
  115. }
  116. $('#' + id).remove()
  117. }
  118. function checkSendDisabled() {
  119. if (toEmailList.length > 0) {
  120. $('#sendButton').removeClass('disabled')
  121. } else {
  122. $('#sendButton').addClass('disabled')
  123. }
  124. }
  125. function mailNew(e) {
  126. window.location.hash = currentFolder + currentPage + '/mailNew'
  127. }
  128. function mailOpen(id) {
  129. window.location.hash = currentFolder + currentPage + '/' + id
  130. }
  131. function openFolder(folder) {
  132. window.location.hash = folder
  133. }
  134. function onHashChanged() {
  135. var hashLocation = window.location.hash
  136. if (hashLocation == "") {
  137. setDetailsVisible(false)
  138. openFolder('Inbox')
  139. return
  140. }
  141. hashRegex = /^#([a-zA-Z]+)(\d*)\/?([A-Fa-f\d]*)/g
  142. hashParts = hashRegex.exec(hashLocation)
  143. page = 0
  144. if (hashParts.length >= 3 && hashParts[2] != "") {
  145. page = parseInt(hashParts[2])
  146. if (typeof page != 'number' || page > pageMax || page < 0) {
  147. page = 0
  148. }
  149. }
  150. if (hashParts.length >= 2 && (hashParts[1] != currentFolder || currentPage != page) && hashParts[1] != "") {
  151. updateMailList(hashParts[1], page)
  152. }
  153. if (hashParts.length >= 4 && hashParts[3] != "" && hashParts[3] != '/mailNew') {
  154. if (currentMail != hashParts[3]) {
  155. requestMail(hashParts[3])
  156. }
  157. } else {
  158. setDetailsVisible(false)
  159. }
  160. hashParts = hashLocation.split('/')
  161. if (hashParts.length == 2 && hashParts[1] == 'mailNew') {
  162. setMailNewVisible(true)
  163. } else {
  164. setMailNewVisible(false)
  165. }
  166. }
  167. function requestMail(mailId) {
  168. if (mailId != "") {
  169. $.ajax({
  170. url: '/mail',
  171. data: {
  172. mailId: mailId
  173. },
  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. },
  185. error: function(jqXHR, textStatus, errorThrown) {
  186. $('#mailDetails').html(textStatus)
  187. setDetailsVisible(true)
  188. showToast(Severity.Critical, 'Unable to open mail: ' + errorThrown + ' ' + textStatus)
  189. }
  190. })
  191. }
  192. }
  193. function loadFolders() {
  194. if (mailbox == '') {
  195. $('#folders').html('Unable to load folder list')
  196. return
  197. }
  198. $.ajax({
  199. url: mailbox + '/folders',
  200. success: function(result) {
  201. folderList = jQuery.parseJSON(result)
  202. for(var i = 0; i < folderList.folders.length; i++) {
  203. folders.push(folderList.folders[i].name)
  204. folderStat(folderList.folders[i].name)
  205. }
  206. $('#folders').html(folderList.html)
  207. },
  208. error: function(jqXHR, textStatus, errorThrown) {
  209. showToast(Severity.Critical, 'Unable to update folder list: ' + errorThrown + ' ' + textStatus)
  210. }
  211. })
  212. }
  213. function folderStat(folder) {
  214. $.ajax({
  215. url: mailbox + '/folderStat',
  216. data: {
  217. folder: folder
  218. },
  219. success: function(result) {
  220. var stats = jQuery.parseJSON(result)
  221. if (stats.unread > 0) {
  222. $('#folderStats'+folder).text(stats.unread)
  223. $('#folder'+folder).addClass('unread')
  224. } else {
  225. $('#folder'+folder).removeClass('unread')
  226. $('#folderStats'+folder).text("")
  227. }
  228. },
  229. error: function(jqXHR, textStatus, errorThrown) {
  230. showToast(Severity.Critical, 'Unable to update folder list: ' + errorThrown + ' ' + textStatus)
  231. }
  232. })
  233. }
  234. function closeDetails() {
  235. window.location.hash = currentFolder + currentPage
  236. }
  237. function closeMailNew() {
  238. window.location.hash = currentFolder + currentPage
  239. }
  240. function loadStatusLine() {
  241. $.ajax({
  242. url: mailbox + '/statusLine',
  243. success: function(result) {
  244. $('#statusLine').html(result)
  245. },
  246. error: function(jqXHR, textStatus, errorThrown) {
  247. showToast(Severity.Critical, 'Unable to load status line: ' + errorThrown + ' ' + textStatus)
  248. }
  249. })
  250. }
  251. function localDate(elementToChange, timestamp) {
  252. var today = new Date()
  253. var date = new Date(timestamp*1000)
  254. dateString = ""
  255. if (today.getDay() == date.getDay()
  256. && today.getMonth() == date.getMonth()
  257. && today.getFullYear() == date.getFullYear()) {
  258. dateString = date.toLocaleTimeString("en-US")
  259. } else if (today.getFullYear() == date.getFullYear()) {
  260. const options = { day: 'numeric', month: 'short' }
  261. dateString = date.toLocaleDateString("en-US", options)
  262. } else {
  263. dateString = date.toLocaleDateString("en-US")
  264. }
  265. $('#'+elementToChange).text(dateString)
  266. }
  267. function setRead(mailId, read) {
  268. $.ajax({
  269. url: '/setRead',
  270. data: {mailId: mailId,
  271. read: read},
  272. success: function(result) {
  273. if (read) {
  274. if ($('#readIcon'+mailId)) {
  275. $('#readIcon'+mailId).attr('src', '/assets/read.svg')
  276. }
  277. if ($('#readListIcon'+mailId)) {
  278. $('#readListIcon'+mailId).attr('src', '/assets/read.svg')
  279. }
  280. $('#mail'+mailId).removeClass('unread')
  281. $('#mail'+mailId).addClass('read')
  282. } else {
  283. if ($('#readIcon'+mailId)) {
  284. $('#readIcon'+mailId).attr('src', '/assets/unread.svg')
  285. }
  286. if ($('#readListIcon'+mailId)) {
  287. $('#readListIcon'+mailId).attr('src', '/assets/unread.svg')
  288. }
  289. $('#mail'+mailId).removeClass('read')
  290. $('#mail'+mailId).addClass('unread')
  291. }
  292. folderStat(currentFolder);//TODO: receive statistic from websocket
  293. },
  294. error: function(jqXHR, textStatus, errorThrown) {
  295. }
  296. })
  297. }
  298. function toggleRead(mailId, iconId) {
  299. setRead(mailId, $('#' + iconId + mailId).attr('src') == '/assets/unread.svg')
  300. }
  301. function removeMail(mailId, callback) {
  302. var url = currentFolder != 'Trash' ? '/remove' : '/delete'
  303. $.ajax({
  304. url: url,
  305. data: {mailId: mailId},
  306. success: function(result) {
  307. $('#mail'+mailId).remove();
  308. if (callback) {
  309. callback();
  310. }
  311. folderStat(currentFolder);//TODO: receive statistic from websocket
  312. folderStat('Trash');//TODO: receive statistic from websocket
  313. },
  314. error: function(jqXHR, textStatus, errorThrown) {
  315. }
  316. })
  317. }
  318. function restoreMail(mailId, callback) {
  319. var url = '/restore'
  320. $.ajax({
  321. url: url,
  322. data: {mailId: mailId},
  323. success: function(result) {
  324. if (currentFolder == 'Trash') {
  325. $('#mail'+mailId).remove();
  326. }
  327. if (callback) {
  328. callback();
  329. }
  330. for (var i = 0; i < folders.length; i++) {
  331. folderStat(folders[i])
  332. }
  333. },
  334. error: function(jqXHR, textStatus, errorThrown) {
  335. }
  336. })
  337. }
  338. function downloadAttachment(attachmentId, filename) {
  339. $.ajax({
  340. url: '/attachment/' + attachmentId,
  341. xhrFields: {
  342. responseType: 'blob'
  343. },
  344. success: function (data) {
  345. // Ah-ha-ha-ha html and web is piece of shit full of hacks...
  346. var a = document.createElement('a');
  347. var url = window.URL.createObjectURL(data);
  348. a.href = url;
  349. a.download = filename;
  350. document.body.append(a);
  351. a.click();
  352. a.remove();
  353. window.URL.revokeObjectURL(url);
  354. },
  355. error: function(jqXHR, textStatus, errorThrown) {
  356. showToast(Severity.Critical, 'Unable to download attachment: ' + errorThrown + ' ' + textStatus)
  357. }
  358. });
  359. }
  360. function setDetailsVisible(visible) {
  361. if (visible) {
  362. $('#mailDetails').show()
  363. $('#mailList').css({pointerEvents: 'none'})
  364. } else {
  365. currentMail = ''
  366. $('#mailDetails').hide()
  367. $('#mailDetails').html('')
  368. $('#mailList').css({pointerEvents: 'auto'})
  369. }
  370. }
  371. function setMailNewVisible(visible) {
  372. if (visible) {
  373. $('#mailNew').show()
  374. $('#mailList').css({pointerEvents: 'none'})
  375. } else {
  376. currentMail = ''
  377. $('#mailNew').hide()
  378. $('#mailList').css({pointerEvents: 'auto'})
  379. }
  380. while (toEmailList.length > 0 && $('#toEmailList').children().length > 1) {
  381. removeToEmail($('#toEmailList').children()[$('#toEmailList').children().length - 2].id, toEmailList[toEmailList.length - 1])
  382. }
  383. toEmailList = new Array()
  384. $('#newMailEditor').val('')
  385. $('#newMailSubject').val('')
  386. $('#newMailTo').val('')
  387. $('#toEmailField').val('')
  388. }
  389. function updateMailList(folder, page) {
  390. if (mailbox == '' || folder == '') {
  391. if ($('#mailList')) {
  392. $('#mailList').html('Unable to load message list')
  393. }
  394. return
  395. }
  396. $.ajax({
  397. url: mailbox + '/mailList',
  398. data: {
  399. folder: folder,
  400. page: page
  401. },
  402. success: function(result) {
  403. var data = jQuery.parseJSON(result)
  404. pageMax = Math.floor(data.total/50)
  405. if ($('#mailList')) {
  406. $('#mailList').html(data.html)
  407. }
  408. currentFolder = folder
  409. currentPage = page
  410. if($('#currentPageIndex')) {
  411. $('#currentPageIndex').text(currentPage + 1)
  412. }
  413. if($('#totalPageCount')) {
  414. $('#totalPageCount').text(pageMax + 1)
  415. }
  416. },
  417. error: function(jqXHR, textStatus, errorThrown) {
  418. if ($('#mailList')) {
  419. $('#mailList').html('Unable to load message list')
  420. }
  421. }
  422. })
  423. }
  424. function nextPage() {
  425. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax
  426. window.location.hash = currentFolder + newPage
  427. }
  428. function prevPage() {
  429. var newPage = currentPage > 0 ? currentPage - 1 : 0
  430. window.location.hash = currentFolder + newPage
  431. }
  432. function toggleDropDown(dd) {
  433. $('#'+dd).toggle()
  434. }
  435. function sendNewMail(force) {
  436. if (toEmailList.length <= 0) {
  437. return
  438. }
  439. if (!force) {
  440. //TODO: Check if subject or body empty and display popup here
  441. // return
  442. }
  443. var composedEmailString = toEmailList[0]
  444. for(var i = 1; i < toEmailList.length; i++) {
  445. composedEmailString += "," + toEmailList[i]
  446. }
  447. $('#newMailTo').val(composedEmailString)
  448. var formValue = $('#mailNewForm').serialize()
  449. $.ajax({
  450. url: mailbox + '/sendNewMail',
  451. data: formValue,
  452. success: function(result) {
  453. $('#newMailEditor').val('')
  454. $('#newMailSubject').val('')
  455. $('#newMailTo').val('')
  456. closeMailNew()
  457. showToast(Severity.Normal, 'Email succesfully send')
  458. },
  459. error: function(jqXHR, textStatus, errorThrown) {
  460. showToast(Severity.Critical, 'Unable to send email: ' + errorThrown + ' ' + textStatus)
  461. }
  462. })
  463. }
  464. function logout() {
  465. window.location.href = '/logout'
  466. }
  467. function settings() {
  468. window.location.href = '/settings'
  469. }
  470. function connectNotifier() {
  471. if (notifierSocket != null) {
  472. return
  473. }
  474. var protocol = 'wss://'
  475. if (window.location.protocol !== 'https:') {
  476. protocol = 'ws://'
  477. }
  478. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + '/notifierSubscribe')
  479. notifierSocket.onmessage = function (e) {
  480. for (var i = 0; i < folders.length; i++) {
  481. folderStat(folders[i])
  482. }
  483. updateMailList(currentFolder, currentPage)
  484. }
  485. }
  486. $(window).on('beforeunload', function(){
  487. if (notifierSocket != null) {
  488. notifierSocket.close();
  489. notifierSocket = null
  490. }
  491. });
  492. window.onbeforeunload = function() {
  493. };
  494. var selectionList = new Array()
  495. function selectMail(id, checkbox) {
  496. var currentState = $(checkbox).prop('checked')
  497. if (currentState == false) {
  498. const i = selectionList.indexOf(id);
  499. if (i >= 0) {
  500. selectionList.splice(i, 1);
  501. }
  502. } else {
  503. selectionList.push(id)
  504. }
  505. if(selectionList.length > 0) {
  506. $('#multiActionsControls').css('display', 'flex');
  507. } else {
  508. $('#multiActionsControls').css('display', 'none');
  509. }
  510. }
  511. function removeSelected(callback) {
  512. }
  513. function readSelected(callback) {
  514. }