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