[PATCH 2 of 2] hooks: add email notification on push

Andrew Shadura andrew at shadura.me
Sat Apr 18 15:54:09 EDT 2015


# HG changeset patch
# User Andrew Shadura <andrew at shadura.me>
# Date 1429347340 -7200
#      Sat Apr 18 10:55:40 2015 +0200
# Node ID bc84617f45acc13325d6086044e075ac36cda2fb
# Parent  d9615df6d46a9c80a0adb3d68e33f1fe091e8127
hooks: add email notification on push

diff --git a/kallithea/lib/hooks.py b/kallithea/lib/hooks.py
--- a/kallithea/lib/hooks.py
+++ b/kallithea/lib/hooks.py
@@ -29,6 +29,9 @@ import os
 import sys
 import time
 import binascii
+import traceback
+
+import pylons
 
 from kallithea.lib.vcs.utils.hgcompat import nullrev, revrange
 from kallithea.lib import helpers as h
@@ -38,7 +41,6 @@ from kallithea.lib.exceptions import HTT
 from kallithea.lib.utils2 import safe_str, _extract_extras
 from kallithea.model.db import Repository, User
 
-
 def _get_scm_size(alias, root_path):
 
     if not alias.startswith('.'):
@@ -163,6 +165,12 @@ def log_push_action(ui, repo, **kwargs):
     :param repo: repo object containing the `ui` object
     """
 
+    from pylons.i18n.translation import _get_translator
+    from pylons.i18n.translation import _
+
+    translator = _get_translator(pylons.config.get('lang'))
+    pylons.translator._push_object(translator)
+
     ex = _extract_extras()
 
     action_tmpl = ex.action + ':%s'
@@ -199,6 +207,53 @@ def log_push_action(ui, repo, **kwargs):
         kw.update(ex)
         callback(**kw)
 
+    send_emails = True
+    if send_emails:
+        from paste.deploy import appconfig
+        import kallithea.lib.app_globals as app_globals
+        from kallithea.config.environment import load_environment
+
+        path, ini_name = os.path.split(ex['config'])
+        conf = appconfig('config:%s' % ini_name, relative_to=path)
+        pylons.config = load_environment(conf.global_conf, conf.local_conf, config_only=True)
+
+
+        from kallithea.lib.celerylib import tasks, run_task
+        from kallithea.model.notification import EmailNotificationModel
+
+        repo = Repository.get_by_repo_name(ex.repository)
+        changesets = []
+        for r in revs:
+            cs = repo.scm_instance.get_changeset(r)
+            changesets.append(cs)
+
+        repo_url = '%(server_url)s/%(repository)s' % ex
+
+        reg_type = EmailNotificationModel.TYPE_NEW_CHANGESETS
+
+        try:
+            txt_body = EmailNotificationModel().get_email_tmpl(reg_type,
+                                                       'txt',
+                                                       username=ex.username,
+                                                       repository=ex.repository,
+                                                       changesets=changesets,
+                                                       repo_url=repo_url,
+                                                       server_url=ex.server_url)
+
+            html_body = EmailNotificationModel().get_email_tmpl(reg_type,
+                                                       'html',
+                                                       username=ex.username,
+                                                       repository=ex.repository,
+                                                       changesets=changesets,
+                                                       repo_url=repo_url,
+                                                       server_url=ex.server_url)
+            run_task(tasks.send_email, ["kallithea-general at sfconservancy.org"],
+                     _("%d new commits pushed to %s") % (len(revs), ex.repository), txt_body, html_body)
+            sys.stdout.write("Email notification sent\n")
+        except Exception:
+            sys.stdout.write(traceback.format_exc())
+            raise
+
     if ex.make_lock is not None and not ex.make_lock:
         Repository.unlock(Repository.get_by_repo_name(ex.repository))
         msg = 'Released lock on repo `%s`\n' % ex.repository
diff --git a/kallithea/model/notification.py b/kallithea/model/notification.py
--- a/kallithea/model/notification.py
+++ b/kallithea/model/notification.py
@@ -278,6 +278,7 @@ class EmailNotificationModel(BaseModel):
     TYPE_REGISTRATION = Notification.TYPE_REGISTRATION
     TYPE_PULL_REQUEST = Notification.TYPE_PULL_REQUEST
     TYPE_PULL_REQUEST_COMMENT = Notification.TYPE_PULL_REQUEST_COMMENT
+    TYPE_NEW_CHANGESETS = 'new_changesets'
     TYPE_DEFAULT = 'default'
 
     def __init__(self):
@@ -291,6 +292,7 @@ class EmailNotificationModel(BaseModel):
             self.TYPE_DEFAULT: 'default',
             self.TYPE_PULL_REQUEST: 'pull_request',
             self.TYPE_PULL_REQUEST_COMMENT: 'pull_request_comment',
+            self.TYPE_NEW_CHANGESETS: 'new_changesets'
         }
         self._subj_map = {
             self.TYPE_CHANGESET_COMMENT: _('Comment on %(repo_name)s changeset %(short_id)s on %(branch)s by %(comment_username)s'),
@@ -299,7 +301,8 @@ class EmailNotificationModel(BaseModel):
             self.TYPE_REGISTRATION: _('New user %(new_username)s registered'),
             # self.TYPE_DEFAULT
             self.TYPE_PULL_REQUEST: _('Review request on %(repo_name)s pull request #%(pr_id)s from %(ref)s by %(pr_username)s'),
-            self.TYPE_PULL_REQUEST_COMMENT: _('Comment on %(repo_name)s pull request #%(pr_id)s from %(ref)s by %(comment_username)s'),
+            self.TYPE_PULL_REQUEST_COMMENT: _('Comment on %(repo_name)s pull request #%(pr_id)s from %(ref)s by %(comment_username)s')
+            # self.TYPE_NEW_CHANGESETS
         }
 
     def get_email_description(self, type_, **kwargs):
diff --git a/kallithea/templates/email_templates/new_changesets.html b/kallithea/templates/email_templates/new_changesets.html
new file mode 100644
--- /dev/null
+++ b/kallithea/templates/email_templates/new_changesets.html
@@ -0,0 +1,12 @@
+## -*- coding: utf-8 -*-
+<%inherit file="main.html"/>
+
+<p>${_('%d new changesets pushed to') % (len(changesets))} <a href="${repo_url}">${repository}</a> ${_('by %s') % (username)}</p>
+
+%for cs in changesets:
+<p>${_('Changeset')}: <a href="${repo_url}/changeset/${cs.raw_id}">${cs.raw_id}</a></p>
+<p>${_('Branch')}: ${cs.branch}</p>
+<p>${_('Date')}: ${h.fmt_date(cs.date)}</p>
+<p>${_('Description')}: ${h.shorter(cs.message, 80)}</p>
+<hr />
+%endfor
diff --git a/kallithea/templates/email_templates/new_changesets.txt b/kallithea/templates/email_templates/new_changesets.txt
new file mode 100644
--- /dev/null
+++ b/kallithea/templates/email_templates/new_changesets.txt
@@ -0,0 +1,13 @@
+## -*- coding: utf-8 -*-
+<%inherit file="main.txt"/>
+
+${_('%d new changesets pushed to') % (len(changesets))|n,unicode} ${repository|n,unicode} ${_('by %s') % (username)|n,unicode}
+
+%for cs in changesets:
+${_('Changeset')}: ${cs.raw_id|n,unicode}
+${_('URL')}: ${repo_url|n,unicode}/changeset/${cs.raw_id|n,unicode}
+${_('Branch')}: ${cs.branch|n,unicode}
+${_('Date')}: ${h.fmt_date(cs.date)|n,unicode}
+${_('Description')}: ${h.shorter(cs.message, 80)|n,unicode}
+
+%endfor


More information about the kallithea-general mailing list