Debian Codegraph @

contrib/ircbot/Sourcehut/plugin.py

raw
1 import email.header
2 import email.utils
3 import json
4 import mailbox
5 from urllib.parse import quote
6 from urllib.request import urlopen
7 import re
8 import traceback
9
10 from supybot import callbacks, httpserver, ircmsgs, world
11 from supybot.ircutils import bold, italic, mircColor, underline
12
13
14 class Sourcehut(callbacks.Plugin):
15 """
16 Supybot plugin to receive Sourcehut webhooks
17 """
18
19 def __init__(self, irc):
20 super().__init__(irc)
21 httpserver.hook("sourcehut", SourcehutServerCallback(self))
22
23 def die(self):
24 httpserver.unhook("sourcehut")
25 super().die()
26
27 def announce(self, channel, message):
28 libera = world.getIrc("libera")
29 if libera is None:
30 print("error: no irc libera")
31 return
32 if channel not in libera.state.channels:
33 print(f"error: not in {channel} channel")
34 return
35 libera.sendMsg(ircmsgs.notice(channel, message))
36
37
38 def decode_header(header: str) -> str:
39 if not header:
40 return ""
41 text = ""
42 for chunk, encoding in email.header.decode_header(header):
43 if isinstance(chunk, bytes):
44 chunk = chunk.decode(encoding or "us-ascii")
45 text += chunk
46 return text
47
48
49 class SourcehutServerCallback(httpserver.SupyHTTPServerCallback):
50 name = "Sourcehut"
51 defaultResponse = "Bad request\n"
52
53 def __init__(self, plugin: Sourcehut):
54 super().__init__()
55 self.plugin = plugin
56
57 SUBJECT = "[PATCH {prefix} v{version}] {subject}"
58 URL = "https://lists.sr.ht/{list[owner][canonicalName]}/{list[name]}"
59 CHANS = {
60 "#public-inbox": "##rjarry",
61 "#aerc-devel": "#aerc",
62 }
63
64 def announce_patch(self, patchset):
65 subject = self.SUBJECT.format(**patchset)
66 url = self.URL.format(**patchset)
67 if not url.startswith("https://lists.sr.ht/~rjarry/"):
68 raise ValueError("unknown list")
69 url += "/patches/{id}".format(**patchset)
70 channel = f"#{patchset['list']['name']}"
71 channel = self.CHANS.get(channel, channel)
72 try:
73 submitter = patchset["submitter"]["canonicalName"]
74 except KeyError:
75 try:
76 submitter = patchset["submitter"]["name"]
77 except KeyError:
78 submitter = patchset["submitter"]["address"]
79 msg = f"{mircColor('received', 'light gray')} {bold(subject)}"
80 msg += f" from {italic(submitter)}: {underline(url)}"
81 self.plugin.announce(channel, msg)
82
83 def announce_apply(self, mail):
84 channel = f"#{mail['list']['name']}"
85 channel = self.CHANS.get(channel, channel)
86 refs = []
87 for header in mail['references']:
88 refs += header.split()
89 for ref in refs:
90 url = self.URL.format(**mail) + quote(f"/{ref}")
91 print(f"GET {url}/raw")
92 with urlopen(f"{url}/raw") as u:
93 msg = mailbox.Message(u.read())
94 subject = re.sub(r"\s+", " ", decode_header(msg["subject"]))
95 if not re.match(r"^\[(RFC )?PATCH", subject):
96 continue
97 for name, addr in email.utils.getaddresses([decode_header(msg["from"])]):
98 if name:
99 submitter = name
100 else:
101 submitter = addr
102 msg = f"{bold(mircColor('applied', 'green'))} {bold(subject)}"
103 msg += f" from {italic(submitter)}: {underline(url)}"
104 self.plugin.announce(channel, msg)
105 return
106
107 def doPost(self, handler, path, form=None):
108 if hasattr(form, "decode"):
109 form = form.decode("utf-8")
110 print(f"POST {path} {form}")
111 try:
112 body = json.loads(form)
113 hook = body["data"]["webhook"]
114 if hook["event"] == "PATCHSET_RECEIVED":
115 self.announce_patch(hook["patchset"])
116 handler.send_response(200)
117 handler.end_headers()
118 handler.wfile.write(b"")
119 return
120
121 if hook["event"] == "EMAIL_RECEIVED":
122 if hook["email"]["patchset_update"] == ["APPLIED"]:
123 self.announce_apply(hook["email"])
124 handler.send_response(200)
125 handler.end_headers()
126 handler.wfile.write(b"")
127 return
128
129 raise ValueError(f"unsupported webhook: {hook}")
130
131 except Exception as e:
132 traceback.print_exception(e)
133 handler.send_response(400)
134 handler.end_headers()
135 handler.wfile.write(b"Bad request\n")
136
137 def log_message(self, format, *args):
138 pass
139
140
141 Class = Sourcehut