Пример #1
0
    def post(self, request):
        # Attempt authentication
        try:
            username = request.POST['username']
            password = request.POST['password']
        except KeyError:
            # Failed to get POST parameters, invalid request
            logger.warning(
                'Did not specify username & password in login request.')
            return HttpResponseBadRequest(
                'Login must be POST request with '
                '"username" and "password" parameters.')

        # Use credentials to authenticate
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Successful authentication with active user, login
            login(request, user)
            logger.info('User logged in: %s.' % user.username)
            return HttpResponse('Login Successful.')
        else:
            # Invalid user credentials, invalid request
            logger.warning('Invalid credentials in login request.')
            logger.debug(request)
            return HttpResponseBadRequest('Invalid Credentials.')
Пример #2
0
    def get(self, request):
        logger.info('Admin downloading team evaluation.')

        # Get the mission to evaluate a team for.
        mission, error = mission_for_request(request.GET)
        if error:
            logger.warning('Could not get mission to evaluate teams.')
            return error

        # Get the optional team to eval.
        users = None
        if 'team' in request.GET:
            try:
                team = int(request.GET['team'])
                users = [User.objects.get(pk=team)]
            except TypeError:
                return HttpResponseBadRequest('Team not an ID.')
            except User.DoesNotExist:
                return HttpResponseNotFound('Team not found.')

        # Get the eval data for the teams
        user_eval_data = mission.evaluate_teams(users)
        if not user_eval_data:
            logger.warning('No data for team evaluation.')
            return HttpResponseServerError(
                'Could not get user evaluation data.')
        # Convert to username key-d map.
        user_eval_data = {u.username: d for u, d in user_eval_data.iteritems()}
        return self.format_response(user_eval_data)
Пример #3
0
    def get(self, request):
        # Log user access to server information.
        logger.info('User downloaded server info: %s.' % request.user.username)
        ServerInfoAccessLog(user=request.user).save()

        # Form response.
        try:
            # Get the server info stored in the active mission.
            server_info_key = '/ServerInfo/latest'
            info = cache.get(server_info_key)
            if info is None:
                (mission, err) = active_mission()
                if err:
                    return err
                info = mission.server_info
                if not info:
                    return HttpResponseServerError(
                        'No server info for mission.')
                cache.set(server_info_key, info)
        except ServerInfo.DoesNotExist:
            # Failed to obtain server info.
            return HttpResponseServerError('No server info available.')

        # Form JSON response.
        data = info.json()
        data['server_time'] = datetime.datetime.now().isoformat()
        return JsonResponse(data)
Пример #4
0
    def get(self, request):
        logger.info('Admin downloading team evaluation.')

        # Get the mission to evaluate a team for.
        mission, error = mission_for_request(request.GET)
        if error:
            logger.warning('Could not get mission to evaluate teams.')
            return error

        # Get the optional team to eval.
        users = None
        if 'team' in request.GET:
            try:
                team = int(request.GET['team'])
                users = [User.objects.get(pk=team)]
            except TypeError:
                return HttpResponseBadRequest('Team not an ID.')
            except User.DoesNotExist:
                return HttpResponseNotFound('Team not found.')

        # Get the eval data for the teams
        user_eval_data = mission.evaluate_teams(users)
        if not user_eval_data:
            logger.warning('No data for team evaluation.')
            return HttpResponseServerError(
                'Could not get user evaluation data.')
        # Convert to username key-d map.
        user_eval_data = {u.username: d for u, d in user_eval_data.iteritems()}
        return self.format_response(user_eval_data)
Пример #5
0
    def post(self, request):
        # Attempt authentication
        try:
            username = request.POST['username']
            password = request.POST['password']
        except KeyError:
            # Failed to get POST parameters, invalid request
            logger.warning(
                'Did not specify username & password in login request.')
            return HttpResponseBadRequest(
                'Login must be POST request with '
                '"username" and "password" parameters.')

        # Use credentials to authenticate
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Successful authentication with active user, login
            login(request, user)
            logger.info('User logged in: %s.' % user.username)
            return HttpResponse('Login Successful.')
        else:
            # Invalid user credentials, invalid request
            logger.warning('Invalid credentials in login request.')
            logger.debug(request)
            return HttpResponseBadRequest('Invalid Credentials.')
Пример #6
0
    def get(self, request):
        # Log user access to server information.
        logger.info('User downloaded server info: %s.' % request.user.username)
        ServerInfoAccessLog(user=request.user).save()

        # Form response.
        try:
            # Get the server info stored in the active mission.
            server_info_key = '/ServerInfo/latest'
            info = cache.get(server_info_key)
            if info is None:
                (mission, err) = active_mission()
                if err:
                    return err
                info = mission.server_info
                if not info:
                    return HttpResponseServerError(
                        'No server info for mission.')
                cache.set(server_info_key, info)
        except ServerInfo.DoesNotExist:
            # Failed to obtain server info.
            return HttpResponseServerError('No server info available.')

        # Form JSON response.
        data = info.json()
        data['server_time'] = datetime.datetime.now().isoformat()
        return JsonResponse(data)
Пример #7
0
    def get(self, request):
        logger.info('Admin downloaded team evaluation.')

        # Get the mission to evaluate a team for.
        mission, error = mission_for_request(request.GET)
        if error:
            logger.warning('Could not get mission to evaluate teams.')
            return error

        # Get the eval data for the teams
        user_eval_data = mission.evaluate_teams()
        if not user_eval_data:
            logger.warning('No data for team evaluation.')
            return HttpResponseServerError(
                'Could not get user evaluation data.')

        # Reformat to column oriented
        user_col_data = {}
        for (user, eval_data) in user_eval_data.iteritems():
            col_data = user_col_data.setdefault(user, {})
            col_data['username'] = user.username
            work_queue = [([], eval_data)]
            while len(work_queue) > 0:
                (cur_prefixes, cur_map) = work_queue.pop()
                for (key, val) in cur_map.iteritems():
                    new_prefixes = copy.copy(cur_prefixes)
                    new_prefixes.append(str(key))
                    if isinstance(val, dict):
                        work_queue.append((new_prefixes, val))
                    else:
                        column_key = '.'.join(new_prefixes)
                        if isinstance(val, list):
                            col_data[column_key] = ','.join(val)
                        else:
                            col_data[column_key] = val
        # Get column headers
        col_headers = set()
        for col_data in user_col_data.values():
            for header in col_data.keys():
                col_headers.add(header)
        col_headers = sorted(col_headers)

        # Write output
        csv_output = cStringIO.StringIO()
        writer = csv.DictWriter(csv_output, fieldnames=col_headers)
        writer.writeheader()
        for col_data in user_col_data.values():
            writer.writerow(col_data)
        output = csv_output.getvalue()
        csv_output.close()
        return HttpResponse(output)
Пример #8
0
    def get(self, request):
        logger.info('Admin downloaded team evaluation.')

        # Get the mission to evaluate a team for.
        mission, error = mission_for_request(request.GET)
        if error:
            logger.warning('Could not get mission to evaluate teams.')
            return error

        # Get the eval data for the teams
        user_eval_data = mission.evaluate_teams()
        if not user_eval_data:
            logger.warning('No data for team evaluation.')
            return HttpResponseServerError(
                'Could not get user evaluation data.')

        # Reformat to column oriented
        user_col_data = {}
        for (user, eval_data) in user_eval_data.iteritems():
            col_data = user_col_data.setdefault(user, {})
            col_data['username'] = user.username
            work_queue = [([], eval_data)]
            while len(work_queue) > 0:
                (cur_prefixes, cur_map) = work_queue.pop()
                for (key, val) in cur_map.iteritems():
                    new_prefixes = copy.copy(cur_prefixes)
                    new_prefixes.append(str(key))
                    if isinstance(val, dict):
                        work_queue.append((new_prefixes, val))
                    else:
                        column_key = '.'.join(new_prefixes)
                        if isinstance(val, list):
                            col_data[column_key] = ','.join(val)
                        else:
                            col_data[column_key] = val
        # Get column headers
        col_headers = set()
        for col_data in user_col_data.values():
            for header in col_data.keys():
                col_headers.add(header)
        col_headers = sorted(col_headers)

        # Write output
        csv_output = cStringIO.StringIO()
        writer = csv.DictWriter(csv_output, fieldnames=col_headers)
        writer.writeheader()
        for col_data in user_col_data.values():
            writer.writerow(col_data)
        output = csv_output.getvalue()
        csv_output.close()
        return HttpResponse(output, content_type='text/csv')
Пример #9
0
    def get(self, request):
        logger.info('Admin downloading team evaluation.')

        # Get the mission to evaluate a team for.
        mission, error = mission_for_request(request.GET)
        if error:
            logger.warning('Could not get mission to evaluate teams.')
            return error

        # Get the optional team to eval.
        users = None
        if 'team' in request.GET:
            try:
                team = int(request.GET['team'])
                users = [User.objects.get(pk=team)]
            except TypeError:
                return HttpResponseBadRequest('Team not an ID.')
            except User.DoesNotExist:
                return HttpResponseNotFound('Team not found.')

        # Get the eval data for the teams.
        mission_eval = mission_evaluation.evaluate_teams(mission, users)
        if not mission_eval:
            logger.warning('No data for team evaluation.')
            return HttpResponseServerError(
                'Could not get user evaluation data.')

        # Form Zip file.
        zip_io = cStringIO.StringIO()
        with zipfile.ZipFile(zip_io, 'w') as zip_file:
            zip_file.writestr(
                '/evaluate_teams/all.json',
                self.pretty_json(json_format.MessageToJson(mission_eval)))
            team_jsons = []
            for team_eval in mission_eval.teams:
                team_json = self.pretty_json(
                    json_format.MessageToJson(team_eval))
                zip_file.writestr(
                    '/evaluate_teams/teams/%s.json' % team_eval.team,
                    team_json)
                team_jsons.append(team_json)

            zip_file.writestr('/evaluate_teams/all.csv',
                              self.csv_from_json(team_jsons))
        zip_output = zip_io.getvalue()
        zip_io.close()

        return HttpResponse(zip_output, content_type='application/zip')
Пример #10
0
    def get(self, request):
        logger.info('Admin downloading team evaluation.')

        # Get the mission to evaluate a team for.
        mission, error = mission_for_request(request.GET)
        if error:
            logger.warning('Could not get mission to evaluate teams.')
            return error

        # Get the optional team to eval.
        users = None
        if 'team' in request.GET:
            try:
                team = int(request.GET['team'])
                users = [User.objects.get(pk=team)]
            except TypeError:
                return HttpResponseBadRequest('Team not an ID.')
            except User.DoesNotExist:
                return HttpResponseNotFound('Team not found.')

        # Get the eval data for the teams.
        mission_eval = mission_evaluation.evaluate_teams(mission, users)
        if not mission_eval:
            logger.warning('No data for team evaluation.')
            return HttpResponseServerError(
                'Could not get user evaluation data.')

        # Form Zip file.
        zip_io = cStringIO.StringIO()
        with zipfile.ZipFile(zip_io, 'w') as zip_file:
            zip_file.writestr(
                '/evaluate_teams/all.json',
                self.pretty_json(json_format.MessageToJson(mission_eval)))
            team_jsons = []
            for team_eval in mission_eval.teams:
                team_json = self.pretty_json(json_format.MessageToJson(
                    team_eval))
                zip_file.writestr('/evaluate_teams/teams/%s.json' %
                                  team_eval.team, team_json)
                team_jsons.append(team_json)

            zip_file.writestr('/evaluate_teams/all.csv',
                              self.csv_from_json(team_jsons))
        zip_output = zip_io.getvalue()
        zip_io.close()

        return HttpResponse(zip_output, content_type='application/zip')
Пример #11
0
    def get(self, request):
        time = timezone.now()

        # ?time=TIMESTAMP to get obstacle location at specific time
        if 'time' in request.GET:
            if not request.user.is_superuser:
                return HttpResponseBadRequest(
                    'Only superusers may set the time parameter')

            try:
                time = iso8601.parse_date(request.GET['time'])
            except iso8601.ParseError:
                return HttpResponseBadRequest("Bad timestamp '%s'" % \
                                                request.GET['time'])

        # Log user access to obstacle info
        logger.info('User downloaded obstacle info: %s.' %
                    request.user.username)

        # Get active mission for forming responses.
        (mission, err) = active_mission()
        if err:
            return err

        # Form JSON response portion for stationary obstacles
        stationary_obstacles_cached = True
        stationary_obstacles_key = '/StationaryObstacle/all'
        stationary_obstacles = cache.get(stationary_obstacles_key)
        if stationary_obstacles is None:
            stationary_obstacles = mission.stationary_obstacles.all()
            stationary_obstacles_cached = False
        stationary_obstacles_json = []
        for cur_obst in stationary_obstacles:
            # Add current obstacle
            cur_obst_json = cur_obst.json()
            stationary_obstacles_json.append(cur_obst_json)

        # Form JSON response portion for moving obstacles
        moving_obstacles_cached = True
        moving_obstacles_key = '/MovingObstacle/all'
        moving_obstacles = cache.get(moving_obstacles_key)
        if moving_obstacles is None:
            moving_obstacles = mission.moving_obstacles.all()
            moving_obstacles_cached = False
        moving_obstacles_json = []
        for cur_obst in moving_obstacles:
            # Add current obstacle
            cur_obst_json = cur_obst.json(time=time)
            moving_obstacles_json.append(cur_obst_json)

        # Form final JSON response
        data = {
            'stationary_obstacles': stationary_obstacles_json,
            'moving_obstacles': moving_obstacles_json
        }

        # Cache obstacles for next request
        if not stationary_obstacles_cached:
            cache.set(stationary_obstacles_key, stationary_obstacles)
        if not moving_obstacles_cached:
            cache.set(moving_obstacles_key, moving_obstacles)

        # Return JSON data
        return HttpResponse(json.dumps(data), content_type="application/json")
Пример #12
0
    def post(self, request):
        """Posts the UAS position with a POST request.

        User must send a POST request with the following paramters:
        latitude: A latitude in decimal degrees.
        longitude: A logitude in decimal degrees.
        altitude_msl: An MSL altitude in decimal feet.
        uas_heading: The UAS (true north) heading in decimal degrees.
        """
        try:
            # Get the parameters
            latitude = float(request.POST['latitude'])
            longitude = float(request.POST['longitude'])
            altitude_msl = float(request.POST['altitude_msl'])
            uas_heading = float(request.POST['uas_heading'])
        except KeyError:
            # Failed to get POST parameters
            logger.warning(
                'User did not specify all params for uas telemetry request.')
            logger.debug(request)
            return HttpResponseBadRequest(
                'Posting UAS position must contain POST parameters "latitude", '
                '"longitude", "altitude_msl", and "uas_heading".')
        except ValueError:
            # Failed to convert parameters
            logger.warning(
                'User specified a param which could not converted to an ' +
                'appropriate type.')
            logger.debug(request)
            return HttpResponseBadRequest(
                'Failed to convert provided POST parameters to correct form.')
        else:
            # Check the values make sense
            if latitude < -90 or latitude > 90:
                logger.warning('User specified latitude out of valid range.')
                logger.debug(request)
                return HttpResponseBadRequest(
                    'Must provide latitude between -90 and 90 degrees.')
            if longitude < -180 or longitude > 180:
                logger.warning('User specified longitude out of valid range.')
                logger.debug(request)
                return HttpResponseBadRequest(
                    'Must provide longitude between -180 and 180 degrees.')
            if uas_heading < 0 or uas_heading > 360:
                logger.warning('User specified altitude out of valid range.')
                logger.debug(request)
                return HttpResponseBadRequest(
                    'Must provide heading between 0 and 360 degrees.')

            # Store telemetry
            logger.info('User uploaded telemetry: %s' % request.user.username)

            gpos = GpsPosition(latitude=latitude, longitude=longitude)
            gpos.save()

            apos = AerialPosition(gps_position=gpos, altitude_msl=altitude_msl)
            apos.save()

            telemetry = UasTelemetry(user=request.user,
                                     uas_position=apos,
                                     uas_heading=uas_heading)
            telemetry.save()

            return HttpResponse('UAS Telemetry Successfully Posted.')
Пример #13
0
    def post(self, request):
        """Posts the UAS position with a POST request.

        User must send a POST request with the following paramters:
        latitude: A latitude in decimal degrees.
        longitude: A logitude in decimal degrees.
        altitude_msl: An MSL altitude in decimal feet.
        uas_heading: The UAS (true north) heading in decimal degrees.
        """
        try:
            # Get the parameters
            latitude = float(request.POST['latitude'])
            longitude = float(request.POST['longitude'])
            altitude_msl = float(request.POST['altitude_msl'])
            uas_heading = float(request.POST['uas_heading'])
        except KeyError:
            # Failed to get POST parameters
            logger.warning(
                'User did not specify all params for uas telemetry request.')
            logger.debug(request)
            return HttpResponseBadRequest(
                'Posting UAS position must contain POST parameters "latitude", '
                '"longitude", "altitude_msl", and "uas_heading".')
        except ValueError:
            # Failed to convert parameters
            logger.warning(
                'User specified a param which could not converted to an ' +
                'appropriate type.')
            logger.debug(request)
            return HttpResponseBadRequest(
                'Failed to convert provided POST parameters to correct form.')
        else:
            # Check the values make sense
            if latitude < -90 or latitude > 90:
                logger.warning('User specified latitude out of valid range.')
                logger.debug(request)
                return HttpResponseBadRequest(
                    'Must provide latitude between -90 and 90 degrees.')
            if longitude < -180 or longitude > 180:
                logger.warning('User specified longitude out of valid range.')
                logger.debug(request)
                return HttpResponseBadRequest(
                    'Must provide longitude between -180 and 180 degrees.')
            if uas_heading < 0 or uas_heading > 360:
                logger.warning('User specified altitude out of valid range.')
                logger.debug(request)
                return HttpResponseBadRequest(
                    'Must provide heading between 0 and 360 degrees.')

            # Store telemetry
            logger.info('User uploaded telemetry: %s' % request.user.username)

            gpos = GpsPosition(latitude=latitude, longitude=longitude)
            gpos.save()

            apos = AerialPosition(gps_position=gpos, altitude_msl=altitude_msl)
            apos.save()

            telemetry = UasTelemetry(
                user=request.user, uas_position=apos, uas_heading=uas_heading)
            telemetry.save()

            return HttpResponse('UAS Telemetry Successfully Posted.')
Пример #14
0
 def get(self, request):
     logger.info('Admin requested to clear the cache.')
     cache.clear()
     return HttpResponse("Cache cleared.")
Пример #15
0
 def get(self, request):
     logger.info('Admin requested to clear the cache.')
     cache.clear()
     return HttpResponse("Cache cleared.")
Пример #16
0
    def get(self, request):
        log_access = True
        time = timezone.now()

        # ?log=(true|false) to enable/disable logging of superusers
        if 'log' in request.GET:
            if not request.user.is_superuser:
                return HttpResponseBadRequest(
                    'Only superusers may set the log parameter')

            try:
                log_access = boolean_param(request.GET['log'])
            except ValueError as e:
                return HttpResponseBadRequest(e)

        # ?time=TIMESTAMP to get obstacle location at specific time
        if 'time' in request.GET:
            if not request.user.is_superuser:
                return HttpResponseBadRequest(
                    'Only superusers may set the time parameter')

            try:
                time = iso8601.parse_date(request.GET['time'])
            except iso8601.ParseError:
                return HttpResponseBadRequest("Bad timestamp '%s'" % \
                                                request.GET['time'])

        # Log user access to obstacle info
        logger.info('User downloaded obstacle info: %s.' %
                    request.user.username)
        if log_access:
            ObstacleAccessLog(user=request.user).save()

        # Get active mission for forming responses.
        (mission, err) = active_mission()
        if err:
            return err

        # Form JSON response portion for stationary obstacles
        stationary_obstacles_cached = True
        stationary_obstacles_key = '/StationaryObstacle/all'
        stationary_obstacles = cache.get(stationary_obstacles_key)
        if stationary_obstacles is None:
            stationary_obstacles = mission.stationary_obstacles.all()
            stationary_obstacles_cached = False
        stationary_obstacles_json = []
        for cur_obst in stationary_obstacles:
            # Add current obstacle
            cur_obst_json = cur_obst.json()
            stationary_obstacles_json.append(cur_obst_json)

        # Form JSON response portion for moving obstacles
        moving_obstacles_cached = True
        moving_obstacles_key = '/MovingObstacle/all'
        moving_obstacles = cache.get(moving_obstacles_key)
        if moving_obstacles is None:
            moving_obstacles = mission.moving_obstacles.all()
            moving_obstacles_cached = False
        moving_obstacles_json = []
        for cur_obst in moving_obstacles:
            # Add current obstacle
            cur_obst_json = cur_obst.json(time=time)
            moving_obstacles_json.append(cur_obst_json)

        # Form final JSON response
        data = {
            'stationary_obstacles': stationary_obstacles_json,
            'moving_obstacles': moving_obstacles_json
        }

        # Cache obstacles for next request
        if not stationary_obstacles_cached:
            cache.set(stationary_obstacles_key, stationary_obstacles)
        if not moving_obstacles_cached:
            cache.set(moving_obstacles_key, moving_obstacles)

        # Return JSON data
        return HttpResponse(json.dumps(data), content_type="application/json")