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