def __call__(self, sender, **kwargs):
        """
        We add the Notification object on behalf of SystemAccount.
        """
        from twistranet.twistapp.models import Twistable
        from twistranet.twistapp.models import SystemAccount
        from twistranet.notifier.models import Notification

        # Prepare the message dict.
        # We use title_or_description on each Twistable argument to display it.
        message_dict = {}
        for param, value in kwargs.items():
            if isinstance(value, Twistable):
                message_dict[param] = value.id

        # We force __account__ to fake user login.
        system = SystemAccount.get()
        __account__ = system
        owner = kwargs.get(self.owner_arg, system)
        publisher = kwargs.get(self.publisher_arg, owner.publisher)
        n = Notification(
            publisher = publisher,
            owner = owner,
            title = "",
            description = self.message,
            parameters = message_dict,
            permissions = self.permissions,
        )
        n.save()
Esempio n. 2
0
    def __call__(self, sender, **kwargs):
        """
        We add the Notification object on behalf of SystemAccount.
        """
        from twistranet.twistapp.models import Twistable
        from twistranet.twistapp.models import SystemAccount
        from twistranet.notifier.models import Notification

        # Prepare the message dict.
        # We use title_or_description on each Twistable argument to display it.
        message_dict = {}
        for param, value in kwargs.items():
            if isinstance(value, Twistable):
                message_dict[param] = value.id

        # We force __account__ to fake user login.
        system = SystemAccount.get()
        __account__ = system
        owner = kwargs.get(self.owner_arg, system)
        publisher = kwargs.get(self.publisher_arg, owner.publisher)
        n = Notification(
            publisher=publisher,
            owner=owner,
            title="",
            description=self.message,
            parameters=message_dict,
            permissions=self.permissions,
        )
        n.save()
Esempio n. 3
0
def _get_site_name_or_baseline(return_baseline = False):
    """
    Read the site name from global community.
    We use tricks to ensure we can get the glob com. even with anonymous requests.
    """
    d = cache.get_many(["twistranet_site_name", "twistranet_baseline"])
    site_name = d.get("site_name", None)
    baseline = d.get("baseline", None)
    if site_name is None or baseline is None:
        from twistranet.twistapp.models import SystemAccount, GlobalCommunity
        __account__ = SystemAccount.get()
        try:
            glob = GlobalCommunity.get()
            site_name = glob.site_name
            baseline = glob.baseline
        finally:
            del __account__
        cache.set('twistranet_site_name', site_name)
        cache.set("twistranet_baseline", baseline)
    if return_baseline:
        return baseline
    return site_name
    def __call__(self, sender, **kwargs):
        """
        Generate the message itself.
        XXX TODO: Handle translation correctly (not from the request only)
        """
        # Fake-Login with SystemAccount so that everybody can be notified,
        # even users this current user can't list.
        from twistranet.twistapp.models import SystemAccount, Account, UserAccount, Community, Twistable
        __account__ = SystemAccount.get()
        from_email = settings.SERVER_EMAIL
        host = settings.EMAIL_HOST
        cache_mimeimages = {}
        if not host:
            # If host is disabled (EMAIL_HOST is None), skip that
            return
        
        # Handle recipients emails
        recipients = kwargs.get(self.recipient_arg, None)
        if not recipients:
            raise ValueError("Recipient must be provided as a '%s' parameter" % self.recipient_arg)
        to_list = []
        if not isinstance(recipients, (list, tuple, QuerySet, )):
            recipients = (recipients, )
        for recipient in recipients:
            if isinstance(recipient, Twistable):
                recipient = recipient.object
            if isinstance(recipient, UserAccount):
                to = recipient.email
                if not to:
                    log.warning("Can't send email for '%s': %s doesn't have an email registered." % (sender, recipient, ))
                    return
                to_list.append(to)
            elif isinstance(recipient, Community):
                if self.managers_only:
                    members = recipient.managers
                else:
                    members = recipient.members
                # XXX Suboptimal for very large communities
                to_list.extend([ member.email for member in members if member.email ])
            elif type(recipient) in (str, unicode, ):
                to_list.append(recipient)        # XXX Todo: check the '@'
            else:
                raise ValueError("Invalid recipient: %s (%s)" % (recipient, type(recipient), ))
                
        # Fetch templates
        text_template = kwargs.get('text_template', self.text_template)
        html_template = kwargs.get('html_template', self.html_template)
                
        # Now generate template and send mail for each recipient
        # XXX TODO: See http://docs.djangoproject.com/en/1.2/topics/email/#sending-multiple-e-mails
        # for the good approach to use.
        for to in to_list:
            # Append domain (and site info) to kwargs
            d = kwargs.copy()
            domain = cache.get("twistranet_site_domain")
            d.update({
                "domain":       domain,
                "site_name":    utils.get_site_name(),
                "baseline":     utils.get_baseline(),
                "recipient":    to,     # A string
            })
        
            # Load both templates and render them with kwargs context
            text_tpl = get_template(text_template)
            c = Context(d)
            text_content = text_tpl.render(c).strip()
            if html_template:
                html_tpl = get_template(html_template)
                html_content = html_tpl.render(c)
            else:
                html_content = None
            
            # Fetch back subject from text template
            subject = self.subject
            if not subject:
                match = SUBJECT_REGEX.search(text_content)
                if match:
                    subject = match.groups()[0]
            if not subject:
                raise ValueError("No subject provided nor 'Subject:' first line in your text template")
            
            # Remove empty lines and "Subject:" line from text templates
            text_content = SUBJECT_REGEX.sub('', text_content)
            text_content = EMPTY_LINE_REGEX.sub('\n', text_content)
        
            # Prepare messages
            msg = EmailMultiAlternatives(subject, text_content, from_email, [ to ], )
            if html_content:
                if getattr(settings, 'SEND_EMAIL_IMAGES_AS_ATTACHMENTS', DEFAULT_SEND_EMAIL_IMAGES_AS_ATTACHMENTS):
                    # we replace img links by img Mime Images
                    mimeimages = []
                    def replace_img_url(match):
                        """Change src url by mimeurl
                           fill the mimeimages list
                        """
                        urlpath = str(match.group('urlpath'))
                        attribute = str(match.group('attribute'))

                        is_static = False
                        pathSplit = urlpath.split('/')
                        if 'static' in pathSplit:
                            filename = urlpath.split('/static/')[-1]
                            is_static = True
                        else:
                            # XXX TODO : need to be improved split with site path (for vhosts)
                            filename = urlpath.split('/')[-1]
                        nb = len(mimeimages)+1
                        mimeimages.append((filename, 'img%i'%nb, is_static))
                        mimeurl = "cid:img%i" %nb
                        return '%s="%s"' % (attribute,mimeurl)

                    img_url_expr = re.compile('(?P<attribute>src)\s*=\s*([\'\"])(%s)?(?P<urlpath>[^\"\']*)\\2' %domain, re.IGNORECASE)
                    html_content = img_url_expr.sub(replace_img_url, html_content)
                    msg.attach_alternative(html_content, "text/html")
                    if mimeimages:
                        msg.mixed_subtype = 'related'
                        for fkey, name, is_static in mimeimages:
                            if cache_mimeimages.has_key(fkey):
                                msgImage = cache_mimeimages[fkey]
                            else:
                                if is_static:
                                    f = open(path.join(settings.TWISTRANET_STATIC_PATH, fkey), 'rb')
                                else:
                                    f = open(path.join(settings.MEDIA_ROOT, fkey), 'rb')
                                cache_mimeimages[fkey] = msgImage = MIMEImage(f.read())
                                f.close()
                            msgImage.add_header('Content-ID', '<%s>' % name)
                            msgImage.add_header('Content-Disposition', 'inline')
                            msg.attach(msgImage)
                # just inline images
                else:
                    msg.attach_alternative(html_content, "text/html")
            # Send safely
            try:
                log.debug("Sending mail: '%s' from '%s' to '%s'" % (subject, from_email, to))
                msg.send()
            except:
                log.warning("Unable to send message to %s" % to)
                log.exception("Here's what we've got as an error.")
Esempio n. 5
0
    def __call__(self, sender, **kwargs):
        """
        Generate the message itself.
        XXX TODO: Handle translation correctly (not from the request only)
        """
        # Fake-Login with SystemAccount so that everybody can be notified,
        # even users this current user can't list.
        from twistranet.twistapp.models import SystemAccount, Account, UserAccount, Community, Twistable
        __account__ = SystemAccount.get()
        from_email = settings.SERVER_EMAIL
        host = settings.EMAIL_HOST
        cache_mimeimages = {}
        if not host:
            # If host is disabled (EMAIL_HOST is None), skip that
            return

        # Handle recipients emails
        recipients = kwargs.get(self.recipient_arg, None)
        if not recipients:
            raise ValueError("Recipient must be provided as a '%s' parameter" %
                             self.recipient_arg)
        to_list = []
        if not isinstance(recipients, (
                list,
                tuple,
                QuerySet,
        )):
            recipients = (recipients, )
        for recipient in recipients:
            if isinstance(recipient, Twistable):
                recipient = recipient.object
            if isinstance(recipient, UserAccount):
                to = recipient.email
                if not to:
                    log.warning(
                        "Can't send email for '%s': %s doesn't have an email registered."
                        % (
                            sender,
                            recipient,
                        ))
                    return
                to_list.append(to)
            elif isinstance(recipient, Community):
                if self.managers_only:
                    members = recipient.managers
                else:
                    members = recipient.members
                # XXX Suboptimal for very large communities
                to_list.extend(
                    [member.email for member in members if member.email])
            elif type(recipient) in (
                    str,
                    unicode,
            ):
                to_list.append(recipient)  # XXX Todo: check the '@'
            else:
                raise ValueError("Invalid recipient: %s (%s)" % (
                    recipient,
                    type(recipient),
                ))

        # Fetch templates
        text_template = kwargs.get('text_template', self.text_template)
        html_template = kwargs.get('html_template', self.html_template)

        # Now generate template and send mail for each recipient
        # XXX TODO: See http://docs.djangoproject.com/en/1.2/topics/email/#sending-multiple-e-mails
        # for the good approach to use.
        for to in to_list:
            # Append domain (and site info) to kwargs
            d = kwargs.copy()
            domain = cache.get("twistranet_site_domain")
            d.update({
                "domain": domain,
                "site_name": utils.get_site_name(),
                "baseline": utils.get_baseline(),
                "recipient": to,  # A string
            })

            # Load both templates and render them with kwargs context
            text_tpl = get_template(text_template)
            c = Context(d)
            text_content = text_tpl.render(c).strip()
            if html_template:
                html_tpl = get_template(html_template)
                html_content = html_tpl.render(c)
            else:
                html_content = None

            # Fetch back subject from text template
            subject = self.subject
            if not subject:
                match = SUBJECT_REGEX.search(text_content)
                if match:
                    subject = match.groups()[0]
            if not subject:
                raise ValueError(
                    "No subject provided nor 'Subject:' first line in your text template"
                )

            # Remove empty lines and "Subject:" line from text templates
            text_content = SUBJECT_REGEX.sub('', text_content)
            text_content = EMPTY_LINE_REGEX.sub('\n', text_content)

            # Prepare messages
            msg = EmailMultiAlternatives(
                subject,
                text_content,
                from_email,
                [to],
            )

            if html_content:
                if getattr(settings, 'SEND_EMAIL_IMAGES_AS_ATTACHMENTS',
                           DEFAULT_SEND_EMAIL_IMAGES_AS_ATTACHMENTS):
                    # we replace img links by img Mime Images
                    mimeimages = []

                    def replace_img_url(match):
                        """Change src url by mimeurl
                           fill the mimeimages list
                        """
                        urlpath = str(match.group('urlpath'))
                        attribute = str(match.group('attribute'))

                        is_static = False
                        pathSplit = urlpath.split('/')
                        if 'static' in pathSplit:
                            filename = urlpath.split('/static/')[-1]
                            is_static = True
                        else:
                            # XXX TODO : need to be improved split with site path (for vhosts)
                            filename = urlpath.split('/')[-1]
                        nb = len(mimeimages) + 1
                        mimeimages.append((filename, 'img%i' % nb, is_static))
                        mimeurl = "cid:img%i" % nb
                        return '%s="%s"' % (attribute, mimeurl)

                    img_url_expr = re.compile(
                        '(?P<attribute>src)\s*=\s*([\'\"])(%s)?(?P<urlpath>[^\"\']*)\\2'
                        % domain, re.IGNORECASE)
                    html_content = img_url_expr.sub(replace_img_url,
                                                    html_content)
                    msg.attach_alternative(html_content, "text/html")
                    if mimeimages:
                        msg.mixed_subtype = 'related'
                        for fkey, name, is_static in mimeimages:
                            if cache_mimeimages.has_key(fkey):
                                msgImage = cache_mimeimages[fkey]
                            else:
                                if is_static:
                                    f = open(
                                        path.join(
                                            settings.TWISTRANET_STATIC_PATH,
                                            fkey), 'rb')
                                else:
                                    f = open(
                                        path.join(settings.MEDIA_ROOT, fkey),
                                        'rb')
                                cache_mimeimages[fkey] = msgImage = MIMEImage(
                                    f.read())
                                f.close()
                            msgImage.add_header('Content-ID', '<%s>' % name)
                            msgImage.add_header('Content-Disposition',
                                                'inline')
                            msg.attach(msgImage)
                # just inline images
                else:
                    msg.attach_alternative(html_content, "text/html")
            # Send safely
            try:
                log.debug("Sending mail: '%s' from '%s' to '%s'" %
                          (subject, from_email, to))
                msg.send()
            except:
                log.warning("Unable to send message to %s" % to)
                log.exception("Here's what we've got as an error.")
Esempio n. 6
0
 def __call__(self, sender, **kwargs):
     """
     Generate the message itself.
     XXX TODO: Handle translation correctly (not from the request only)
     """
     # Fake-Login with SystemAccount so that everybody can be notified,
     # even users this current user can't list.
     from twistranet.twistapp.models import SystemAccount, Account, UserAccount, Community, Twistable
     __account__ = SystemAccount.get()
     from_email = settings.SERVER_EMAIL
     host = settings.EMAIL_HOST
     if not host:
         # If host is disabled (EMAIL_HOST is None), skip that
         return
     
     # Handle recipients emails
     recipients = kwargs.get(self.recipient_arg, None)
     if not recipients:
         raise ValueError("Recipient must be provided as a '%s' parameter" % self.recipient_arg)
     to_list = []
     if not isinstance(recipients, (list, tuple, QuerySet, )):
         recipients = (recipients, )
     for recipient in recipients:
         if isinstance(recipient, Twistable):
             recipient = recipient.object
         if isinstance(recipient, UserAccount):
             to = recipient.email
             if not to:
                 log.warning("Can't send email for '%s': %s doesn't have an email registered." % (sender, recipient, ))
                 return
             to_list.append(to)
         elif isinstance(recipient, Community):
             if self.managers_only:
                 members = recipient.managers
             else:
                 members = recipient.members
             # XXX Suboptimal for very large communities
             to_list.extend([ member.email for member in members if member.email ])
         elif type(recipient) in (str, unicode, ):
             to_list.append(recipient)        # XXX Todo: check the '@'
         else:
             raise ValueError("Invalid recipient: %s (%s)" % (recipient, type(recipient), ))
             
     # Fetch templates
     text_template = kwargs.get('text_template', self.text_template)
     html_template = kwargs.get('html_template', self.html_template)
             
     # Now generate template and send mail for each recipient
     # XXX TODO: See http://docs.djangoproject.com/en/1.2/topics/email/#sending-multiple-e-mails
     # for the good approach to use.
     for to in to_list:
         # Append domain (and site info) to kwargs
         d = kwargs.copy()
         domain = cache.get("twistranet_site_domain")
         d.update({
             "domain":       domain,
             "site_name":    utils.get_site_name(),
             "baseline":     utils.get_baseline(),
             "recipient":    to,     # A string
         })
     
         # Load both templates and render them with kwargs context
         text_tpl = get_template(text_template)
         c = Context(d)
         text_content = text_tpl.render(c).strip()
         if html_template:
             html_tpl = get_template(html_template)
             html_content = html_tpl.render(c)
         else:
             html_content = None
         
         # Fetch back subject from text template
         subject = self.subject
         if not subject:
             match = SUBJECT_REGEX.search(text_content)
             if match:
                 subject = match.groups()[0]
         if not subject:
             raise ValueError("No subject provided nor 'Subject:' first line in your text template")
         
         # Remove empty lines and "Subject:" line from text templates
         text_content = SUBJECT_REGEX.sub('', text_content)
         text_content = EMPTY_LINE_REGEX.sub('\n', text_content)
     
         # Prepare messages
         msg = EmailMultiAlternatives(subject, text_content, from_email, [ to ], )
         if html_content:
             msg.attach_alternative(html_content, "text/html")
         
         # Send safely
         try:
             log.debug("Sending mail: '%s' from '%s' to '%s'" % (subject, from_email, to))
             msg.send()
         except:
             log.warning("Unable to send message to %s" % to)
             log.exception("Here's what we've got as an error.")