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