|
13 | 13 | from email.header import Header |
14 | 14 | from email.mime.text import MIMEText |
15 | 15 |
|
| 16 | +from pathlib import Path |
| 17 | +from string import Template |
16 | 18 | from urllib.parse import quote |
17 | 19 |
|
18 | 20 | import logging |
19 | | -logger = logging.getLogger("isso") |
20 | 21 |
|
21 | 22 | try: |
22 | 23 | import uwsgi |
23 | 24 | except ImportError: |
24 | 25 | uwsgi = None |
25 | 26 |
|
26 | | -from isso import local |
| 27 | +from isso import dist, local |
| 28 | +from isso.views.comments import isurl |
27 | 29 |
|
28 | 30 | from _thread import start_new_thread |
29 | 31 |
|
| 32 | +from requests import HTTPError, Session |
| 33 | + |
| 34 | +# Globals |
| 35 | +logger = logging.getLogger("isso") |
| 36 | + |
30 | 37 |
|
31 | 38 | class SMTPConnection(object): |
32 | 39 |
|
@@ -224,3 +231,183 @@ def _delete_comment(self, id): |
224 | 231 |
|
225 | 232 | def _activate_comment(self, thread, comment): |
226 | 233 | logger.info("comment %(id)s activated" % thread) |
| 234 | + |
| 235 | + |
| 236 | +class WebHook(object): |
| 237 | + """Notification handler for web hook. |
| 238 | +
|
| 239 | + :param isso_instance: Isso application instance. Used to get moderation key. |
| 240 | + :type isso_instance: object |
| 241 | +
|
| 242 | + :raises ValueError: if the provided URL is not valid |
| 243 | + :raises FileExistsError: if the provided JSON template doesn't exist |
| 244 | + :raises TypeError: if the provided template file is not a JSON |
| 245 | + """ |
| 246 | + |
| 247 | + def __init__(self, isso_instance: object): |
| 248 | + """Instanciate class.""" |
| 249 | + # store isso instance |
| 250 | + self.isso_instance = isso_instance |
| 251 | + # retrieve relevant configuration |
| 252 | + self.public_endpoint = isso_instance.conf.get( |
| 253 | + section="server", option="public-endpoint" |
| 254 | + ) or local("host") |
| 255 | + webhook_conf_section = isso_instance.conf.section("webhook") |
| 256 | + self.wh_url = webhook_conf_section.get("url") |
| 257 | + self.wh_template = webhook_conf_section.get("template") |
| 258 | + |
| 259 | + # check required settings |
| 260 | + if not isurl(self.wh_url): |
| 261 | + raise ValueError( |
| 262 | + "Web hook requires a valid URL. " |
| 263 | + "The provided one is not correct: {}".format(self.wh_url) |
| 264 | + ) |
| 265 | + |
| 266 | + # check optional template |
| 267 | + if not len(self.wh_template): |
| 268 | + self.wh_template = None |
| 269 | + logger.debug("No template provided.") |
| 270 | + elif not Path(self.wh_template).is_file(): |
| 271 | + raise FileExistsError( |
| 272 | + "Invalid web hook template path: {}".format(self.wh_template) |
| 273 | + ) |
| 274 | + elif not Path(self.wh_template).suffix == ".json": |
| 275 | + raise TypeError()( |
| 276 | + "Template must be a JSON file: {}".format(self.wh_template) |
| 277 | + ) |
| 278 | + else: |
| 279 | + self.wh_template = Path(self.wh_template) |
| 280 | + |
| 281 | + def __iter__(self): |
| 282 | + |
| 283 | + yield "comments.new:after-save", self.new_comment |
| 284 | + |
| 285 | + def new_comment(self, thread: dict, comment: dict) -> bool: |
| 286 | + """Triggered when a new comment is saved. |
| 287 | +
|
| 288 | + :param thread: comment thread |
| 289 | + :type thread: dict |
| 290 | + :param comment: comment object |
| 291 | + :type comment: dict |
| 292 | +
|
| 293 | + :return: True if eveythring went fine. False if not. |
| 294 | + :rtype: bool |
| 295 | + """ |
| 296 | + |
| 297 | + try: |
| 298 | + # get moderation URLs |
| 299 | + moderation_urls = self.moderation_urls(thread, comment) |
| 300 | + |
| 301 | + if self.wh_template: |
| 302 | + post_data = self.render_template(thread, comment, moderation_urls) |
| 303 | + else: |
| 304 | + post_data = { |
| 305 | + "author_name": comment.get("author", "Anonymous"), |
| 306 | + "author_email": comment.get("email"), |
| 307 | + "author_website": comment.get("website"), |
| 308 | + "comment_ip_address": comment.get("remote_addr"), |
| 309 | + "comment_text": comment.get("text"), |
| 310 | + "comment_url_activate": moderation_urls[0], |
| 311 | + "comment_url_delete": moderation_urls[1], |
| 312 | + "comment_url_view": moderation_urls[2], |
| 313 | + } |
| 314 | + |
| 315 | + self.send(post_data) |
| 316 | + except Exception as err: |
| 317 | + logger.error(err) |
| 318 | + return False |
| 319 | + |
| 320 | + return True |
| 321 | + |
| 322 | + def moderation_urls(self, thread: dict, comment: dict) -> tuple: |
| 323 | + """Helper to build comment related URLs (deletion, activation, etc.). |
| 324 | +
|
| 325 | + :param thread: comment thread |
| 326 | + :type thread: dict |
| 327 | + :param comment: comment object |
| 328 | + :type comment: dict |
| 329 | +
|
| 330 | + :return: tuple of URS in alpha order (activate, admin, delete, view) |
| 331 | + :rtype: tuple |
| 332 | + """ |
| 333 | + uri = "{}/id/{}".format(self.public_endpoint, comment.get("id")) |
| 334 | + key = self.isso_instance.sign(comment.get("id")) |
| 335 | + |
| 336 | + url_activate = "{}/activate/{}".format(uri, key) |
| 337 | + url_delete = "{}/delete/{}".format(uri, key) |
| 338 | + url_view = "{}#isso-{}".format( |
| 339 | + local("origin") + thread.get("uri"), comment.get("id") |
| 340 | + ) |
| 341 | + |
| 342 | + return url_activate, url_delete, url_view |
| 343 | + |
| 344 | + def render_template( |
| 345 | + self, thread: dict, comment: dict, moderation_urls: tuple |
| 346 | + ) -> str: |
| 347 | + """Format comment information as webhook payload filling the specified template. |
| 348 | +
|
| 349 | + :param thread: isso thread |
| 350 | + :type thread: dict |
| 351 | + :param comment: isso comment |
| 352 | + :type comment: dict |
| 353 | + :param moderation_urls: comment moderation URLs |
| 354 | + :type comment: tuple |
| 355 | +
|
| 356 | + :return: formatted message from template |
| 357 | + :rtype: str |
| 358 | + """ |
| 359 | + # load template |
| 360 | + with self.wh_template.open("r") as in_file: |
| 361 | + tpl_json_data = json.load(in_file) |
| 362 | + tpl_str = Template(json.dumps(tpl_json_data)) |
| 363 | + |
| 364 | + # substitute |
| 365 | + out_msg = tpl_str.substitute( |
| 366 | + AUTHOR_NAME=comment.get("author", "Anonymous"), |
| 367 | + AUTHOR_EMAIL="<{}>".format(comment.get("email", "")), |
| 368 | + AUTHOR_WEBSITE=comment.get("website", ""), |
| 369 | + COMMENT_IP_ADDRESS=comment.get("remote_addr"), |
| 370 | + COMMENT_TEXT=comment.get("text"), |
| 371 | + COMMENT_URL_ACTIVATE=moderation_urls[0], |
| 372 | + COMMENT_URL_DELETE=moderation_urls[1], |
| 373 | + COMMENT_URL_VIEW=moderation_urls[2], |
| 374 | + ) |
| 375 | + |
| 376 | + return out_msg |
| 377 | + |
| 378 | + def send(self, structured_msg: str) -> bool: |
| 379 | + """Send the structured message as a notification to the class webhook URL. |
| 380 | +
|
| 381 | + :param str structured_msg: structured message to send |
| 382 | +
|
| 383 | + :rtype: bool |
| 384 | + """ |
| 385 | + # load the message to ensure encoding |
| 386 | + msg_json = json.loads(structured_msg) |
| 387 | + |
| 388 | + with Session() as requests_session: |
| 389 | + |
| 390 | + # send requests |
| 391 | + response = requests_session.post( |
| 392 | + url=self.wh_url, |
| 393 | + json=json.dumps(msg_json), |
| 394 | + headers={ |
| 395 | + "Content-Type": "application/json", |
| 396 | + "User-Agent": "Isso/{0} (+https://posativ.org/isso)".format( |
| 397 | + dist.version |
| 398 | + ), |
| 399 | + }, |
| 400 | + ) |
| 401 | + |
| 402 | + try: |
| 403 | + response.raise_for_status() |
| 404 | + logger.info("Web hook sent to %s" % self.wh_url) |
| 405 | + except HTTPError as err: |
| 406 | + logger.error( |
| 407 | + "Something went wrong during POST request to the web hook. Trace: %s" |
| 408 | + % err |
| 409 | + ) |
| 410 | + return False |
| 411 | + |
| 412 | + # if no error occurred |
| 413 | + return True |
0 commit comments