Example #1
0
    def render_view(self,):
        """
        Render the given template with the specified params (dict)...
        ...PLUS adds some parameters to provide better integration:
        - actions
        - current_account
        """

        # Populate parameters
        params = {}
        for param in self.template_variables:
            if isinstance(param, tuple):
                k, attr = param
            else:
                k = attr = param
            if params.has_key(k):
                continue
            v = getattr(self, attr)
            if callable(v):
                v = v()
            params[k] = v

        # Generate actions and other params
        params["actions"] = self.get_actions()
        params["current_account"] = self.auth
        params["site_name"] = utils.get_site_name()
        params["baseline"] = utils.get_baseline()

        # Render template
        t = get_template(self.template)
        c = RequestContext(self.request, params)
        return self.response_handler_method(t.render(c))
Example #2
0
 def render_view(self, ):
     """
     Render the given template with the specified params (dict)...
     ...PLUS adds some parameters to provide better integration:
     - actions
     - current_account
     """
       
     # Populate parameters
     params = {}
     for param in self.template_variables:
         if isinstance(param, tuple):
             k, attr = param
         else:
             k = attr = param
         if params.has_key(k):
             continue
         v = getattr(self, attr)
         if callable(v):
             v = v()
         params[k] = v
         
     # Generate actions and other params
     params["actions"] = self.get_actions()
     params["current_account"] = self.auth
     params["site_name"] = utils.get_site_name()
     params["baseline"] = utils.get_baseline()
     bodyclass = ''
     if not params.get('context_boxes', []):
         bodyclass = 'noleftcol'
     if not params.get('global_boxes', []):
         if not bodyclass:
             bodyclass = 'norightcol'
         else:
             bodyclass = 'nocol'
     params["body_class"] = bodyclass
     # Render template
     if self.request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
         return self.render_ajax_view(params)
     t = get_template(self.template)
     c = RequestContext(self.request, params)
     return self.response_handler_method(t.render(c))
    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.")
Example #4
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.")
Example #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
     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.")