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