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