Fixed area filter
[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         return command, extension
249
250
251 @http_authenticate(auth, 'ais')
252 def vessel(request, strmmsi):
253     mmsi = strmmsi_to_mmsi(strmmsi)
254     vessel = get_object_or_404(Vessel, pk=mmsi)
255     nmea = Nmea.new_from_lastinfo(strmmsi)
256     #if not nmea.timestamp_1 and not nmea.timestamp_5:
257     #    raise Http404
258     return render_to_response('vessel.html', {'nmea': nmea, 'form': HistoryForm()}, RequestContext(request))
259
260
261 class VesselManualInputForm(forms.Form):
262     timestamp = forms.DateTimeField(label=u'When', help_text=u'When was the observation made in GMT. Use YYYY-MM-DD HH:MM:SS format')
263     imo = forms.IntegerField(required=False, min_value=1000000, max_value=9999999)
264     name = forms.CharField(max_length=20, required=False)
265     callsign = forms.CharField(max_length=7, required=False)
266     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)
267     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)
268     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)
269     latitude = forms.CharField(required=False)
270     longitude = forms.CharField(required=False)
271     cog = forms.FloatField(label='Course', help_text='Over ground', required=False, min_value=0.0, max_value=359.9)
272     heading = forms.IntegerField(required=False, min_value=0, max_value=359)
273
274     @staticmethod
275     def _clean_ais_charset(ustr):
276         ustr = remove_decoration(ustr) # benign cleaning, but can increase size (œ->oe)
277         ustr = ustr.upper() # benign cleaning
278         str = clean_ais_charset(ustr.encode('ascii', 'replace'))
279         if unicode(str) != ustr:
280             raise forms.ValidationError('Invalid character: AIS alphabet is @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^- !"#$%&\'()*+,-./0123456789:;<=>?')
281         return str
282
283     def clean_timestamp(self):
284         data = self.cleaned_data['timestamp']
285         if data is None:
286             return None
287         if data < datetime.utcnow() - timedelta(365):
288             raise forms.ValidationError('Date is too much is the past.')
289         if data > datetime.utcnow():
290             raise forms.ValidationError('Date is be in the future. This form is only for observed results.')
291         return datetime_to_timestamp(data)
292
293     def clean_imo(self):
294         data = self.cleaned_data['imo']
295         if data is None:
296             return 0
297         return data
298
299     def clean_name(self):
300         name = self.cleaned_data['name']
301         if name is None:
302             return ''
303         name = VesselManualInputForm._clean_ais_charset(name)
304         if len(name)>20:
305             raise forms.ValidationError('Ensure this value has at most 20 characters (it has %s).' % len(name))
306         return name
307
308     def clean_callsign(self):
309         callsign = self.cleaned_data['callsign']
310         if callsign is None:
311             return ''
312         callsign = VesselManualInputForm._clean_ais_charset(callsign)
313         if len(callsign)>7:
314             raise forms.ValidationError('Ensure this value has at most 7 characters (it has %s).' % len(callsign))
315         return callsign
316
317     def clean_sog(self):
318         sog = self.cleaned_data['sog']
319         if sog is None:
320             return AIS_SOG_NOT_AVAILABLE
321         return int(sog*AIS_SOG_SCALE)
322
323     def clean_latitude(self):
324         #TODO: use ntools.clean_latitude
325         data = self.cleaned_data['latitude']
326         data = data.replace(u"''", u'"') # common mistake
327         data = data.replace(u' ', u'') # remove spaces
328         sides = u'SN'
329         if not data:
330             return AIS_LAT_NOT_AVAILABLE
331         tmp, side = data[:-1], data[-1]
332         if side == sides[0]:
333             side = -1
334         elif side == sides[1]:
335             side = 1
336         else:
337             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
338         spl = tmp.split(u'°')
339         if len(spl) == 1:
340             raise forms.ValidationError(u'You need to use the ° character.')
341         d, tmp = spl
342         try:
343             d = float(d)
344         except ValueError:
345             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
346         spl = tmp.split(u"'", 1)
347         if len(spl) == 1:
348             # no ' sign: ok only if there is nothing but the side after °
349             # we don't accept seconds if there is no minutes:
350             # It might be an entry mistake
351             tmp = spl[0]
352             if len(tmp) == 0:
353                 m = s = 0
354             else:
355                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
356         else:
357             m, tmp = spl
358             try:
359                 m = float(m)
360             except ValueError:
361                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
362             if len(tmp) == 0:
363                 s = 0
364             else:
365                 if tmp[-1] != '"':
366                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
367                 s = tmp[:-1]
368                 try:
369                     s = float(s)
370                 except ValueError:
371                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
372         data = side * ( d + m / 60 + s / 3600)
373
374         if data < -90 or data > 90:
375             raise forms.ValidationError(u'%s in not in -90..90 range' % data)
376         return int(data * AIS_LATLON_SCALE)
377
378     def clean_longitude(self):
379         #TODO: use ntools.clean_latitude
380         data = self.cleaned_data['longitude']
381         data = data.replace(u"''", u'"') # common mistake
382         data = data.replace(u' ', u'') # remove spaces
383         sides = u'WE'
384         if not data:
385             return AIS_LON_NOT_AVAILABLE
386         tmp, side = data[:-1], data[-1]
387         if side == sides[0]:
388             side = -1
389         elif side == sides[1]:
390             side = 1
391         else:
392             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
393         spl = tmp.split(u'°')
394         if len(spl) == 1:
395             raise forms.ValidationError(u'You need to use the ° character.')
396         d, tmp = spl
397         try:
398             d = float(d)
399         except ValueError:
400             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
401         spl = tmp.split(u"'", 1)
402         if len(spl) == 1:
403             # no ' sign: ok only if there is nothing but the side after °
404             # we don't accept seconds if there is no minutes:
405             # It might be an entry mistake
406             tmp = spl[0]
407             if len(tmp) == 0:
408                 m = s = 0
409             else:
410                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
411         else:
412             m, tmp = spl
413             try:
414                 m = float(m)
415             except ValueError:
416                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
417             if len(tmp) == 0:
418                 s = 0
419             else:
420                 if tmp[-1] != '"':
421                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
422                 s = tmp[:-1]
423                 try:
424                     s = float(s)
425                 except ValueError:
426                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
427         data = side * ( d + m / 60 + s / 3600)
428
429         if data < -180 or data > 180:
430             raise forms.ValidationError(u'%s in not in -180..180 range' % data)
431         return int(data * AIS_LATLON_SCALE)
432
433     def clean_cog(self):
434         data = self.cleaned_data['cog']
435         if data is None:
436             return AIS_COG_NOT_AVAILABLE
437         return int(data * AIS_COG_SCALE)
438     
439     def clean_heading(self):
440         #raise forms.ValidationError(u'clean_heading called')
441         data = self.cleaned_data['heading']
442         if data is None:
443             return AIS_NO_HEADING
444         return data
445
446     def clean(self):
447         cleaned_data = self.cleaned_data
448         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):
449             raise forms.ValidationError('It makes no sense to enter just a latitude or a longitude. Enter both or none.')
450         if cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE:
451             if cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) != AIS_STATUS_NOT_AVAILABLE:
452                 raise forms.ValidationError('It makes no sense to enter a status without coordinates. Please enter latitute and longitude too.')
453             if cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) != AIS_SOG_NOT_AVAILABLE:
454                 raise forms.ValidationError('It makes no sense to enter a speed without coordinates. Please enter latitute and longitude too.')
455             if cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) != AIS_COG_NOT_AVAILABLE:
456                 raise forms.ValidationError('It makes no sense to enter a course without coordinates. Please enter latitute and longitude too.')
457             if cleaned_data.get('heading', AIS_NO_HEADING) != AIS_NO_HEADING:
458                 raise forms.ValidationError('It makes no sense to enter a heading without coordinates. Please enter latitute and longitude too.')
459
460         if cleaned_data.get('timestamp', None) \
461         and cleaned_data.get('imo', 0) == 0 \
462         and cleaned_data.get('name', '') == '' \
463         and cleaned_data.get('callsign', '') == '' \
464         and cleaned_data.get('type', 0) == 0 \
465         and cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) == AIS_STATUS_NOT_AVAILABLE \
466         and cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) == AIS_SOG_NOT_AVAILABLE \
467         and cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE \
468         and cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE \
469         and cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) == AIS_COG_NOT_AVAILABLE \
470         and cleaned_data.get('heading', AIS_NO_HEADING) == AIS_NO_HEADING:
471             raise forms.ValidationError("You must enter some data, beside when.")
472         return cleaned_data
473
474 @http_authenticate(auth, 'ais')
475 def vessel_manual_input(request, strmmsi):
476     strmmsi = strmmsi.encode('utf-8')
477     nmea = Nmea.new_from_lastinfo(strmmsi)
478     if request.method == 'POST' or request.META['QUERY_STRING']:
479         form = VesselManualInputForm(request.REQUEST)
480         if form.is_valid():
481             data = form.cleaned_data
482             source = 'U' +  struct.pack('<I', request.user.id)[0:3]
483             result = u''
484             if data['imo'] != 0 \
485             or data['name'] != '' \
486             or data['callsign'] != '' \
487             or data['type'] != 0:
488                 toto = (strmmsi, data['timestamp'], data['imo'], data['name'], data['callsign'], data['type'], 0,0,0,0, 0,0,24,60, 0, '', source)
489                 result += 'UPDATING NMEA 5: '+repr(toto)+'<br>'
490                 add_nmea5_partial(*toto)
491             if data['status'] != AIS_STATUS_NOT_AVAILABLE \
492             or data['sog'] != AIS_SOG_NOT_AVAILABLE \
493             or data['latitude'] != AIS_LAT_NOT_AVAILABLE \
494             or data['longitude'] != AIS_LON_NOT_AVAILABLE \
495             or data['cog'] != AIS_COG_NOT_AVAILABLE \
496             or data['heading'] != AIS_NO_HEADING:
497                 
498                 toto = (strmmsi, data['timestamp'], data['status'], AIS_ROT_NOT_AVAILABLE, data['sog'], data['latitude'], data['longitude'], data['cog'], data['heading'], source)
499                 result += 'UPDATING NMEA 1: '+repr(toto)+'<br>'
500                 add_nmea1(*toto)
501             return HttpResponse('Not fully implemented: '+repr(data) + '<br>' + result)
502     else: # GET
503         form = VesselManualInputForm()
504     return render_to_response('vessel_manual_input.html', {'form': form, 'nmea': nmea}, RequestContext(request))
505
506
507 @http_authenticate(auth, 'ais')
508 def vessel_lastpos(request, strmmsi):
509     value = kml_to_kmz(format_fleet([ strmmsi ], document_name=strmmsi).encode('utf-8'))
510     response = HttpResponse(value, mimetype="application/vnd.google-earth.kmz")
511     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
512     return response
513
514 @http_authenticate(auth, 'ais')
515 def vessel_history(request, strmmsi):
516     """
517     TODO
518     That view is called from Google Earth, so that it must support GET method.  
519     """
520     initial = {}
521     if request.method == 'POST':
522         form = HistoryForm(request.POST, initial=initial)
523         if form.is_valid():
524             command, extension = form.get_cmdext()
525
526             command += u' ' + strmmsi
527
528             job = Job()
529             job.queue_time = datetime.utcnow()
530             job.friendly_filename = u'%s.%s' % (strmmsi, extension)
531             job.user = request.user
532             job.command = command
533             job.save()
534             if not jobrunner.wakeup_daemon():
535                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
536             return HttpResponseRedirect('/job/%s/download' % job.id)
537     else: # GET
538         form = HistoryForm(initial=initial)
539     strmmsi = strmmsi.encode('utf-8')
540     nmea = Nmea.new_from_lastinfo(strmmsi)
541     return render_to_response('vessel_history.html', {'nmea': nmea, 'form':form}, RequestContext(request))
542
543
544 @http_authenticate(auth, 'ais')
545 def fleets(request):
546     fleetusers = request.user.fleetuser_set.order_by('fleet')
547     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
548
549
550 @http_authenticate(auth, 'ais')
551 def fleet(request, fleetname):
552     fleet = get_object_or_404(Fleet, name=fleetname)
553     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
554         return HttpResponseForbidden('<h1>Forbidden</h1>')
555     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
556
557
558 class FleetEditForm(forms.Form):
559     name = forms.CharField(max_length=50)
560     description = forms.CharField(widget=forms.Textarea)
561
562     def clean_name(self):
563         name = self.cleaned_data['name']
564         if name == u'add':
565             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
566         if name != self.initial.get('name', None):
567             if Fleet.objects.filter(name=name).count():
568                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
569         return remove_decoration(name).replace(u' ', u'_')
570         
571
572 @http_authenticate(auth, 'ais')
573 def fleet_edit(request, fleetname):
574     initial = {}
575     if fleetname is not None:
576         fleet = get_object_or_404(Fleet, name=fleetname)
577         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
578             return HttpResponseForbidden('<h1>Forbidden</h1>')
579
580         initial['name'] = fleet.name
581         initial['description'] = fleet.description
582     else:
583         fleet = Fleet()
584
585     if request.method == 'POST':
586         form = FleetEditForm(request.POST, initial=initial)
587         if form.is_valid():
588             fleet.name = form.cleaned_data['name']
589             fleet.description = form.cleaned_data['description']
590             fleet.save()
591             if not fleetname: # new one
592                 fu = FleetUser()
593                 fu.fleet = fleet
594                 fu.user = request.user
595                 fu.save()
596             request.user.info('Fleet updated')
597             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
598     else: # GET
599         form = FleetEditForm(initial=initial)
600     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
601
602
603 @http_authenticate(auth, 'ais')
604 def fleet_vessels(request, fleetname):
605     fleet = get_object_or_404(Fleet, name=fleetname)
606     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
607         return HttpResponseForbidden('<h1>Forbidden</h1>')
608     vessels = fleet.vessel.all()
609     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
610
611
612 @http_authenticate(auth, 'ais')
613 def fleet_vessel_add(request, fleetname):
614     fleet = get_object_or_404(Fleet, name=fleetname)
615     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
616         return HttpResponseForbidden('<h1>Forbidden</h1>')
617     strmmsi = request.REQUEST['mmsi']
618     mmsi = strmmsi_to_mmsi(strmmsi)
619     try:
620         vessel = Vessel.objects.get(pk=mmsi)
621     except Vessel.DoesNotExist:
622         request.user.error('No such vessel')
623     else:
624         try:
625             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
626         except FleetVessel.DoesNotExist:
627             FleetVessel(fleet=fleet, vessel=vessel).save()
628             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
629         else:
630             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
631     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
632
633
634 class FleetAddVessel(forms.Form):
635     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
636     #name = forms.CharField(max_length=20, required=False)
637     #imo = forms.IntegerField(required=False)
638     #callsign = forms.CharField(max_length=7, required=False)
639     #destination = forms.CharField(max_length=20, required=False)
640     def clean(self):
641         cleaned_data = self.cleaned_data
642         for value in cleaned_data.values():
643             if value:
644                 return cleaned_data
645         raise forms.ValidationError("You must enter at least one criteria")
646
647 @http_authenticate(auth, 'ais')
648 def fleet_vessel_add2(request, fleetname):
649     fleet = get_object_or_404(Fleet, name=fleetname)
650     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
651         return HttpResponseForbidden('<h1>Forbidden</h1>')
652     if request.method == 'POST' or request.META['QUERY_STRING']:
653         form = FleetAddVessel(request.REQUEST)
654         if form.is_valid():
655             data = form.cleaned_data
656             result = []
657             a_strmmsi = request.REQUEST['mmsi']
658             if a_strmmsi:
659                 for strmmsi in a_strmmsi.split('\n'):
660                     strmmsi = strmmsi.strip('\r')
661                     if not strmmsi:
662                         continue
663                     try:
664                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
665                     except AssertionError:
666                         result.append('Invalid mmsi %s' % strmmsi)
667                         continue
668                     try:
669                         vessel = Vessel.objects.get(pk=sqlmmsi)
670                     except Vessel.DoesNotExist:
671                         result.append('No vessel with MMSI '+strmmsi)
672                         continue
673                     try:
674                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
675                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
676                     except FleetVessel.DoesNotExist:
677                         FleetVessel(fleet=fleet, vessel=vessel).save()
678                         result.append('Vessel with MMSI %s added' % strmmsi)
679
680             return HttpResponse('<br>'.join(result))
681     else: # GET
682         form = FleetAddVessel()
683
684     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
685
686
687 @http_authenticate(auth, 'ais')
688 def fleet_users(request, fleetname):
689     fleet = get_object_or_404(Fleet, name=fleetname)
690     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
691         return HttpResponseForbidden('<h1>Forbidden</h1>')
692
693     if request.method == 'POST' or request.META['QUERY_STRING']:
694         action = request.REQUEST['action']
695         userlogin = request.REQUEST['user']
696         try:
697             user = User.objects.get(login=userlogin)
698         except User.DoesNotExist:
699             request.user.error(u'User %s does not exist.' % userlogin)
700         else:
701             if action == u'add':
702                 try:
703                     fu = FleetUser.objects.get(fleet=fleet, user=user)
704                     request.user.error(u'User %s already has access.' % user.login)
705                 except FleetUser.DoesNotExist:
706                     FleetUser(fleet=fleet, user=user).save()
707                     #TODO log
708                     request.user.info(u'Granted access to user %s.' % user.login)
709             elif action == u'revoke':
710                 try:
711                     fu = FleetUser.objects.get(fleet=fleet, user=user)
712                     fu.delete()
713                     #TODO log
714                     request.user.info(u'Revoked access to user %s.' % user.login)
715                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
716                         fleet.delete()
717                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
718                         return HttpResponseRedirect('/fleet/')
719                 except FleetUser.DoesNotExist:
720                     request.user.error(u'User %s didn\'t have access.' % user.login)
721             else:
722                 request.user.error(u'Unknown action %s' % action)
723
724     fleetusers = fleet.fleetuser_set.all()
725     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
726     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
727
728
729 @http_authenticate(auth, 'ais')
730 def fleet_lastpos(request, fleetname):
731     fleet = get_object_or_404(Fleet, name=fleetname)
732     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
733         return HttpResponseForbidden('<h1>Forbidden</h1>')
734     fleet_uset = load_fleet_to_uset(fleet.id)
735     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
736     response = HttpResponse(value, mimetype="application/vnd.google-earth.kmz")
737     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
738     return response
739
740 @http_authenticate(auth, 'ais')
741 def fleet_history(request, fleetname):
742     fleet = get_object_or_404(Fleet, name=fleetname)
743     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
744         return HttpResponseForbidden('<h1>Forbidden</h1>')
745     initial = {}
746     if request.method == 'POST':
747         form = HistoryForm(request.POST, initial=initial)
748         if form.is_valid():
749             command, extension = form.get_cmdext()
750
751             command += u' @' + fleetname
752
753             job = Job()
754             job.queue_time = datetime.utcnow()
755             job.friendly_filename = u'%s.%s' % (fleetname, extension)
756             job.user = request.user
757             job.command = command
758             job.save()
759             if not jobrunner.wakeup_daemon():
760                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
761             return HttpResponseRedirect('/job/%s/download' % job.id)
762     else: # GET
763         form = HistoryForm(initial=initial)
764     return render_to_response('fleet_history.html', {'fleet': fleet, 'form':form}, RequestContext(request))
765
766
767 @http_authenticate(auth, 'ais')
768 def jobs_index(request):
769     show_archive = request.REQUEST.has_key('archive')
770     if show_archive:
771         jobs = request.user.job_set.all()
772     else:
773         jobs = request.user.job_set.filter(archive_time__isnull=True)
774     
775     response = render_to_response('jobs.html', {'jobs': jobs, 'queue_size': Job.queue_size(), 'archive': show_archive }, RequestContext(request))
776     response['Refresh'] = 15
777     return response
778
779 @http_authenticate(auth, 'ais')
780 def job_detail(request, jobid):
781     job = get_object_or_404(Job, id=jobid)
782     if job.user != request.user:
783         return HttpResponseForbidden('403 Forbidden')
784     response = render_to_response('job.html', {'job': job, 'queue_size': Job.queue_size()}, RequestContext(request))
785     if not job.finish_time:
786         response['Refresh'] = 5
787     elif not job.archive_time:
788         # finished but not archived:
789         response['Refresh'] = '0;url=https://' + request.get_host() + '/job/%s/download' % job.id
790         # careful not to modify other unschronized columns
791         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
792     return response
793
794 @http_authenticate(auth, 'ais')
795 def job_get(request, jobid):
796     job = get_object_or_404(Job, id=jobid)
797     if job.user != request.user:
798         return HttpResponseForbidden('403 Forbidden')
799     total_wait = 0
800     while not job.finish_time:
801         sleep(1)
802         total_wait += 1
803         if total_wait > 15:
804             request.user.info('Your query is slow. Please be patient.')
805             # TODO: Do not overwrite job.finishtime / result
806             if not job.notify:
807                 # careful not to modify other unschronized columns
808                 Job.objects.filter(id=jobid).update(notify = 'W') # Web
809             return HttpResponseRedirect('/job/%s/' % job.id)
810         job = get_object_or_404(Job, id=jobid)
811     
812     if not job.archive_time:
813         # careful not to modify other unschronized columns
814         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
815
816     if job.result:
817         # Error occured
818          return HttpResponseRedirect('/job/%s/' % job.id)
819     extension = os.path.splitext(job.friendly_filename)[-1]
820     return HttpResponseRedirect('/job_result/%s%s/%s' % (job.id, extension, job.friendly_filename))
821
822 @http_authenticate(auth, 'ais')
823 def users(request):
824     users = User.objects.order_by('name')
825     for user in users:
826         user.admin_ok = user.is_admin_by(request.user.id)
827     if request.REQUEST.has_key('showtree'):
828         local_users = {}
829         for user in users:
830             user.children = []
831             local_users[user.id] = user
832         for user in users:
833             if user.father_id == None:
834                 root = user
835             else:
836                 local_users[user.father_id].children.append(user)
837         assert root
838         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
839     else:
840         return render_to_response('users.html', {'users':users}, RequestContext(request))
841
842 phone_re = re.compile('^\\+.+')
843
844 class UserEditForm(forms.Form):
845     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
846         error_message ='Login must only contain letters, numbers and underscores')
847     name = forms.CharField(max_length=50)
848     email = forms.EmailField()
849     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
850         error_message ='Phones must start with a \'+\'')
851     def __init__(self, *args, **kargs):
852         forms.Form.__init__(self, *args, **kargs)
853         self.old_login = kargs['initial']['login']
854     def clean_login(self):
855         new_login = self.cleaned_data['login']
856         if new_login != self.old_login:
857             if User.objects.filter(login=new_login).count():
858                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
859             if new_login == u'add':
860                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
861         return new_login
862
863 @http_authenticate(auth, 'ais')
864 def user_detail(request, login):
865     user = get_object_or_404(User, login=login)
866     user.admin_ok = user.is_admin_by(request.user.id)
867     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
868
869 @http_authenticate(auth, 'ais')
870 def user_edit(request, login):
871     initial = {}
872     if login:
873         user = get_object_or_404(User, login=login)
874         if not user.is_admin_by(request.user.id):
875             return HttpResponseForbidden('403 Forbidden')
876     else:
877         user = User()
878         user.father_id = request.user.id;
879     initial['login'] = user.login
880     initial['name'] = user.name
881     initial['email'] = user.email
882     initial['phone'] = user.phone
883     if request.method == 'POST':
884         form = UserEditForm(request.POST, initial=initial)
885         if form.is_valid():
886             user.login = form.cleaned_data['login']
887             user.name = form.cleaned_data['name']
888             user.email = form.cleaned_data['email']
889             user.phone = form.cleaned_data['phone']
890             user.save()
891             user.check_sandbox_access(request.user)
892             return HttpResponseRedirect('/user/')
893     else: # GET
894         form = UserEditForm(initial=initial)
895
896     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
897
898
899 class ChangePasswordForm(forms.Form):
900     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
901     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
902
903     def clean_generic_password(self, field_name):
904         password = self.cleaned_data[field_name]
905         try:
906             crack.FascistCheck(password)
907         except ValueError, err:
908             raise forms.ValidationError(err.message)
909         return password
910
911     def clean_new_password(self):
912         return self.clean_generic_password('new_password')
913
914     def clean_new_password_check(self):
915         return self.clean_generic_password('new_password_check')
916
917     def clean(self):
918         cleaned_data = self.cleaned_data
919         pass1 = cleaned_data.get('new_password')
920         pass2 = cleaned_data.get('new_password_check')
921         if pass1 != pass2 and pass2:
922             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
923             del cleaned_data['new_password_check'] # FIXME
924         return cleaned_data
925
926
927 @http_authenticate(auth, 'ais')
928 def user_change_password(request, login):
929     user = get_object_or_404(User, login=login)
930     if not user.is_admin_by(request.user.id):
931         return HttpResponseForbidden('403 Forbidden')
932     if request.method == 'POST':
933         form = ChangePasswordForm(request.POST)
934         if form.is_valid():
935             user.set_password(form.cleaned_data['new_password'])
936             user.save()
937             return HttpResponseRedirect('/user/')
938     else: # GET
939         form = ChangePasswordForm()
940     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
941
942
943 @http_authenticate(auth, 'ais')
944 def user_delete(request, login):
945     user = get_object_or_404(User, login=login)
946     if not user.is_admin_by(request.user.id):
947         return HttpResponseForbidden('403 Forbidden')
948     if request.REQUEST.get('confirm', None):
949         user.delete()
950         return HttpResponseRedirect('/user/')
951     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
952
953
954 def logout(request):
955     # TODO
956     return HttpResponse('Not implemented')
957     #response = render_to_response('logout.html', {}, RequestContext(request))
958     #return response
959
960 periods = ({
961     'name_tiny': '2h',
962     'name_long': '2 hours',
963     'seconds': 2*60*60
964     }, {
965     'name_tiny': '6h',
966     'name_long': '6 hours',
967     'seconds': 6*60*60,
968     'default': True,
969     }, {
970     'name_tiny': '2d',
971     'name_long': '2 days',
972     'seconds': 2*24*60*60
973     }, {
974     'name_tiny': '14d',
975     'name_long': '2 weeks',
976     'seconds': 14*24*60*60
977     }, {
978     'name_tiny': '90d',
979     'name_long': '3 monthes',
980     'seconds': 90*24*60*60
981     }, {
982     'name_tiny': '180d',
983     'name_long': '6 monthes',
984     'seconds': 180*24*60*60
985     })
986         
987 class StatsSelectorForm(forms.Form):
988     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
989     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
990     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
991
992 @http_authenticate(auth, 'ais')
993 def sources_index(request):
994     ACTIVE_MINUTES = 5
995     peers_config = peers_get_config()
996     peers_display = []
997     for id4, peer in peers_config.iteritems():
998         peer['id4'] = id4
999         peer['id2'] = id4[2:]
1000         peer['active'] = is_id4_active(id4, 60*ACTIVE_MINUTES)
1001         peers_display.append(peer)
1002         
1003     peers_display = sorted(peers_display, key=lambda k: k['id4'])
1004
1005     form = StatsSelectorForm()
1006
1007     response = render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': ACTIVE_MINUTES, 'form': form}, RequestContext(request))
1008     response['Refresh'] = 60*ACTIVE_MINUTES
1009     return response
1010
1011
1012 @http_authenticate(auth, 'ais')
1013 def sources_stats(request):
1014     filter_peers = request.REQUEST.get('peers', None)
1015     if filter_peers:
1016         filter_peers = filter_peers.split(u',')
1017
1018     peers_config = peers_get_config()
1019     peers_display = []
1020
1021     for id4, peer in peers_config.iteritems():
1022         if filter_peers:
1023             if unicode(id4) not in filter_peers:
1024                 continue
1025         peer['id4'] = id4
1026         peers_display.append(peer)
1027
1028     peers_display = sorted(peers_display, key=lambda k: k['id4'])
1029
1030     filter_types = request.REQUEST.get('types', None)
1031     if filter_types:
1032         filter_types = filter_types.split(u',')
1033     else:
1034         filter_types = [ 'bytes', 'counts' ]
1035     logging.error('filter_types=%s', filter_types)
1036
1037     filter_periods = request.REQUEST.get('periods', None)
1038     if filter_periods:
1039         display_periods = []
1040         for period_name in filter_periods.split(u','):
1041             for period in periods:
1042                 if period['name_tiny'] == period_name:
1043                     display_periods.append(period)
1044     else:
1045         display_periods = periods
1046     #logging.error('display_periods=%s', display_periods)
1047
1048
1049     now = int(get_timestamp())
1050     for config in peers_display:
1051         id4 = config['id4']
1052         for period in periods:
1053             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
1054                 '--lazy', \
1055                 '-l', '0', \
1056                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
1057                 '--start', '%d' % (now - period['seconds']), \
1058                 '--end', '%d' % now, \
1059                 '--vertical-label', 'bps', \
1060                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1061                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1062                 'CDEF:bits=bytes,8,*', \
1063                 'CDEF:rawbits=rawbytes,8,*', \
1064                 'LINE:bits#00FF00:IP payload', \
1065                 'LINE:rawbits#FF0000:IP with headers'
1066             rrdtool.graph(*args)
1067             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
1068                 '--lazy', \
1069                 '-l', '0', \
1070                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
1071                 '--start', '%d' % (now-period['seconds']), \
1072                 '--end', '%d' % now, \
1073                 '--vertical-label', 'Hz', \
1074                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1075                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1076                 'LINE:packets#FF0000:input packets', \
1077                 'LINE:lines#00FF00:AIVDM lines'
1078             rrdtool.graph(*args)
1079     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))
1080
1081
1082 @http_authenticate(auth, 'ais')
1083 def news(request, page):
1084     NEWS_PER_PAGE = 5
1085     if page:
1086         page = int(page)
1087     else:
1088         page = 1
1089     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) // NEWS_PER_PAGE)
1090     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
1091     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
1092
1093 @http_authenticate(auth, 'ais')
1094 def news_atom(request):
1095     from django.db import connection
1096
1097     news = News.objects.order_by('-created')
1098
1099     cursor = connection.cursor()
1100     cursor.execute("SELECT MAX(updated) FROM news")
1101     row = cursor.fetchone()
1102     last_update = row[0]
1103
1104     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')