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