index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. $("#mail"+mailId).removeClass("unread")
  177. $("#mail"+mailId).addClass("read")
  178. $("#mailDetails").html(result);
  179. setDetailsVisible(true);
  180. folderStat(currentFolder);//TODO: receive statistic from websocket
  181. },
  182. error: function(jqXHR, textStatus, errorThrown) {
  183. $("#mailDetails").html(textStatus)
  184. setDetailsVisible(true)
  185. }
  186. })
  187. }
  188. }
  189. function loadFolders() {
  190. if (mailbox == "") {
  191. $("#folders").html("Unable to load folder list")
  192. return
  193. }
  194. $.ajax({
  195. url: mailbox + "/folders",
  196. success: function(result) {
  197. folderList = jQuery.parseJSON(result)
  198. for(var i = 0; i < folderList.folders.length; i++) {
  199. folders.push(folderList.folders[i].name)
  200. folderStat(folderList.folders[i].name)
  201. }
  202. $("#folders").html(folderList.html)
  203. },
  204. error: function(jqXHR, textStatus, errorThrown) {
  205. //TODO: some toast message here once implemented
  206. }
  207. })
  208. }
  209. function folderStat(folder) {
  210. $.ajax({
  211. url: mailbox + "/folderStat",
  212. data: {
  213. folder: folder
  214. },
  215. success: function(result) {
  216. var stats = jQuery.parseJSON(result)
  217. if (stats.unread > 0) {
  218. $("#folderStats"+folder).text(stats.unread)
  219. $("#folder"+folder).addClass("unread")
  220. } else {
  221. $("#folder"+folder).removeClass("unread")
  222. $("#folderStats"+folder).text("")
  223. }
  224. },
  225. error: function(jqXHR, textStatus, errorThrown) {
  226. //TODO: some toast message here once implemented
  227. }
  228. })
  229. }
  230. function closeDetails() {
  231. window.location.hash = currentFolder + currentPage
  232. }
  233. function closeMailNew() {
  234. window.location.hash = currentFolder + currentPage
  235. }
  236. function loadStatusLine() {
  237. $.ajax({
  238. url: mailbox + "/statusLine",
  239. success: function(result) {
  240. $("#statusLine").html(result)
  241. },
  242. error: function(jqXHR, textStatus, errorThrown) {
  243. //TODO: some toast message here once implemented
  244. }
  245. })
  246. }
  247. function localDate(elementToChange, timestamp) {
  248. var today = new Date()
  249. var date = new Date(timestamp*1000)
  250. dateString = ""
  251. if (today.getDay() == date.getDay()
  252. && today.getMonth() == date.getMonth()
  253. && today.getFullYear() == date.getFullYear()) {
  254. dateString = date.toLocaleTimeString("en-US")
  255. } else if (today.getFullYear() == date.getFullYear()) {
  256. const options = { day: 'numeric', month: 'short' }
  257. dateString = date.toLocaleDateString("en-US", options)
  258. } else {
  259. dateString = date.toLocaleDateString("en-US")
  260. }
  261. $("#"+elementToChange).text(dateString)
  262. }
  263. function setRead(mailId, read) {
  264. $.ajax({
  265. url: "/setRead",
  266. data: {mailId: mailId,
  267. read: read},
  268. success: function(result) {
  269. if (read) {
  270. if ($("#readIcon"+mailId)) {
  271. $("#readIcon"+mailId).attr("src", "/assets/read.svg")
  272. }
  273. if ($("#readListIcon"+mailId)) {
  274. $("#readListIcon"+mailId).attr("src", "/assets/read.svg")
  275. }
  276. $("#mail"+mailId).removeClass("unread")
  277. $("#mail"+mailId).addClass("read")
  278. } else {
  279. if ($("#readIcon"+mailId)) {
  280. $("#readIcon"+mailId).attr("src", "/assets/unread.svg")
  281. }
  282. if ($("#readListIcon"+mailId)) {
  283. $("#readListIcon"+mailId).attr("src", "/assets/unread.svg")
  284. }
  285. $("#mail"+mailId).removeClass("read")
  286. $("#mail"+mailId).addClass("unread")
  287. }
  288. folderStat(currentFolder);//TODO: receive statistic from websocket
  289. },
  290. error: function(jqXHR, textStatus, errorThrown) {
  291. }
  292. })
  293. }
  294. function toggleRead(mailId, iconId) {
  295. if ($("#"+iconId+mailId)) {
  296. setRead(mailId, $("#"+iconId+mailId).attr("src") == "/assets/unread.svg")
  297. }
  298. }
  299. function removeMail(mailId, callback) {
  300. var url = currentFolder != "Trash" ? "/remove" : "/delete"
  301. $.ajax({
  302. url: url,
  303. data: {mailId: mailId},
  304. success: function(result) {
  305. $("#mail"+mailId).remove();
  306. if (callback) {
  307. callback();
  308. }
  309. folderStat(currentFolder);//TODO: receive statistic from websocket
  310. folderStat("Trash");//TODO: receive statistic from websocket
  311. },
  312. error: function(jqXHR, textStatus, errorThrown) {
  313. }
  314. })
  315. }
  316. function restoreMail(mailId, callback) {
  317. var url = "/restore"
  318. $.ajax({
  319. url: url,
  320. data: {mailId: mailId},
  321. success: function(result) {
  322. if (currentFolder == "Trash") {
  323. $("#mail"+mailId).remove();
  324. }
  325. if (callback) {
  326. callback();
  327. }
  328. for (var i = 0; i < folders.length; i++) {
  329. folderStat(folders[i])
  330. }
  331. },
  332. error: function(jqXHR, textStatus, errorThrown) {
  333. }
  334. })
  335. }
  336. function setDetailsVisible(visible) {
  337. if (visible) {
  338. $("#mailDetails").show()
  339. $("#mailList").css({pointerEvents: "none"})
  340. } else {
  341. currentMail = ""
  342. $("#mailDetails").hide()
  343. $("#mailDetails").html("")
  344. $("#mailList").css({pointerEvents: "auto"})
  345. }
  346. }
  347. function setMailNewVisible(visible) {
  348. if (visible) {
  349. $("#mailNew").show()
  350. $("#mailList").css({pointerEvents: "none"})
  351. } else {
  352. currentMail = ""
  353. $("#mailNew").hide()
  354. $("#mailList").css({pointerEvents: "auto"})
  355. }
  356. while (toEmailList.length > 0 && $("#toEmailList").children().length > 1) {
  357. removeToEmail($("#toEmailList").children()[$("#toEmailList").children().length - 2].id, toEmailList[toEmailList.length - 1])
  358. }
  359. toEmailList = new Array()
  360. $("#newMailEditor").val("")
  361. $("#newMailSubject").val("")
  362. $("#newMailTo").val("")
  363. $("#toEmailField").val("")
  364. }
  365. function updateMailList(folder, page) {
  366. if (mailbox == "" || folder == "") {
  367. if ($("#mailList")) {
  368. $("#mailList").html("Unable to load message list")
  369. }
  370. return
  371. }
  372. $.ajax({
  373. url: mailbox + "/mailList",
  374. data: {
  375. folder: folder,
  376. page: page
  377. },
  378. success: function(result) {
  379. var data = jQuery.parseJSON(result)
  380. pageMax = Math.floor(data.total/50)
  381. if ($("#mailList")) {
  382. $("#mailList").html(data.html)
  383. }
  384. currentFolder = folder
  385. currentPage = page
  386. if($("#currentPageIndex")) {
  387. $("#currentPageIndex").text(currentPage + 1)
  388. }
  389. if($("#totalPageCount")) {
  390. $("#totalPageCount").text(pageMax + 1)
  391. }
  392. },
  393. error: function(jqXHR, textStatus, errorThrown) {
  394. if ($("#mailList")) {
  395. $("#mailList").html("Unable to load message list")
  396. }
  397. }
  398. })
  399. }
  400. function nextPage() {
  401. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax
  402. window.location.hash = currentFolder + newPage
  403. }
  404. function prevPage() {
  405. var newPage = currentPage > 0 ? currentPage - 1 : 0
  406. window.location.hash = currentFolder + newPage
  407. }
  408. function toggleDropDown(dd) {
  409. $("#"+dd).toggle()
  410. }
  411. function sendNewMail(force) {
  412. if (toEmailList.length <= 0) {
  413. return
  414. }
  415. if (!force) {
  416. //TODO: Check if subject or body empty and display popup here
  417. // return
  418. }
  419. var composedEmailString = toEmailList[0]
  420. for(var i = 1; i < toEmailList.length; i++) {
  421. composedEmailString += "," + toEmailList[i]
  422. }
  423. $("#newMailTo").val(composedEmailString)
  424. var formValue = $("#mailNewForm").serialize()
  425. $.ajax({
  426. url: mailbox + "/sendNewMail",
  427. data: formValue,
  428. success: function(result) {
  429. $("#newMailEditor").val("")
  430. $("#newMailSubject").val("")
  431. $("#newMailTo").val("")
  432. closeMailNew()
  433. },
  434. error: function(jqXHR, textStatus, errorThrown) {
  435. //TODO: some toast message here once implemented
  436. }
  437. })
  438. }
  439. function logout() {
  440. window.location.href = "/logout"
  441. }
  442. function connectNotifier() {
  443. if (notifierSocket != null) {
  444. return
  445. }
  446. var protocol = "wss://"
  447. if(window.location.protocol !== "https:") {
  448. protocol = "ws://"
  449. }
  450. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + "/notifierSubscribe")
  451. notifierSocket.onopen = function() {
  452. };
  453. notifierSocket.onmessage = function (e) {
  454. for (var i = 0; i < folders.length; i++) {
  455. folderStat(folders[i])
  456. }
  457. updateMailList(currentFolder, currentPage)
  458. }
  459. notifierSocket.onclose = function () {
  460. }
  461. }
  462. window.onbeforeunload = function() {
  463. if (notifierSocket != null) {
  464. notifierSocket.onclose = function () {}; // disable onclose handler first
  465. notifierSocket.close();
  466. }
  467. };