index.js 16 KB

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