]> git.aero2k.de Git - dfde/quickmods.git/blob - quickmod.user.js
JTH: ban user, close mod notification
[dfde/quickmods.git] / quickmod.user.js
1 // ==UserScript==
2 // @name          debianforum.de-quickmod-additions
3 // @namespace     org.free.for.all
4 // @include       https://debianforum.de/forum/viewtopic.php*
5 // @match         https://debianforum.de/forum/viewtopic.php*
6 // @author        Thorsten Sperber
7 // @author        JTH
8 // @version       1.3
9 // ==/UserScript==
10
11 const ARCHIVFORUMID = 35;
12
13 async function banUser(username, reason) {
14     /* The URL to the ban form does not need any IDs or hidden inputs. We
15      * hardcode it here.
16      */
17     let resp = await fetch("./mcp.php?i=ban&mode=user");
18     if (!resp.ok) {
19         throw "Konnte Formular zum Sperren von Benutzern nicht laden.";
20     }
21
22     let form, formData;
23     try {
24         [form, formData] = await openForm(resp, "form#mcp_ban");
25     } catch {
26         throw "Konnte Formular zum Sperren von Benutzern nicht öffnen.";
27     }
28
29     formData.set("ban", username);
30     formData.set("banreason", reason);
31     //formData.set("bangivereason", reason);
32     resp = await postForm(form, formData, "bansubmit");
33     if (!resp.ok) {
34         throw "Konnte Sperrung des Benutzers nicht anfragen.";
35     }
36
37     try {
38         await confirmAction(resp);
39     } catch (err) {
40         throw `Konnte Sperrung des Benutzers nicht bestätigen: ${err}`;
41     }
42 }
43
44 async function closeReport(post) {
45     const reportLink = post.querySelector(".post-notice.reported a");
46
47     let resp = await fetch(reportLink.href);
48     if (!resp.ok) {
49         throw "Konnte Meldung nicht öffnen.";
50     }
51
52     let form, formData;
53     try {
54         [form, formData] = await openForm(resp, "form#mcp_report");
55     } catch {
56         throw "Konnte Formular zum Schließen der Meldung nicht öffnen.";
57     }
58
59     resp = await postForm(form, formData, "action[close]");
60     if (!resp.ok) {
61         throw "Konnte Schließen der Meldung nicht anfragen.";
62     }
63
64     try {
65         await confirmAction(resp);
66     } catch (err) {
67         throw `Konnte Schließen der Meldung nicht bestätigen: ${err}`;
68     }
69 }
70
71 async function confirmAction(response) {
72     const [form, formData] = await openForm(response, "form#confirm");
73
74     /* Have to use explicit getAttribute() below since there is an input with
75      * name="action" which would be accessed with `form.action` :-/
76      */
77     const resp = await postForm(form, formData, "confirm");
78     if (!resp.ok) {
79         throw `${resp.url}: ${resp.status}`;
80     }
81     return await resp.text();
82 }
83
84 function ellipsify(str, maxlen) {
85     const ell = str.length > maxlen ? " […]" : "";
86     return str.substring(0, maxlen - ell.length) + ell;
87 }
88
89 function isPostReported(post) {
90     return post.querySelector(".post-notice.reported a") !== null;
91 }
92
93 async function openForm(response, selector) {
94     const parser = new DOMParser();
95     const txt = await response.text();
96     const doc = parser.parseFromString(txt, "text/html");
97     const form = doc.querySelector(selector);
98     return [form, new FormData(form)];
99 }
100
101 function postForm(form, formData, submitName) {
102     /* "Press" the right submit button. */
103     const submitBtn = form.elements[submitName];
104     formData.set(submitBtn.name, submitBtn.value);
105
106     /* Have to use explicit getAttribute() below since there is an input with
107      * name="action" which would be accessed with `form.action` :-/
108      */
109     return fetch(form.getAttribute("action"),
110         { body: new URLSearchParams(formData), method: "POST" });
111 }
112
113 async function remove_post_handler(event) {
114     const post = event.currentTarget.closest('.post');
115     const username = post.querySelector(".author .username,.author .username-coloured").text;
116     const thread_title = document.querySelector('.topic-title a').text;
117     const content = ellipsify(post.querySelector(".content").innerText, 250);
118
119     const splitReason = window.prompt(`Folgenden Beitrag von „${username}“ im Thema „${ellipsify(thread_title, 100)}“ wirklich als Spam archivieren?\n\n„${content}“\n\nGrund:`, "Spam");
120     if (splitReason === null) {
121         /* Don't do any of the other actions if splitting was cancelled. */
122         return;
123     }
124
125     /* Prompting for a separate ban reason in case there is something more
126      * specific to note here.
127      */
128     const banReason = window.prompt(`Benutzer „${username}“ sperren?\n\nGrund:`, "Spam");
129     const shouldCloseReport = isPostReported(post) && window.confirm("Meldung zum Beitrag schließen?");
130
131     /* Initially, I wanted to use Promise.allSettled() below to trigger and wait
132      * for all actions in parallel. But that made at least one of them fail in
133      * most cases. Not sure, if there was a mistake in here somewhere (totally
134      * not impossible) or if phpBB just does not cope well with parallel mod
135      * actions (there are some session IDs and confirm_keys involved when a mod
136      * action is executed and confirmed).
137      *
138      * So essentially, we do not have any asynchronous execution here,
139      * unfortunately.
140      */
141     const errors = new Array();
142     try {
143         await send_mcp_request_archival(post, splitReason);
144     } catch (err) {
145         errors.push(err);
146     }
147
148     if (banReason !== null) {
149         try {
150             await banUser(username, banReason);
151         } catch (err) {
152             errors.push(err);
153         }
154     }
155
156     if (shouldCloseReport) {
157         try {
158             await closeReport(post);
159         } catch (err) {
160             errors.push(err);
161         }
162     }
163
164     for (const error of errors) {
165         console.log(error);
166         window.alert(`ACHTUNG!\n\n${error}`);
167     }
168
169     if (errors.length === 0) {
170         updatePageAfterSplit(post);
171     }
172 }
173
174 async function send_mcp_request_archival(post, reason) {
175     const splitLink = document.querySelector("#quickmod .dropdown-contents a[href*='action=split']");
176     let resp = await fetch(splitLink.href);
177     if (!resp.ok) {
178         throw "Konnte Formular zum Aufteilen des Themas nicht laden.";
179     }
180
181     let form, formData;
182     try {
183         [form, formData] = await openForm(resp, "form#mcp");
184     } catch {
185         throw "Konnte Formular zum Aufteilen des Themas nicht öffnen.";
186     }
187
188     const post_id = post.id.slice(1);
189     const thread_title = (() => {
190         const prefix = `[${reason}]`;
191         let title = formData.get("subject");
192         if (reason && !title.toLowerCase().includes(prefix.toLowerCase())) {
193             title = `${prefix} ${title}`;
194         }
195         return title.slice(0, form.elements["subject"].maxLength);
196     })();
197     formData.set("post_id_list[]", post_id);
198     formData.set("subject", thread_title);
199     formData.set("to_forum_id", ARCHIVFORUMID);
200
201     resp = await postForm(form, formData, "mcp_topic_submit");
202     if (!resp.ok) {
203         throw "Konnte Aufteilen des Themas nicht anfragen.";
204     }
205
206     try {
207         await confirmAction(resp);
208     } catch (err) {
209         throw `Konnte Aufteilen des Themas nicht bestätigen: ${err}`;
210     }
211 }
212
213 function updatePageAfterSplit(post) {
214     if (document.querySelectorAll(".post").length > 1) {
215         post.parentNode.removeChild(post);
216     } else {
217         /* TODO: Make the location configurable, redirect to homepage, "Aktive
218          * Themen", "Neue Beiträge", or other?
219          */
220         window.location = "/";
221     }
222 }
223
224 function add_buttons() {
225     const del_post_btn_outer = document.createElement('li');
226     const del_post_btn = document.createElement('a');
227     del_post_btn.className = 'button button-icon-only';
228     del_post_btn.innerHTML = '<i class="icon fa-fire-extinguisher fa-fw" aria-hidden="true"></i><span class="sr-only">Abfall</span>';
229     del_post_btn.addEventListener("click", remove_post_handler);
230     del_post_btn.title = "Als Spam archivieren";
231     del_post_btn_outer.append(del_post_btn);
232
233     for (const postButtons of document.querySelectorAll(".post-buttons")) {
234         const del_post_btn_outer_clone = del_post_btn_outer.cloneNode(true);
235         del_post_btn_outer_clone.addEventListener("click", remove_post_handler);
236         postButtons.appendChild(del_post_btn_outer_clone);
237     }
238 }
239
240 add_buttons();