Пример #1
0
    def send_report(self):
        if settings.DEBUG:
            print_info('New feedback {}. Sending report to managers'.format(
                self.pk))

        context = {'feedback': self, 'site': Site.objects.get_current()}

        subject = render_to_string(
            'spicy.feedback/mail/report_email_subject.txt', context).strip()
        body = render_to_string('spicy.feedback/mail/report_email_body.txt',
                                context)

        send_to = [admin_email for admin_name, admin_email in settings.ADMINS]
        if self.pattern:
            to_emails = []
            for ems in (x.strip().split(',')
                        for x in self.pattern.managers_emails.split('\n')):
                for email in ems:
                    if email:
                        to_emails.append(email)
            if to_emails:
                send_to = to_emails
        mail = EmailMessage(subject=subject,
                            body=body,
                            from_email=self.email
                            or settings.DEFAULT_FROM_EMAIL,
                            to=send_to)

        try:
            mail.send()
        except Exception, e:
            print_error(
                'Error sending email to ADMINS feedback.id={0}: {1}'.format(
                    self.id, str(e)))
            print_text(traceback.format_exc())
Пример #2
0
    def email_user(self, subject, message, email=None, html_body=None):
        email = email or self.email

        if not email:
            # No email - do nothing.
            return

        try:
            mail = EmailMultiAlternatives(subject=subject.strip('\n'),
                                          body=message,
                                          from_email=None,
                                          to=[email],
                                          headers={'format': 'flowed'})
            if html_body:
                mail.attach_alternative(html_body, 'text/html')
            mail.send()
            return True
        except socket.error, e:
            # TODO: log error
            if e.errno == errno.ECONNREFUSED:
                print_error(
                    'Connection refused, please configure your mail server '
                    'correctly.\n')
            else:
                print_error('Can not send mail, error: {}\n'.format(e))
Пример #3
0
def page_not_found(request):
    """
    Default 404 handler.
    """
    if defaults.DEBUG_ERROR_PAGES:
        print_error('handler404: %s %s %s %s\n' % (
            dt.now(), request.GET, request.POST, request.get_full_path()))

    response = render_simplepage(request, '/errors/404/')
    response.status_code = 404
    return response
Пример #4
0
def server_error(request):
    """
    500 error handler.
    """
    if defaults.DEBUG_ERROR_PAGES:
        print_error(
            'handler505: %s %s %s %s\n' %
            (dt.now(), request.GET, request.POST, request.get_full_path()))

    response = render_simplepage(request, '/errors/500/')
    response.status_code = 500
    return response
Пример #5
0
def page_not_found(request):
    """
    Default 404 handler.
    """
    if defaults.DEBUG_ERROR_PAGES:
        print_error(
            'handler404: %s %s %s %s\n' %
            (dt.now(), request.GET, request.POST, request.get_full_path()))

    response = render_simplepage(request, '/errors/404/')
    response.status_code = 404
    return response
Пример #6
0
def server_error(request):
    """
    500 error handler.
    """
    if defaults.DEBUG_ERROR_PAGES:
        print_error(
            'handler505: %s %s %s %s\n' % (
                dt.now(), request.GET, request.POST, request.get_full_path()))

    response = render_simplepage(request, '/errors/500/')
    response.status_code = 500
    return response
Пример #7
0
 def notify_managers(self, user_password=None):
     context = {
         'user': self, 'site': Site.objects.get_current(), 'user_password': user_password}
     subject = render_to_string(
         'spicy.core.profile/mail/notify_managers_subject.txt', context)
     subject = ''.join(subject.splitlines())
     message = render_to_string(
         'spicy.core.profile/mail/notify_managers_email.txt', context)
     try:
         send_mail(
             subject.strip('\n'), message, None,
             [admin_email for admin_name, admin_email in settings.ADMINS])
     except Exception, e:
         print_error(
             'Can not send registration notify, error: {}\n'.format(e))
Пример #8
0
    def update_context(self, context):
        """
        :param context: dictionary for template rendering.
        :type dict

        return context
        """
        if self.use_admin and self.module.__name__ != 'spicy.core.admin.conf':
            # warn: cross import error
            from spicy.core.admin.conf import admin_apps_register
            try:
                context.update(dict(app=admin_apps_register[self.app_name]))
            except KeyError:
                print_error('Can not load admin application class: {0}'.format(
                    self.module.__name__))

        return context
Пример #9
0
    def update_context(self, context):
        """
        :param context: dictionary for template rendering.
        :type dict

        return context
        """
        if self.use_admin and self.module.__name__ != 'spicy.core.admin.conf':
            # warn: cross import error
            from spicy.core.admin.conf import admin_apps_register
            try:
                context.update(dict(app=admin_apps_register[self.app_name]))
            except KeyError:
                print_error('Can not load admin application class: {0}'.format(
                    self.module.__name__))

        return context
Пример #10
0
 def notify_managers(self, user_password=None):
     context = {
         'user': self,
         'site': Site.objects.get_current(),
         'user_password': user_password
     }
     subject = render_to_string(
         'spicy.core.profile/mail/notify_managers_subject.txt', context)
     subject = ''.join(subject.splitlines())
     message = render_to_string(
         'spicy.core.profile/mail/notify_managers_email.txt', context)
     try:
         send_mail(
             subject.strip('\n'), message, None,
             [admin_email for admin_name, admin_email in settings.ADMINS])
     except Exception, e:
         print_error(
             'Can not send registration notify, error: {}\n'.format(e))
    def handle(self, *args, **options):

        from spicy.utils.models import get_custom_model_class
        from spicy.feedback import defaults

        Feedback = get_custom_model_class(defaults.CUSTOM_FEEDBACK_MODEL)
        from spicy.utils.printing import print_error, print_info, print_warning

        now = datetime.datetime.utcnow().replace(tzinfo=utc)

        feedback_timeout = Feedback.objects.filter(
            pattern__isnull=False,
            email_has_been_sent=False,
        ).distinct('email').order_by('email', '-submit_date').values_list(
            'id', 'pattern__auto_response_timeout')

        feedbacks = []

        for id, timeout in feedback_timeout:
            feedbacks.append(
                Feedback.objects.filter(pk=id,
                                        submit_date__lte=now -
                                        timedelta(minutes=timeout)))

        if not feedbacks:
            print_info('Has no new auto feedbacks')
        else:
            totalCount = len(feedbacks)
            sentCount = 0

            print_info('Sending\r\n')
            for feedback in feedbacks[:defaults.MESSAGES_PER_MINUTE]:
                try:
                    print_info('%s\r\n' % feedback.email)
                    feedback.send_using_pattern()
                    sentCount += 1
                except Exception as e:
                    print_error('Error sending to %s: "%s"\r\n' %
                                (feedback.email, str(e)))

            print_info('Total to send: %i\r\nSuccessfully sent: %i\r\n' %
                       (totalCount, sentCount))
Пример #12
0
    def send_to_customers(self, realhost=None):
        if not self.email:
            print_info('This feedback {} has no email for customer response '
                       'generation'.format(self.pk))
            return

        if self.pattern is None:
            print_error('This feedback {} has no response pattern'.format(
                self.pk))
            return

        mail = self.pattern.get_mail(self, realhost)

        try:
            mail.send()
            self.email_has_been_sent = True
            self.save()
        except Exception, e:
            print_error('Error sending email id={0}: {1}'.format(
                self.id, str(e)))
            print_text(traceback.format_exc())
Пример #13
0
    def email_user(self, subject, message, email=None, html_body=None):
        email = email or self.email

        if not email:
            # No email - do nothing.
            return

        try:
            mail = EmailMultiAlternatives(subject=subject.strip('\n'), body=message,
                from_email=None, to=[email], headers={'format': 'flowed'})
            if html_body:
                mail.attach_alternative(html_body, 'text/html')
            mail.send()
            return True
        except socket.error, e:
            # TODO: log error
            if e.errno == errno.ECONNREFUSED:
                print_error(
                    'Connection refused, please configure your mail server '
                    'correctly.\n')
            else:
                print_error('Can not send mail, error: {}\n'.format(e))
Пример #14
0
class AbstractProfile(User, MediaConsumerAbstractModel):
    IS_ACTIVATED = 'Already activated'
    user_ptr = models.OneToOneField(User, parent_link=True)
    activation_key = models.CharField(_('activation key'), max_length=40)
    is_banned = models.BooleanField(_('user is banned'),
                                    blank=True,
                                    default=defaults.MANUAL_ACTIVATION)
    accept_agreement = models.BooleanField(_('Accept user agreement'),
                                           blank=True,
                                           default=True)
    subscribe_me = models.BooleanField(_('Subscribe me for news update'),
                                       blank=True,
                                       default=True)
    hide_email = models.BooleanField(_('Hide my email'), default=True)
    second_name = models.CharField(_('Second name'),
                                   max_length=255,
                                   blank=True)
    phone = models.CharField(_('Phone'), max_length=100, blank=True)
    timezone = models.CharField(max_length=50,
                                default=settings.TIME_ZONE,
                                blank=True)
    google_profile_id = models.CharField(
        _('Google profile ID'),
        max_length=100,
        blank=True,
        help_text=_(
            'Visit http://profiles.google.com/me to find out ID from redirect '
            'URL'))
    sites = models.ManyToManyField(Site, blank=True)

    objects = ProfileManager()
    on_site = CurrentSiteManager(field_name='sites')

    class Meta:
        abstract = True
        ordering = ['-date_joined', '-id']
        #db_table = 'auth_profile'
        permissions = (
            ('view_profile', 'Can view user profiles'),
            ('moderate_profile', 'Can moderate profiles'),
        )

    def save(self, *args, **kwargs):
        is_old = bool(self.id or False)
        if is_old:
            old = self.__class__.objects.get(pk=self.pk)

        result = super(AbstractProfile, self).save(*args, **kwargs)
        if is_old:
            if old.is_banned != self.is_banned:
                self.email_banned()

        elif not self.sites.all():
            self.sites = [Site.objects.get_current()]

        return result

    @classmethod
    def get_field_label(cls, field):
        try:
            label = cls._meta.get_field_by_name(field)[0].verbose_name
        except FieldDoesNotExist:
            try:
                label = getattr(
                    cls,
                    field,
                ).__doc__
            except AttributeError:
                if field.endswith('_id'):
                    label = getattr(cls, field[:-3]).field.verbose_name
                else:
                    raise
        return unicode(label)

    @classmethod
    def get_exported_fields(cls):
        return [
            'username', 'email', 'password', 'first_name', 'second_name',
            'last_name', 'phone', 'subscribe_me'
        ]

    @property
    def screenname(self):
        # Social auth sets a string value to self.fullname, here's a
        # workaround for this shit.
        if hasattr(self, 'fullname'):
            return self.fullname
        return self.get_fullname()

    def get_fullname(self):
        name = self.first_name + ' ' + self.last_name
        if not name.strip():
            name = self.username
        name = escape(name)
        return name

    def __unicode__(self):
        return self.screenname

    def activate(self):
        self.is_active = True
        self.activation_key = self.IS_ACTIVATED
        self.save()

    def check_activation(self):
        if (dt.datetime.now() - self.date_joined) < dt.timedelta(days=1):
            return True
        return self.is_active  # and (self.activation_key == self.IS_ACTIVATED)

    def generate_activation_key(self,
                                send_email=True,
                                password=None,
                                realhost=None,
                                next_url=None):
        if next_url is None:
            next_url = settings.LOGIN_URL
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
        username = smart_str(self.username)
        self.activation_key = sha_constructor(salt + username).hexdigest()
        self.date_joined = dt.datetime.now()
        self.save()
        if send_email:
            self.email_activation_key(password, realhost, next_url=next_url)

    def activation_key_expired(self):
        expiration_date = dt.timedelta(
            days=int(defaults.ACCOUNT_ACTIVATION_DAYS))
        return self.activation_key == self.IS_ACTIVATED or (
            self.date_joined + expiration_date <= dt.datetime.now())

    activation_key_expired.boolean = True

    def get_hash(self, email=None):
        if email is None:
            email = self.email
        key = ':'.join((str(self.pk), email, settings.SECRET_KEY))
        return sha_constructor(key).hexdigest()

    def email_user(self, subject, message, email=None, html_body=None):
        email = email or self.email

        if not email:
            # No email - do nothing.
            return

        try:
            mail = EmailMultiAlternatives(subject=subject.strip('\n'),
                                          body=message,
                                          from_email=None,
                                          to=[email],
                                          headers={'format': 'flowed'})
            if html_body:
                mail.attach_alternative(html_body, 'text/html')
            mail.send()
            return True
        except socket.error, e:
            # TODO: log error
            if e.errno == errno.ECONNREFUSED:
                print_error(
                    'Connection refused, please configure your mail server '
                    'correctly.\n')
            else:
                print_error('Can not send mail, error: {}\n'.format(e))
        except smtplib.SMTPException, e:
            print_error('Can not send mail, SMTP error: {}\n'.format(e))