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