views.py 11.9 KB
Newer Older
stef's avatar
stef committed
1
from forms import AddViolation, SearchViolation
stef's avatar
stef committed
2
from django.http import HttpResponse, HttpResponseRedirect, Http404
3
from django.shortcuts import render_to_response, get_object_or_404
4
from django.template import RequestContext
stef's avatar
stef committed
5
6
from django.core.files import File
from django.conf import settings
stef's avatar
stef committed
7
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
8
from django.core.exceptions import ObjectDoesNotExist
9
from django.contrib import messages
10
from django.contrib.auth.models import User
stef's avatar
stef committed
11
from django.utils.translation import ugettext_lazy as _
stef's avatar
stef committed
12
from django.db.models import Count
13
from models import Violation, Attachment, Comment, Confirmation, COUNTRIES
stef's avatar
stef committed
14
15
from tempfile import mkstemp
from datetime import datetime
16
17
18
import hashlib, os, re, json, smtplib
from random import randint
from email.mime.text import MIMEText
stef's avatar
stef committed
19
from email.header import Header
20
21
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup, Comment as BComment
stef's avatar
stef committed
22
from operator import itemgetter
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

def sanitizeHtml(value, base_url=None):
    rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:'))
    rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:'))
    re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)
    validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()
    validAttrs = 'href src width height'.split()
    urlAttrs = 'href src'.split() # Attributes which should have a URL
    soup = BeautifulSoup(value)
    for comment in soup.findAll(text=lambda text: isinstance(text, BComment)):
        # Get rid of comments
        comment.extract()
    for tag in soup.findAll(True):
        if tag.name not in validTags:
            tag.hidden = True
        attrs = tag.attrs
        tag.attrs = []
        for attr, val in attrs:
            if attr in validAttrs:
                val = re_scripts.sub('', val) # Remove scripts (vbs & js)
                if attr in urlAttrs:
                    val = urljoin(base_url, val) # Calculate the absolute url
                tag.attrs.append((attr, val))

    return soup.renderContents().decode('utf8')
stef's avatar
stef committed
48

49
def activate(request):
50
51
52
    try:
        v=Violation.objects.get(activationid=request.GET.get('key','asdf'))
    except:
53
        return HttpResponse(_('Thank you, this key has been already activated'))
54
55
56
    if v:
        actid = hashlib.sha1(''.join([chr(randint(32, 122)) for x in range(12)])).hexdigest()
        to=[x.email for x in User.objects.filter(groups__name='moderator')]
stef's avatar
stef committed
57
58
59
        details='\n'.join(["%s: %s" % (k.capitalize(), val) for k,val in v.__dict__.items() if not k.startswith('_') and val])
        msg = MIMEText("A new report was submitted. To approve click here: %s/moderate/?key=%s\n\nDetails follow:\n%s\n%s" %
                       (settings.ROOT_URL or 'http://localhost:8001/', actid, details, v.comment_set.get().comment), _charset="utf-8")
stef's avatar
stef committed
60
        msg['Subject'] = 'NNMon submission approval'.encode("Utf-8")
stef's avatar
stef committed
61
        msg['From'] = 'nnmon@respectmynet.eu'
62
63
        msg['To'] = ', '.join(to)
        s = smtplib.SMTP('localhost')
stef's avatar
stef committed
64
        s.sendmail('nnmon@respectmynet.eu', to, msg.as_string())
65
66
67
        s.quit()
        v.activationid=actid
        v.save()
Benjamin Sonntag's avatar
Benjamin Sonntag committed
68
        messages.add_message(request, messages.INFO, _('Thank you for verifying your submission. It will be listed shortly, after we\'ve checked that the report is valid.').encode("Utf-8"))
69
70
    return HttpResponseRedirect('/') # Redirect after POST

71
def moderate(request):
72
73
74
    try:
        v=Violation.objects.get(activationid=request.GET.get('key','asdf'))
    except:
stef's avatar
stef committed
75
        return HttpResponse(_('Thank you, this key has been already activated'))
76
77
78
79
    if not v:
        messages.add_message(request, messages.INFO, _('No such key'))
        return HttpResponseRedirect('/') # Redirect after POST
    if request.GET.get('action','')=='approve':
stef's avatar
stef committed
80
81
82
83
84
85
86
87
88
        messages.add_message(request, messages.INFO, _('Thank you for approving the <a href="/view/%s">submission</a>.' % v.id))

        msg = MIMEText(_("Your report has been approved.\nTo see it, please visit: %s/view/%s") % (settings.ROOT_URL or 'http://localhost:8001/', v.id), _charset="utf-8")
        msg['Subject'] = Header(_('NNMon submission approved').encode("Utf-8"), 'utf-8')
        msg['From'] = 'nnmon@respectmynet.eu'
        msg['To'] = v.comment_set.get().submitter_email
        s = smtplib.SMTP('localhost')
        s.sendmail('nnmon@respectmynet.eu', [msg['To']], msg.as_string())
        s.quit()
89
        if settings.TWITTER_API:
stef's avatar
stef committed
90
            try:
stef's avatar
stef committed
91
                settings.TWITTER_API.PostUpdate("New #NetNeutrality violation reported for %s (%s) %s %s/%s" % (v.operator, v.country, v.contract, settings.ROOT_URL or 'http://localhost:8001/', v.id))
stef's avatar
stef committed
92
93
            except:
                pass
94
95
        v.activationid=''
        v.save()
96
        return HttpResponseRedirect('/view/%s' % v.id ) # Redirect after POST
97
98
99
100
101
102
    if request.GET.get('action','')=='delete':
        v.delete()
        messages.add_message(request, messages.INFO, _('Thank you for deleting the submission.'))
        return HttpResponseRedirect('/') # Redirect after POST
    return render_to_response('view.html', { 'v': v, 'key': request.GET.get('key') },context_instance=RequestContext(request))

stef's avatar
stef committed
103
104
105
def confirm(request, id, name=None):
    if name:
        if Confirmation.objects.filter(email=name, violation=id).count()==0:
stef's avatar
stef committed
106
107
            msg=_("Thank you for confirming a case. To finalize your confirmation please validate using your confirmation key.\nYour confirmation key is %s/%s%s")
            actid=sendverifymail('confirm/',name, msg)
108
109
110
            try:
                c=Confirmation(key=actid, email=name, violation=Violation.objects.get(pk=id))
            except:
stef's avatar
stef committed
111
                return HttpResponse(unicode(_("Thank you, this has been already confirmed")))
stef's avatar
stef committed
112
            c.save()
stef's avatar
stef committed
113
        return HttpResponse('<div class="confirm_thanks">%s</div>' % unicode(_('Thank you for your confirmation')) )
stef's avatar
stef committed
114
115
116
117
118
119
    try:
        c = get_object_or_404(Confirmation, key=id)
    except:
        return HttpResponse(unicode(_("Thank you, this has been already confirmed")))
    c.key=''
    c.save()
stef's avatar
stef committed
120
    messages.add_message(request, messages.INFO, unicode(_('Thank you for verifying your confirmation')))
121
    return HttpResponseRedirect('/') # Redirect after POST
stef's avatar
stef committed
122

stef's avatar
stef committed
123
def sendverifymail(service,to,msg):
stef's avatar
stef committed
124
    actid = hashlib.sha1(''.join([chr(randint(32, 122)) for x in range(12)])).hexdigest()
stef's avatar
stef committed
125
    msg = MIMEText(msg % (settings.ROOT_URL or 'http://localhost:8001/', service, actid), _charset="utf-8")
stef's avatar
stef committed
126
    msg['Subject'] = Header(_('NNMon submission verification').encode("Utf-8"), 'utf-8')
stef's avatar
stef committed
127
    msg['From'] = 'nnmon@respectmynet.eu'
stef's avatar
stef committed
128
    msg['To'] = Header(to.encode("Utf-8"), 'utf-8')
stef's avatar
stef committed
129
    s = smtplib.SMTP('localhost')
stef's avatar
stef committed
130
    s.sendmail('nnmon@respectmynet.eu', [to], msg.as_string())
stef's avatar
stef committed
131
132
133
    s.quit()
    return actid

stef's avatar
stef committed
134
def add(request):
stef's avatar
stef committed
135
136
137
    if request.method == 'POST':
        form = AddViolation(request.POST)
        if form.is_valid():
stef's avatar
stef committed
138
139
            msg=_("Thank you for submitting a new report. To finalize your submission please confirm using your validation key.\nYour verification key is %s/%s%s\nPlease note that reports are moderated, it might take some time before your report appears online. Thank you for your patience.")
            actid=sendverifymail('activate?key=',form.cleaned_data['email'], msg)
stef's avatar
stef committed
140
141
142
143
144
            v=Violation(
                country = form.cleaned_data['country'],
                operator = form.cleaned_data['operator'],
                contract = form.cleaned_data['contract'],
                resource = form.cleaned_data['resource'],
stef's avatar
stef committed
145
                resource_name = form.cleaned_data['resource_name'],
stef's avatar
stef committed
146
147
148
149
                type = form.cleaned_data['type'],
                media = form.cleaned_data['media'],
                temporary = form.cleaned_data['temporary'],
                contractual = form.cleaned_data['contractual'],
150
                contract_excerpt = sanitizeHtml(form.cleaned_data['contract_excerpt']),
151
152
                loophole = form.cleaned_data['loophole'],
                activationid = actid
stef's avatar
stef committed
153
154
                )
            v.save()
stef's avatar
stef committed
155
156
            #c=Confirmation(key='', email=form.cleaned_data['email'], violation=v)
            #c.save()
stef's avatar
stef committed
157
158
            c = Comment(
                comment=form.cleaned_data['comment'],
159
160
                submitter_email=form.cleaned_data['email'],
                submitter_name=form.cleaned_data['nick'],
stef's avatar
stef committed
161
162
163
164
165
                timestamp=datetime.now(),
                violation=v,
                )
            c.save()
            for f in request.FILES.getlist('attachments[]'):
166
167
168
169
170
171
                a=Attachment(comment=c, name=f.name)
                m = hashlib.sha256()
                for chunk in f.chunks():
                    m.update(chunk)
                sname=m.hexdigest()
                a.storage.save(sname,f)
stef's avatar
stef committed
172
                a.save()
173

stef's avatar
stef committed
174
            messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email shortly.'))
stef's avatar
stef committed
175
176
            return HttpResponseRedirect('/') # Redirect after POST
    else:
stef's avatar
stef committed
177
        form = AddViolation()
stef's avatar
stef committed
178

179
    v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
stef's avatar
stef committed
180
    return render_to_response(
181
        'index.html',
182
183
        { 'form': form,
          'violations': v_list },
stef's avatar
stef committed
184
        context_instance=RequestContext(request))
stef's avatar
stef committed
185

186
187
def ajax(request, country=None, operator=None):
    if not operator:
188
        return HttpResponse(json.dumps(sorted(list(set([x.operator for x in Violation.objects.filter(country=country,activationid='')])))))
189
    else:
190
        return HttpResponse(json.dumps(sorted(list(set([x.contract for x in Violation.objects.filter(country=country,activationid='',operator=operator)])))))
stef's avatar
stef committed
191
192

def index(request):
193
    v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
stef's avatar
stef committed
194
195
196
197
198
199
200
    form = AddViolation()

    return render_to_response(
        'index.html',
        { 'form': form,
          'violations': v_list },
        context_instance=RequestContext(request))
201
202
203
204
205
206
207
208
209

def filter_violations(request, country, operator=None):
    if country not in map(itemgetter(0),COUNTRIES):
        raise Http404
    if not operator:
        violations = Violation.objects.filter(activationid='', country=country)
    else:
        violations = Violation.objects.filter(activationid='', country=country, operator=operator)
    return render_to_response('list.html', {"violations": violations},context_instance=RequestContext(request))
stef's avatar
stef committed
210
211

def list_violations(request):
212
    violations = Violation.objects.filter(activationid='')
stef's avatar
stef committed
213
214
215
216
217
218
219
220
221
222
223
224
    countries=sorted([(i['total'],i['country'])
                      for i in Violation.objects.values('country').filter(activationid='').annotate(total=Count('country'))],
                     reverse=True)
    countries=json.dumps(dict([(c.lower(),"#ff%x00" % (3*int(64*(float(w)/countries[0][0]))+63)) for w,c in countries]))
    #confirms=sorted([(i['total'],i['country'])
    #                 for i in Violation.objects.values('country').filter(activationid='').annotate(total=Count('confirmation'))],
    #                reverse=True)
    return render_to_response('list.html',
                              {"violations": violations,
                               "countries": countries,},
                               #"confirms": confirms,},
                              context_instance=RequestContext(request))
225
226
227

def view(request,id):
    v = get_object_or_404(Violation, pk=id)
228
229
    if v.activationid:
        raise Http404
stef's avatar
stef committed
230
    return render_to_response('view.html', { 'v': v, },context_instance=RequestContext(request))
stef's avatar
stef committed
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

def lookup(request):
    if request.method == 'GET':
        form = SearchViolation(request.GET)
        if form.is_valid():
            v=Violation.objects.filter(
                country = form.cleaned_data['country'],
                operator = form.cleaned_data['operator'],
                contract = form.cleaned_data['contract'],
                media = form.cleaned_data['media'],
                activationid = ''
                )
            res=json.dumps(sorted([(x.id,x.resource_name) for x in v],reverse=True))
            return HttpResponse(res)
    return HttpResponse('')