3a8ab79e962719b589c6f669e4be2a1c64790e4f
[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 SecondsWidget(forms.MultiWidget):
119     '''
120     A widget that splits period number and period type in a integer and a choice widgets
121     Does not work well for more than a week, as month lengthes do vary.
122     '''
123     __periods = (
124         (u'1', u'second(s)'),
125         (u'60', u'minute(s)'),
126         (u'3600', u'hour(s)'),
127         (u'86400', u'day(s)'),
128         (u'604800', u'week(s)'),
129         (u'2592000', u'month(es)'))
130
131     def __init__(self, attrs=None):
132         textattrs = { 'size': 3 }
133         if attrs:
134             textattrs.update(attrs)
135         widgets = (
136             forms.TextInput(attrs=textattrs),
137             forms.Select(choices=self.__periods, attrs=attrs))
138         super(SecondsWidget, self).__init__(widgets, attrs)
139
140     def decompress(self, value):
141         if value:
142             for period_second in reversed([int(sec_txt[0]) for sec_txt in self.__periods]):
143                 if value >= period_second and not value % period_second:
144                     return [ unicode(value // period_second), unicode(period_second) ]
145         return [None, None]
146
147 class SecondsField(forms.MultiValueField):
148     widget = SecondsWidget
149
150     def __init__(self, *args, **kargs):
151         fields = (
152             forms.IntegerField(),
153             forms.CharField(),
154         )
155         forms.MultiValueField.__init__(self, fields=fields, *args, **kargs)
156
157     def compress(self, data_list):
158         #print 'data_list=', data_list
159         if data_list and data_list[0] is not None and data_list[1] is not None:
160             try:
161                 return data_list[0] * int(data_list[1])
162             except ValueError:
163                 pass
164         return None
165
166 class HistoryForm(forms.Form):
167     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();")}))
168     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);")}))
169     start_date = forms.DateTimeField(required=False, widget=AisCalendarWidget(attrs={'class':'vDateField'}))
170     duration = SecondsField(required=False, label='Period length', initial=7*86400)
171     end_date = forms.DateTimeField(required=False, widget=AisCalendarWidget(attrs={'class':'vDateField'}))
172     grain = SecondsField(label='One position every', initial=3600)
173
174     def clean_start_date(self):
175         period_type = self.cleaned_data.get('period_type', None)
176         start_date = self.cleaned_data.get('start_date', None)
177         if period_type in (u'date_date', u'start_duration') and start_date is None:
178             raise forms.ValidationError('That is field is required.')
179         return start_date
180
181     def clean_duration(self):
182         period_type = self.cleaned_data.get('period_type', None)
183         duration = self.cleaned_data.get('duration', None)
184         print 'duration=', duration
185         if period_type in (u'duration', u'start_duration') and duration is None:
186             raise forms.ValidationError('That is field is required.')
187         return duration
188     
189     def clean_end_date(self):
190         period_type = self.cleaned_data.get('period_type', None)
191         end_date = self.cleaned_data.get('end_date', None)
192         if period_type in (u'date_date',) and end_date is None:
193             raise forms.ValidationError('That is field is required.')
194         return end_date
195
196     def clean(self):
197         cleaned_data = self.cleaned_data
198         period_type = self.cleaned_data.get('period_type', None)
199         start_date = self.cleaned_data.get('start_date', None)
200         #duration = self.cleaned_data.get('duration', None)
201         end_date = self.cleaned_data.get('end_date', None)
202         #if period_type in (u'date_date', u'start_duration') and start_date is None:
203         #    self._errors["start_date"] = self.error_class(['That field is required.'])
204         #if period_type in (u'duration', u'start_duration') and duration is None:
205         #    self._errors["duration"] = self.error_class(['That field is required.'])
206         #if period_type in (u'date_date',) and end_date is None:
207         #    self._errors["end_date"] = self.error_class(['That field is required.'])
208         if period_type == u'date_date' and start_date is not None and end_date is not None:
209             if start_date >= end_date:
210                 self._errors["start_date"] = self.error_class(['Start date must be before end date.'])
211         return cleaned_data
212
213 @http_authenticate(auth, 'ais')
214 def vessel(request, strmmsi):
215     mmsi = strmmsi_to_mmsi(strmmsi)
216     vessel = get_object_or_404(Vessel, pk=mmsi)
217     nmea = Nmea.new_from_lastinfo(strmmsi)
218     #if not nmea.timestamp_1 and not nmea.timestamp_5:
219     #    raise Http404
220     return render_to_response('vessel.html', {'nmea': nmea, 'form': HistoryForm()}, RequestContext(request))
221
222
223 class VesselManualInputForm(forms.Form):
224     timestamp = forms.DateTimeField(label=u'When', help_text=u'When was the observation made in GMT. Use YYYY-MM-DD HH:MM:SS format')
225     imo = forms.IntegerField(required=False, min_value=1000000, max_value=9999999)
226     name = forms.CharField(max_length=20, required=False)
227     callsign = forms.CharField(max_length=7, required=False)
228     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)
229     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)
230     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)
231     latitude = forms.CharField(required=False)
232     longitude = forms.CharField(required=False)
233     cog = forms.FloatField(label='Course', help_text='Over ground', required=False, min_value=0.0, max_value=359.9)
234     heading = forms.IntegerField(required=False, min_value=0, max_value=359)
235
236     @staticmethod
237     def _clean_ais_charset(ustr):
238         ustr = remove_decoration(ustr) # benign cleaning, but can increase size (œ->oe)
239         ustr = ustr.upper() # benign cleaning
240         str = clean_ais_charset(ustr.encode('ascii', 'replace'))
241         if unicode(str) != ustr:
242             raise forms.ValidationError('Invalid character: AIS alphabet is @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^- !"#$%&\'()*+,-./0123456789:;<=>?')
243         return str
244
245     def clean_timestamp(self):
246         data = self.cleaned_data['timestamp']
247         if data is None:
248             return None
249         if data < datetime.utcnow() - timedelta(365):
250             raise forms.ValidationError('Date is too much is the past.')
251         if data > datetime.utcnow():
252             raise forms.ValidationError('Date is be in the future. This form is only for observed results.')
253         return datetime_to_timestamp(data)
254
255     def clean_imo(self):
256         data = self.cleaned_data['imo']
257         if data is None:
258             return 0
259         return data
260
261     def clean_name(self):
262         name = self.cleaned_data['name']
263         if name is None:
264             return ''
265         name = VesselManualInputForm._clean_ais_charset(name)
266         if len(name)>20:
267             raise forms.ValidationError('Ensure this value has at most 20 characters (it has %s).' % len(name))
268         return name
269
270     def clean_callsign(self):
271         callsign = self.cleaned_data['callsign']
272         if callsign is None:
273             return ''
274         callsign = VesselManualInputForm._clean_ais_charset(callsign)
275         if len(callsign)>7:
276             raise forms.ValidationError('Ensure this value has at most 7 characters (it has %s).' % len(callsign))
277         return callsign
278
279     def clean_sog(self):
280         sog = self.cleaned_data['sog']
281         if sog is None:
282             return AIS_SOG_NOT_AVAILABLE
283         return int(sog*AIS_SOG_SCALE)
284
285     def clean_latitude(self):
286         data = self.cleaned_data['latitude']
287         data = data.replace(u"''", u'"') # commong mistake
288         data = data.replace(u' ', u'') # remove spaces
289         sides = u'SN'
290         if not data:
291             return AIS_LAT_NOT_AVAILABLE
292         tmp, side = data[:-1], data[-1]
293         if side == sides[0]:
294             side = -1
295         elif side == sides[1]:
296             side = 1
297         else:
298             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
299         spl = tmp.split(u'°')
300         if len(spl) == 1:
301             raise forms.ValidationError(u'You need to use the ° character.')
302         d, tmp = spl
303         try:
304             d = float(d)
305         except ValueError:
306             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
307         spl = tmp.split(u"'", 1)
308         if len(spl) == 1:
309             # no ' sign: ok only if there is nothing but the side after °
310             # we don't accept seconds if there is no minutes:
311             # It might be an entry mistake
312             tmp = spl[0]
313             if len(tmp) == 0:
314                 m = s = 0
315             else:
316                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
317         else:
318             m, tmp = spl
319             try:
320                 m = float(m)
321             except ValueError:
322                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
323             if len(tmp) == 0:
324                 s = 0
325             else:
326                 if tmp[-1] != '"':
327                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
328                 s = tmp[:-1]
329                 try:
330                     s = float(s)
331                 except ValueError:
332                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
333         data = side * ( d + m / 60 + s / 3600)
334
335         if data < -90 or data > 90:
336             raise forms.ValidationError(u'%s in not in -90..90 range' % data)
337         return int(data * AIS_LATLON_SCALE)
338
339     def clean_longitude(self):
340         data = self.cleaned_data['longitude']
341         data = data.replace(u"''", u'"') # commong mistake
342         data = data.replace(u' ', u'') # remove spaces
343         sides = u'WE'
344         if not data:
345             return AIS_LON_NOT_AVAILABLE
346         tmp, side = data[:-1], data[-1]
347         if side == sides[0]:
348             side = -1
349         elif side == sides[1]:
350             side = 1
351         else:
352             raise forms.ValidationError(u'Last character must be either %s or %s.' % (sides[0], sides[1]))
353         spl = tmp.split(u'°')
354         if len(spl) == 1:
355             raise forms.ValidationError(u'You need to use the ° character.')
356         d, tmp = spl
357         try:
358             d = float(d)
359         except ValueError:
360             raise forms.ValidationError(u'Degrees must be an number. It\'s %s.' % d)
361         spl = tmp.split(u"'", 1)
362         if len(spl) == 1:
363             # no ' sign: ok only if there is nothing but the side after °
364             # we don't accept seconds if there is no minutes:
365             # It might be an entry mistake
366             tmp = spl[0]
367             if len(tmp) == 0:
368                 m = s = 0
369             else:
370                 raise forms.ValidationError(u'You must use the \' character between ° and %s.' % data[-1])
371         else:
372             m, tmp = spl
373             try:
374                 m = float(m)
375             except ValueError:
376                 raise forms.ValidationError(u'Minutes must be an number. It\'s %s.' % m)
377             if len(tmp) == 0:
378                 s = 0
379             else:
380                 if tmp[-1] != '"':
381                     raise forms.ValidationError(u'You must use the " character between seconds and %s.' % data[-1])
382                 s = tmp[:-1]
383                 try:
384                     s = float(s)
385                 except ValueError:
386                     raise forms.ValidationError(u'Seconds must be an number. It\'s %s.' % s)
387         data = side * ( d + m / 60 + s / 3600)
388
389         if data < -180 or data > 180:
390             raise forms.ValidationError(u'%s in not in -180..180 range' % data)
391         return int(data * AIS_LATLON_SCALE)
392
393     def clean_cog(self):
394         data = self.cleaned_data['cog']
395         if data is None:
396             return AIS_COG_NOT_AVAILABLE
397         return int(data * AIS_COG_SCALE)
398     
399     def clean_heading(self):
400         #raise forms.ValidationError(u'clean_heading called')
401         data = self.cleaned_data['heading']
402         if data is None:
403             return AIS_NO_HEADING
404         return data
405
406     def clean(self):
407         cleaned_data = self.cleaned_data
408         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):
409             raise forms.ValidationError('It makes no sense to enter just a latitude or a longitude. Enter both or none.')
410         if cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE:
411             if cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) != AIS_STATUS_NOT_AVAILABLE:
412                 raise forms.ValidationError('It makes no sense to enter a status without coordinates. Please enter latitute and longitude too.')
413             if cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) != AIS_SOG_NOT_AVAILABLE:
414                 raise forms.ValidationError('It makes no sense to enter a speed without coordinates. Please enter latitute and longitude too.')
415             if cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) != AIS_COG_NOT_AVAILABLE:
416                 raise forms.ValidationError('It makes no sense to enter a course without coordinates. Please enter latitute and longitude too.')
417             if cleaned_data.get('heading', AIS_NO_HEADING) != AIS_NO_HEADING:
418                 raise forms.ValidationError('It makes no sense to enter a heading without coordinates. Please enter latitute and longitude too.')
419
420         if cleaned_data.get('timestamp', None) \
421         and cleaned_data.get('imo', 0) == 0 \
422         and cleaned_data.get('name', '') == '' \
423         and cleaned_data.get('callsign', '') == '' \
424         and cleaned_data.get('type', 0) == 0 \
425         and cleaned_data.get('status', AIS_STATUS_NOT_AVAILABLE) == AIS_STATUS_NOT_AVAILABLE \
426         and cleaned_data.get('sog', AIS_SOG_NOT_AVAILABLE) == AIS_SOG_NOT_AVAILABLE \
427         and cleaned_data.get('latitude', AIS_LAT_NOT_AVAILABLE) == AIS_LAT_NOT_AVAILABLE \
428         and cleaned_data.get('longitude', AIS_LON_NOT_AVAILABLE) == AIS_LON_NOT_AVAILABLE \
429         and cleaned_data.get('cog', AIS_COG_NOT_AVAILABLE) == AIS_COG_NOT_AVAILABLE \
430         and cleaned_data.get('heading', AIS_NO_HEADING) == AIS_NO_HEADING:
431             raise forms.ValidationError("You must enter some data, beside when.")
432         return cleaned_data
433
434 @http_authenticate(auth, 'ais')
435 def vessel_manual_input(request, strmmsi):
436     strmmsi = strmmsi.encode('utf-8')
437     nmea = Nmea.new_from_lastinfo(strmmsi)
438     if request.method == 'POST' or request.META['QUERY_STRING']:
439         form = VesselManualInputForm(request.REQUEST)
440         if form.is_valid():
441             data = form.cleaned_data
442             source = 'U' +  struct.pack('<I', request.user.id)[0:3]
443             result = u''
444             if data['imo'] != 0 \
445             or data['name'] != '' \
446             or data['callsign'] != '' \
447             or data['type'] != 0:
448                 toto = (strmmsi, data['timestamp'], data['imo'], data['name'], data['callsign'], data['type'], 0,0,0,0, 0,0,24,60, 0, '', source)
449                 result += 'UPDATING NMEA 5: '+repr(toto)+'<br>'
450                 add_nmea5_partial(*toto)
451             if data['status'] != AIS_STATUS_NOT_AVAILABLE \
452             or data['sog'] != AIS_SOG_NOT_AVAILABLE \
453             or data['latitude'] != AIS_LAT_NOT_AVAILABLE \
454             or data['longitude'] != AIS_LON_NOT_AVAILABLE \
455             or data['cog'] != AIS_COG_NOT_AVAILABLE \
456             or data['heading'] != AIS_NO_HEADING:
457                 
458                 toto = (strmmsi, data['timestamp'], data['status'], AIS_ROT_NOT_AVAILABLE, data['sog'], data['latitude'], data['longitude'], data['cog'], data['heading'], source)
459                 result += 'UPDATING NMEA 1: '+repr(toto)+'<br>'
460                 add_nmea1(*toto)
461             return HttpResponse('Not fully implemented: '+repr(data) + '<br>' + result)
462     else: # GET
463         form = VesselManualInputForm()
464     return render_to_response('vessel_manual_input.html', {'form': form, 'nmea': nmea}, RequestContext(request))
465
466
467 @http_authenticate(auth, 'ais')
468 def vessel_lastpos(request, strmmsi):
469     value = kml_to_kmz(format_fleet([ strmmsi ], document_name=strmmsi).encode('utf-8'))
470     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
471     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
472     return response
473
474 @http_authenticate(auth, 'ais')
475 def vessel_history(request, strmmsi):
476     """
477     TODO
478     That view is called from Google Earth, so that it must support GET method.  
479     """
480     initial = {}
481     if request.method == 'POST':
482         form = HistoryForm(request.POST, initial=initial)
483         if form.is_valid():
484             data = form.cleaned_data
485             if data['period_type'] == 'duration':
486                 date_start = datetime.utcnow() - timedelta(0, data['duration'])
487                 date_end = None # Now
488             elif data['period_type'] == 'date_date':
489                 date_start = data['start_date']
490                 date_end = data['end_date']
491             else:
492                 assert data['period_type'] == 'start_duration', ('Invalid period type %s' % data['period_type'])
493                 date_start = data['start_date']
494                 date_end = date_start + timedelta(0, data['duration'])
495
496             format = data['format']
497
498             if format == u'track':
499                 command = u'show_targets_ships'
500                 command += u' --format=track'
501                 extension = u'kmz'
502
503             elif format == u'animation':
504                 command = u'show_targets_ships'
505                 command += u' --format=animation'
506                 extension = u'kmz'
507             
508             elif format == u'csv':
509                 command = u'common'
510                 extension = u'csv'
511             else:
512                 raise Http404(u'Invalid archive format')
513             
514             command += u' --start=\'' + date_start.strftime('%Y%m%d %H%M%S') + u'\''
515             if date_end:
516                 command += u' --end=\'' + date_end.strftime('%Y%m%d %H%M%S') + u'\''
517             
518             grain = data['grain']
519             command += u' --granularity=' + unicode(grain)
520
521             command += u' ' + strmmsi
522
523             job = Job()
524             job.friendly_filename = u'%s.%s' % (strmmsi, extension)
525             job.user = request.user
526             job.command = command
527             job.save()
528             if not jobrunner.wakeup_daemon():
529                 return HttpResponseServerError(jobrunner.DAEMON_WAKEUP_ERROR)
530             return HttpResponseRedirect('/job/%s/download' % job.id)
531     else: # GET
532         form = HistoryForm(initial=initial)
533     strmmsi = strmmsi.encode('utf-8')
534     nmea = Nmea.new_from_lastinfo(strmmsi)
535     return render_to_response('vessel_history.html', {'nmea': nmea, 'form':form}, RequestContext(request))
536
537
538 @http_authenticate(auth, 'ais')
539 def fleets(request):
540     fleetusers = request.user.fleetuser_set.order_by('fleet')
541     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
542
543
544 @http_authenticate(auth, 'ais')
545 def fleet(request, fleetname):
546     fleet = get_object_or_404(Fleet, name=fleetname)
547     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
548         return HttpResponseForbidden('<h1>Forbidden</h1>')
549     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
550
551
552 class FleetEditForm(forms.Form):
553     name = forms.CharField(max_length=50)
554     description = forms.CharField(widget=forms.Textarea)
555
556     def clean_name(self):
557         name = self.cleaned_data['name']
558         if name == u'add':
559             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
560         if name != self.initial.get('name', None):
561             if Fleet.objects.filter(name=name).count():
562                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
563         return remove_decoration(name).replace(u' ', u'_')
564         
565
566 @http_authenticate(auth, 'ais')
567 def fleet_edit(request, fleetname):
568     initial = {}
569     if fleetname is not None:
570         fleet = get_object_or_404(Fleet, name=fleetname)
571         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
572             return HttpResponseForbidden('<h1>Forbidden</h1>')
573
574         initial['name'] = fleet.name
575         initial['description'] = fleet.description
576     else:
577         fleet = Fleet()
578
579     if request.method == 'POST':
580         form = FleetEditForm(request.POST, initial=initial)
581         if form.is_valid():
582             fleet.name = form.cleaned_data['name']
583             fleet.description = form.cleaned_data['description']
584             fleet.save()
585             if not fleetname: # new one
586                 fu = FleetUser()
587                 fu.fleet = fleet
588                 fu.user = request.user
589                 fu.save()
590             request.user.info('Fleet updated')
591             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
592     else: # GET
593         form = FleetEditForm(initial=initial)
594     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
595
596
597 @http_authenticate(auth, 'ais')
598 def fleet_vessels(request, fleetname):
599     fleet = get_object_or_404(Fleet, name=fleetname)
600     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
601         return HttpResponseForbidden('<h1>Forbidden</h1>')
602     vessels = fleet.vessel.all()
603     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
604
605
606 @http_authenticate(auth, 'ais')
607 def fleet_vessel_add(request, fleetname):
608     fleet = get_object_or_404(Fleet, name=fleetname)
609     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
610         return HttpResponseForbidden('<h1>Forbidden</h1>')
611     strmmsi = request.REQUEST['mmsi']
612     mmsi = strmmsi_to_mmsi(strmmsi)
613     try:
614         vessel = Vessel.objects.get(pk=mmsi)
615     except Vessel.DoesNotExist:
616         request.user.error('No such vessel')
617     else:
618         try:
619             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
620         except FleetVessel.DoesNotExist:
621             FleetVessel(fleet=fleet, vessel=vessel).save()
622             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
623         else:
624             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
625     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
626
627
628 class FleetAddVessel(forms.Form):
629     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
630     #name = forms.CharField(max_length=20, required=False)
631     #imo = forms.IntegerField(required=False)
632     #callsign = forms.CharField(max_length=7, required=False)
633     #destination = forms.CharField(max_length=20, required=False)
634     def clean(self):
635         cleaned_data = self.cleaned_data
636         for value in cleaned_data.values():
637             if value:
638                 return cleaned_data
639         raise forms.ValidationError("You must enter at least one criteria")
640
641 @http_authenticate(auth, 'ais')
642 def fleet_vessel_add2(request, fleetname):
643     fleet = get_object_or_404(Fleet, name=fleetname)
644     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
645         return HttpResponseForbidden('<h1>Forbidden</h1>')
646     if request.method == 'POST' or request.META['QUERY_STRING']:
647         form = FleetAddVessel(request.REQUEST)
648         if form.is_valid():
649             data = form.cleaned_data
650             result = []
651             a_strmmsi = request.REQUEST['mmsi']
652             if a_strmmsi:
653                 for strmmsi in a_strmmsi.split('\n'):
654                     strmmsi = strmmsi.strip('\r')
655                     if not strmmsi:
656                         continue
657                     try:
658                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
659                     except AssertionError:
660                         result.append('Invalid mmsi %s' % strmmsi)
661                         continue
662                     try:
663                         vessel = Vessel.objects.get(pk=sqlmmsi)
664                     except Vessel.DoesNotExist:
665                         result.append('No vessel with MMSI '+strmmsi)
666                         continue
667                     try:
668                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
669                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
670                     except FleetVessel.DoesNotExist:
671                         FleetVessel(fleet=fleet, vessel=vessel).save()
672                         result.append('Vessel with MMSI %s added' % strmmsi)
673
674             return HttpResponse('<br>'.join(result))
675     else: # GET
676         form = FleetAddVessel()
677
678     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
679
680
681 @http_authenticate(auth, 'ais')
682 def fleet_users(request, fleetname):
683     fleet = get_object_or_404(Fleet, name=fleetname)
684     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
685         return HttpResponseForbidden('<h1>Forbidden</h1>')
686
687     if request.method == 'POST' or request.META['QUERY_STRING']:
688         action = request.REQUEST['action']
689         userlogin = request.REQUEST['user']
690         try:
691             user = User.objects.get(login=userlogin)
692         except User.DoesNotExist:
693             request.user.error(u'User %s does not exist.' % userlogin)
694         else:
695             if action == u'add':
696                 try:
697                     fu = FleetUser.objects.get(fleet=fleet, user=user)
698                     request.user.error(u'User %s already has access.' % user.login)
699                 except FleetUser.DoesNotExist:
700                     FleetUser(fleet=fleet, user=user).save()
701                     #TODO log
702                     request.user.info(u'Granted access to user %s.' % user.login)
703             elif action == u'revoke':
704                 try:
705                     fu = FleetUser.objects.get(fleet=fleet, user=user)
706                     fu.delete()
707                     #TODO log
708                     request.user.info(u'Revoked access to user %s.' % user.login)
709                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
710                         fleet.delete()
711                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
712                         return HttpResponseRedirect('/fleet/')
713                 except FleetUser.DoesNotExist:
714                     request.user.error(u'User %s didn\'t have access.' % user.login)
715             else:
716                 request.user.error(u'Unknown action %s' % action)
717
718     fleetusers = fleet.fleetuser_set.all()
719     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
720     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
721
722
723 @http_authenticate(auth, 'ais')
724 def fleet_lastpos(request, fleetname):
725     fleet = get_object_or_404(Fleet, name=fleetname)
726     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
727         return HttpResponseForbidden('<h1>Forbidden</h1>')
728     fleet_uset = load_fleet_to_uset(fleet.id)
729     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
730     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
731     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
732     return response
733
734
735 @http_authenticate(auth, 'ais')
736 def jobs_index(request):
737     show_archive = request.REQUEST.has_key('archive')
738     if show_archive:
739         jobs = request.user.job_set.all()
740     else:
741         jobs = request.user.job_set.filter(archive_time__isnull=True)
742     
743     response = render_to_response('jobs.html', {'jobs': jobs, 'queue_size': Job.queue_size(), 'archive': show_archive }, RequestContext(request))
744     response['Refresh'] = 15
745     return response
746
747 @http_authenticate(auth, 'ais')
748 def job_detail(request, jobid):
749     job = get_object_or_404(Job, id=jobid)
750     if job.user != request.user:
751         return HttpResponseForbidden('403 Forbidden')
752     response = render_to_response('job.html', {'job': job, 'queue_size': Job.queue_size()}, RequestContext(request))
753     if not job.finish_time:
754         response['Refresh'] = 5
755     elif not job.archive_time:
756         # finished but not archived:
757         # TODO: use hostname
758         response['Refresh'] = '0;url=https://ais.nirgal.com/job/%s/download' % job.id
759         # careful not to modify other unschronized columns
760         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
761     return response
762
763 @http_authenticate(auth, 'ais')
764 def job_get(request, jobid):
765     job = get_object_or_404(Job, id=jobid)
766     if job.user != request.user:
767         return HttpResponseForbidden('403 Forbidden')
768     total_wait = 0
769     while not job.finish_time:
770         sleep(1)
771         total_wait += 1
772         if total_wait > 15:
773             request.user.info('Your query is slow. Please be patient.')
774             # TODO: Do not overwrite job.finishtime / result
775             if not job.notify:
776                 # careful not to modify other unschronized columns
777                 Job.objects.filter(id=jobid).update(notify = 'W') # Web
778             return HttpResponseRedirect('/job/%s/' % job.id)
779         job = get_object_or_404(Job, id=jobid)
780     
781     if not job.archive_time:
782         # careful not to modify other unschronized columns
783         Job.objects.filter(id=jobid).update(archive_time = datetime.utcnow())
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     response = render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': ACTIVE_MINUTES, 'form': form}, RequestContext(request))
977     response['Refresh'] = 60*ACTIVE_MINUTES
978     return response
979
980
981 @http_authenticate(auth, 'ais')
982 def sources_stats(request):
983     filter_peers = request.REQUEST.get('peers', None)
984     if filter_peers:
985         filter_peers = filter_peers.split(u',')
986
987     peers_config = peers_get_config()
988     peers_display = []
989
990     for id4, peer in peers_config.iteritems():
991         if filter_peers:
992             if unicode(id4) not in filter_peers:
993                 continue
994         peer['id4'] = id4
995         peers_display.append(peer)
996
997     peers_display = sorted(peers_display, key=lambda k: k['id4'])
998
999     filter_types = request.REQUEST.get('types', None)
1000     if filter_types:
1001         filter_types = filter_types.split(u',')
1002     else:
1003         filter_types = [ 'bytes', 'counts' ]
1004     logging.error('filter_types=%s', filter_types)
1005
1006     filter_periods = request.REQUEST.get('periods', None)
1007     if filter_periods:
1008         display_periods = []
1009         for period_name in filter_periods.split(u','):
1010             for period in periods:
1011                 if period['name_tiny'] == period_name:
1012                     display_periods.append(period)
1013     else:
1014         display_periods = periods
1015     #logging.error('display_periods=%s', display_periods)
1016
1017
1018     now = int(get_timestamp())
1019     for config in peers_display:
1020         id4 = config['id4']
1021         for period in periods:
1022             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
1023                 '--lazy', \
1024                 '-l', '0', \
1025                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
1026                 '--start', '%d' % (now - period['seconds']), \
1027                 '--end', '%d' % now, \
1028                 '--vertical-label', 'bps', \
1029                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1030                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1031                 'CDEF:bits=bytes,8,*', \
1032                 'CDEF:rawbits=rawbytes,8,*', \
1033                 'LINE:bits#00FF00:IP payload', \
1034                 'LINE:rawbits#FF0000:IP with headers'
1035             rrdtool.graph(*args)
1036             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
1037                 '--lazy', \
1038                 '-l', '0', \
1039                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
1040                 '--start', '%d' % (now-period['seconds']), \
1041                 '--end', '%d' % now, \
1042                 '--vertical-label', 'Hz', \
1043                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1044                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
1045                 'LINE:packets#FF0000:input packets', \
1046                 'LINE:lines#00FF00:AIVDM lines'
1047             rrdtool.graph(*args)
1048     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))
1049
1050
1051 @http_authenticate(auth, 'ais')
1052 def news(request, page):
1053     NEWS_PER_PAGE = 5
1054     if page:
1055         page = int(page)
1056     else:
1057         page = 1
1058     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) // NEWS_PER_PAGE)
1059     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
1060     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
1061
1062 @http_authenticate(auth, 'ais')
1063 def news_atom(request):
1064     from django.db import connection
1065
1066     news = News.objects.order_by('-created')
1067
1068     cursor = connection.cursor()
1069     cursor.execute("SELECT MAX(updated) FROM news")
1070     row = cursor.fetchone()
1071     last_update = row[0]
1072
1073     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')