]> code.citadel.org Git - citadel.git/blob - webcit-ng/static/js/view_mail.js
0cbd527058b16c9bd4a93929705ff3837c3ab4a0
[citadel.git] / webcit-ng / static / js / view_mail.js
1 // This module handles the view for "mailbox" rooms.
2 //
3 // Copyright (c) 2016-2022 by the citadel.org team
4 //
5 // This program is open source software.  Use, duplication, or
6 // disclosure are subject to the GNU General Public License v3.
7
8
9 var displayed_message = 0;                                                      // ID of message currently being displayed
10 var RefreshMailboxInterval;                                                     // We store our refresh timer here
11 var highest_mailnum;                                                            // This is used to detect newly arrived mail
12 var newmail_notify = {
13         NO  : 0,                                                                // do not perform new mail notifications
14         YES : 1                                                                 // yes, perform new mail notifications
15 };
16
17
18 // This is the async back end for mail_delete_selected()
19 mail_delete_func = async(table, row) => {
20         let m = parseInt(row["id"].substring(12));      // derive msgnum from row id
21         response = await fetch(
22                 "/ctdl/r/" + escapeHTMLURI(current_room) + "/" + m,
23                 {
24                         method: "MOVE",
25                         headers: { "Destination" : "/ctdl/r/_TRASH_" }
26                 },
27         );
28         if (response.ok) {                              // If the server accepted the delete, blank out the message div.
29                 table.deleteRow(row.rowIndex);
30                 if (m == displayed_message) {
31                         document.getElementById("ctdl-mailbox-reading-pane").innerHTML = "";
32                         displayed_message = 0;
33                 }
34         }
35 }
36
37
38 // Delete the selected messages (can be activated by mouse click or keypress)
39 function mail_delete_selected() {
40         var table = document.getElementById("ctdl-onscreen-mailbox");
41         var i, row;
42         for (i=0; row=table.rows[i]; ++i) {
43                 if (row.classList.contains("ctdl-mail-selected")) {
44                         mail_delete_func(table, row);
45                 }
46         }
47 }
48
49
50 // Handler function for keypresses detected while the mail view is displayed.  Mainly for deleting messages.
51 function mail_keypress(event) {
52
53         // If the "ctdl-mailbox-pane" no longer exists, the user has navigated to a different part of the site,
54         // so cancel the event listener.
55         try {
56                 document.getElementById("ctdl-mailbox-pane").innerHTML;
57         }
58         catch {
59                 document.removeEventListener("keydown", mail_keypress);
60                 return;
61         }
62
63         const key = event.key.toLowerCase();
64         if (key == "delete") {
65                 mail_delete_selected();
66         }
67
68 }
69
70
71 // Render reply address for a message (FIXME figure out how to deal with "reply-to:")
72 function reply_addr(msg) {
73         //if (msg.locl) {
74                 //return([msg.from]);
75         //}
76         //else {
77                 return([msg.from + " <" + msg.rfca + ">"]);
78         //}
79 }
80
81
82 // Render the To: recipients for a reply-all operation
83 function replyall_to(msg) {
84         return([...reply_addr(msg), ...msg.rcpt]);
85 }
86
87
88 // Render a message into the mailbox view
89 // (We want the message number and the message itself because we need to keep the msgnum for reply purposes)
90 function mail_render_one(msgnum, msg, target_div, include_controls) {
91         let div = "";
92         try {
93                 outmsg =
94                   "<div class=\"ctdl-mmsg-wrapper\">"                           // begin message wrapper
95                 ;
96
97                 if (include_controls) {                                         // omit controls if this is a pull quote
98                         outmsg +=
99                           render_userpic(msg.from)                              // user avatar
100                         + "<div class=\"ctdl-mmsg-content\">"                   // begin content
101                         + "<div class=\"ctdl-msg-header\">"                     // begin header
102                         + "<span class=\"ctdl-msg-header-info\">"               // begin header info on left side
103                         + render_msg_author(msg, views.VIEW_MAILBOX)
104                         + "<span class=\"ctdl-msgdate\">"
105                         + string_timestamp(msg.time,0)
106                         + "</span>"                                             // end msgdate
107                         + "</span>"                                             // end header info on left side
108                         + "<span class=\"ctdl-msg-header-buttons\">"            // begin buttons on right side
109                 
110                         + "<span class=\"ctdl-msg-button\">"                    // Reply (mail is always Quoted)
111                         + "<a href=\"javascript:mail_compose(true,'"+msg.wefw+"','"+msgnum+"', reply_addr(msg), [], 'Re: '+msg.subj);\">"
112                         + "<i class=\"fa fa-reply\"></i> " 
113                         + _("Reply")
114                         + "</a></span>"
115                 
116                         + "<span class=\"ctdl-msg-button\">"                    // Reply-All (mail is always Quoted)
117                         + "<a href=\"javascript:mail_compose(true,'"+msg.wefw+"','"+msgnum+"', replyall_to(msg), msg.cccc, 'Re: '+msg.subj);\">"
118                         + "<i class=\"fa fa-reply-all\"></i> " 
119                         + _("ReplyAll")
120                         + "</a></span>";
121                 
122                         if (can_delete_messages) {
123                                 outmsg +=
124                                 "<span class=\"ctdl-msg-button\">"
125                                 + "<a href=\"javascript:forum_delete_message('"+div+"','"+msg.msgnum+"');\">"
126                                 + "<i class=\"fa fa-trash\"></i> " 
127                                 + _("Delete")
128                                 + "</a></span>";
129                         }
130                 
131                         outmsg +=
132                           "</span>";                                            // end buttons on right side
133
134                         // Display the To: recipients, if any are present
135                         if (msg.rcpt) {
136                                 outmsg += "<br><span>" + _("To:") + " ";
137                                 for (var r=0; r<msg.rcpt.length; ++r) {
138                                         if (r != 0) {
139                                                 outmsg += ", ";
140                                         }
141                                         outmsg += escapeHTML(msg.rcpt[r]);
142                                 }
143                                 outmsg += "</span>";
144                         }
145
146                         // Display the Cc: recipients, if any are present
147                         if (msg.cccc) {
148                                 outmsg += "<br><span>" + _("Cc:") + " ";
149                                 for (var r=0; r<msg.cccc.length; ++r) {
150                                         if (r != 0) {
151                                                 outmsg += ", ";
152                                         }
153                                         outmsg += escapeHTML(msg.cccc[r]);
154                                 }
155                                 outmsg += "</span>";
156                         }
157
158                         // Display a subject line, but only if the message has a subject (internal Citadel messages often don't)
159                         if (msg.subj) {
160                                 outmsg +=
161                                 "<br><span class=\"ctdl-msgsubject\">" + msg.subj + "</span>";
162                         }
163
164                         outmsg +=
165                           "</div>";                                             // end header
166                 }
167
168                 outmsg +=
169                   "<div class=\"ctdl-msg-body\" id=\"" + div + "_body\">"       // begin body
170                 + msg.text
171                 + "</div>"                                                      // end body
172                 + "</div>"                                                      // end content
173                 + "</div>"                                                      // end wrapper
174                 ;
175         }
176         catch(err) {
177                 outmsg = "<div class=\"ctdl-mmsg-wrapper\">" + err.message + "</div>";
178         }
179
180         target_div.innerHTML = outmsg;
181 }
182
183
184 // display an individual message (note: this wants an actual div object, not a string containing the name of a div)
185 function mail_display_message(msgnum, target_div, include_controls) {
186         url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/" + msgnum + "/json";
187         mail_fetch_msg = async() => {
188                 response = await fetch(url);
189                 msg = await(response.json());
190                 if (response.ok) {
191                         mail_render_one(msgnum, msg, target_div, include_controls);
192                 }
193         }
194         mail_fetch_msg();
195 }
196
197
198 // A message has been selected...
199 function click_message(event, msgnum) {
200         var table = document.getElementById("ctdl-onscreen-mailbox");
201         var i, m, row;
202
203         // ctrl + click = toggle an individual message without changing existing selection
204         if (event.ctrlKey) {
205                 document.getElementById("ctdl-msgsum-" + msgnum).classList.toggle("ctdl-mail-selected");
206         }
207
208         // shift + click = select a range of messages
209         else if (event.shiftKey) {
210                 for (i=0; row=table.rows[i]; ++i) {
211                         m = parseInt(row["id"].substring(12));                          // derive msgnum from row id
212                         if (
213                                 ((msgnum >= displayed_message) && (m >= displayed_message) && (m <= msgnum))
214                                 || ((msgnum <= displayed_message) && (m <= displayed_message) && (m >= msgnum))
215                         ) {
216                                 row.classList.add("ctdl-mail-selected");
217                         }
218                         else {
219                                 row.classList.remove("ctdl-mail-selected");
220                         }
221                 }
222         }
223
224         // click + no modifiers = select one message and unselect all others
225         else {
226                 for (i=0; row=table.rows[i]; ++i) {
227                         if (row["id"] == "ctdl-msgsum-" + msgnum) {
228                                 row.classList.add("ctdl-mail-selected");
229                         }
230                         else {
231                                 row.classList.remove("ctdl-mail-selected");
232                         }
233                 }
234         }
235
236         // display the message if it isn't already displayed
237         if (displayed_message != msgnum) {
238                 displayed_message = msgnum;
239                 mail_display_message(msgnum, document.getElementById("ctdl-mailbox-reading-pane"), 1);
240         }
241 }
242
243
244 // render one row in the mailbox table (this could be called from one of several places)
245 function mail_render_row(msg, is_selected) {
246         row     = "<tr "
247                 + "id=\"ctdl-msgsum-" + msg["msgnum"] + "\" "
248                 + (is_selected ? "class=\"ctdl-mail-selected\" " : "")
249                 + "onClick=\"click_message(event," + msg["msgnum"] + ");\""
250                 + "onselectstart=\"return false;\""
251                 + ">"
252                 + "<td class=\"ctdl-mail-subject\">" + msg["subject"] + "</td>"
253                 + "<td class=\"ctdl-mail-sender\">" + msg["author"] + "</td>"
254                 + "<td class=\"ctdl-mail-date\">" + string_timestamp(msg["time"],1) + "</td>"
255                 + "<td class=\"ctdl-mail-msgnum\">" + msg["msgnum"] + "</td>"
256                 + "</tr>";
257         return(row);
258 }
259
260
261 // RENDERER FOR THIS VIEW
262 function view_render_mail() {
263         // Put the "enter new message" button into the topbar
264         document.getElementById("ctdl-newmsg-button").innerHTML = "<i class=\"fa fa-edit\"></i>" + _("Write mail");
265         document.getElementById("ctdl-newmsg-button").style.display = "block";
266
267         // Put the "delete message(s)" button into the topbar
268         let d = document.getElementById("ctdl-delete-button");
269         d.innerHTML = "<i class=\"fa fa-trash\"></i>" + _("Delete");
270         d.style.display = "block";
271         //d.addEventListener("click", mail_delete_selected);
272
273         document.getElementById("ctdl-main").innerHTML
274                 = "<div id=\"ctdl-mailbox-grid-container\" class=\"ctdl-mailbox-grid-container\">"
275                 + "<div id=\"ctdl-mailbox-pane\" class=\"ctdl-mailbox-pane\"></div>"
276                 + "<div id=\"ctdl-mailbox-reading-pane\" class=\"ctdl-mailbox-reading-pane\"></div>"
277                 + "</div>"
278         ;
279
280         highest_mailnum = 0;                                    // Keep track of highest message number to track newly arrived messages
281         render_mailbox_display(newmail_notify.NO);
282         try {                                                   // if this was already set up, clear it so there aren't multiple
283                 clearInterval(RefreshMailboxInterval);
284         }
285         catch {
286         }
287         RefreshMailboxInterval = setInterval(refresh_mail_display, 10000);
288 }
289
290
291 // Refresh the mailbox, either for the first time or whenever needed
292 function refresh_mail_display() {
293         // If the "ctdl-mailbox-pane" no longer exists, the user has navigated to a different part of the site,
294         // so cancel the refresh.
295         try {
296                 document.getElementById("ctdl-mailbox-pane").innerHTML;
297         }
298         catch {
299                 clearInterval(RefreshMailboxInterval);
300                 return;
301         }
302
303         // Ask the server if the room has been written to since our last look at it.
304         url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/stat";
305         fetch_stat = async() => {
306                 response = await fetch(url);
307                 stat = await(response.json());
308                 if (stat.room_mtime > room_mtime) {                     // FIXME commented out to force refreshes
309                         room_mtime = stat.room_mtime;
310                         render_mailbox_display(newmail_notify.YES);
311                 }
312         }
313         fetch_stat();
314 }
315
316
317 // This is where the rendering of the message list in the mailbox view is performed.
318 // Set notify to newmail_notify.NO or newmail_notify.YES depending on whether we are interested in the arrival of new messages.
319 function render_mailbox_display(notify) {
320
321         url = "/ctdl/r/" + escapeHTMLURI(current_room) + "/mailbox";
322         fetch_mailbox = async() => {
323                 response = await fetch(url);
324                 msgs = await(response.json());
325                 if (response.ok) {
326                         var previously_selected = [];
327                         var oldtable = document.getElementById("ctdl-onscreen-mailbox");
328                         var i, row;
329
330                         // If one or more messages was already selected, remember them so we can re-select them
331                         if ( (displayed_message > 0) && (oldtable) ) {
332                                 for (i=0; row=oldtable.rows[i]; ++i) {
333                                         if (row.classList.contains("ctdl-mail-selected")) {
334                                                 previously_selected.push(parseInt(row["id"].substring(12)));
335                                         }
336                                 }
337                         }
338
339                         // begin rendering the mailbox table
340                         box =   "<table id=\"ctdl-onscreen-mailbox\" class=\"ctdl-mailbox-table\" width=100%><tr>"
341                                 + "<th>" + _("Subject") + "</th>"
342                                 + "<th>" + _("Sender") + "</th>"
343                                 + "<th>" + _("Date") + "</th>"
344                                 + "<th>#</th>"
345                                 + "</tr>";
346
347                         for (let i=0; i<msgs.length; ++i) {
348                                 let m = parseInt(msgs[i].msgnum);
349                                 let s = (previously_selected.includes(m));
350                                 box += mail_render_row(msgs[i], s);
351                                 if (m > highest_mailnum) {
352                                         highest_mailnum = m;
353                                 }
354                         }
355
356                         box +=  "</table>";
357                         document.getElementById("ctdl-mailbox-pane").innerHTML = box;
358                         document.addEventListener("keydown", mail_keypress);
359                 }
360         }
361         fetch_mailbox();
362 }
363
364
365 // Compose a new mail message (called by the Reply button here, or by the dispatcher in views.js)
366 function mail_compose(is_quoted, references, quoted_msgnum, m_to, m_cc, m_subject) {
367         // m_to will be an array of zero or more recipients for the To: field.  Convert it to a string.
368         if (m_to) {
369                 m_to = Array.from(new Set(m_to));       // remove dupes
370                 m_to_str = "";
371                 for (i=0; i<m_to.length; ++i) {
372                         if (i > 0) {
373                                 m_to_str += ", ";
374                         }
375                         m_to_str += m_to[i].replaceAll("<", "&lt;").replaceAll(">", "&gt;");
376                 }
377         }
378         else {
379                 m_to_str = "";
380         }
381
382         // m_to will be an array of zero or more recipients for the Cc: field.  Convert it to a string.
383         if (m_cc) {
384                 m_cc = Array.from(new Set(m_cc));       // remove dupes
385                 m_cc_str = "";
386                 for (i=0; i<m_cc.length; ++i) {
387                         if (i > 0) {
388                                 m_cc_str += ", ";
389                         }
390                         m_cc_str += m_cc[i].replaceAll("<", "&lt;").replaceAll(">", "&gt;");
391                 }
392         }
393         else {
394                 m_cc_str = "";
395         }
396
397         quoted_div_name = randomString();
398
399         // Make the "Write mail" button disappear.  We're already there!
400         document.getElementById("ctdl-newmsg-button").style.display = "none";
401
402         // is_quoted    true or false depending on whether the user selected "reply quoted" (is this appropriate for mail?)
403         // references   list of references, be sure to use this in a reply
404         // msgid        if a reply, the msgid of the most recent message in the chain, the one to which we are replying
405
406         // Now display the screen.
407         compose_screen =
408                 // Hidden values that we are storing right here in the document tree for later
409                   "<input id=\"ctdl_mc_is_quoted\" style=\"display:none\" value=\"" + is_quoted + "\"></input>"
410                 + "<input id=\"ctdl_mc_references\" style=\"display:none\" value=\"" + references + "\"></input>"
411
412                 // Header fields, the composition window, and the button bar are arranged using a Grid layout.
413                 + "<div id=\"ctdl-compose-mail\" class=\"ctdl-compose-mail\">"
414
415                 // Visible To: field, plus a box to make the CC/BCC lines appear
416                 + "<div class=\"ctdl-compose-to-label\">" + _("To:") + "</div>"
417                 + "<div class=\"ctdl-compose-to-line\">"
418                 + "<div class=\"ctdl-compose-to-field\" id=\"ctdl-compose-to-field\" contenteditable=\"true\">" + m_to_str + "</div>"
419                 + "<div class=\"ctdl-cc-bcc-buttons ctdl-msg-button\" id=\"ctdl-cc-bcc-buttons\" "
420                 + "onClick=\"make_cc_bcc_visible()\">"
421                 + _("CC:") + "/" + _("BCC:") + "</div>"
422                 + "</div>"
423
424                 // CC/BCC
425                 + "<div class=\"ctdl-compose-cc-label\" id=\"ctdl-compose-cc-label\">" + _("CC:") + "</div>"
426                 + "<div class=\"ctdl-compose-cc-field\" id=\"ctdl-compose-cc-field\" contenteditable=\"true\">" + m_cc_str + "</div>"
427                 + "<div class=\"ctdl-compose-bcc-label\" id=\"ctdl-compose-bcc-label\">" + _("BCC:") + "</div>"
428                 + "<div class=\"ctdl-compose-bcc-field\" id=\"ctdl-compose-bcc-field\" contenteditable=\"true\"></div>"
429
430                 // Visible subject field
431                 + "<div class=\"ctdl-compose-subject-label\">" + _("Subject:") + "</div>"
432                 + "<div class=\"ctdl-compose-subject-field\" id=\"ctdl-compose-subject-field\" contenteditable=\"true\">" + m_subject + "</div>"
433
434                 // Message composition box
435                 + "<div class=\"ctdl-compose-message-box\" id=\"ctdl-editor-body\" contenteditable=\"true\">"
436         ;
437
438         if (is_quoted) {
439                 compose_screen += "<br><br><blockquote><div id=\"" + quoted_div_name + "\"></div></blockquote>";
440         }
441
442         compose_screen +=
443                   "</div>"
444
445                 // The button bar is a Grid element, and is also a Flexbox container.
446                 + "<div class=\"ctdl-compose-toolbar\">"
447                 + "<span class=\"ctdl-msg-button\" onclick=\"mail_send_message()\"><i class=\"fa fa-paper-plane\" style=\"color:green\"></i> " + _("Send message") + "</span>"
448                 + "<span class=\"ctdl-msg-button\">" + _("Save to Drafts") + "</span>"
449                 + "<span class=\"ctdl-msg-button\">" + _("Attachments:") + " 0" + "</span>"
450                 + "<span class=\"ctdl-msg-button\">" + _("Contacts") + "</span>"
451                 + "<span class=\"ctdl-msg-button\" onClick=\"gotoroom(current_room)\"><i class=\"fa fa-trash\" style=\"color:red\"></i> " + _("Cancel") + "</span>"
452                 + "</div>"
453         ;
454
455         document.getElementById("ctdl-main").innerHTML = compose_screen;
456         mail_display_message(quoted_msgnum, document.getElementById(quoted_div_name), 0);
457         if (m_cc) {
458                 document.getElementById("ctdl-compose-cc-label").style.display = "block";
459                 document.getElementById("ctdl-compose-cc-field").style.display = "block";
460         }
461 }
462
463
464 // Called when the user clicks the button to make the hidden "CC" and "BCC" lines appear.
465 // It is also called automatically during a Reply when CC is pre-populated.
466 function make_cc_bcc_visible() {
467         document.getElementById("ctdl-cc-bcc-buttons").style.display = "none";
468         document.getElementById("ctdl-compose-bcc-label").style.display = "block";
469         document.getElementById("ctdl-compose-bcc-field").style.display = "block";
470 }
471
472
473 // Helper function for mail_send_messages() to extract and decode metadata values.
474 function msm_field(element_name, separator) {
475         let s1 = document.getElementById(element_name).innerHTML;
476         let s2 = s1.replaceAll("|",separator);          // Replace "|" with "!" because "|" is a field separator in Citadel wire protocol
477         let s3 = decodeURI(s2);
478         let s4 = document.createElement("textarea");    // This One Weird Trick Unescapes All HTML Entities
479         s4.innerHTML = s3;
480         let s5 = s4.value;
481         return(s5);
482 }
483
484
485 // Save the posted message to the server
486 function mail_send_message() {
487
488         document.body.style.cursor = "wait";
489         let url = "/ctdl/r/" + escapeHTMLURI(current_room)
490                 + "/dummy_name_for_new_mail"
491                 + "?wefw="      + msm_field("ctdl_mc_references", "!")                          // references (if present)
492                 + "&subj="      + msm_field("ctdl-compose-subject-field", " ")                  // subject (if present)
493                 + "&mailto="    + msm_field("ctdl-compose-to-field", ",")                       // To: (required)
494                 + "&mailcc="    + msm_field("ctdl-compose-cc-field", ",")                       // Cc: (if present)
495                 + "&mailbcc="   + msm_field("ctdl-compose-bcc-field", ",")                      // Bcc: (if present)
496         ;
497         boundary = randomString();
498         body_text =
499                 "--" + boundary + "\r\n"
500                 + "Content-type: text/html\r\n"
501                 + "Content-transfer-encoding: quoted-printable\r\n"
502                 + "\r\n"
503                 + quoted_printable_encode(
504                         "<html><body>" + document.getElementById("ctdl-editor-body").innerHTML + "</body></html>"
505                 ) + "\r\n"
506                 + "--" + boundary + "--\r\n"
507         ;
508
509         var request = new XMLHttpRequest();
510         request.open("PUT", url, true);
511         request.setRequestHeader("Content-type", "multipart/mixed; boundary=\"" + boundary + "\"");
512         request.onreadystatechange = function() {
513                 if (request.readyState == 4) {
514                         document.body.style.cursor = "default";
515                         if (Math.trunc(request.status / 100) == 2) {
516                                 headers = request.getAllResponseHeaders().split("\n");
517                                 for (var i in headers) {
518                                         if (headers[i].startsWith("etag: ")) {
519                                                 new_msg_num = headers[i].split(" ")[1];
520                                         }
521                                 }
522
523                                 // After saving the message, go back to the mailbox view.
524                                 gotoroom(current_room);
525
526                         }
527                         else {
528                                 error_message = request.responseText;
529                                 if (error_message.length == 0) {
530                                         error_message = _("An error has occurred.");
531                                 }
532                                 alert(error_message);                                           // editor remains open
533                         }
534                 }
535         };
536         request.send(body_text);
537 }