No longer storing the 'python -m ais.' prefix in job commands
[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     return render_to_response('jobs.html', {'jobs': jobs, 'archive': show_archive }, RequestContext(request))
683
684 @http_authenticate(auth, 'ais')
685 def job_detail(request, jobid):
686     job = get_object_or_404(Job, id=jobid)
687     if job.user != request.user:
688         return HttpResponseForbidden('403 Forbidden')
689     response = render_to_response('job.html', {'job': job}, RequestContext(request))
690     if not job.finish_time:
691         response['Refresh'] = 5
692     elif not job.archive_time:
693         # finished but not archived:
694         response['Refresh'] = '0;url=https://ais.nirgal.com/job/%s/download' % job.id
695         job.archive_time = datetime.utcnow()
696         job.save()
697     return response
698
699 @http_authenticate(auth, 'ais')
700 def job_get(request, jobid):
701     job = get_object_or_404(Job, id=jobid)
702     if job.user != request.user:
703         return HttpResponseForbidden('403 Forbidden')
704     total_wait = 0
705     while not job.finish_time:
706         sleep(1)
707         total_wait += 1
708         if total_wait > 15:
709             request.user.info('Your query is slow. Please be patient.')
710             return HttpResponseRedirect('/job/%s/' % job.id)
711         job = get_object_or_404(Job, id=jobid)
712     
713     if not job.archive_time:
714         job.archive_time = datetime.utcnow()
715         job.save()
716
717     extension = os.path.splitext(job.friendly_filename)[-1]
718     return HttpResponseRedirect('/job_result/%s%s/%s' % (job.id, extension, job.friendly_filename))
719
720 @http_authenticate(auth, 'ais')
721 def users(request):
722     users = User.objects.order_by('name')
723     for user in users:
724         user.admin_ok = user.is_admin_by(request.user.id)
725     if request.REQUEST.has_key('showtree'):
726         local_users = {}
727         for user in users:
728             user.children = []
729             local_users[user.id] = user
730         for user in users:
731             if user.father_id == None:
732                 root = user
733             else:
734                 local_users[user.father_id].children.append(user)
735         assert root
736         return render_to_response('users_tree.html', {'root': root, 'auser': request.user.id}, RequestContext(request))
737     else:
738         return render_to_response('users.html', {'users':users}, RequestContext(request))
739
740 phone_re = re.compile('^\\+.+')
741
742 class UserEditForm(forms.Form):
743     login = forms.RegexField(regex=r'^[a-zA-Z0-9_]+$', max_length=16,
744         error_message ='Login must only contain letters, numbers and underscores')
745     name = forms.CharField(max_length=50)
746     email = forms.EmailField()
747     phone = forms.RegexField(regex='\\+.+', max_length=20, required=False,
748         error_message ='Phones must start with a \'+\'')
749     def __init__(self, *args, **kargs):
750         forms.Form.__init__(self, *args, **kargs)
751         self.old_login = kargs['initial']['login']
752     def clean_login(self):
753         new_login = self.cleaned_data['login']
754         if new_login != self.old_login:
755             if User.objects.filter(login=new_login).count():
756                 raise forms.ValidationError("Sorry that login is already in use. Try another one.")
757             if new_login == u'add':
758                 raise forms.ValidationError("Sorry that login is reserved. Try another one.")
759         return new_login
760
761 @http_authenticate(auth, 'ais')
762 def user_detail(request, login):
763     user = get_object_or_404(User, login=login)
764     user.admin_ok = user.is_admin_by(request.user.id)
765     return render_to_response('user_detail.html', {'auser': user}, RequestContext(request))
766
767 @http_authenticate(auth, 'ais')
768 def user_edit(request, login):
769     initial = {}
770     if login:
771         user = get_object_or_404(User, login=login)
772         if not user.is_admin_by(request.user.id):
773             return HttpResponseForbidden('403 Forbidden')
774     else:
775         user = User()
776         user.father_id = request.user.id;
777     initial['login'] = user.login
778     initial['name'] = user.name
779     initial['email'] = user.email
780     initial['phone'] = user.phone
781     if request.method == 'POST':
782         form = UserEditForm(request.POST, initial=initial)
783         if form.is_valid():
784             user.login = form.cleaned_data['login']
785             user.name = form.cleaned_data['name']
786             user.email = form.cleaned_data['email']
787             user.phone = form.cleaned_data['phone']
788             user.save()
789             user.check_sandbox_access(request.user)
790             return HttpResponseRedirect('/user/')
791     else: # GET
792         form = UserEditForm(initial=initial)
793
794     return render_to_response('user_edit.html', {'form':form, 'auser': user}, RequestContext(request))
795
796
797 class ChangePasswordForm(forms.Form):
798     new_password = forms.CharField(max_length=16, widget=forms.PasswordInput())
799     new_password_check = forms.CharField(max_length=16, widget=forms.PasswordInput())
800
801     def clean_generic_password(self, field_name):
802         password = self.cleaned_data[field_name]
803         try:
804             crack.FascistCheck(password)
805         except ValueError, err:
806             raise forms.ValidationError(err.message)
807         return password
808
809     def clean_new_password(self):
810         return self.clean_generic_password('new_password')
811
812     def clean_new_password_check(self):
813         return self.clean_generic_password('new_password_check')
814
815     def clean(self):
816         cleaned_data = self.cleaned_data
817         pass1 = cleaned_data.get('new_password')
818         pass2 = cleaned_data.get('new_password_check')
819         if pass1 != pass2 and pass2:
820             self._errors['new_password_check'] = forms.util.ErrorList(['Passwords must match'])
821             del cleaned_data['new_password_check'] # FIXME
822         return cleaned_data
823
824
825 @http_authenticate(auth, 'ais')
826 def user_change_password(request, login):
827     user = get_object_or_404(User, login=login)
828     if not user.is_admin_by(request.user.id):
829         return HttpResponseForbidden('403 Forbidden')
830     if request.method == 'POST':
831         form = ChangePasswordForm(request.POST)
832         if form.is_valid():
833             user.set_password(form.cleaned_data['new_password'])
834             user.save()
835             return HttpResponseRedirect('/user/')
836     else: # GET
837         form = ChangePasswordForm()
838     return render_to_response('user_change_password.html', {'form':form, 'auser':user}, RequestContext(request))
839
840
841 @http_authenticate(auth, 'ais')
842 def user_delete(request, login):
843     user = get_object_or_404(User, login=login)
844     if not user.is_admin_by(request.user.id):
845         return HttpResponseForbidden('403 Forbidden')
846     if request.REQUEST.get('confirm', None):
847         user.delete()
848         return HttpResponseRedirect('/user/')
849     return render_to_response('user_delete.html', {'form':None, 'auser':user}, RequestContext(request))
850
851
852 def logout(request):
853     # TODO
854     return HttpResponse('Not implemented')
855     #response = render_to_response('logout.html', {}, RequestContext(request))
856     #return response
857
858 periods = ({
859     'name_tiny': '2h',
860     'name_long': '2 hours',
861     'seconds': 2*60*60
862     }, {
863     'name_tiny': '6h',
864     'name_long': '6 hours',
865     'seconds': 6*60*60,
866     'default': True,
867     }, {
868     'name_tiny': '2d',
869     'name_long': '2 days',
870     'seconds': 2*24*60*60
871     }, {
872     'name_tiny': '14d',
873     'name_long': '2 weeks',
874     'seconds': 14*24*60*60
875     }, {
876     'name_tiny': '90d',
877     'name_long': '3 monthes',
878     'seconds': 90*24*60*60
879     }, {
880     'name_tiny': '180d',
881     'name_long': '6 monthes',
882     'seconds': 180*24*60*60
883     })
884         
885 class StatsSelectorForm(forms.Form):
886     peers = forms.ChoiceField(choices=[('', 'All')] + [(id4,source['name']) for id4,source in peers_get_config().iteritems()])
887     types = forms.ChoiceField(choices=[('', 'All'), ('bytes', 'Bandwidth'), ('counts', "Packet'izer")], initial='counts')
888     periods = forms.ChoiceField(choices=[(period['name_tiny'], period['name_long']) for period in periods] + [('', 'All')], initial='2d')
889
890 @http_authenticate(auth, 'ais')
891 def sources_index(request):
892     active_minutes = 5
893     peers_config = peers_get_config()
894     peers_display = []
895     for id4, peer in peers_config.iteritems():
896         peer['id4'] = id4
897         peer['id2'] = id4[2:]
898         peer['active'] = is_id4_active(id4, 60*active_minutes)
899         peers_display.append(peer)
900         
901     peers_display = sorted(peers_display, key=lambda k: k['id4'])
902
903     form = StatsSelectorForm()
904
905     return render_to_response('sources_index.html', {'sources':peers_display, 'active_minutes': active_minutes, 'form': form}, RequestContext(request))
906
907
908 @http_authenticate(auth, 'ais')
909 def sources_stats(request):
910     filter_peers = request.REQUEST.get('peers', None)
911     if filter_peers:
912         filter_peers = filter_peers.split(u',')
913
914     peers_config = peers_get_config()
915     peers_display = []
916
917     for id4, peer in peers_config.iteritems():
918         if filter_peers:
919             if unicode(id4) not in filter_peers:
920                 continue
921         peer['id4'] = id4
922         peers_display.append(peer)
923
924     peers_display = sorted(peers_display, key=lambda k: k['id4'])
925
926     filter_types = request.REQUEST.get('types', None)
927     if filter_types:
928         filter_types = filter_types.split(u',')
929     else:
930         filter_types = [ 'bytes', 'counts' ]
931     logging.error('filter_types=%s', filter_types)
932
933     filter_periods = request.REQUEST.get('periods', None)
934     if filter_periods:
935         display_periods = []
936         for period_name in filter_periods.split(u','):
937             for period in periods:
938                 if period['name_tiny'] == period_name:
939                     display_periods.append(period)
940     else:
941         display_periods = periods
942     #logging.error('display_periods=%s', display_periods)
943
944
945     now = int(get_timestamp())
946     for config in peers_display:
947         id4 = config['id4']
948         for period in periods:
949             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-bytes.png'), \
950                 '--lazy', \
951                 '-l', '0', \
952                 '--title', config['name'] + ' - Bandwidth usage - ' + period['name_long'], \
953                 '--start', '%d' % (now - period['seconds']), \
954                 '--end', '%d' % now, \
955                 '--vertical-label', 'bps', \
956                 'DEF:bytes=%s:bytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
957                 'DEF:rawbytes=%s:rawbytes:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
958                 'CDEF:bits=bytes,8,*', \
959                 'CDEF:rawbits=rawbytes,8,*', \
960                 'LINE:bits#00FF00:IP payload', \
961                 'LINE:rawbits#FF0000:IP with headers'
962             rrdtool.graph(*args)
963             args = os.path.join(STATS_DIR, id4+'-'+period['name_tiny']+'-counts.png'), \
964                 '--lazy', \
965                 '-l', '0', \
966                 '--title', config['name'] + ' - Packet\'izer stats - ' + period['name_long'], \
967                 '--start', '%d' % (now-period['seconds']), \
968                 '--end', '%d' % now, \
969                 '--vertical-label', 'Hz', \
970                 'DEF:packets=%s:packets:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
971                 'DEF:lines=%s:lines:AVERAGE' % os.path.join(STATS_DIR, id4+'.rrd'), \
972                 'LINE:packets#FF0000:input packets', \
973                 'LINE:lines#00FF00:AIVDM lines'
974             rrdtool.graph(*args)
975     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))
976
977
978 @http_authenticate(auth, 'ais')
979 def news(request, page):
980     NEWS_PER_PAGE = 10
981     if page:
982         page = int(page)
983     else:
984         page = 1
985     # TODO __future__
986     npages = int((News.objects.count() + NEWS_PER_PAGE - 1) / NEWS_PER_PAGE)
987     news = News.objects.order_by('-created')[(page - 1) * NEWS_PER_PAGE : page * NEWS_PER_PAGE]
988     return render_to_response('news.html', {'news':news, 'page': page, 'npages': npages}, RequestContext(request))
989
990 @http_authenticate(auth, 'ais')
991 def news_atom(request):
992     from django.db import connection
993
994     news = News.objects.order_by('-created')
995
996     cursor = connection.cursor()
997     cursor.execute("SELECT MAX(updated) FROM news")
998     row = cursor.fetchone()
999     last_update = row[0]
1000
1001     return render_to_response('news.atom', {'news':news, 'last_update':last_update}, RequestContext(request), mimetype='application/atom+xml')