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