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