Slightly improved vessel history download form
[ais.git] / bin / djais / views.py
1 # -*- coding: utf-8 -*-
2
3 #from __future__ import division
4
5 import os
6 from datetime import *
7 import re
8 from time import time as get_timestamp
9 import logging
10 import crack
11 import struct
12 import operator
13 import rrdtool
14 import csv
15 from StringIO import StringIO
16 from django.http import *
17 from django.template import loader, RequestContext
18 from django import forms
19 from django.shortcuts import render_to_response, get_object_or_404
20 from django.db import IntegrityError
21
22 from decoratedstr import remove_decoration
23
24 from ais.djais.basicauth import http_authenticate
25 from ais.djais.models import *
26 from ais.show_targets_ships import *
27 from ais.common import COUNTRIES_MID, Nmea, NmeaFeeder, strmmsi_to_mmsi, SHIP_TYPES, STATUS_CODES, AIS_STATUS_NOT_AVAILABLE, AIS_ROT_NOT_AVAILABLE, AIS_LATLON_SCALE, AIS_LON_NOT_AVAILABLE, AIS_LAT_NOT_AVAILABLE, AIS_COG_SCALE, AIS_COG_NOT_AVAILABLE, AIS_NO_HEADING, AIS_SOG_SCALE, AIS_SOG_NOT_AVAILABLE, AIS_SOG_MAX_SPEED, add_nmea1, add_nmea5_partial, load_fleet_to_uset
28 from ais.ntools import datetime_to_timestamp, clean_ais_charset
29 from ais.inputs.common import is_id4_active
30 from ais.inputs.stats import STATS_DIR
31 from ais.inputs.config import peers_get_config
32
33 def auth(username, raw_password):
34     try:
35         user = User.objects.get(login=username)
36     except User.DoesNotExist:
37         return None
38     if not user.check_password(raw_password):
39         return None
40     user.update_access_datetime()
41     return user
42
43
44 @http_authenticate(auth, 'ais')
45 def index(request):
46     news = News.objects.order_by('-created')[:5]
47     return render_to_response('index.html', {'news':news}, RequestContext(request))
48
49
50 class VesselSearchForm(forms.Form):
51     def country_choices():
52         choices = {}
53         for mid, countryname in COUNTRIES_MID.iteritems():
54             if choices.has_key(countryname):
55                 choices[countryname] += u','+unicode(mid)
56             else:
57                 choices[countryname] = unicode(mid)
58         choices = [ (countryname, mids) for mids, countryname in choices.iteritems() ]
59         choices = sorted(choices, key=operator.itemgetter(1))
60         return [(u'', u'Any')] + choices
61
62     mmsi = forms.CharField(max_length=9, required=False)
63     name = forms.CharField(max_length=20, required=False)
64     imo = forms.IntegerField(required=False)
65     callsign = forms.CharField(max_length=7, required=False)
66     flag = forms.ChoiceField(choices=country_choices(), required=False)
67     destination = forms.CharField(max_length=20, required=False)
68
69
70     def clean(self):
71         cleaned_data = self.cleaned_data
72         for value in cleaned_data.values():
73             if value:
74                 return cleaned_data
75         raise forms.ValidationError("You must enter at least one criteria")
76
77     def clean_mmsi(self):
78         mmsi = self.cleaned_data['mmsi']
79         try:
80             mmsi = strmmsi_to_mmsi(mmsi)
81         except AssertionError:
82             raise forms.ValidationError("Invalid MMSI")
83         return mmsi
84
85
86 @http_authenticate(auth, 'ais')
87 def vessel_search(request):
88     if request.method == 'POST' or request.META['QUERY_STRING']:
89         form = VesselSearchForm(request.REQUEST)
90         if form.is_valid():
91             data = form.cleaned_data
92             vessels = Vessel.objects
93             if data['mmsi']:
94                 vessels = vessels.filter(mmsi=data['mmsi'])
95             if data['name']:
96                 vessels = vessels.filter(name__contains=data['name'].upper())
97             if data['imo']:
98                 vessels = vessels.filter(imo=data['imo'])
99             if data['callsign']:
100                 vessels = vessels.filter(callsign__contains=data['callsign'].upper())
101             if data['destination']:
102                 vessels = vessels.filter(destination__contains=data['destination'].upper())
103             if data['flag']:
104                 vessels = vessels.extra(where=['mmsi/1000000 IN (%s) ' % data['flag']])
105             return render_to_response('vessels.html', {'vessels': vessels}, RequestContext(request))
106     else: # GET
107         form = VesselSearchForm()
108
109     return render_to_response('vessel_index.html', {'form': form}, RequestContext(request))
110
111 @http_authenticate(auth, 'ais')
112 def vessel(request, strmmsi):
113     mmsi = strmmsi_to_mmsi(strmmsi)
114     vessel = get_object_or_404(Vessel, pk=mmsi)
115     nmea = Nmea.new_from_lastinfo(strmmsi)
116     #if not nmea.timestamp_1 and not nmea.timestamp_5:
117     #    raise Http404
118     return render_to_response('vessel.html', {'nmea': nmea}, RequestContext(request))
119
120
121 class VesselManualInputForm(forms.Form):
122     timestamp = forms.DateTimeField(label=u'When', help_text=u'When was the observation made in GMT. Use YYYY-MM-DD HH:MM:SS format')
123     imo = forms.IntegerField(required=False, min_value=1000000, max_value=9999999)
124     name = forms.CharField(max_length=20, required=False)
125     callsign = forms.CharField(max_length=7, required=False)
126     type = forms.TypedChoiceField(required=False, choices = [ kv for kv in SHIP_TYPES.iteritems() if 'reserved' not in kv[1].lower()], coerce=int, empty_value=0, initial=0)
127     status = forms.TypedChoiceField(required=False, choices = [ kv for kv in STATUS_CODES.iteritems() if 'reserved' not in kv[1].lower()], coerce=int, empty_value=AIS_STATUS_NOT_AVAILABLE, initial=AIS_STATUS_NOT_AVAILABLE)
128     sog = forms.FloatField(label='Speed', help_text='Over ground, in knots', required=False, min_value=0, max_value=AIS_SOG_MAX_SPEED/AIS_SOG_SCALE)
129     latitude = forms.CharField(required=False)
130     longitude = forms.CharField(required=False)
131     cog = forms.FloatField(label='Course', help_text='Over ground', required=False, min_value=0.0, max_value=359.9)
132     heading = forms.IntegerField(required=False, min_value=0, max_value=359)
133
134     @staticmethod
135     def _clean_ais_charset(ustr):
136         ustr = remove_decoration(ustr) # benign cleaning, but can increase size (œ->oe)
137         ustr = ustr.upper() # benign cleaning
138         str = clean_ais_charset(ustr.encode('ascii', 'replace'))
139         if unicode(str) != ustr:
140             raise forms.ValidationError('Invalid character: AIS alphabet is @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^- !"#$%&\'()*+,-./0123456789:;<=>?')
141         return str
142
143     def clean_timestamp(self):
144         data = self.cleaned_data['timestamp']
145         if data is None:
146             return None
147         if data < datetime.utcnow() - timedelta(365):
148             raise forms.ValidationError('Date is too much is the past.')
149         if data > datetime.utcnow():
150             raise forms.ValidationError('Date is be in the future. This form is only for observed results.')
151         return datetime_to_timestamp(data)
152
153     def clean_imo(self):
154         data = self.cleaned_data['imo']
155         if data is None:
156             return 0
157         return data
158
159     def clean_name(self):
160         name = self.cleaned_data['name']
161         if name is None:
162             return ''
163         name = VesselManualInputForm._clean_ais_charset(name)
164         if len(name)>20:
165             raise forms.ValidationError('Ensure this value has at most 20 characters (it has %s).' % len(name))
166         return name
167
168     def clean_callsign(self):
169         callsign = self.cleaned_data['callsign']
170         if callsign is None:
171             return ''
172         callsign = VesselManualInputForm._clean_ais_charset(callsign)
173         if len(callsign)>7:
174             raise forms.ValidationError('Ensure this value has at most 7 characters (it has %s).' % len(callsign))
175         return callsign
176
177     def clean_sog(self):
178         sog = self.cleaned_data['sog']
179         if sog is None:
180             return AIS_SOG_NOT_AVAILABLE
181         return int(sog*AIS_SOG_SCALE)
182
183     def clean_latitude(self):
184         data = self.cleaned_data['latitude']
185         data = data.replace(u"''", u'"') # commong mistake
186         data = data.replace(u' ', u'') # remove spaces
187         sides = u'SN'
188         if not data:
189             return AIS_LAT_NOT_AVAILABLE
190         tmp, side = data[:-1], data[-1]
191         if side == sides[0]:
192             side = -1
193         elif side == sides[1]:
194             side = 1
195         else:
196             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
197         spl = tmp.split(u'°')
198         if len(spl) == 1:
199             raise forms.ValidationError(u'You need to use the ° character.')
200         d, tmp = spl
201         try:
202             d = float(d)
203         except ValueError:
204             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
205         spl = tmp.split(u"'", 1)
206         if len(spl) == 1:
207             # no ' sign: ok only if there is nothing but the side after °
208             # we don't accept seconds if there is no minutes:
209             # It might be an entry mistake
210             tmp = spl[0]
211             if len(tmp) == 0:
212                 m = s = 0
213             else:
214                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
215         else:
216             m, tmp = spl
217             try:
218                 m = float(m)
219             except ValueError:
220                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
221             if len(tmp) == 0:
222                 s = 0
223             else:
224                 if tmp[-1] != '"':
225                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
226                 s = tmp[:-1]
227                 try:
228                     s = float(s)
229                 except ValueError:
230                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
231         data = side * ( d + m / 60 + s / 3600)
232
233         if data < -90 or data > 90:
234             raise forms.ValidationError(u'%s in not in -90..90 range' % data)
235         return int(data * AIS_LATLON_SCALE)
236
237     def clean_longitude(self):
238         data = self.cleaned_data['longitude']
239         data = data.replace(u"''", u'"') # commong mistake
240         data = data.replace(u' ', u'') # remove spaces
241         sides = u'WE'
242         if not data:
243             return AIS_LON_NOT_AVAILABLE
244         tmp, side = data[:-1], data[-1]
245         if side == sides[0]:
246             side = -1
247         elif side == sides[1]:
248             side = 1
249         else:
250             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
251         spl = tmp.split(u'°')
252         if len(spl) == 1:
253             raise forms.ValidationError(u'You need to use the ° character.')
254         d, tmp = spl
255         try:
256             d = float(d)
257         except ValueError:
258             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
259         spl = tmp.split(u"'", 1)
260         if len(spl) == 1:
261             # no ' sign: ok only if there is nothing but the side after °
262             # we don't accept seconds if there is no minutes:
263             # It might be an entry mistake
264             tmp = spl[0]
265             if len(tmp) == 0:
266                 m = s = 0
267             else:
268                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
269         else:
270             m, tmp = spl
271             try:
272                 m = float(m)
273             except ValueError:
274                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
275             if len(tmp) == 0:
276                 s = 0
277             else:
278                 if tmp[-1] != '"':
279                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
280                 s = tmp[:-1]
281                 try:
282                     s = float(s)
283                 except ValueError:
284                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
285         data = side * ( d + m / 60 + s / 3600)
286
287         if data < -180 or data > 180:
288             raise forms.ValidationError(u'%s in not in -180..180 range' % data)
289         return int(data * AIS_LATLON_SCALE)
290
291     def clean_cog(self):
292         data = self.cleaned_data['cog']
293         if data is None:
294             return AIS_COG_NOT_AVAILABLE
295         return int(data * AIS_COG_SCALE)
296     
297     def clean_heading(self):
298         #raise forms.ValidationError(u'clean_heading called')
299         data = self.cleaned_data['heading']
300         if data is None:
301             return AIS_NO_HEADING
302         return data
303
304     def clean(self):
305         cleaned_data = self.cleaned_data
306         if (cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE ) ^ ( cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE):
307             raise forms.ValidationError('It makes no sense to enter just a latitude or a longitude. Enter both or none.')
308         if cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE:
309             if cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) != AIS_STATUS_NOT_AVAILABLE:
310                 raise forms.ValidationError('It makes no sense to enter a status without coordinates. Please enter latitute and longitude too.')
311             if cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) != AIS_SOG_NOT_AVAILABLE:
312                 raise forms.ValidationError('It makes no sense to enter a speed without coordinates. Please enter latitute and longitude too.')
313             if cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) != AIS_COG_NOT_AVAILABLE:
314                 raise forms.ValidationError('It makes no sense to enter a course without coordinates. Please enter latitute and longitude too.')
315             if cleaned_data.get('heading', AIS_NO_HEADING) != AIS_NO_HEADING:
316                 raise forms.ValidationError('It makes no sense to enter a heading without coordinates. Please enter latitute and longitude too.')
317
318         if cleaned_data.get('timestamp', None) \
319         and cleaned_data.get('imo', 0) == 0 \
320         and cleaned_data.get('name', '') == '' \
321         and cleaned_data.get('callsign', '') == '' \
322         and cleaned_data.get('type', 0) == 0 \
323         and cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) == AIS_STATUS_NOT_AVAILABLE \
324         and cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) == AIS_SOG_NOT_AVAILABLE \
325         and cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE \
326         and cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE \
327         and cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) == AIS_COG_NOT_AVAILABLE \
328         and cleaned_data.get('heading', AIS_NO_HEADING) == AIS_NO_HEADING:
329             raise forms.ValidationError("You must enter some data, beside when.")
330         return cleaned_data
331
332 @http_authenticate(auth, 'ais')
333 def vessel_manual_input(request, strmmsi):
334     strmmsi = strmmsi.encode('utf-8')
335     nmea = Nmea.new_from_lastinfo(strmmsi)
336     if request.method == 'POST' or request.META['QUERY_STRING']:
337         form = VesselManualInputForm(request.REQUEST)
338         if form.is_valid():
339             data = form.cleaned_data
340             source = 'U' +  struct.pack('<I', request.user.id)[0:3]
341             result = u''
342             if data['imo'] != 0 \
343             or data['name'] != '' \
344             or data['callsign'] != '' \
345             or data['type'] != 0:
346                 toto = (strmmsi, data['timestamp'], data['imo'], data['name'], data['callsign'], data['type'], 0,0,0,0, 0,0,24,60, 0, '', source)
347                 result += 'UPDATING NMEA 5: '+repr(toto)+'<br>'
348                 add_nmea5_partial(*toto)
349             if data['status'] != AIS_STATUS_NOT_AVAILABLE \
350             or data['sog'] != AIS_SOG_NOT_AVAILABLE \
351             or data['latitude'] != AIS_LAT_NOT_AVAILABLE \
352             or data['longitude'] != AIS_LON_NOT_AVAILABLE \
353             or data['cog'] != AIS_COG_NOT_AVAILABLE \
354             or data['heading'] != AIS_NO_HEADING:
355                 
356                 toto = (strmmsi, data['timestamp'], data['status'], AIS_ROT_NOT_AVAILABLE, data['sog'], data['latitude'], data['longitude'], data['cog'], data['heading'], source)
357                 result += 'UPDATING NMEA 1: '+repr(toto)+'<br>'
358                 add_nmea1(*toto)
359             return HttpResponse('Not fully implemented: '+repr(data) + '<br>' + result)
360     else: # GET
361         form = VesselManualInputForm()
362     return render_to_response('vessel_manual_input.html', {'form': form, 'nmea': nmea}, RequestContext(request))
363
364
365 @http_authenticate(auth, 'ais')
366 def vessel_history(request, strmmsi, format=None):
367     """
368     That view is called from Google Earth, so that it must support GET method.  
369     """
370     ndays = request.REQUEST.get('ndays', None)
371     if ndays is not None:
372         try:
373             ndays = int(ndays)
374         except ValueError:
375             ndays = 90
376         period = ndays * 86400
377     else:
378         period = request.REQUEST.get('period', u'1')
379         try:
380             period = int(period)
381         except ValueError:
382             period = 1
383         period_type = request.REQUEST.get('period_type', u'86400')
384         try:
385             period_type = int(period_type)
386         except ValueError:
387             period_type = 86400
388
389     grain = request.REQUEST.get('grain', 1)
390     try:
391         grain = int(grain)
392     except ValueError:
393         grain = 1
394     grain_type = request.REQUEST.get('grain_type', 3600)
395     try:
396         grain_type = int(grain_type)
397     except ValueError:
398         grain_type = 3600
399
400     date_end = datetime.utcnow()
401     date_start = date_end - timedelta(0,period*period_type)
402     print date_start
403     nmea_iterator = NmeaFeeder(strmmsi, date_end, date_start, granularity=grain*grain_type)
404     
405     if format is None:
406         format = request.REQUEST.get('format', u'track')
407     if format == u'track':
408         value = kml_to_kmz(format_boat_track(nmea_iterator))
409         response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
410         response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
411         return response
412
413     elif format == u'animation':
414         value = kml_to_kmz(format_boat_intime(nmea_iterator))
415         response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
416         response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
417         return response
418
419     elif format == u'csv':
420         value = StringIO()
421         output = csv.writer(value)
422         output.writerow(Nmea.csv_headers)
423         for nmea in nmea_iterator:
424             output.writerow(nmea.get_dump_row())
425         response = HttpResponse(value.getvalue(), mimetype='text/csv; charset="UTF-8"')
426         response['Content-Disposition'] = 'attachment; filename=%s.csv' % strmmsi
427         return response
428     else:
429         request.user.error(u'Invalid archive format')
430         return HttpResponseRedirect('/vessel/%s/' % strmmsi)
431
432
433 @http_authenticate(auth, 'ais')
434 def fleets(request):
435     fleetusers = request.user.fleetuser_set.order_by('fleet')
436     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
437
438
439 @http_authenticate(auth, 'ais')
440 def fleet(request, fleetname):
441     fleet = get_object_or_404(Fleet, name=fleetname)
442     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
443         return HttpResponseForbidden('<h1>Forbidden</h1>')
444     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
445
446
447 class FleetEditForm(forms.Form):
448     name = forms.CharField(max_length=50)
449     description = forms.CharField(widget=forms.Textarea)
450
451     def clean_name(self):
452         name = self.cleaned_data['name']
453         if name == u'add':
454             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
455         if name != self.initial.get('name', None):
456             if Fleet.objects.filter(name=name).count():
457                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
458         return remove_decoration(name).replace(u' ', u'_')
459         
460
461 @http_authenticate(auth, 'ais')
462 def fleet_edit(request, fleetname):
463     initial = {}
464     if fleetname is not None:
465         fleet = get_object_or_404(Fleet, name=fleetname)
466         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
467             return HttpResponseForbidden('<h1>Forbidden</h1>')
468
469         initial['name'] = fleet.name
470         initial['description'] = fleet.description
471     else:
472         fleet = Fleet()
473
474     if request.method == 'POST':
475         form = FleetEditForm(request.POST, initial=initial)
476         if form.is_valid():
477             fleet.name = form.cleaned_data['name']
478             fleet.description = form.cleaned_data['description']
479             fleet.save()
480             if not fleetname: # new one
481                 fu = FleetUser()
482                 fu.fleet = fleet
483                 fu.user = request.user
484                 fu.save()
485             request.user.info('Fleet updated')
486             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
487     else: # GET
488         form = FleetEditForm(initial=initial)
489     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
490
491
492 @http_authenticate(auth, 'ais')
493 def fleet_vessels(request, fleetname):
494     fleet = get_object_or_404(Fleet, name=fleetname)
495     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
496         return HttpResponseForbidden('<h1>Forbidden</h1>')
497     vessels = fleet.vessel.all()
498     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
499
500
501 @http_authenticate(auth, 'ais')
502 def fleet_vessel_add(request, fleetname):
503     fleet = get_object_or_404(Fleet, name=fleetname)
504     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
505         return HttpResponseForbidden('<h1>Forbidden</h1>')
506     strmmsi = request.REQUEST['mmsi']
507     mmsi = strmmsi_to_mmsi(strmmsi)
508     try:
509         vessel = Vessel.objects.get(pk=mmsi)
510     except Vessel.DoesNotExist:
511         request.user.error('No such vessel')
512     else:
513         try:
514             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
515         except FleetVessel.DoesNotExist:
516             FleetVessel(fleet=fleet, vessel=vessel).save()
517             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
518         else:
519             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
520     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
521
522
523 class FleetAddVessel(forms.Form):
524     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
525     #name = forms.CharField(max_length=20, required=False)
526     #imo = forms.IntegerField(required=False)
527     #callsign = forms.CharField(max_length=7, required=False)
528     #destination = forms.CharField(max_length=20, required=False)
529     def clean(self):
530         cleaned_data = self.cleaned_data
531         for value in cleaned_data.values():
532             if value:
533                 return cleaned_data
534         raise forms.ValidationError("You must enter at least one criteria")
535
536 @http_authenticate(auth, 'ais')
537 def fleet_vessel_add2(request, fleetname):
538     fleet = get_object_or_404(Fleet, name=fleetname)
539     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
540         return HttpResponseForbidden('<h1>Forbidden</h1>')
541     if request.method == 'POST' or request.META['QUERY_STRING']:
542         form = FleetAddVessel(request.REQUEST)
543         if form.is_valid():
544             data = form.cleaned_data
545             result = []
546             a_strmmsi = request.REQUEST['mmsi']
547             if a_strmmsi:
548                 for strmmsi in a_strmmsi.split('\n'):
549                     strmmsi = strmmsi.strip('\r')
550                     if not strmmsi:
551                         continue
552                     try:
553                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
554                     except AssertionError:
555                         result.append('Invalid mmsi %s' % strmmsi)
556                         continue
557                     try:
558                         vessel = Vessel.objects.get(pk=sqlmmsi)
559                     except Vessel.DoesNotExist:
560                         result.append('No vessel with MMSI '+strmmsi)
561                         continue
562                     try:
563                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
564                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
565                     except FleetVessel.DoesNotExist:
566                         FleetVessel(fleet=fleet, vessel=vessel).save()
567                         result.append('Vessel with MMSI %s added' % strmmsi)
568
569             return HttpResponse('<br>'.join(result))
570     else: # GET
571         form = FleetAddVessel()
572
573     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
574
575
576 @http_authenticate(auth, 'ais')
577 def fleet_users(request, fleetname):
578     fleet = get_object_or_404(Fleet, name=fleetname)
579     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
580         return HttpResponseForbidden('<h1>Forbidden</h1>')
581
582     if request.method == 'POST' or request.META['QUERY_STRING']:
583         action = request.REQUEST['action']
584         userlogin = request.REQUEST['user']
585         try:
586             user = User.objects.get(login=userlogin)
587         except User.DoesNotExist:
588             request.user.error(u'User %s does not exist.' % userlogin)
589         else:
590             if action == u'add':
591                 try:
592                     fu = FleetUser.objects.get(fleet=fleet, user=user)
593                     request.user.error(u'User %s already has access.' % user.login)
594                 except FleetUser.DoesNotExist:
595                     FleetUser(fleet=fleet, user=user).save()
596                     #TODO log
597                     request.user.info(u'Granted access to user %s.' % user.login)
598             elif action == u'revoke':
599                 try:
600                     fu = FleetUser.objects.get(fleet=fleet, user=user)
601                     fu.delete()
602                     #TODO log
603                     request.user.info(u'Revoked access to user %s.' % user.login)
604                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
605                         fleet.delete()
606                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
607                         return HttpResponseRedirect('/fleet/')
608                 except FleetUser.DoesNotExist:
609                     request.user.error(u'User %s didn\'t have access.' % user.login)
610             else:
611                 request.user.error(u'Unknown action %s' % action)
612
613     fleetusers = fleet.fleetuser_set.all()
614     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
615     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
616
617
618 @http_authenticate(auth, 'ais')
619 def fleet_lastpos(request, fleetname):
620     fleet = get_object_or_404(Fleet, name=fleetname)
621     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
622         return HttpResponseForbidden('<h1>Forbidden</h1>')
623     fleet_uset = load_fleet_to_uset(fleet.id)
624     # = set([mmsi_to_strmmsi(vessel.mmsi) for vessel in fleet.vessel.all()])
625     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
626     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
627     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
628     return response
629
630
631 @http_authenticate(auth, 'ais')
632 def users(request):
633     users = User.objects.order_by('name')
634     for user in users:
635         user.admin_ok = user.is_admin_by(request.user.id)
636     if request.REQUEST.has_key('showtree'):
637         local_users = {}
638         for user in users:
639             user.children = []
640             local_users[user.id] = user
641         for user in users:
642             if user.father_id == None:
643                 root = user
644             else:
645                 local_users[user.father_id].children.append(user)
646         assert root
647         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
648     else:
649         return render_to_response('users.html', {'users':users}, RequestContext(request))
650
651 phone_re = re.compile('^\\+.+')
652
653 class UserEditForm(forms.Form):
654     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
655         error_message ='Login must only contain letters, numbers and underscores')
656     name = forms.CharField(max_length=50)
657     email = forms.EmailField()
658     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
659         error_message ='Phones must start with a \'+\'')
660     def __init__(self, *args, **kargs):
661         forms.Form.__init__(self, *args, **kargs)
662         self.old_login = kargs['initial']['login']
663     def clean_login(self):
664         new_login = self.cleaned_data['login']
665         if new_login != self.old_login:
666             if User.objects.filter(login=new_login).count():
667                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
668             if new_login == u'add':
669                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
670         return new_login
671
672 @http_authenticate(auth, 'ais')
673 def user_detail(request, login):
674     user = get_object_or_404(User, login=login)
675     user.admin_ok = user.is_admin_by(request.user.id)
676     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
677
678 @http_authenticate(auth, 'ais')
679 def user_edit(request, login):
680     initial = {}
681     if login:
682         user = get_object_or_404(User, login=login)
683         if not user.is_admin_by(request.user.id):
684             return HttpResponseForbidden('403 Forbidden')
685     else:
686         user = User()
687         user.father_id = request.user.id;
688     initial['login'] = user.login
689     initial['name'] = user.name
690     initial['email'] = user.email
691     initial['phone'] = user.phone
692     if request.method == 'POST':
693         form = UserEditForm(request.POST, initial=initial)
694         if form.is_valid():
695             user.login = form.cleaned_data['login']
696             user.name = form.cleaned_data['name']
697             user.email = form.cleaned_data['email']
698             user.phone = form.cleaned_data['phone']
699             user.save()
700             user.check_sandbox_access(request.user)
701             return HttpResponseRedirect('/user/')
702     else: # GET
703         form = UserEditForm(initial=initial)
704
705     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
706
707
708 class ChangePasswordForm(forms.Form):
709     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
710     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
711
712     def clean_generic_password(self, field_name):
713         password = self.cleaned_data[field_name]
714         try:
715             crack.FascistCheck(password)
716         except ValueError, err:
717             raise forms.ValidationError(err.message)
718         return password
719
720     def clean_new_password(self):
721         return self.clean_generic_password('new_password')
722
723     def clean_new_password_check(self):
724         return self.clean_generic_password('new_password_check')
725
726     def clean(self):
727         cleaned_data = self.cleaned_data
728         pass1 = cleaned_data.get('new_password')
729         pass2 = cleaned_data.get('new_password_check')
730         if pass1 != pass2 and pass2:
731             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
732             del cleaned_data['new_password_check'] # FIXME
733         return cleaned_data
734
735
736 @http_authenticate(auth, 'ais')
737 def user_change_password(request, login):
738     user = get_object_or_404(User, login=login)
739     if not user.is_admin_by(request.user.id):
740         return HttpResponseForbidden('403 Forbidden')
741     if request.method == 'POST':
742         form = ChangePasswordForm(request.POST)
743         if form.is_valid():
744             user.set_password(form.cleaned_data['new_password'])
745             user.save()
746             return HttpResponseRedirect('/user/')
747     else: # GET
748         form = ChangePasswordForm()
749     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
750
751
752 @http_authenticate(auth, 'ais')
753 def user_delete(request, login):
754     user = get_object_or_404(User, login=login)
755     if not user.is_admin_by(request.user.id):
756         return HttpResponseForbidden('403 Forbidden')
757     if request.REQUEST.get('confirm', None):
758         user.delete()
759         return HttpResponseRedirect('/user/')
760     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
761
762
763 def logout(request):
764     # TODO
765     return HttpResponse('Not implemented')
766     #response = render_to_response('logout.html', {}, RequestContext(request))
767     #return response
768
769 periods = ({
770     'name_tiny': '2h',
771     'name_long': '2 hours',
772     'seconds': 2*60*60
773     }, {
774     'name_tiny': '6h',
775     'name_long': '6 hours',
776     'seconds': 6*60*60,
777     'default': True,
778     }, {
779     'name_tiny': '2d',
780     'name_long': '2 days',
781     'seconds': 2*24*60*60
782     }, {
783     'name_tiny': '14d',
784     'name_long': '2 weeks',
785     'seconds': 14*24*60*60
786     }, {
787     'name_tiny': '90d',
788     'name_long': '3 monthes',
789     'seconds': 90*24*60*60
790     }, {
791     'name_tiny': '180d',
792     'name_long': '6 monthes',
793     'seconds': 180*24*60*60
794     })
795         
796 class StatsSelectorForm(forms.Form):
797     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
798     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
799     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
800
801 @http_authenticate(auth, 'ais')
802 def sources_index(request):
803     active_minutes = 5
804     peers_config = peers_get_config()
805     peers_display = []
806     for id4, peer in peers_config.iteritems():
807         peer['id4'] = id4
808         peer['id2'] = id4[2:]
809         peer['active'] = is_id4_active(id4, 60*active_minutes)
810         peers_display.append(peer)
811         
812     peers_display = sorted(peers_display, key=lambda k: k['id4'])
813
814     form = StatsSelectorForm()
815
816     return render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': active_minutes, 'form': form}, RequestContext(request))
817
818
819 @http_authenticate(auth, 'ais')
820 def sources_stats(request):
821     filter_peers = request.REQUEST.get('peers', None)
822     if filter_peers:
823         filter_peers = filter_peers.split(u',')
824
825     peers_config = peers_get_config()
826     peers_display = []
827
828     for id4, peer in peers_config.iteritems():
829         if filter_peers:
830             if unicode(id4) not in filter_peers:
831                 continue
832         peer['id4'] = id4
833         peers_display.append(peer)
834
835     peers_display = sorted(peers_display, key=lambda k: k['id4'])
836
837     filter_types = request.REQUEST.get('types', None)
838     if filter_types:
839         filter_types = filter_types.split(u',')
840     else:
841         filter_types = [ 'bytes', 'counts' ]
842     logging.error('filter_types=%s', filter_types)
843
844     filter_periods = request.REQUEST.get('periods', None)
845     if filter_periods:
846         display_periods = []
847         for period_name in filter_periods.split(u','):
848             for period in periods:
849                 if period['name_tiny'] == period_name:
850                     display_periods.append(period)
851     else:
852         display_periods = periods
853     #logging.error('display_periods=%s', display_periods)
854
855
856     now = int(get_timestamp())
857     for config in peers_display:
858         id4 = config['id4']
859         for period in periods:
860             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
861                 '--lazy', \
862                 '-l', '0', \
863                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
864                 '--start', '%d' % (now - period['seconds']), \
865                 '--end', '%d' % now, \
866                 '--vertical-label', 'bps', \
867                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
868                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
869                 'CDEF:bits=bytes,8,*', \
870                 'CDEF:rawbits=rawbytes,8,*', \
871                 'LINE:bits#00FF00:IP payload', \
872                 'LINE:rawbits#FF0000:IP with headers'
873             rrdtool.graph(*args)
874             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
875                 '--lazy', \
876                 '-l', '0', \
877                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
878                 '--start', '%d' % (now-period['seconds']), \
879                 '--end', '%d' % now, \
880                 '--vertical-label', 'Hz', \
881                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
882                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
883                 'LINE:packets#FF0000:input packets', \
884                 'LINE:lines#00FF00:AIVDM lines'
885             rrdtool.graph(*args)
886     return render_to_response('sources.html', {'sources':peers_display, 'show_bytes': 'bytes' in filter_types,  'show_counts': 'counts' in filter_types, 'periods': display_periods}, RequestContext(request))
887
888
889 @http_authenticate(auth, 'ais')
890 def news(request, page):
891     NEWS_PER_PAGE = 10
892     if page:
893         page = int(page)
894     else:
895         page = 1
896     # TODO __future__
897     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) / NEWS_PER_PAGE)
898     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
899     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
900
901 @http_authenticate(auth, 'ais')
902 def news_atom(request):
903     from django.db import connection
904
905     news = News.objects.order_by('-created')
906
907     cursor = connection.cursor()
908     cursor.execute("SELECT MAX(updated) FROM news")
909     row = cursor.fetchone()
910     last_update = row[0]
911
912     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')