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