Added archive_date for jobs.
[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     user.update_access_datetime()
41     return user
42
43
44 @http_authenticate(auth, 'ais')
45 def index(request):
46     news = News.objects.order_by('-created')[:5]
47     return render_to_response('index.html', {'news':news}, RequestContext(request))
48
49
50 class VesselSearchForm(forms.Form):
51     def country_choices():
52         choices = {}
53         for mid, countryname in COUNTRIES_MID.iteritems():
54             if choices.has_key(countryname):
55                 choices[countryname] += u','+unicode(mid)
56             else:
57                 choices[countryname] = unicode(mid)
58         choices = [ (countryname, mids) for mids, countryname in choices.iteritems() ]
59         choices = sorted(choices, key=operator.itemgetter(1))
60         return [(u'', u'Any')] + choices
61
62     mmsi = forms.CharField(max_length=9, required=False)
63     name = forms.CharField(max_length=20, required=False)
64     imo = forms.IntegerField(required=False)
65     callsign = forms.CharField(max_length=7, required=False)
66     flag = forms.ChoiceField(choices=country_choices(), required=False)
67     destination = forms.CharField(max_length=20, required=False)
68
69
70     def clean(self):
71         cleaned_data = self.cleaned_data
72         for value in cleaned_data.values():
73             if value:
74                 return cleaned_data
75         raise forms.ValidationError("You must enter at least one criteria")
76
77     def clean_mmsi(self):
78         mmsi = self.cleaned_data['mmsi']
79         if 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
366 @http_authenticate(auth, 'ais')
367 def vessel_history(request, strmmsi, format=None):
368     """
369     That view is called from Google Earth, so that it must support GET method.  
370     """
371     ndays = request.REQUEST.get('ndays', None)
372     if ndays is not None:
373         try:
374             ndays = int(ndays)
375         except ValueError:
376             ndays = 90
377         period = ndays * 86400
378     else:
379         period = request.REQUEST.get('period', u'1')
380         try:
381             period = int(period)
382         except ValueError:
383             period = 1
384         period_type = request.REQUEST.get('period_type', u'86400')
385         try:
386             period_type = int(period_type)
387         except ValueError:
388             period_type = 86400
389
390     grain = request.REQUEST.get('grain', 1)
391     try:
392         grain = int(grain)
393     except ValueError:
394         grain = 1
395     grain_type = request.REQUEST.get('grain_type', 3600)
396     try:
397         grain_type = int(grain_type)
398     except ValueError:
399         grain_type = 3600
400
401     date_end = datetime.utcnow()
402     date_start = date_end - timedelta(0,period*period_type)
403     nmea_iterator = NmeaFeeder(strmmsi, date_end, date_start, granularity=grain*grain_type)
404     
405     queue = request.REQUEST.get('queue', None)
406
407     if format is None:
408         format = request.REQUEST.get('format', u'track')
409
410     if format == u'track':
411         if queue:
412             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
413             job = Job()
414             job.user = request.user
415             job.command = command
416             job.extension = u'kmz'
417             job.save()
418             request.user.info('Request queued as job %s' % job.id)
419         else:
420             value = kml_to_kmz(format_boat_track(nmea_iterator))
421             response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
422             response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
423             return response
424
425     elif format == u'animation':
426         if queue:
427             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
428             job = Job()
429             job.user = request.user
430             job.command = command
431             job.extension = u'kmz'
432             job.save()
433             request.user.info('Request queued as job %s' % job.id)
434         else:
435             value = kml_to_kmz(format_boat_intime(nmea_iterator))
436             response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
437             response['Content-Disposition'] = 'attachment; filename=%s.kmz' % strmmsi
438             return response
439
440     elif format == u'csv':
441         if queue:
442             command = u'python -m ais.common --start=\'' + date_start.strftime('%Y%m%d %H%M%S') + u'\' --granularity=' + unicode(grain*grain_type) + ' ' + strmmsi
443             job = Job()
444             job.user = request.user
445             job.command = command
446             job.extension = u'csv'
447             job.save()
448             request.user.info('Request queued as job %s' % job.id)
449         else:
450             value = StringIO()
451             output = csv.writer(value)
452             output.writerow(Nmea.csv_headers)
453             for nmea in nmea_iterator:
454                 output.writerow(nmea.get_dump_row())
455             response = HttpResponse(value.getvalue(), mimetype='text/csv; charset="UTF-8"')
456             response['Content-Disposition'] = 'attachment; filename=%s.csv' % strmmsi
457             return response
458     else:
459         request.user.error(u'Invalid archive format')
460     return HttpResponseRedirect('/vessel/%s/' % strmmsi)
461
462
463 @http_authenticate(auth, 'ais')
464 def fleets(request):
465     fleetusers = request.user.fleetuser_set.order_by('fleet')
466     return render_to_response('fleets.html', {'fleetusers':fleetusers}, RequestContext(request))
467
468
469 @http_authenticate(auth, 'ais')
470 def fleet(request, fleetname):
471     fleet = get_object_or_404(Fleet, name=fleetname)
472     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
473         return HttpResponseForbidden('<h1>Forbidden</h1>')
474     return render_to_response('fleet.html', {'fleet':fleet}, RequestContext(request))
475
476
477 class FleetEditForm(forms.Form):
478     name = forms.CharField(max_length=50)
479     description = forms.CharField(widget=forms.Textarea)
480
481     def clean_name(self):
482         name = self.cleaned_data['name']
483         if name == u'add':
484             raise forms.ValidationError("Sorry that name is reserved. Try another one.")
485         if name != self.initial.get('name', None):
486             if Fleet.objects.filter(name=name).count():
487                 raise forms.ValidationError("Sorry that fleet name is already in use. Try another one.")
488         return remove_decoration(name).replace(u' ', u'_')
489         
490
491 @http_authenticate(auth, 'ais')
492 def fleet_edit(request, fleetname):
493     initial = {}
494     if fleetname is not None:
495         fleet = get_object_or_404(Fleet, name=fleetname)
496         if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
497             return HttpResponseForbidden('<h1>Forbidden</h1>')
498
499         initial['name'] = fleet.name
500         initial['description'] = fleet.description
501     else:
502         fleet = Fleet()
503
504     if request.method == 'POST':
505         form = FleetEditForm(request.POST, initial=initial)
506         if form.is_valid():
507             fleet.name = form.cleaned_data['name']
508             fleet.description = form.cleaned_data['description']
509             fleet.save()
510             if not fleetname: # new one
511                 fu = FleetUser()
512                 fu.fleet = fleet
513                 fu.user = request.user
514                 fu.save()
515             request.user.info('Fleet updated')
516             return HttpResponseRedirect('/fleet/%s/' % fleet.name)
517     else: # GET
518         form = FleetEditForm(initial=initial)
519     return render_to_response('fleet_edit.html', {'fleet':fleet, 'form':form}, RequestContext(request))
520
521
522 @http_authenticate(auth, 'ais')
523 def fleet_vessels(request, fleetname):
524     fleet = get_object_or_404(Fleet, name=fleetname)
525     if not FleetUser.objects.filter(fleet=fleet, user=request.user.id).all():
526         return HttpResponseForbidden('<h1>Forbidden</h1>')
527     vessels = fleet.vessel.all()
528     return render_to_response('fleet_vessels.html', {'fleet':fleet, 'vessels': vessels}, RequestContext(request))
529
530
531 @http_authenticate(auth, 'ais')
532 def fleet_vessel_add(request, fleetname):
533     fleet = get_object_or_404(Fleet, name=fleetname)
534     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
535         return HttpResponseForbidden('<h1>Forbidden</h1>')
536     strmmsi = request.REQUEST['mmsi']
537     mmsi = strmmsi_to_mmsi(strmmsi)
538     try:
539         vessel = Vessel.objects.get(pk=mmsi)
540     except Vessel.DoesNotExist:
541         request.user.error('No such vessel')
542     else:
543         try:
544             fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
545         except FleetVessel.DoesNotExist:
546             FleetVessel(fleet=fleet, vessel=vessel).save()
547             request.user.info(u'Vessel %s added to fleet %s.' % (vessel.name, fleetname))
548         else:
549             request.user.error('Vessel with MMSI %s is already in that fleet' % strmmsi)
550     return HttpResponseRedirect('/fleet/%s/list' % fleetname)
551
552
553 class FleetAddVessel(forms.Form):
554     mmsi = forms.CharField(help_text=u'Enter one MMSI per line', required=False, widget=forms.Textarea)
555     #name = forms.CharField(max_length=20, required=False)
556     #imo = forms.IntegerField(required=False)
557     #callsign = forms.CharField(max_length=7, required=False)
558     #destination = forms.CharField(max_length=20, required=False)
559     def clean(self):
560         cleaned_data = self.cleaned_data
561         for value in cleaned_data.values():
562             if value:
563                 return cleaned_data
564         raise forms.ValidationError("You must enter at least one criteria")
565
566 @http_authenticate(auth, 'ais')
567 def fleet_vessel_add2(request, fleetname):
568     fleet = get_object_or_404(Fleet, name=fleetname)
569     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
570         return HttpResponseForbidden('<h1>Forbidden</h1>')
571     if request.method == 'POST' or request.META['QUERY_STRING']:
572         form = FleetAddVessel(request.REQUEST)
573         if form.is_valid():
574             data = form.cleaned_data
575             result = []
576             a_strmmsi = request.REQUEST['mmsi']
577             if a_strmmsi:
578                 for strmmsi in a_strmmsi.split('\n'):
579                     strmmsi = strmmsi.strip('\r')
580                     if not strmmsi:
581                         continue
582                     try:
583                         sqlmmsi = strmmsi_to_mmsi(strmmsi)
584                     except AssertionError:
585                         result.append('Invalid mmsi %s' % strmmsi)
586                         continue
587                     try:
588                         vessel = Vessel.objects.get(pk=sqlmmsi)
589                     except Vessel.DoesNotExist:
590                         result.append('No vessel with MMSI '+strmmsi)
591                         continue
592                     try:
593                         fv = FleetVessel.objects.get(fleet=fleet, vessel=vessel)
594                         result.append('Vessel with MMSI %s is already in that fleet' % strmmsi)
595                     except FleetVessel.DoesNotExist:
596                         FleetVessel(fleet=fleet, vessel=vessel).save()
597                         result.append('Vessel with MMSI %s added' % strmmsi)
598
599             return HttpResponse('<br>'.join(result))
600     else: # GET
601         form = FleetAddVessel()
602
603     return render_to_response('fleet_vessel_add.html', {'form': form, 'fleet': fleet}, RequestContext(request))
604
605
606 @http_authenticate(auth, 'ais')
607 def fleet_users(request, fleetname):
608     fleet = get_object_or_404(Fleet, name=fleetname)
609     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
610         return HttpResponseForbidden('<h1>Forbidden</h1>')
611
612     if request.method == 'POST' or request.META['QUERY_STRING']:
613         action = request.REQUEST['action']
614         userlogin = request.REQUEST['user']
615         try:
616             user = User.objects.get(login=userlogin)
617         except User.DoesNotExist:
618             request.user.error(u'User %s does not exist.' % userlogin)
619         else:
620             if action == u'add':
621                 try:
622                     fu = FleetUser.objects.get(fleet=fleet, user=user)
623                     request.user.error(u'User %s already has access.' % user.login)
624                 except FleetUser.DoesNotExist:
625                     FleetUser(fleet=fleet, user=user).save()
626                     #TODO log
627                     request.user.info(u'Granted access to user %s.' % user.login)
628             elif action == u'revoke':
629                 try:
630                     fu = FleetUser.objects.get(fleet=fleet, user=user)
631                     fu.delete()
632                     #TODO log
633                     request.user.info(u'Revoked access to user %s.' % user.login)
634                     if FleetUser.objects.filter(fleet=fleet).count() == 0:
635                         fleet.delete()
636                         request.user.info(u"Deleted fleet %s (no more users)." % fleet.name)
637                         return HttpResponseRedirect('/fleet/')
638                 except FleetUser.DoesNotExist:
639                     request.user.error(u'User %s didn\'t have access.' % user.login)
640             else:
641                 request.user.error(u'Unknown action %s' % action)
642
643     fleetusers = fleet.fleetuser_set.all()
644     otherusers = User.objects.exclude(id__in=[fu.user.id for fu in fleetusers]).order_by('name')
645     return render_to_response('fleet_users.html', {'fleet':fleet, 'fleetusers': fleetusers, 'otherusers': otherusers}, RequestContext(request))
646
647
648 @http_authenticate(auth, 'ais')
649 def fleet_lastpos(request, fleetname):
650     fleet = get_object_or_404(Fleet, name=fleetname)
651     if not FleetUser.objects.filter(fleet=fleet.id, user=request.user.id).all():
652         return HttpResponseForbidden('<h1>Forbidden</h1>')
653     fleet_uset = load_fleet_to_uset(fleet.id)
654     # = set([mmsi_to_strmmsi(vessel.mmsi) for vessel in fleet.vessel.all()])
655     value = kml_to_kmz(format_fleet(fleet_uset, document_name=fleetname+' fleet').encode('utf-8'))
656     response = HttpResponse(value, mimetype="application/vnd.google-earth.kml")
657     response['Content-Disposition'] = 'attachment; filename=%s.kmz' % fleetname
658     return response
659
660
661 @http_authenticate(auth, 'ais')
662 def jobs_index(request):
663     show_archive = request.REQUEST.has_key('archive')
664     if show_archive:
665         jobs = request.user.job_set.all()
666     else:
667         jobs = request.user.job_set.filter(archive_time__isnull=True)
668     return render_to_response('jobs.html', {'jobs': jobs, 'archive': show_archive }, RequestContext(request))
669
670 @http_authenticate(auth, 'ais')
671 def job_get(request, jobid):
672     job = get_object_or_404(Job, id=jobid)
673     if job.user != request.user:
674         return HttpResponseForbidden('403 Forbidden')
675     if not job.archive_time:
676         job.archive_time = datetime.utcnow()
677         job.save()
678     return HttpResponseRedirect('/job_result/%s.%s' % (job.id, job.extension))
679
680 @http_authenticate(auth, 'ais')
681 def users(request):
682     users = User.objects.order_by('name')
683     for user in users:
684         user.admin_ok = user.is_admin_by(request.user.id)
685     if request.REQUEST.has_key('showtree'):
686         local_users = {}
687         for user in users:
688             user.children = []
689             local_users[user.id] = user
690         for user in users:
691             if user.father_id == None:
692                 root = user
693             else:
694                 local_users[user.father_id].children.append(user)
695         assert root
696         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
697     else:
698         return render_to_response('users.html', {'users':users}, RequestContext(request))
699
700 phone_re = re.compile('^\\+.+')
701
702 class UserEditForm(forms.Form):
703     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
704         error_message ='Login must only contain letters, numbers and underscores')
705     name = forms.CharField(max_length=50)
706     email = forms.EmailField()
707     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
708         error_message ='Phones must start with a \'+\'')
709     def __init__(self, *args, **kargs):
710         forms.Form.__init__(self, *args, **kargs)
711         self.old_login = kargs['initial']['login']
712     def clean_login(self):
713         new_login = self.cleaned_data['login']
714         if new_login != self.old_login:
715             if User.objects.filter(login=new_login).count():
716                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
717             if new_login == u'add':
718                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
719         return new_login
720
721 @http_authenticate(auth, 'ais')
722 def user_detail(request, login):
723     user = get_object_or_404(User, login=login)
724     user.admin_ok = user.is_admin_by(request.user.id)
725     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
726
727 @http_authenticate(auth, 'ais')
728 def user_edit(request, login):
729     initial = {}
730     if login:
731         user = get_object_or_404(User, login=login)
732         if not user.is_admin_by(request.user.id):
733             return HttpResponseForbidden('403 Forbidden')
734     else:
735         user = User()
736         user.father_id = request.user.id;
737     initial['login'] = user.login
738     initial['name'] = user.name
739     initial['email'] = user.email
740     initial['phone'] = user.phone
741     if request.method == 'POST':
742         form = UserEditForm(request.POST, initial=initial)
743         if form.is_valid():
744             user.login = form.cleaned_data['login']
745             user.name = form.cleaned_data['name']
746             user.email = form.cleaned_data['email']
747             user.phone = form.cleaned_data['phone']
748             user.save()
749             user.check_sandbox_access(request.user)
750             return HttpResponseRedirect('/user/')
751     else: # GET
752         form = UserEditForm(initial=initial)
753
754     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
755
756
757 class ChangePasswordForm(forms.Form):
758     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
759     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
760
761     def clean_generic_password(self, field_name):
762         password = self.cleaned_data[field_name]
763         try:
764             crack.FascistCheck(password)
765         except ValueError, err:
766             raise forms.ValidationError(err.message)
767         return password
768
769     def clean_new_password(self):
770         return self.clean_generic_password('new_password')
771
772     def clean_new_password_check(self):
773         return self.clean_generic_password('new_password_check')
774
775     def clean(self):
776         cleaned_data = self.cleaned_data
777         pass1 = cleaned_data.get('new_password')
778         pass2 = cleaned_data.get('new_password_check')
779         if pass1 != pass2 and pass2:
780             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
781             del cleaned_data['new_password_check'] # FIXME
782         return cleaned_data
783
784
785 @http_authenticate(auth, 'ais')
786 def user_change_password(request, login):
787     user = get_object_or_404(User, login=login)
788     if not user.is_admin_by(request.user.id):
789         return HttpResponseForbidden('403 Forbidden')
790     if request.method == 'POST':
791         form = ChangePasswordForm(request.POST)
792         if form.is_valid():
793             user.set_password(form.cleaned_data['new_password'])
794             user.save()
795             return HttpResponseRedirect('/user/')
796     else: # GET
797         form = ChangePasswordForm()
798     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
799
800
801 @http_authenticate(auth, 'ais')
802 def user_delete(request, login):
803     user = get_object_or_404(User, login=login)
804     if not user.is_admin_by(request.user.id):
805         return HttpResponseForbidden('403 Forbidden')
806     if request.REQUEST.get('confirm', None):
807         user.delete()
808         return HttpResponseRedirect('/user/')
809     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
810
811
812 def logout(request):
813     # TODO
814     return HttpResponse('Not implemented')
815     #response = render_to_response('logout.html', {}, RequestContext(request))
816     #return response
817
818 periods = ({
819     'name_tiny': '2h',
820     'name_long': '2 hours',
821     'seconds': 2*60*60
822     }, {
823     'name_tiny': '6h',
824     'name_long': '6 hours',
825     'seconds': 6*60*60,
826     'default': True,
827     }, {
828     'name_tiny': '2d',
829     'name_long': '2 days',
830     'seconds': 2*24*60*60
831     }, {
832     'name_tiny': '14d',
833     'name_long': '2 weeks',
834     'seconds': 14*24*60*60
835     }, {
836     'name_tiny': '90d',
837     'name_long': '3 monthes',
838     'seconds': 90*24*60*60
839     }, {
840     'name_tiny': '180d',
841     'name_long': '6 monthes',
842     'seconds': 180*24*60*60
843     })
844         
845 class StatsSelectorForm(forms.Form):
846     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
847     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
848     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
849
850 @http_authenticate(auth, 'ais')
851 def sources_index(request):
852     active_minutes = 5
853     peers_config = peers_get_config()
854     peers_display = []
855     for id4, peer in peers_config.iteritems():
856         peer['id4'] = id4
857         peer['id2'] = id4[2:]
858         peer['active'] = is_id4_active(id4, 60*active_minutes)
859         peers_display.append(peer)
860         
861     peers_display = sorted(peers_display, key=lambda k: k['id4'])
862
863     form = StatsSelectorForm()
864
865     return render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': active_minutes, 'form': form}, RequestContext(request))
866
867
868 @http_authenticate(auth, 'ais')
869 def sources_stats(request):
870     filter_peers = request.REQUEST.get('peers', None)
871     if filter_peers:
872         filter_peers = filter_peers.split(u',')
873
874     peers_config = peers_get_config()
875     peers_display = []
876
877     for id4, peer in peers_config.iteritems():
878         if filter_peers:
879             if unicode(id4) not in filter_peers:
880                 continue
881         peer['id4'] = id4
882         peers_display.append(peer)
883
884     peers_display = sorted(peers_display, key=lambda k: k['id4'])
885
886     filter_types = request.REQUEST.get('types', None)
887     if filter_types:
888         filter_types = filter_types.split(u',')
889     else:
890         filter_types = [ 'bytes', 'counts' ]
891     logging.error('filter_types=%s', filter_types)
892
893     filter_periods = request.REQUEST.get('periods', None)
894     if filter_periods:
895         display_periods = []
896         for period_name in filter_periods.split(u','):
897             for period in periods:
898                 if period['name_tiny'] == period_name:
899                     display_periods.append(period)
900     else:
901         display_periods = periods
902     #logging.error('display_periods=%s', display_periods)
903
904
905     now = int(get_timestamp())
906     for config in peers_display:
907         id4 = config['id4']
908         for period in periods:
909             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
910                 '--lazy', \
911                 '-l', '0', \
912                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
913                 '--start', '%d' % (now - period['seconds']), \
914                 '--end', '%d' % now, \
915                 '--vertical-label', 'bps', \
916                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
917                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
918                 'CDEF:bits=bytes,8,*', \
919                 'CDEF:rawbits=rawbytes,8,*', \
920                 'LINE:bits#00FF00:IP payload', \
921                 'LINE:rawbits#FF0000:IP with headers'
922             rrdtool.graph(*args)
923             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
924                 '--lazy', \
925                 '-l', '0', \
926                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
927                 '--start', '%d' % (now-period['seconds']), \
928                 '--end', '%d' % now, \
929                 '--vertical-label', 'Hz', \
930                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
931                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
932                 'LINE:packets#FF0000:input packets', \
933                 'LINE:lines#00FF00:AIVDM lines'
934             rrdtool.graph(*args)
935     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))
936
937
938 @http_authenticate(auth, 'ais')
939 def news(request, page):
940     NEWS_PER_PAGE = 10
941     if page:
942         page = int(page)
943     else:
944         page = 1
945     # TODO __future__
946     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) / NEWS_PER_PAGE)
947     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
948     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
949
950 @http_authenticate(auth, 'ais')
951 def news_atom(request):
952     from django.db import connection
953
954     news = News.objects.order_by('-created')
955
956     cursor = connection.cursor()
957     cursor.execute("SELECT MAX(updated) FROM news")
958     row = cursor.fetchone()
959     last_update = row[0]
960
961     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')