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