import re

from trac.core import *
from trac.ticket.api import ITicketChangeListener
from trac.ticket.notification import TicketNotifyEmail


class Notifications(Component):
    """Send notification to the mentioned persons"""
    implements(ITicketChangeListener)

    ping_regex = r'\B@(\w+)\b'

    def _find_mentions(self, ticket, text, newticket=False):
        recipients = re.findall(self.ping_regex, text)

        if recipients:
            pn = PingNotifyEmail(self.env, recipients=recipients)
            pn.notify(ticket, newticket, modtime=ticket.values['changetime'])

    def ticket_created(self, ticket):
        self._find_mentions(ticket, ticket.values['description'], True)

    def ticket_changed(self, ticket, comment, author, old_values):
        if comment:
            self._find_mentions(ticket, comment)

        if 'description' in old_values:
            self._find_mentions(ticket, ticket.values['description'])

    def ticket_deleted(self, ticket):
        pass

    def ticket_comment_modified(self, ticket, cdate, author, comment, old_comment):
        self._find_mentions(ticket, comment)
        pass

    def ticket_change_deleted(self, ticket, cdate, changes):
        pass


class PingNotifyEmail(TicketNotifyEmail):
    _recipients = None

    def __init__(self, env, recipients):
        self._recipients = recipients
        TicketNotifyEmail.__init__(self, env)

    def get_recipients(self, resid):
        return (self._recipients, [])

@@ -133,16 +133,77 @@
 fyEmail%0A
+from trac.perm import IPermissionRequestor, PermissionSystem%0A
 %0A%0Aclass 
@@ -317,16 +317,38 @@
 Listener
+, IPermissionRequestor
 )%0A%0A    p
@@ -416,16 +416,22 @@
 t, text,
+ user,
  newtick
@@ -441,16 +441,126 @@
 False):%0A
+        if not PermissionSystem(self.env).check_permission('MENTION_NOTIFY', user):%0A            return False%0A%0A
         
@@ -771,24 +771,167 @@
 ngetime'%5D)%0A%0A
+    # IPermissionRequestor method%0A    def get_permission_actions(self):%0A        return %5B'MENTION_NOTIFY'%5D%0A%0A    # ITicketChangeListener methods%0A
     def tick
@@ -1021,16 +1021,43 @@
 ption'%5D,
+ ticket.values%5B'reporter'%5D,
  True)%0A%0A
@@ -1190,16 +1190,24 @@
  comment
+, author
 )%0A%0A     
@@ -1309,16 +1309,24 @@
 iption'%5D
+, author
 )%0A%0A    d
@@ -1499,16 +1499,24 @@
  comment
+, author
 )%0A      

Add permission support