views.py 6.86 KB
Newer Older
1
from go.models import URL, RegisteredUser
Jean Michel Rouly's avatar
Jean Michel Rouly committed
2
from go.forms import URLForm, SignupForm
3
from datetime import timedelta
4
from django.conf import settings
Jean Michel Rouly's avatar
Jean Michel Rouly committed
5
from django.http import Http404
6
from django.utils import timezone
Jean Michel Rouly's avatar
Jean Michel Rouly committed
7
from django.contrib.auth.models import User
8
from django.core.exceptions import PermissionDenied
9
from django.contrib.auth.decorators import login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
10
from django.shortcuts import render, get_object_or_404, redirect
11
import os
12

Jean Michel Rouly's avatar
Jean Michel Rouly committed
13
14
15
16
17
18
19

##############################################################################
"""
Define useful helper methods here.
"""


20
def is_registered( user ):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
21
22
23
24
25
    """
    This function checks if a user account has a corresponding RegisteredUser,
    thus checking if the user is registered.
    """

26
    try:
27
        registered = RegisteredUser.objects.get( username=user.username )
28
29
30
31
        return True
    except RegisteredUser.DoesNotExist:
        return False

Jean Michel Rouly's avatar
Jean Michel Rouly committed
32
33
34
35
36
37
38

##############################################################################
"""
Define error page handling here.
"""


39
def error_404(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
40
41
42
43
    """
    Error 404 view, in case a url is not found.
    """

44
45
46
47
48
    return render(request, '404.html', {
    },
    )

def error_500(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
49
50
51
52
    """
    Error 500 view, in case a server error occurs.
    """

53
54
55
56
    return render(request, '500.html', {
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
57
58
59
60
61
62
63

##############################################################################
"""
Define user views here.
"""


64
@login_required
Jean Michel Rouly's avatar
Jean Michel Rouly committed
65
def index(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
66
67
68
69
70
71
72
73
74
    """
    This view handles the homepage that the user is presented with when
    they request '/'. If they're not logged in, they're redirected to
    login. If they're logged in but not registered, they're given the
    not_registered error page. If they are logged in AND registered, they
    get the URL registration form.
    """

    # If the user isn't registered, don't give them any leeway.
75
76
77
    if not is_registered(request.user):
        return render(request, 'not_registered.html')

78
79
80
81
82
83
    url_form = URLForm() # unbound form

    if request.method == 'POST':
        url_form = URLForm( request.POST ) # bind dat form
        if url_form.is_valid():

Jean Michel Rouly's avatar
Jean Michel Rouly committed
84
85
            # We don't commit the url object yet because we need to add its
            # owner, and parse its date field.
86
87
88
            url = url_form.save(commit=False)
            url.owner = request.user

Jean Michel Rouly's avatar
Jean Michel Rouly committed
89
            # If the user entered a short url, it's already been validated,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
90
91
            # so accept it. If they did not, however, then generate a
            # random one and use that instead.
92
            short = url_form.cleaned_data.get('short').strip()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
93
94
95
96
            if len(short) > 0:
                url.short = short
            else:
                url.short = URL.generate_valid_short()
97

Jean Michel Rouly's avatar
Jean Michel Rouly committed
98
99
100
            # Grab the expiration field value. It's currently an unsable
            # string value, so we need to parse it into a datetime object
            # relative to right now.
101
            expires = url_form.cleaned_data.get('expires')
102
103
104
105
106
107
108
109
110
111

            if expires == URLForm.DAY:
                url.expires = timezone.now() + timedelta(days=1)
            elif expires == URLForm.WEEK:
                url.expires = timezone.now() + timedelta(weeks=1)
            elif expires == URLForm.MONTH:
                url.expires = timezone.now() + timedelta(weeks=3)
            else:
                pass # leave the field NULL

Jean Michel Rouly's avatar
Jean Michel Rouly committed
112
113
            # Make sure that our new URL object is clean, then save it and
            # let's redirect to view this baby.
114
115
            url.full_clean()
            url.save()
Jean Michel Rouly's avatar
Jean Michel Rouly committed
116
            return redirect('view', url.short)
117
118
119

    return render(request, 'index.html', {
        'form': url_form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
120
121
122
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
123

Jean Michel Rouly's avatar
Jean Michel Rouly committed
124
def view(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
125
126
127
128
129
    """
    This view allows the user to view details about a URL. Note that they
    do not need to be logged in to view info.
    """

Jean Michel Rouly's avatar
Jean Michel Rouly committed
130
131
    url = get_object_or_404(URL, short__iexact = short)
    return render(request, 'view.html', {
132
133
134
135
        'url': url,
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
136

137
@login_required
138
def my_links(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
139
140
141
142
143
    """
    This view displays all the information about all of your URLs. You
    obviously need to be logged in to view your URLs.
    """

144
145
    if not is_registered(request.user):
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
146

147
    urls = URL.objects.filter( owner = request.user )
148
    return render(request, 'my_links.html', {
149
        'urls' : urls,
150
151
152
    },
    )

Jean Michel Rouly's avatar
Jean Michel Rouly committed
153

154
@login_required
155
def delete(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
156
157
158
159
160
    """
    This view deletes a URL if you have the permission to. User must be
    logged in and registered, and must also be the owner of the URL.
    """

161
162
    if not is_registered(request.user):
        return render(request, 'not_registered.html')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
163

Jean Michel Rouly's avatar
Jean Michel Rouly committed
164
    url = get_object_or_404(URL, short__iexact = short )
165
166
    if url.owner == request.user:
        url.delete()
167
168
        return redirect('my_links')
    else:
169
        raise PermissionDenied()
170

Jean Michel Rouly's avatar
Jean Michel Rouly committed
171
172

def signup(request):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
173
174
175
176
177
178
179
180
    """
    This view presents the user with a registration form. You can register
    yourself, or another person.

    TODO: Add email notification to sysadmin that a new registration has
    occurred.
    """

Jean Michel Rouly's avatar
Jean Michel Rouly committed
181
182
183
184
185
186
187
188
    form = SignupForm()

    if request.method == 'POST':
        form = SignupForm( request.POST )
        if form.is_valid():
            username = form.cleaned_data.get('username')
            full_name = form.cleaned_data.get('full_name')
            description = form.cleaned_data.get('description')
189

Jean Michel Rouly's avatar
Jean Michel Rouly committed
190
191
192
193
194
195

            """
            This code simply writes out to a file the registration.
            Ideally, we will be sending an administrator an email instead.
            But we need an email account to do that.
            """
196
197
198
199
200
201
202
203
204
205
206
            f = open(os.path.join(settings.MEDIA_ROOT, 'registrations.txt'), 'a')
            f.write( str(timezone.now()) )
            f.write( str('\n') )
            f.write( str(username) )
            f.write( str('\n') )
            f.write( str(full_name) )
            f.write( str('\n') )
            f.write( str(description) )
            f.write( str('\n\n\n') )
            f.close()

Jean Michel Rouly's avatar
Jean Michel Rouly committed
207
            return redirect('index')
Jean Michel Rouly's avatar
Jean Michel Rouly committed
208

Jean Michel Rouly's avatar
Jean Michel Rouly committed
209
210
    return render(request, 'signup.html', {
        'form': form,
Jean Michel Rouly's avatar
Jean Michel Rouly committed
211
212
    },
    )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
213

Jean Michel Rouly's avatar
Jean Michel Rouly committed
214

Jean Michel Rouly's avatar
Jean Michel Rouly committed
215
def redirection(request, short):
Jean Michel Rouly's avatar
Jean Michel Rouly committed
216
217
218
    """
    This view redirects a user based on the short URL they requested.
    """
Jean Michel Rouly's avatar
Jean Michel Rouly committed
219

Jean Michel Rouly's avatar
Jean Michel Rouly committed
220
    url = get_object_or_404( URL, short__iexact = short )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
221
222
    url.clicks = url.clicks + 1
    url.save()
223

Jean Michel Rouly's avatar
Jean Michel Rouly committed
224
225
226
227
228
    """
    Include server-side tracking because there is no template displayed to
    the user which would include javascript tracking.
    """

229
230
231
232
233
234
235
    from piwikapi.tracking import PiwikTracker
    from django.conf import settings
    piwiktracker = PiwikTracker(settings.PIWIK_SITE_ID, request)
    piwiktracker.set_api_url(settings.PIWIK_URL)
    piwiktracker.do_track_page_view('Redirect to %s' % url.target)

    return redirect( url.target )
Jean Michel Rouly's avatar
Jean Michel Rouly committed
236
237
238
239
240
241
242
243
244
245
246
247
248


##############################################################################
"""
Define static user views here.
"""


def about(request):
    return render(request, 'about.html', {
    },
    )