Exemple #1
0
def get_department_courses_endpoint(request, *args, **kwargs):
    """
    Returns all the courses in UCL with relevant ID
    """
    try:
        department_id = request.GET["department"]
    except KeyError:
        response = JsonResponse(
            {
                "ok": False,
                "error": "No department ID provided."
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    courses = {"ok": True, "courses": []}
    for course in Course.objects.filter(owner=department_id,
                                        setid=_SETID,
                                        linkcode="YY"):
        courses["courses"].append({
            "course_name": course.name,
            "course_id": course.courseid,
            "years": course.numyears
        })
    return JsonResponse(courses, custom_header_data=kwargs)
Exemple #2
0
def get_survey_sensors(request, *args, **kwargs):
    try:
        survey_id = request.GET["survey_id"]
    except KeyError:
        response = JsonResponse({
            "ok": False,
            "error": "Please specify a survey_id."
        })
        response.status_code = 400
        return response

    api = OccupEyeApi()
    try:
        data = api.get_survey_sensors(survey_id)
    except BadOccupEyeRequest:
        response = JsonResponse({
            "ok":
            False,
            "error":
            "The survey_id you specified was not valid."
        })
        response.status_code = 400
        return response

    response = JsonResponse({"ok": True, **data}, custom_header_data=kwargs)
    return response
Exemple #3
0
def get_survey_sensors(request, *args, **kwargs):
    try:
        survey_id = request.GET["survey_id"]
    except KeyError:
        response = JsonResponse({
            "ok": False,
            "error": "Please specify a survey_id."
        })
        response.status_code = 400
        return response

    # # Check if state data should be returned
    # try:
    #     return_states = request.GET["return_states"].lower() == "true"
    # except KeyError:
    #     return_states = False

    api = OccupEyeApi()
    try:
        data = api.get_survey_sensors(survey_id
                                      # return_states=return_states
                                      )
    except BadOccupEyeRequest:
        response = JsonResponse({
            "ok":
            False,
            "error":
            "The survey_id you specified was not valid."
        })
        response.status_code = 400
        return response

    response = JsonResponse({"ok": True, **data})
    return response
Exemple #4
0
def get_survey_max_timestamp(request, *args, **kwargs):
    try:
        survey_id = request.GET["survey_id"]
    except KeyError:
        response = JsonResponse({
            "ok": False,
            "error": "Please specify a survey_id."
        })
        response.status_code = 400
        return response

    api = OccupEyeApi()
    try:
        (survey_id_int,
         max_timestamp) = api.get_max_survey_timestamp(survey_id)
    except BadOccupEyeRequest:
        response = JsonResponse({
            "ok":
            False,
            "error":
            "The survey_id you specified was not valid."
        })
        response.status_code = 400
        return response

    response = JsonResponse(
        {
            "ok": True,
            "survey_id": survey_id_int,
            "last_updated": max_timestamp
        },
        custom_header_data=kwargs)

    return response
Exemple #5
0
def get_department_modules(request, *args, **kwargs):
    """
    Returns all modules taught by a particular department.
    """
    try:
        department_id = request.GET["department"]
    except KeyError:
        response = JsonResponse({
            "ok": False,
            "error": "Supply a Department ID using the department parameter."
        }, rate_limiting_data=kwargs)
        response.status_code = 400
        return response

    modules = {"ok": True, "modules": []}
    lock = Lock.objects.all()[0]
    m = ModuleA if lock.a else ModuleB
    for module in m.objects.filter(owner=department_id, setid=_SETID):
        modules["modules"].append({
            "module_id": module.moduleid,
            "name": module.name,
            "module_code": module.linkcode,
            "class_size": module.csize
        })

    return JsonResponse(modules, rate_limiting_data=kwargs)
Exemple #6
0
def get_modules_timetable_endpoint(request, *args, **kwargs):
    module_ids = request.GET.get("modules")
    if module_ids is None:
        return JsonResponse({
            "ok": False,
            "error": "No module IDs provided."
        },
                            custom_header_data=kwargs)

    try:
        modules = module_ids.split(',')
    except ValueError:
        return JsonResponse(
            {
                "ok": False,
                "error": "Invalid module IDs provided."
            },
            custom_header_data=kwargs)

    date_filter = request.GET.get("date_filter")
    custom_timetable = get_custom_timetable(modules, date_filter)

    if custom_timetable:
        response_json = {"ok": True, "timetable": custom_timetable}
        return JsonResponse(response_json, custom_header_data=kwargs)
    else:
        response_json = {
            "ok": False,
            "error": "One or more invalid Module IDs supplied."
        }
        response = JsonResponse(response_json, custom_header_data=kwargs)
        response.status_code = 400
        return response
Exemple #7
0
def get_map_image(request, *args, **kwargs):
    try:
        image_id = request.GET['image_id']
    except KeyError:
        response = JsonResponse({
            "ok": False,
            "error": "No Image ID provided."
        },
                                custom_header_data=kwargs)
        response.status_code = 400
        return response

    api = OccupEyeApi()

    try:
        (image_b64, content_type) = api.get_image(image_id)
    except BadOccupEyeRequest:
        response = JsonResponse(
            {
                "ok": False,
                "error": ("The image with the ID you requested "
                          "does not exist.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    image_format = request.GET.get("image_format", "base64")

    if image_format == "raw":
        return HttpResponse(content=b64decode(image_b64),
                            custom_header_data=kwargs,
                            content_type=content_type)
    elif image_format == "base64":
        response = JsonResponse(
            {
                "ok": True,
                "content_type": content_type,
                "data": image_b64
            },
            custom_header_data=kwargs)
        return response
    else:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("You specified a response format that "
                          "was not either raw or base64.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response
Exemple #8
0
def get_pc_availability(request, *args, **kwargs):
    try:
        r = requests.get(os.environ["PCA_LINK"])
    except requests.exceptions.MissingSchema:
        resp = JsonResponse(
            {
                "ok":
                False,
                "error": ("Could not retrieve availability data."
                          " Please try again later or contact us for support.")
            },
            rate_limiting_data=kwargs)
        resp.status_code = 400
        return resp

    try:
        e = etree.fromstring(r.content)
    except (ValueError, etree.XMLSyntaxError):
        resp = JsonResponse(
            {
                "ok":
                False,
                "error": ("Could not parse the desktop availability data."
                          " Please try again later or contact us for support.")
            },
            rate_limiting_data=kwargs)
        resp.status_code = 400
        return resp

    data = []
    for pc in e.findall("room"):
        _ = pc.get
        data.append({
            "location": {
                "roomname": _("location"),
                "room_id": _("rid"),
                "latitude": _("latitude"),
                "longitude": _("longitude"),
                "building_name": _("buildingName"),
                "address": _("buildingAddress"),
                "postcode": _("buildingPostcode")
            },
            "free_seats": _("free"),
            "total_seats": _("seats"),
            "room_status": _("info")
        })

    return JsonResponse({"ok": True, "data": data}, rate_limiting_data=kwargs)
Exemple #9
0
def people(request, *args, **kwargs):
    """
    Backend for the /search endpoint. Provided a query will search for people
    in the UCL database with an attribute such as name or e-mail that matches
    the search parameter.
    """
    if "query" not in request.GET:
        response = JsonResponse({
            "ok": False,
            "error": "No query provided."
        },
                                custom_header_data=kwargs)
        response.status_code = 400
        return response

    query = request.GET["query"]

    url = ("{}?{}={}".format(
        os.environ["SEARCH_API_URL"],
        os.environ["SEARCH_API_QUERY_PARAMS"],
        query,
    ))

    r = requests.get(url)

    results = r.json()["response"]["resultPacket"]["results"][:20]

    def serialize_person(person):
        return {
            "name": person["title"],
            "department": person["metaData"].get("7", ""),
            "email": person["metaData"].get("E", ""),
            "status": person["metaData"].get("g", ""),
        }

    people = [serialize_person(person) for person in results]

    return JsonResponse({
        "ok": True,
        "people": people
    },
                        custom_header_data=kwargs)
Exemple #10
0
def get_department_modules_endpoint(request, *args, **kwargs):
    """
    Returns all modules taught by a particular department.
    """
    try:
        department_id = request.GET["department"]
    except KeyError:
        response = JsonResponse(
            {
                "ok": False,
                "error":
                "Supply a Department ID using the department parameter."
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    modules = {"ok": True, "modules": get_departmental_modules(department_id)}

    return JsonResponse(modules, custom_header_data=kwargs)
Exemple #11
0
def get_departments(request, *args, **kwargs):
    """
    Returns all departments at UCL
    """
    depts = {"ok": True, "departments": []}
    for dept in Depts.objects.all():
        depts["departments"].append({
            "department_id": dept.deptid,
            "name": dept.name
        }, rate_limiting_data=kwargs)
    return JsonResponse(depts, rate_limiting_data=kwargs)
Exemple #12
0
def get_personal_timetable_endpoint(request, *args, **kwargs):
    token = kwargs['token']
    user = token.user
    try:
        date_filter = request.GET["date_filter"]
        timetable = get_student_timetable(user.employee_id, date_filter)
    except KeyError:
        timetable = get_student_timetable(user.employee_id)

    response = {"ok": True, "timetable": timetable}
    return JsonResponse(response, custom_header_data=kwargs)
Exemple #13
0
def get_surveys(request, *args, **kwargs):
    api = OccupEyeApi()
    consts = OccupEyeConstants()

    survey_filter = request.GET.get("survey_filter", "student")
    if survey_filter not in consts.VALID_SURVEY_FILTERS:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("The survey filter you provided is invalid. "
                          "Valid survey filters are: ") +
                str(consts.VALID_SURVEY_FILTERS)
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    response_data = {"ok": True, "surveys": api.get_surveys(survey_filter)}
    return JsonResponse(response_data, custom_header_data=kwargs)
Exemple #14
0
def get_survey_sensors_summary(request, *args, **kwargs):
    survey_ids = request.GET.get("survey_ids", None)

    survey_filter = request.GET.get("survey_filter", "student")
    consts = OccupEyeConstants()
    if survey_filter not in consts.VALID_SURVEY_FILTERS:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("The survey filter you provided is invalid. "
                          "Valid survey filters are: ") +
                str(consts.VALID_SURVEY_FILTERS)
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    api = OccupEyeApi()
    try:
        data = api.get_survey_sensors_summary(survey_ids, survey_filter)
    except BadOccupEyeRequest:
        response = JsonResponse(
            {
                "ok":
                False,
                "error":
                ("One or more of the survey_ids you requested is not valid.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    response = JsonResponse({
        "ok": True,
        "surveys": data
    },
                            custom_header_data=kwargs)

    return response
Exemple #15
0
def get_department_courses(request, *args, **kwargs):
    """
    Returns all the courses in UCL with relevant ID
    """
    try:
        department_id = request.GET["department"]
    except KeyError:
        response = JsonResponse({
            "ok": False,
            "error": "Supply a Department ID using the department parameter."
        }, rate_limiting_data=kwargs)
        response.status_code = 400
        return response

    courses = {"ok": True, "courses": []}
    for course in Course.objects.filter(owner=department_id, setid=_SETID):
        courses["courses"].append({
            "course_name": course.name,
            "course_id": course.courseid,
            "years": course.numyears
        })
    return JsonResponse(courses, rate_limiting_data=kwargs)
Exemple #16
0
def people(request, *args, **kwargs):
    if "query" not in request.GET:
        response = JsonResponse({
            "ok": False,
            "error": "No query provided."
        },
                                rate_limiting_data=kwargs)
        response.status_code = 400
        return response

    query = request.GET["query"]

    url = ("{}?{}={}".format(
        os.environ["SEARCH_API_URL"],
        os.environ["SEARCH_API_QUERY_PARAMS"],
        query,
    ))

    r = requests.get(url)

    results = r.json()["response"]["resultPacket"]["results"][:20]

    def serialize_person(person):
        return {
            "name": person["title"],
            "department": person["metaData"].get("7", ""),
            "email": person["metaData"].get("E", ""),
            "status": person["metaData"].get("g", ""),
        }

    people = [serialize_person(person) for person in results]

    return JsonResponse({
        "ok": True,
        "people": people
    },
                        rate_limiting_data=kwargs)
Exemple #17
0
def get_survey_sensors_summary(request, *args, **kwargs):
    survey_ids = request.GET.get("survey_ids", None)
    api = OccupEyeApi()
    try:
        data = api.get_survey_sensors_summary(survey_ids)
    except BadOccupEyeRequest:
        response = JsonResponse(
            {
                "ok":
                False,
                "error":
                ("One or more of the survey_ids you requested is not valid.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    response = JsonResponse({
        "ok": True,
        "surveys": data
    },
                            custom_header_data=kwargs)

    return response
Exemple #18
0
def get_course_modules_endpoint(request, *args, **kwargs):
    """
    Returns all modules taught on a particular course.
    """
    try:
        course_id = request.GET["course"]
    except KeyError:
        response = JsonResponse(
            {
                "ok": False,
                "error": "No course ID provided."
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    if not validate_amp_query_params(request.query_params):
        response = JsonResponse(
            {
                "ok": False,
                "error": "Given parameter is not of corrrect type"
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    if request.query_params.get('only_compulsory'):
        try:
            strtobool(request.query_params.get('only_compulsory'))
        except ValueError:
            response = JsonResponse(
                {
                    "ok": False,
                    "error": "Given parameter is not of correct type"
                },
                custom_header_data=kwargs)
            response.status_code = 400
            return response

    if request.query_params.get('only_available'):
        try:
            strtobool(request.query_params.get('only_available'))
        except ValueError:
            response = JsonResponse(
                {
                    "ok": False,
                    "error": "Given parameter is not of correct type"
                },
                custom_header_data=kwargs)
            response.status_code = 400
            return response

    if (request.query_params.get('only_available')
            and request.query_params.get('only_compulsory')):
        if (strtobool(request.query_params.get('only_available'))
                and strtobool(request.query_params.get('only_compulsory'))):
            response = JsonResponse(
                {
                    "ok":
                    False,
                    "error":
                    "only_available and only_compulsory"
                    " cannot both be true"
                },
                custom_header_data=kwargs)
            response.status_code = 400
            return response

    modules = {
        "ok": True,
        "modules": get_course_modules(course_id, request.query_params)
    }

    return JsonResponse(modules, custom_header_data=kwargs)
Exemple #19
0
def test_timetable_request(request, *args, **kwargs):
    return JsonResponse({"ok": True}, custom_header_data=kwargs)
Exemple #20
0
def test_timetable_request(request, *args, **kwargs):
    return JsonResponse({
        "ok": True
    }, rate_limiting_data=kwargs)
Exemple #21
0
def get_historical_time_data(request, *args, **kwargs):
    api = OccupEyeApi()
    consts = OccupEyeConstants()
    survey_ids = request.GET.get("survey_ids", None)
    try:
        day_count = request.GET["days"]
    except KeyError:
        response = JsonResponse(
            {
                "ok":
                False,
                "error":
                ("You did not specify how many days of historical data "
                 "should be returned. Valid options are: ") +
                str(consts.VALID_HISTORICAL_DATA_DAYS)
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    if not day_count.isdigit():
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("You did not specify an integer number of days of "
                          "historical days. Valid options are: ") +
                str(consts.VALID_HISTORICAL_DATA_DAYS)
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    day_count = int(day_count)

    if day_count not in consts.VALID_HISTORICAL_DATA_DAYS:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("You did not specify a valid number of days of "
                          "historical days. Valid options are: ") +
                str(consts.VALID_HISTORICAL_DATA_DAYS)
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    try:
        data = api.get_historical_time_usage_data(survey_ids, day_count)
    except BadOccupEyeRequest:
        response = JsonResponse(
            {
                "ok":
                False,
                "error":
                ("One or more of the survey_ids you requested is not valid.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    response = JsonResponse({
        "ok": True,
        "surveys": data
    },
                            custom_header_data=kwargs)

    return response
Exemple #22
0
def get_departments_endpoint(request, *args, **kwargs):
    """
    Returns all departments at UCL
    """
    departments = {"ok": True, "departments": get_departments()}
    return JsonResponse(departments, custom_header_data=kwargs)
Exemple #23
0
def get_surveys(request, *args, **kwargs):
    api = OccupEyeApi()
    response_data = {"ok": True, "surveys": api.get_surveys()}
    return JsonResponse(response_data, custom_header_data=kwargs)
Exemple #24
0
def get_live_map(request, *args, **kwargs):
    try:
        survey_id = request.GET["survey_id"]
        map_id = request.GET["map_id"]
    except KeyError:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("You must provide a Survey ID and a Map ID "
                          "to get a live sensor status image.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    # Thank you Stack Overflow
    # https://stackoverflow.com/a/1636354/5297057
    colour_pattern = re.compile("^#(?:[0-9a-fA-F]{3}){1,2}$")

    absent_colour = request.GET.get("absent_colour", "#ABE00C")

    occupied_colour = request.GET.get("occupied_colour", "#FFC90E")

    image_scale_str = request.GET.get("image_scale", "0.02")

    circle_radius_str = request.GET.get("circle_radius", "128")

    if not re.match(colour_pattern, absent_colour) or \
       not re.match(colour_pattern, occupied_colour):
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("The custom colours you specfied did not match "
                          "the format of HTML hex colours. Colours must "
                          "either be in the format #ABC or #ABCDEF.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    try:
        image_scale = float(image_scale_str)
    except ValueError:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("The scale you specified is not valid. It "
                          "must be a floating point number, such as 1 "
                          "or 0.02.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    try:
        circle_radius = float(circle_radius_str)
    except ValueError:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("The circle radiuus you specified is not valid. "
                          "It must be a floating point number, such as 128 or "
                          "100.5.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    try:
        ib = ImageBuilder(survey_id, map_id)
    except BadOccupEyeRequest:
        response = JsonResponse(
            {
                "ok":
                False,
                "error": ("Either the IDs you sent were not "
                          "integers, or they do not exist.")
            },
            custom_header_data=kwargs)
        response.status_code = 400
        return response

    ib.set_colours(absent=absent_colour, occupied=occupied_colour)
    ib.set_circle_radius(circle_radius=circle_radius)
    ib.set_image_scale(image_scale=image_scale)
    map_svg = ib.get_live_map()

    response = HttpResponse(map_svg,
                            content_type="image/svg+xml",
                            custom_header_data=kwargs)
    response["Content-Length"] = len(map_svg)

    return response