]> git.aero2k.de Git - dfde/quickmods.git/blob - quickmod.user.js
16891e2b09261971d418ffe68e3c9ca521de6a36
[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.4
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 form, formData;
18     try {
19         [form, formData] = await openForm(toAbsoluteURL("./mcp.php?i=ban&mode=user"),
20             "form#mcp_ban");
21     } catch (err) {
22         throw `Konnte Formular zum Sperren von Benutzern nicht öffnen: ${err}`;
23     }
24
25     formData.set("ban", username);
26     formData.set("banreason", reason);
27     //formData.set("bangivereason", reason);
28     const resp = await postForm(form, formData, "bansubmit");
29     if (!resp.ok) {
30         throw "Konnte Sperrung des Benutzers nicht anfragen.";
31     }
32
33     try {
34         await confirmAction(resp);
35     } catch (err) {
36         throw `Konnte Sperrung des Benutzers nicht bestätigen: ${err}`;
37     }
38 }
39
40 async function closeReport(post) {
41     const reportLink = post.querySelector(".post-notice.reported a");
42
43     let form, formData;
44     try {
45         [form, formData] = await openForm(toAbsoluteURL(reportLink.href),
46             "form#mcp_report");
47     } catch (err) {
48         throw `Konnte Formular zum Schließen der Meldung nicht öffnen: ${err}`;
49     }
50
51     const resp = await postForm(form, formData, "action[close]");
52     if (!resp.ok) {
53         throw "Konnte Schließen der Meldung nicht anfragen.";
54     }
55
56     try {
57         await confirmAction(resp);
58     } catch (err) {
59         throw `Konnte Schließen der Meldung nicht bestätigen: ${err}`;
60     }
61 }
62
63 async function confirmAction(response) {
64     const [form, formData] = await openForm(response, "form#confirm");
65
66     const resp = await postForm(form, formData, "confirm");
67     if (!resp.ok) {
68         throw `${resp.url}: ${resp.status}`;
69     }
70     return resp.text();
71 }
72
73 function ellipsify(str, maxlen) {
74     const ell = str.length > maxlen ? " […]" : "";
75     return str.substring(0, maxlen - ell.length) + ell;
76 }
77
78 function isPostReported(post) {
79     return post.querySelector(".post-notice.reported a") !== null;
80 }
81
82 async function openForm(urlOrResponse, selector) {
83     const resp = urlOrResponse instanceof Response ? urlOrResponse :
84         await fetch(urlOrResponse);
85     if (!resp.ok) {
86         throw `${resp.url}: ${resp.status}`;
87     }
88
89     const parser = new DOMParser();
90     const txt = await resp.text();
91     const doc = parser.parseFromString(txt, "text/html");
92     const form = doc.querySelector(selector);
93     return [form, new FormData(form)];
94 }
95
96 function postForm(form, formData, submitName) {
97     /* "Press" the right submit button. */
98     const submitBtn = form.elements[submitName];
99     formData.set(submitBtn.name, submitBtn.value);
100
101     /* Have to use explicit getAttribute() below since there is an input with
102      * name="action" which would be accessed with `form.action` :-/
103      */
104     return fetch(toAbsoluteURL(form.getAttribute("action")),
105         { body: new URLSearchParams(formData), method: "POST" });
106 }
107
108 async function remove_post_handler(event) {
109     const post = event.currentTarget.closest('.post');
110     const usernameElem = post.querySelector(".author .username,.author .username-coloured");
111     const username = usernameElem.textContent;
112     const thread_title = document.querySelector('.topic-title a').text;
113     const content = ellipsify(post.querySelector(".content").innerText, 250);
114
115     const splitReason = window.prompt(`Folgenden Beitrag von „${username}“ im Thema „${ellipsify(thread_title, 100)}“ wirklich als Spam archivieren?\n\n„${content}“\n\nGrund:`, "Spam");
116     if (splitReason === null) {
117         /* Don't do any of the other actions if splitting was cancelled. */
118         return;
119     }
120
121     /* Prompting for a separate ban reason in case there is something more
122      * specific to note here.
123      */
124     const userStillExists = usernameElem.nodeName === "A";
125     const banReason = userStillExists &&
126         window.prompt(`Benutzer „${username}“ sperren?\n\nGrund:`, "Spam");
127     const shouldCloseReport = isPostReported(post) && window.confirm("Meldung zum Beitrag schließen?");
128
129     /* Initially, I wanted to use Promise.allSettled() below to trigger and wait
130      * for all actions in parallel. But that made at least one of them fail in
131      * most cases. Not sure, if there was a mistake in here somewhere (totally
132      * not impossible) or if phpBB just does not cope well with parallel mod
133      * actions (there are some session IDs and confirm_keys involved when a mod
134      * action is executed and confirmed).
135      *
136      * So essentially, we do not have any asynchronous execution here,
137      * unfortunately.
138      */
139     const errors = new Array();
140     try {
141         await send_mcp_request_archival(post, splitReason);
142     } catch (err) {
143         errors.push(err);
144     }
145
146     if (banReason) {
147         try {
148             await banUser(username, banReason);
149         } catch (err) {
150             errors.push(err);
151         }
152     } else if (!userStillExists) {
153         window.alert(`Benutzer „${username}“ wurde schon gelöscht und kann nicht mehr gesperrt werden.`);
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
177     let form, formData;
178     try {
179         [form, formData] = await openForm(toAbsoluteURL(splitLink.href), "form#mcp");
180     } catch (err) {
181         throw `Konnte Formular zum Aufteilen des Themas nicht öffnen: ${err}`;
182     }
183
184     const post_id = post.id.slice(1);
185     const thread_title = (() => {
186         const prefix = `[${reason}]`;
187         let title = formData.get("subject");
188         if (reason && !title.toLowerCase().includes(prefix.toLowerCase())) {
189             title = `${prefix} ${title}`;
190         }
191         return title.slice(0, form.elements["subject"].maxLength);
192     })();
193     formData.set("post_id_list[]", post_id);
194     formData.set("subject", thread_title);
195     formData.set("to_forum_id", ARCHIVFORUMID);
196
197     const resp = await postForm(form, formData, "mcp_topic_submit");
198     if (!resp.ok) {
199         throw "Konnte Aufteilen des Themas nicht anfragen.";
200     }
201
202     try {
203         await confirmAction(resp);
204     } catch (err) {
205         throw `Konnte Aufteilen des Themas nicht bestätigen: ${err}`;
206     }
207 }
208
209 function toAbsoluteURL(relativeOrAbsoluteURL) {
210     return new URL(relativeOrAbsoluteURL, window.location);
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();