Пример #1
0
def for_event(request, event_id):
	try:
		return_dict = {}
		queries_dict = {}
		
		event = Event.objects.get(id = event_id)
		queries = Query.objects.filter(event = event)
		
		return_dict['count'] = queries.count()
		return_dict['active_count'] = 0
		
		for query in queries:
			query_entry = {'query'      : query.query,
						   'step'       : query.step,
						   'operator'   : query.operator,
						   'created'    : query.created,
						   'active'     : query.active,
						   'logical_not': query.logical_not,}
			
			if query.active:
				return_dict['active_count'] += 1
			
			queries_dict[query.id] = query_entry
		
		return_dict['terms'] = queries_dict
		return generate_response(return_dict)
	except ObjectDoesNotExist:
		return generate_response({}, status = Status_Codes.NOT_FOUND)
Пример #2
0
def order(request, event_id):
	try:
		event = Event.objects.get(id = event_id)
		
		if request.GET.get('sequence') is None or request.GET.get('sequence') == '' or request.method != 'POST':
			return generate_response({}, status = Status_Codes.NOT_FOUND)
		
		try:
			sequence = list(map(int, request.GET.get('sequence').split(',')))
		except ValueError:
			return generate_response({}, status = Status_Codes.NOT_FOUND)
		
		count = 1
		
		# Loop through all the queries for the specified event, supplying each one with a new step value.
		for query_id in sequence:
			query = Query.objects.get(id = query_id)
			query.step = count
			query.save()
			
			count += 1
		
		return generate_response({'success': True, 'order': sequence})
	
	except ObjectDoesNotExist:
		return generate_response({}, status = Status_Codes.NOT_FOUND)
Пример #3
0
 def on_get(self, req: falcon.Request, rsp: falcon.Response):
     blueprint_id = req.get_param_as_int('id', required=True)
     rows = self.query(blueprint_id)
     if rows:
         result = {
             'blueprint': {
                 'typeID': rows[0][0],
                 'text': rows[0][1],
                 'maxProductionLimit': rows[0][2],
                 'duration': rows[0][3],
             },
             'product': {
                 'typeID': rows[0][4],
                 'text': rows[0][5],
                 'quantity': rows[0][6],
             },
             'materials': [],
         }
         for row in rows:
             result['materials'].append({
                 'typeID': row[7],
                 'text': row[8],
                 'quantity': row[9],
                 'blueprintID': -1 if row[10] is None else row[10],
                 'blueprintActivityID': -1 if row[11] is None else row[11],
             })
         response = generate_response()
         response['data'].update(result)
     else:
         response = generate_response(1, 'blueprint not found')
     rsp.body = json_encode(response)
Пример #4
0
 def on_get(self, req: falcon.Request, rsp: falcon.Response):
     q = req.get_param('q', required=True).strip()
     length = len(q)
     if length < 2 or length > 32:
         rsp.body = json_encode(generate_response(1, 'query too short'))
         return
     rows = search(q, 11)
     response = generate_response()
     response['data']['reaction'] = [{
         'typeID': row[0],
         'reactionText': row[2]
     } for row in rows]
     rsp.body = json_encode(response)
Пример #5
0
def not_found(request):
	
	info = {'error_code': 404,
			'info'      : 'The requested resource was not found.',
			'path'      : request.path,}
	
	return generate_response(info, status = Status_Codes.NOT_FOUND)
Пример #6
0
def server_error(request):
	
	info = {'error_code': 500,
			'info'      : 'An internal server error occured.',
			'path'      : request.path,}
	
	return generate_response(info, status = Status_Codes.SERVER_ERROR)
Пример #7
0
def single_query(request, event_id, query_id):
	try:
		event = Event.objects.get(id = event_id)
		query = Query.objects.get(id = query_id)
		
		if query.event != event:
			return generate_response({}, status = Status_Codes.NOT_FOUND)
		
		if request.GET.get('operator') is not None and request.method == 'POST':
			operator = request.GET.get('operator').upper()
			
			if operator == 'AND' or operator == 'OR':
				query.operator = operator
				query.save()
				
				return generate_response({'operator': query.operator.lower()})
			elif operator == 'NOT':
				if query.logical_not:
					query.logical_not = False
				else:
					query.logical_not = True
				
				query.save()
				return generate_response({'logical_not': query.logical_not})
			
			return generate_response({}, status = Status_Codes.NOT_FOUND)
		elif request.GET.get('active') is not None and request.method == 'POST':
			if query.active:
				query.active = False
			else:
				query.active = True
			
			query.save()
			
			active_queries = Query.objects.filter(active = True, event = event)
			return generate_response({'success': True, 'active': query.active, 'active_count': active_queries.count(),})
		elif request.GET.get('delete') is not None and request.method == 'DELETE':
			query.delete()
			
			queries = Query.objects.filter(event = event)
			active_queries = Query.objects.filter(event = event, active = True)
			return generate_response({'success': True, 'total_count': queries.count(), 'active_count': active_queries.count()})
		elif request.GET.get('text') is not None and request.method == 'POST':
			query.query = unquote(request.GET.get('text'))
			query.save()
			
			return generate_response({'success': True,})
		
		return generate_response({}, status = Status_Codes.NOT_FOUND)
	except ObjectDoesNotExist:
		return generate_response({}, status = Status_Codes.NOT_FOUND)
Пример #8
0
def add(request):
    if request.method == 'POST':
        try:
            # Attempt to read and convert the information from the request to the relevant type.
            # Fails if information is missing, or of the wrong type.
            name = request.GET.get('name')
            longitude = float(request.GET.get('longitude'))
            latitude = float(request.GET.get('latitude'))
            distance = int(request.GET.get('distance'))
        except TypeError:
            return generate_response({}, status=Status_Codes.BAD_REQUEST)
        except ValueError:
            return generate_response({}, status=Status_Codes.BAD_REQUEST)

        try:
            # Attempt to pick an event that has the same name.
            # Fails if no event exists.
            previous = Event.objects.get(name=name)
            return generate_response({}, status=Status_Codes.BAD_REQUEST)
        except ObjectDoesNotExist:
            # Clever! Use the catch to create a new event; we know that an event with
            # the same name doesn't already exist.
            new_event = Event(name=name,
                              longitude=longitude,
                              latitude=latitude,
                              distance=distance,
                              active=True,
                              created=datetime.datetime.now())

            new_event.save()

            # Spawn a new thread to create the geographical index for the new event.
            # Currently joins so it's pointles, but will be eventually taken out.
            index_thread = Thread(target=add_index, args=(new_event, ))
            index_thread.start()
            index_thread.join()

            return generate_response({
                'event_id': new_event.id,
                'tab_url': get_tab_name(new_event.name),
                'name': new_event.name,
                'active': new_event.active,
            })
    else:
        return generate_response({}, status=Status_Codes.NOT_FOUND)
Пример #9
0
def list_sources(request, event_id):
    try:
        event = Event.objects.get(id=event_id)
        sources = event.sources.filter(active=True)

        return_dict = {}

        for source in sources:
            temp = {
                'id': source.sys_name,
                'name': source.name,
            }

            return_dict[source.sys_name] = temp

        return generate_response(return_dict)
    except ObjectDoesNotExist:
        return generate_response({}, status=Status_Codes.NOT_FOUND)
Пример #10
0
def single(request, event_id):
    try:
        event = Event.objects.get(id=event_id)

        event_dict = {
            'id': event.id,
            'name': event.name,
            'active': event.active,
            'created': event.created,
            'latitude': event.latitude,
            'longitude': event.longitude,
            'distance': event.distance,
        }

        return generate_response({
            'event': event_dict,
        })
    except ObjectDoesNotExist:
        return generate_response({}, status=Status_Codes.NOT_FOUND)
Пример #11
0
def add(request, event_id):
	try:
		event = Event.objects.get(id = event_id)
		
		if request.GET.get('query') is None or request.GET.get('query') == '' or request.method != 'POST':
			return generate_response({}, status = Status_Codes.NOT_FOUND)
		
		existing = Query.objects.filter(event = event).order_by('-step')
		
		# Plonk the new query term in at the end of the sequence.
		# Work out the step value based on the step values we currently have.
		if existing.count() == 0:
			step = 1
		else:
			step = existing[0].step + 1
		
		query = Query(event   = event,
					  query   = unquote(request.GET.get('query')),
					  step    = step,
					  created = datetime.datetime.now(),
					  active  = True)
		
		# Save the new query to the model.
		query.save()
		
		# Return information on the newly created query back to the caller.
		# Can be used for validation.
		return_dict = {'id'         : query.id,
					   'event_id'   : query.event.id,
					   'query'      : query.query,
					   'operator'   : query.operator,
					   'step'       : query.step,
					   'created'    : query.created,
					   'active'     : query.active,
					   'logical_not': query.logical_not,}
		
		return generate_response(return_dict)
	# The event specified does not exist!
	except ObjectDoesNotExist:
		return generate_response({}, status = Status_Codes.NOT_FOUND)
Пример #12
0
def list_all(request):
    streams_dict = {}

    for source in Source.objects.all():
        source_dict = {
            'id': source.sys_name,
            'name': source.name,
            'active': source.active,
        }

        streams_dict[source.sys_name] = source_dict

    return generate_response(streams_dict)
Пример #13
0
def toggle_source(request, event_id, source):
    try:
        if request.method == 'POST':
            event = Event.objects.get(id=event_id)
            selected = Source.objects.get(sys_name=source)
            event_sources = event.sources.all()

            if selected in event_sources:
                event.sources.remove(selected)
                return generate_response({
                    'id': selected.sys_name,
                    'active': False,
                })
            else:
                event.sources.add(selected)
                return generate_response({
                    'id': selected.sys_name,
                    'active': True,
                })

        return generate_response({}, status=Status_Codes.FORBIDDEN)
    except ObjectDoesNotExist:
        return generate_response({}, status=Status_Codes.NOT_FOUND)
Пример #14
0
def toggle_active(request, event_id):

    if request.method == 'POST':
        try:
            event = Event.objects.get(id=event_id)

            if event.active:
                event.active = False
            else:
                event.active = True

            event.save()

            response = {
                'id': event.id,
                'active': event.active,
            }

            return generate_response(response)

        except ObjectDoesNotExist:
            return generate_response({}, status=Status_Codes.NOT_FOUND)

    return generate_response({}, status=Status_Codes.FORBIDDEN)
Пример #15
0
def list_all(request):
    events_dict = {}

    for event in Event.objects.all():
        event_dict = {
            'id': event.id,
            'name': event.name,
            'active': event.active,
            'created': event.created,
            'latitude': event.latitude,
            'longitude': event.longitude,
            'distance': event.distance,
        }

        events_dict[get_tab_name(event.name)] = event_dict

    return generate_response(events_dict)
Пример #16
0
def list(request, event_id, media = None):
	try:
		event = Event.objects.get(id = event_id)
		sources = event.sources.filter(active = True)
	except ObjectDoesNotExist:
		return generate_response({}, status = Status_Codes.NOT_FOUND)
	
	start = request.GET.get('start')
	end = request.GET.get('end')
	since = request.GET.get('since')
	limit = request.GET.get('limit')
	time_only = request.GET.get('time_only')
	query = request.GET.get('query')
	sentiment = request.GET.get('sentiment')
	
	new_since = get_utc(datetime.datetime.now())
	new_since = datetime.datetime(new_since.year, new_since.month, new_since.day, new_since.hour, new_since.minute, new_since.second)
	
	# Take each variable from the request and try to convert it to the appropriate type.
	# If we get a problem, we just set it to None to indicate that nothing has been supplied.
	
	if start:
		try:
			start = datetime.datetime.strptime(start, "%Y-%m-%dT%H:%M:%S")
		except ValueError:
			start = None
	
	if end:
		try:
			end = datetime.datetime.strptime(end, "%Y-%m-%dT%H:%M:%S")
		except ValueError:
			end = None
	
	if since:
		try:
			since = datetime.datetime.strptime(since, "%Y-%m-%dT%H:%M:%S")
		except ValueError:
			since = None
	
	if limit:
		try:
			limit = int(limit)
		except ValueError:
			limit = None
	
	if time_only:
		try:
			time_only = bool(time_only)
		except ValueError:
			time_only = False
	else:
		time_only = False
	
	if query:
		query = unquote(query.encode('UTF-8'))
	
	if sentiment:
		acceptable = ['positive', 'negative']
		
		if sentiment not in acceptable:
			sentiment = None
	
	# Get a handle on all the source indexes, then call get_stream to pull information out of the indexes.
	
	indexes = obtain_indexes(sources)
	stream = get_stream(indexes, event, start, end, since, limit, media, time_only, query, sentiment)
	
	# Reverse the stream to get the latest information first.
	stream.reverse()
	
	# Construct a dictionary to return to the caller, then append information related to the request
	# to the dictionary. Finally, send it off.
	return_dict = {'items'     : stream,
				   'since_time': new_since.replace(tzinfo = None),
				   'count'     : len(stream),}
	
	if query:
		return_dict['query'] = query
	
	if limit == None:
		return_dict['stream_limit'] = DEFAULT_LIMIT
	elif limit == 0:
		return_dict['stream_limit'] = 0
	else:
		return_dict['stream_limit'] = limit
	
	return generate_response(return_dict)