forked from mlq/limnoria-gitlab
/
plugin.py
306 lines (244 loc) · 10.6 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
###
# Copyright (c) 2015, Moritz Lipp
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import json
from supybot.commands import wrap
import supybot.ircdb as ircdb
import supybot.ircmsgs as ircmsgs
import supybot.callbacks as callbacks
import supybot.log as log
import supybot.httpserver as httpserver
import supybot.world as world
try:
from supybot.i18n import PluginInternationalization
from supybot.i18n import internationalizeDocstring
_ = PluginInternationalization('Gogs')
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
def _(x):
return x
def internationalizeDocstring(x):
return x
class GogsHandler(object):
"""Handle Gogs messages"""
def __init__(self, plugin):
# HACK: instead of refactoring everything, I can just replace this with each handle_payload() call.
self.irc = None
self.plugin = plugin
self.log = log.getPluginLogger('Gogs')
def handle_payload(self, headers, payload, irc):
if 'X-Gogs-Event' not in headers:
self.log.info('Invalid header: Missing X-Gogs-Event entry')
return
self.irc = irc
self.log.debug('Gogs: running on network %r', irc.network)
event_type = headers['X-Gogs-Event']
if event_type not in ['push', 'create']:
self.log.info('Unsupported X-Gogs-Event type')
return
# Check if any channel has subscribed to this project
for channel in irc.state.channels.keys():
projects = self.plugin._load_projects(channel)
for slug, url in projects.items():
# Parse project url
if event_type == 'push' or event_type == 'create':
if url != payload['repository']['html_url']:
continue
else:
continue
# Handle types
if event_type == 'push':
self._push_hook(channel, payload)
elif event_type == 'create':
self._create_push_hook(channel, payload)
def _push_hook(self, channel, payload):
# Send general message
payload['total_commits_count'] = len(payload['commits'])
msg = self._build_message(channel, 'push', payload)
self._send_message(channel, msg)
# Send commits
for commit in payload['commits']:
commit['repository'] = {
'id': payload['repository']['id'],
'name': payload['repository']['name'],
'url': payload['repository']['html_url']
}
commit['short_message'] = commit['message'].splitlines()[0]
commit['short_id'] = commit['id'][0:10]
msg = self._build_message(channel, 'commit', commit)
self._send_message(channel, msg)
def _create_push_hook(self, channel, payload):
msg = self._build_message(channel, 'create', payload)
self._send_message(channel, msg)
def _build_message(self, channel, format_string_identifier, args):
format_string = str(
self.plugin.registryValue(
'format.' +
format_string_identifier,
channel))
msg = format_string.format(**args)
return msg
def _send_message(self, channel, msg):
if self.plugin.registryValue('use-notices', channel):
announce_msg = ircmsgs.notice(channel, msg)
else:
announce_msg = ircmsgs.privmsg(channel, msg)
self.irc.queueMsg(announce_msg)
class GogsWebHookService(httpserver.SupyHTTPServerCallback):
"""https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/web_hooks/web_hooks.md"""
name = "GogsWebHookService"
defaultResponse = """This plugin handles only POST request, please don't use other requests."""
def __init__(self, plugin):
self.log = log.getPluginLogger('Gogs')
self.gogs = GogsHandler(plugin)
self.plugin = plugin
def _send_error(self, handler, message):
handler.send_response(403)
handler.send_header('Content-type', 'text/plain')
handler.end_headers()
handler.wfile.write(message.encode('utf-8'))
def _send_ok(self, handler):
handler.send_response(200)
handler.send_header('Content-type', 'text/plain')
handler.end_headers()
handler.wfile.write(bytes('OK', 'utf-8'))
def doPost(self, handler, path, form):
headers = dict(self.headers)
network = None
try:
information = path.split('/')[1:]
network = information[0]
except IndexError:
self._send_error(handler, _("""Error: You need to provide the
network name in the URL."""))
return
irc = world.getIrc(network)
if irc is None:
self._send_error(handler, (_('Error: Unknown network %r') % network))
return
# Handle payload
payload = None
try:
payload = json.JSONDecoder().decode(form.decode('utf-8'))
except Exception as e:
self.log.info(e)
self._send_error(handler, _('Error: Invalid JSON data sent.'))
return
try:
self.gogs.handle_payload(headers, payload, irc)
except Exception as e:
self.log.info(e)
self._send_error(handler, _('Error: Invalid data sent.'))
return
# Return OK
self._send_ok(handler)
class Gogs(callbacks.Plugin):
"""Plugin for communication and notifications of a Gogs project
management tool instance"""
threaded = True
def __init__(self, irc):
global instance
self.__parent = super(Gogs, self)
self.__parent.__init__(irc)
instance = self
callback = GogsWebHookService(self)
httpserver.hook('gogs', callback)
def die(self):
httpserver.unhook('gogs')
self.__parent.die()
def _load_projects(self, channel):
projects = self.registryValue('projects', channel)
if projects is None:
return {}
else:
return projects
def _save_projects(self, projects, channel):
self.setRegistryValue('projects', value=projects, channel=channel)
def _check_capability(self, irc, msg):
if ircdb.checkCapability(msg.prefix, 'admin'):
return True
else:
irc.errorNoCapability('admin')
return False
class gogs(callbacks.Commands):
"""Gogs commands"""
class project(callbacks.Commands):
"""Project commands"""
@internationalizeDocstring
def add(self, irc, msg, args, channel, project_slug, project_url):
"""[<channel>] <project-slug> <project-url>
Announces the changes of the project with the slug
<project-slug> and the url <project-url> to <channel>.
"""
if not instance._check_capability(irc, msg):
return
projects = instance._load_projects(channel)
if project_slug in projects:
irc.error(
_('This project is already announced to this channel.'))
return
# Save new project mapping
projects[project_slug] = project_url
instance._save_projects(projects, channel)
irc.replySuccess()
add = wrap(add, ['channel', 'somethingWithoutSpaces', 'httpUrl'])
@internationalizeDocstring
def remove(self, irc, msg, args, channel, project_slug):
"""[<channel>] <project-slug>
Stops announcing the changes of the project slug <project-slug>
to <channel>.
"""
if not instance._check_capability(irc, msg):
return
projects = instance._load_projects(channel)
if project_slug not in projects:
irc.error(
_('This project is not registered to this channel.'))
return
# Remove project mapping
del projects[project_slug]
instance._save_projects(projects, channel)
irc.replySuccess()
remove = wrap(remove, ['channel', 'somethingWithoutSpaces'])
@internationalizeDocstring
def list(self, irc, msg, args, channel):
"""[<channel>]
Lists the registered projects in <channel>.
"""
if not instance._check_capability(irc, msg):
return
projects = instance._load_projects(channel)
if projects is None or len(projects) == 0:
irc.error(_('This channel has no registered projects.'))
return
for project_slug, project_url in projects.items():
irc.reply("%s: %s" % (project_slug, project_url))
list = wrap(list, ['channel'])
Class = Gogs
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: