index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. if ($("#"+iconId+mailId)) {
  300. setRead(mailId, $("#"+iconId+mailId).attr("src") == "/assets/unread.svg")
  301. }
  302. }
  303. function removeMail(mailId, callback) {
  304. var url = currentFolder != "Trash" ? "/remove" : "/delete"
  305. $.ajax({
  306. url: url,
  307. data: {mailId: mailId},
  308. success: function(result) {
  309. $("#mail"+mailId).remove();
  310. if (callback) {
  311. callback();
  312. }
  313. folderStat(currentFolder);//TODO: receive statistic from websocket
  314. folderStat("Trash");//TODO: receive statistic from websocket
  315. },
  316. error: function(jqXHR, textStatus, errorThrown) {
  317. }
  318. })
  319. }
  320. function restoreMail(mailId, callback) {
  321. var url = "/restore"
  322. $.ajax({
  323. url: url,
  324. data: {mailId: mailId},
  325. success: function(result) {
  326. if (currentFolder == "Trash") {
  327. $("#mail"+mailId).remove();
  328. }
  329. if (callback) {
  330. callback();
  331. }
  332. for (var i = 0; i < folders.length; i++) {
  333. folderStat(folders[i])
  334. }
  335. },
  336. error: function(jqXHR, textStatus, errorThrown) {
  337. }
  338. })
  339. }
  340. function setDetailsVisible(visible) {
  341. if (visible) {
  342. $("#mailDetails").show()
  343. $("#mailList").css({pointerEvents: "none"})
  344. } else {
  345. currentMail = ""
  346. $("#mailDetails").hide()
  347. $("#mailDetails").html("")
  348. $("#mailList").css({pointerEvents: "auto"})
  349. }
  350. }
  351. function setMailNewVisible(visible) {
  352. if (visible) {
  353. $("#mailNew").show()
  354. $("#mailList").css({pointerEvents: "none"})
  355. } else {
  356. currentMail = ""
  357. $("#mailNew").hide()
  358. $("#mailList").css({pointerEvents: "auto"})
  359. }
  360. while (toEmailList.length > 0 && $("#toEmailList").children().length > 1) {
  361. removeToEmail($("#toEmailList").children()[$("#toEmailList").children().length - 2].id, toEmailList[toEmailList.length - 1])
  362. }
  363. toEmailList = new Array()
  364. $("#newMailEditor").val("")
  365. $("#newMailSubject").val("")
  366. $("#newMailTo").val("")
  367. $("#toEmailField").val("")
  368. }
  369. function updateMailList(folder, page) {
  370. if (mailbox == "" || folder == "") {
  371. if ($("#mailList")) {
  372. $("#mailList").html("Unable to load message list")
  373. }
  374. return
  375. }
  376. $.ajax({
  377. url: mailbox + "/mailList",
  378. data: {
  379. folder: folder,
  380. page: page
  381. },
  382. success: function(result) {
  383. var data = jQuery.parseJSON(result)
  384. pageMax = Math.floor(data.total/50)
  385. if ($("#mailList")) {
  386. $("#mailList").html(data.html)
  387. }
  388. currentFolder = folder
  389. currentPage = page
  390. if($("#currentPageIndex")) {
  391. $("#currentPageIndex").text(currentPage + 1)
  392. }
  393. if($("#totalPageCount")) {
  394. $("#totalPageCount").text(pageMax + 1)
  395. }
  396. },
  397. error: function(jqXHR, textStatus, errorThrown) {
  398. if ($("#mailList")) {
  399. $("#mailList").html("Unable to load message list")
  400. }
  401. }
  402. })
  403. }
  404. function nextPage() {
  405. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax
  406. window.location.hash = currentFolder + newPage
  407. }
  408. function prevPage() {
  409. var newPage = currentPage > 0 ? currentPage - 1 : 0
  410. window.location.hash = currentFolder + newPage
  411. }
  412. function toggleDropDown(dd) {
  413. $("#"+dd).toggle()
  414. }
  415. function sendNewMail(force) {
  416. if (toEmailList.length <= 0) {
  417. return
  418. }
  419. if (!force) {
  420. //TODO: Check if subject or body empty and display popup here
  421. // return
  422. }
  423. var composedEmailString = toEmailList[0]
  424. for(var i = 1; i < toEmailList.length; i++) {
  425. composedEmailString += "," + toEmailList[i]
  426. }
  427. $("#newMailTo").val(composedEmailString)
  428. var formValue = $("#mailNewForm").serialize()
  429. $.ajax({
  430. url: mailbox + "/sendNewMail",
  431. data: formValue,
  432. success: function(result) {
  433. $("#newMailEditor").val("")
  434. $("#newMailSubject").val("")
  435. $("#newMailTo").val("")
  436. closeMailNew()
  437. showToast(Severity.Normal, "Email succesfully send")
  438. },
  439. error: function(jqXHR, textStatus, errorThrown) {
  440. showToast(Severity.Critical, "Unable to send email: " + errorThrown + " " + textStatus)
  441. }
  442. })
  443. }
  444. function logout() {
  445. window.location.href = "/logout"
  446. }
  447. function settings() {
  448. window.location.href = "/settings"
  449. }
  450. function connectNotifier() {
  451. if (notifierSocket != null) {
  452. return
  453. }
  454. var protocol = "wss://"
  455. if(window.location.protocol !== "https:") {
  456. protocol = "ws://"
  457. }
  458. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + "/notifierSubscribe")
  459. notifierSocket.onmessage = function (e) {
  460. for (var i = 0; i < folders.length; i++) {
  461. folderStat(folders[i])
  462. }
  463. updateMailList(currentFolder, currentPage)
  464. }
  465. }
  466. $(window).on('beforeunload', function(){
  467. if (notifierSocket != null) {
  468. notifierSocket.close();
  469. notifierSocket = null
  470. }
  471. });
  472. window.onbeforeunload = function() {
  473. };