index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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").keyup(function(e){
  70. if (e.keyCode == 8 && toEmailPreviousSelectionPosition == 0 && e.target.selectionStart == 0 && toEmailList.length > 0 && $("#toEmailList").children().length > 0) {
  71. removeToEmail($("#toEmailList").children().last().attr("id"), toEmailList[toEmailList.length - 1])
  72. }
  73. toEmailPreviousSelectionPosition = e.target.selectionStart
  74. })
  75. })
  76. function toEmailFieldChanged(e) {
  77. const selectionPosition = e.target.selectionStart - 1
  78. var actualText = $("#toEmailField").val()
  79. if (actualText.length <= 0 || selectionPosition <= 0) {
  80. return
  81. }
  82. var lastChar = actualText[selectionPosition]
  83. if (lastChar.match(emailEndRegex)) {
  84. var toEmail = actualText.slice(0, selectionPosition)
  85. $("#toEmailField").val(actualText.slice(selectionPosition + 1, actualText.length))
  86. if (toEmail.length <= 0) {
  87. return
  88. }
  89. var style = toEmail.match(emailRegex) ? "valid" : "invalid"
  90. $("#toEmailList").append("<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>")
  91. toEmailIndex++
  92. toEmailList.push(toEmail)
  93. }
  94. }
  95. function removeToEmail(id, email) {
  96. const index = toEmailList.indexOf(email)
  97. if (index >= 0) {
  98. toEmailList.splice(index, 1)
  99. }
  100. $("#" + id).remove()
  101. console.log("Remove email: " + email + " index:" + index)
  102. console.log("toEmailList: " + toEmailList)
  103. }
  104. function mailNew(e) {
  105. window.location.hash = currentFolder + currentPage + "/mailNew"
  106. }
  107. function mailOpen(id) {
  108. window.location.hash = currentFolder + currentPage + "/" + id
  109. }
  110. function openFolder(folder) {
  111. window.location.hash = folder
  112. }
  113. function onHashChanged() {
  114. var hashLocation = window.location.hash
  115. if (hashLocation == "") {
  116. setDetailsVisible(false)
  117. openFolder("Inbox")
  118. return
  119. }
  120. hashRegex = /^#([a-zA-Z]+)(\d*)\/?([A-Fa-f\d]*)/g
  121. hashParts = hashRegex.exec(hashLocation)
  122. page = 0
  123. if (hashParts.length >= 3 && hashParts[2] != "") {
  124. page = parseInt(hashParts[2])
  125. if (typeof page != "number" || page > pageMax || page < 0) {
  126. page = 0
  127. }
  128. }
  129. if (hashParts.length >= 2 && (hashParts[1] != currentFolder || currentPage != page) && hashParts[1] != "") {
  130. updateMailList(hashParts[1], page)
  131. }
  132. if (hashParts.length >= 4 && hashParts[3] != "" && hashParts[3] != "/mailNew") {
  133. if (currentMail != hashParts[3]) {
  134. requestMail(hashParts[3])
  135. }
  136. } else {
  137. setDetailsVisible(false)
  138. }
  139. hashParts = hashLocation.split("/")
  140. if (hashParts.length == 2 && hashParts[1] == "mailNew") {
  141. setMailNewVisible(true)
  142. } else {
  143. setMailNewVisible(false)
  144. }
  145. }
  146. function requestMail(mailId) {
  147. if (mailId != "") {
  148. $.ajax({
  149. url: "/mail",
  150. data: {
  151. mailId: mailId
  152. },
  153. success: function(result) {
  154. currentMail = mailId
  155. $("#mail"+mailId).removeClass("unread")
  156. $("#mail"+mailId).addClass("read")
  157. $("#mailDetails").html(result);
  158. setDetailsVisible(true);
  159. folderStat(currentFolder);//TODO: receive statistic from websocket
  160. },
  161. error: function(jqXHR, textStatus, errorThrown) {
  162. $("#mailDetails").html(textStatus)
  163. setDetailsVisible(true)
  164. }
  165. })
  166. }
  167. }
  168. function loadFolders() {
  169. if (mailbox == "") {
  170. $("#folders").html("Unable to load folder list")
  171. return
  172. }
  173. $.ajax({
  174. url: mailbox + "/folders",
  175. success: function(result) {
  176. folderList = jQuery.parseJSON(result)
  177. for(var i = 0; i < folderList.folders.length; i++) {
  178. folders.push(folderList.folders[i].name)
  179. folderStat(folderList.folders[i].name)
  180. }
  181. $("#folders").html(folderList.html)
  182. },
  183. error: function(jqXHR, textStatus, errorThrown) {
  184. //TODO: some toast message here once implemented
  185. }
  186. })
  187. }
  188. function folderStat(folder) {
  189. $.ajax({
  190. url: mailbox + "/folderStat",
  191. data: {
  192. folder: folder
  193. },
  194. success: function(result) {
  195. var stats = jQuery.parseJSON(result)
  196. if (stats.unread > 0) {
  197. $("#folderStats"+folder).text(stats.unread)
  198. $("#folder"+folder).addClass("unread")
  199. } else {
  200. $("#folder"+folder).removeClass("unread")
  201. $("#folderStats"+folder).text("")
  202. }
  203. },
  204. error: function(jqXHR, textStatus, errorThrown) {
  205. //TODO: some toast message here once implemented
  206. }
  207. })
  208. }
  209. function closeDetails() {
  210. window.location.hash = currentFolder + currentPage
  211. }
  212. function closeMailNew() {
  213. window.location.hash = currentFolder + currentPage
  214. }
  215. function loadStatusLine() {
  216. $.ajax({
  217. url: mailbox + "/statusLine",
  218. success: function(result) {
  219. $("#statusLine").html(result)
  220. },
  221. error: function(jqXHR, textStatus, errorThrown) {
  222. //TODO: some toast message here once implemented
  223. }
  224. })
  225. }
  226. function localDate(elementToChange, timestamp) {
  227. var today = new Date()
  228. var date = new Date(timestamp*1000)
  229. dateString = ""
  230. if (today.getDay() == date.getDay()
  231. && today.getMonth() == date.getMonth()
  232. && today.getFullYear() == date.getFullYear()) {
  233. dateString = date.toLocaleTimeString("en-US")
  234. } else if (today.getFullYear() == date.getFullYear()) {
  235. const options = { day: 'numeric', month: 'short' }
  236. dateString = date.toLocaleDateString("en-US", options)
  237. } else {
  238. dateString = date.toLocaleDateString("en-US")
  239. }
  240. $("#"+elementToChange).text(dateString)
  241. }
  242. function setRead(mailId, read) {
  243. $.ajax({
  244. url: "/setRead",
  245. data: {mailId: mailId,
  246. read: read},
  247. success: function(result) {
  248. if (read) {
  249. if ($("#readIcon"+mailId)) {
  250. $("#readIcon"+mailId).attr("src", "/assets/read.svg")
  251. }
  252. if ($("#readListIcon"+mailId)) {
  253. $("#readListIcon"+mailId).attr("src", "/assets/read.svg")
  254. }
  255. $("#mail"+mailId).removeClass("unread")
  256. $("#mail"+mailId).addClass("read")
  257. } else {
  258. if ($("#readIcon"+mailId)) {
  259. $("#readIcon"+mailId).attr("src", "/assets/unread.svg")
  260. }
  261. if ($("#readListIcon"+mailId)) {
  262. $("#readListIcon"+mailId).attr("src", "/assets/unread.svg")
  263. }
  264. $("#mail"+mailId).removeClass("read")
  265. $("#mail"+mailId).addClass("unread")
  266. }
  267. folderStat(currentFolder);//TODO: receive statistic from websocket
  268. },
  269. error: function(jqXHR, textStatus, errorThrown) {
  270. }
  271. })
  272. }
  273. function toggleRead(mailId, iconId) {
  274. if ($("#"+iconId+mailId)) {
  275. setRead(mailId, $("#"+iconId+mailId).attr("src") == "/assets/unread.svg")
  276. }
  277. }
  278. function removeMail(mailId, callback) {
  279. var url = currentFolder != "Trash" ? "/remove" : "/delete"
  280. $.ajax({
  281. url: url,
  282. data: {mailId: mailId},
  283. success: function(result) {
  284. $("#mail"+mailId).remove();
  285. if (callback) {
  286. callback();
  287. }
  288. folderStat(currentFolder);//TODO: receive statistic from websocket
  289. folderStat("Trash");//TODO: receive statistic from websocket
  290. },
  291. error: function(jqXHR, textStatus, errorThrown) {
  292. }
  293. })
  294. }
  295. function restoreMail(mailId, callback) {
  296. var url = "/restore"
  297. $.ajax({
  298. url: url,
  299. data: {mailId: mailId},
  300. success: function(result) {
  301. if (currentFolder == "Trash") {
  302. $("#mail"+mailId).remove();
  303. }
  304. if (callback) {
  305. callback();
  306. }
  307. for (var i = 0; i < folders.length; i++) {
  308. folderStat(folders[i])
  309. }
  310. },
  311. error: function(jqXHR, textStatus, errorThrown) {
  312. }
  313. })
  314. }
  315. function setDetailsVisible(visible) {
  316. if (visible) {
  317. $("#mailDetails").show()
  318. $("#mailList").css({pointerEvents: "none"})
  319. } else {
  320. currentMail = ""
  321. $("#mailDetails").hide()
  322. $("#mailDetails").html("")
  323. $("#mailList").css({pointerEvents: "auto"})
  324. }
  325. }
  326. function setMailNewVisible(visible) {
  327. if (visible) {
  328. $("#mailNew").show()
  329. $("#mailList").css({pointerEvents: "none"})
  330. } else {
  331. currentMail = ""
  332. $("#mailNew").hide()
  333. $("#mailList").css({pointerEvents: "auto"})
  334. }
  335. }
  336. function updateMailList(folder, page) {
  337. if (mailbox == "" || folder == "") {
  338. if ($("#mailList")) {
  339. $("#mailList").html("Unable to load message list")
  340. }
  341. return
  342. }
  343. $.ajax({
  344. url: mailbox + "/mailList",
  345. data: {
  346. folder: folder,
  347. page: page
  348. },
  349. success: function(result) {
  350. var data = jQuery.parseJSON(result)
  351. pageMax = Math.floor(data.total/50)
  352. if ($("#mailList")) {
  353. $("#mailList").html(data.html)
  354. }
  355. currentFolder = folder
  356. currentPage = page
  357. if($("#currentPageIndex")) {
  358. $("#currentPageIndex").text(currentPage + 1)
  359. }
  360. if($("#totalPageCount")) {
  361. $("#totalPageCount").text(pageMax + 1)
  362. }
  363. },
  364. error: function(jqXHR, textStatus, errorThrown) {
  365. if ($("#mailList")) {
  366. $("#mailList").html("Unable to load message list")
  367. }
  368. }
  369. })
  370. }
  371. function nextPage() {
  372. var newPage = currentPage < (pageMax - 1) ? currentPage + 1 : pageMax
  373. window.location.hash = currentFolder + newPage
  374. }
  375. function prevPage() {
  376. var newPage = currentPage > 0 ? currentPage - 1 : 0
  377. window.location.hash = currentFolder + newPage
  378. }
  379. function toggleDropDown(dd) {
  380. $("#"+dd).toggle()
  381. }
  382. function sendNewMail() {
  383. var composedEmailString = toEmailList[0]
  384. for(var i = 1; i < toEmailList.length; i++) {
  385. composedEmailString += "," + toEmailList[i]
  386. }
  387. $("#newMailTo").val(composedEmailString)
  388. var formValue = $("#mailNewForm").serialize()
  389. console.log("formValue: " + formValue)
  390. $.ajax({
  391. url: mailbox + "/sendNewMail",
  392. data: formValue,
  393. success: function(result) {
  394. $("#newMailEditor").val("")
  395. $("#newMailSubject").val("")
  396. $("#newMailTo").val("")
  397. closeMailNew()
  398. },
  399. error: function(jqXHR, textStatus, errorThrown) {
  400. //TODO: some toast message here once implemented
  401. }
  402. })
  403. }
  404. function logout() {
  405. window.location.href = "/logout"
  406. }
  407. function connectNotifier() {
  408. if (notifierSocket != null) {
  409. return
  410. }
  411. var protocol = "wss://"
  412. if(window.location.protocol !== "https:") {
  413. protocol = "ws://"
  414. }
  415. notifierSocket = new WebSocket(protocol + window.location.host + mailbox + "/notifierSubscribe")
  416. notifierSocket.onopen = function() {
  417. };
  418. notifierSocket.onmessage = function (e) {
  419. for (var i = 0; i < folders.length; i++) {
  420. folderStat(folders[i])
  421. }
  422. updateMailList(currentFolder, currentPage)
  423. }
  424. notifierSocket.onclose = function () {
  425. }
  426. }
  427. window.onbeforeunload = function() {
  428. if (notifierSocket != null) {
  429. notifierSocket.onclose = function () {}; // disable onclose handler first
  430. notifierSocket.close();
  431. }
  432. };