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