index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 setDetailsVisible(visible) {
  339. if (visible) {
  340. $('#mailDetails').show()
  341. $('#mailList').css({pointerEvents: 'none'})
  342. } else {
  343. currentMail = ''
  344. $('#mailDetails').hide()
  345. $('#mailDetails').html('')
  346. $('#mailList').css({pointerEvents: 'auto'})
  347. }
  348. }
  349. function setMailNewVisible(visible) {
  350. if (visible) {
  351. $('#mailNew').show()
  352. $('#mailList').css({pointerEvents: 'none'})
  353. } else {
  354. currentMail = ''
  355. $('#mailNew').hide()
  356. $('#mailList').css({pointerEvents: 'auto'})
  357. }
  358. while (toEmailList.length > 0 && $('#toEmailList').children().length > 1) {
  359. removeToEmail($('#toEmailList').children()[$('#toEmailList').children().length - 2].id, toEmailList[toEmailList.length - 1])
  360. }
  361. toEmailList = new Array()
  362. $('#newMailEditor').val('')
  363. $('#newMailSubject').val('')
  364. $('#newMailTo').val('')
  365. $('#toEmailField').val('')
  366. }
  367. function updateMailList(folder, page) {
  368. if (mailbox == '' || folder == '') {
  369. if ($('#mailList')) {
  370. $('#mailList').html('Unable to load message list')
  371. }
  372. return
  373. }
  374. $.ajax({
  375. url: mailbox + '/mailList',
  376. data: {
  377. folder: folder,
  378. page: page
  379. },
  380. success: function(result) {
  381. var data = jQuery.parseJSON(result)
  382. pageMax = Math.floor(data.total/50)
  383. if ($('#mailList')) {
  384. $('#mailList').html(data.html)
  385. }
  386. currentFolder = folder
  387. currentPage = page
  388. if($('#currentPageIndex')) {
  389. $('#currentPageIndex').text(currentPage + 1)
  390. }
  391. if($('#totalPageCount')) {
  392. $('#totalPageCount').text(pageMax + 1)
  393. }
  394. },
  395. error: function(jqXHR, textStatus, errorThrown) {
  396. if ($('#mailList')) {
  397. $('#mailList').html('Unable to load message list')
  398. }
  399. }
  400. })
  401. }
  402. function nextPage() {
  403. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax
  404. window.location.hash = currentFolder + newPage
  405. }
  406. function prevPage() {
  407. var newPage = currentPage > 0 ? currentPage - 1 : 0
  408. window.location.hash = currentFolder + newPage
  409. }
  410. function toggleDropDown(dd) {
  411. $('#'+dd).toggle()
  412. }
  413. function sendNewMail(force) {
  414. if (toEmailList.length <= 0) {
  415. return
  416. }
  417. if (!force) {
  418. //TODO: Check if subject or body empty and display popup here
  419. // return
  420. }
  421. var composedEmailString = toEmailList[0]
  422. for(var i = 1; i < toEmailList.length; i++) {
  423. composedEmailString += "," + toEmailList[i]
  424. }
  425. $('#newMailTo').val(composedEmailString)
  426. var formValue = $('#mailNewForm').serialize()
  427. $.ajax({
  428. url: mailbox + '/sendNewMail',
  429. data: formValue,
  430. success: function(result) {
  431. $('#newMailEditor').val('')
  432. $('#newMailSubject').val('')
  433. $('#newMailTo').val('')
  434. closeMailNew()
  435. showToast(Severity.Normal, 'Email succesfully send')
  436. },
  437. error: function(jqXHR, textStatus, errorThrown) {
  438. showToast(Severity.Critical, 'Unable to send email: ' + errorThrown + ' ' + textStatus)
  439. }
  440. })
  441. }
  442. function logout() {
  443. window.location.href = '/logout'
  444. }
  445. function settings() {
  446. window.location.href = '/settings'
  447. }
  448. function connectNotifier() {
  449. if (notifierSocket != null) {
  450. return
  451. }
  452. var protocol = 'wss://'
  453. if (window.location.protocol !== 'https:') {
  454. protocol = 'ws://'
  455. }
  456. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + '/notifierSubscribe')
  457. notifierSocket.onmessage = function (e) {
  458. for (var i = 0; i < folders.length; i++) {
  459. folderStat(folders[i])
  460. }
  461. updateMailList(currentFolder, currentPage)
  462. }
  463. }
  464. $(window).on('beforeunload', function(){
  465. if (notifierSocket != null) {
  466. notifierSocket.close();
  467. notifierSocket = null
  468. }
  469. });
  470. window.onbeforeunload = function() {
  471. };
  472. var selectionList = new Array()
  473. function selectMail(id, checkbox) {
  474. var currentState = $(checkbox).prop('checked')
  475. if (currentState == false) {
  476. const i = selectionList.indexOf(id);
  477. if (i >= 0) {
  478. selectionList.splice(i, 1);
  479. }
  480. } else {
  481. selectionList.push(id)
  482. }
  483. if(selectionList.length > 0) {
  484. $('#multiActionsControls').css('display', 'flex');
  485. } else {
  486. $('#multiActionsControls').css('display', 'none');
  487. }
  488. }
  489. function removeSelected(callback) {
  490. }
  491. function readSelected(callback) {
  492. }