functions.py 8.64 KB
Newer Older
Antony Chazapis's avatar
Antony Chazapis committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Copyright 2011 GRNET S.A. All rights reserved.
# 
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
# 
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
# 
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# 
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

import logging
35
import socket
Antony Chazapis's avatar
Antony Chazapis committed
36
37
38
39
40

from django.utils.translation import ugettext as _
from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
41
from django.core.exceptions import ValidationError
42
from django.template import Context, loader
43

44
from urllib import quote
Antony Chazapis's avatar
Antony Chazapis committed
45
from urlparse import urljoin
46
from smtplib import SMTPException
Antony Chazapis's avatar
Antony Chazapis committed
47

48
from astakos.im.settings import DEFAULT_CONTACT_EMAIL, DEFAULT_FROM_EMAIL, SITENAME, BASEURL, DEFAULT_ADMIN_EMAIL
49
from astakos.im.models import Invitation, AstakosUser
Antony Chazapis's avatar
Antony Chazapis committed
50
51
52

logger = logging.getLogger(__name__)

53
def send_verification(user, template_name='im/activation_email.txt'):
Antony Chazapis's avatar
Antony Chazapis committed
54
    """
55
    Send email to user to verify his/her email and activate his/her account.
Antony Chazapis's avatar
Antony Chazapis committed
56
    
57
    Raises SendVerificationError
Antony Chazapis's avatar
Antony Chazapis committed
58
    """
59
60
61
62
63
64
65
66
67
68
    url = '%s?auth=%s&next=%s' % (urljoin(BASEURL, reverse('astakos.im.views.activate')),
                                    quote(user.auth_token),
                                    quote(BASEURL))
    message = render_to_string(template_name, {
            'user': user,
            'url': url,
            'baseurl': BASEURL,
            'site_name': SITENAME,
            'support': DEFAULT_CONTACT_EMAIL})
    sender = DEFAULT_FROM_EMAIL
69
70
71
72
73
74
75
    try:
        send_mail('%s alpha2 testing account activation is needed' % SITENAME, message, sender, [user.email])
    except (SMTPException, socket.error) as e:
        logger.exception(e)
        raise SendVerificationError()
    else:
        logger.info('Sent activation %s', user)
76

77
def send_admin_notification(user, template_name='im/admin_notification.txt'):
78
79
80
    """
    Send email to DEFAULT_ADMIN_EMAIL to notify for a new user registration.
    
81
    Raises SendNotificationError
82
83
84
85
86
87
88
89
90
    """
    if not DEFAULT_ADMIN_EMAIL:
        return
    message = render_to_string(template_name, {
            'user': user,
            'baseurl': BASEURL,
            'site_name': SITENAME,
            'support': DEFAULT_CONTACT_EMAIL})
    sender = DEFAULT_FROM_EMAIL
91
92
93
94
95
96
97
    try:
        send_mail('%s alpha2 testing account notification' % SITENAME, message, sender, [DEFAULT_ADMIN_EMAIL])
    except (SMTPException, socket.error) as e:
        logger.exception(e)
        raise SendNotificationError()
    else:
        logger.info('Sent admin notification for user %s', user)
98
99
100
101
102

def send_invitation(invitation, template_name='im/invitation.txt'):
    """
    Send invitation email.
    
103
    Raises SendInvitationError
104
105
    """
    subject = _('Invitation to %s alpha2 testing' % SITENAME)
106
    url = '%s?code=%d' % (urljoin(BASEURL, reverse('astakos.im.views.index')), invitation.code)
107
108
109
110
111
112
113
    message = render_to_string('im/invitation.txt', {
                'invitation': invitation,
                'url': url,
                'baseurl': BASEURL,
                'site_name': SITENAME,
                'support': DEFAULT_CONTACT_EMAIL})
    sender = DEFAULT_FROM_EMAIL
114
115
116
117
118
119
120
    try:
        send_mail(subject, message, sender, [invitation.username])
    except (SMTPException, socket.error) as e:
        logger.exception(e)
        raise SendInvitationError()
    else:
        logger.info('Sent invitation %s', invitation)
121
122
123
124

def send_greeting(user, email_template_name='im/welcome_email.txt'):
    """
    Send welcome email.
Antony Chazapis's avatar
Antony Chazapis committed
125
126
127
    
    Raises SMTPException, socket.error
    """
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
128
    subject = _('Welcome to %s alpha2 testing' % SITENAME)
Antony Chazapis's avatar
Antony Chazapis committed
129
130
    message = render_to_string(email_template_name, {
                'user': user,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
131
                'url': urljoin(BASEURL, reverse('astakos.im.views.index')),
Antony Chazapis's avatar
Antony Chazapis committed
132
133
                'baseurl': BASEURL,
                'site_name': SITENAME,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
134
                'support': DEFAULT_CONTACT_EMAIL})
135
    sender = DEFAULT_FROM_EMAIL
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    try:
        send_mail(subject, message, sender, [user.email])
    except (SMTPException, socket.error) as e:
        logger.exception(e)
        raise SendGreetingError()
    else:
        logger.info('Sent greeting %s', user)

def send_feedback(msg, data, user, email_template_name='im/feedback_mail.txt'):
    subject = _("Feedback from %s alpha2 testing" % SITENAME)
    from_email = user.email
    recipient_list = [DEFAULT_CONTACT_EMAIL]
    content = render_to_string(email_template_name, {
        'message': msg,
        'data': data,
        'user': user})
    try:
        send_mail(subject, content, from_email, recipient_list)
    except (SMTPException, socket.error) as e:
        logger.exception(e)
        raise SendFeedbackError()
    else:
        logger.info('Sent feedback from %s', user.email)
Antony Chazapis's avatar
Antony Chazapis committed
159

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def send_change_email(ec, request, email_template_name='registration/email_change_email.txt'):
    try:
        url = reverse('email_change_confirm',
                      kwargs={'activation_key':ec.activation_key})
        url = request.build_absolute_uri(url)
        t = loader.get_template(email_template_name)
        c = {'url': url, 'site_name': SITENAME}
        from_email = DEFAULT_FROM_EMAIL
        send_mail(_("Email change on %s alpha2 testing") % SITENAME,
            t.render(Context(c)), from_email, [ec.new_email_address])
    except (SMTPException, socket.error) as e:
        logger.exception(e)
        raise ChangeEmailError()
    else:
        logger.info('Sent change email for %s', ec.user.email)

176
177
178
179
def activate(user, email_template_name='im/welcome_email.txt'):
    """
    Activates the specific user and sends email.
    
180
    Raises SendGreetingError, ValidationError
181
182
183
184
185
    """
    user.is_active = True
    user.save()
    send_greeting(user, email_template_name)

186
def invite(invitation, inviter, email_template_name='im/welcome_email.txt'):
Antony Chazapis's avatar
Antony Chazapis committed
187
188
189
    """
    Send an invitation email and upon success reduces inviter's invitation by one.
    
190
    Raises SendInvitationError
Antony Chazapis's avatar
Antony Chazapis committed
191
    """
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
192
193
    invitation.inviter = inviter
    invitation.save()
194
    send_invitation(invitation, email_template_name)
Antony Chazapis's avatar
Antony Chazapis committed
195
    inviter.invitations = max(0, inviter.invitations - 1)
196
    inviter.save()
197
198
199

def set_user_credibility(email, has_credits):
    try:
200
        user = AstakosUser.objects.get(email=email, is_active=True)
201
202
203
        user.has_credits = has_credits
        user.save()
    except AstakosUser.DoesNotExist, e:
204
        logger.exception(e)
205
206
    except ValidationError, e:
        logger.exception(e)
207
208

class SendMailError(Exception):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
209
    pass
210
211
212
213

class SendAdminNotificationError(SendMailError):
    def __init__(self):
        self.message = _('Failed to send notification')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
214
        super(SendAdminNotificationError, self).__init__()
215

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
216
class SendVerificationError(SendMailError):
217
218
    def __init__(self):
        self.message = _('Failed to send verification')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
219
        super(SendVerificationError, self).__init__()
220

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
221
class SendInvitationError(SendMailError):
222
223
    def __init__(self):
        self.message = _('Failed to send invitation')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
224
        super(SendInvitationError, self).__init__()
225

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
226
class SendGreetingError(SendMailError):
227
228
    def __init__(self):
        self.message = _('Failed to send greeting')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
229
        super(SendGreetingError, self).__init__()
230

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
231
class SendFeedbackError(SendMailError):
232
233
    def __init__(self):
        self.message = _('Failed to send feedback')
234
235
236
237
238
239
        super(SendFeedbackError, self).__init__()

class ChangeEmailError(SendMailError):
    def __init__(self):
        self.message = _('Failed to send change email')
        super(ChangeEmailError, self).__init__()