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