Beispiel #1
0
def fetch_location(user, device_type=None):
    import requests
    import datetime
    import pytz

    token = get_token(user)
    print(token)
    data = {'output': []}
    data['output'].append(token)

    eastern = pytz.timezone('US/Eastern')
    data['token'] = token
    data['test_fetch'] = True
    url = "https://campus.cornelltech.io/api/location/mostrecent/"
    payload = {'device_type': device_type}
    headers = {'Authorization': "Bearer " + token}
    res = requests.get(url, headers=headers, params=payload)
    if res.status_code == 200:
        data['location'] = res.json()
        ts = datetime.datetime.fromtimestamp(data['location']['timestamp'],
                                             tz=pytz.utc)
        loc_dt = ts.astimezone(eastern)
        data['location']['timestamp'] = loc_dt.strftime("%c")
    else:
        raise AncileException("Couldn't fetch location from the server.")

    return data
Beispiel #2
0
def rdl_fetch(user=None,
              url='https://localhost:9980',
              api_to_fetch=None,
              username=None,
              **kwargs):
    """
    Fetches Web Search Data From RDL
    :param username:
    :param user:
    :param url:
    :param kwargs:
    :param api_to_fetch
    :return:
    """
    data = {'output': []}
    token = get_token(user)
    params = {'username': username}
    r = requests.get(f'{url}/test/api/{api_to_fetch}',
                     headers={'Authorization': f'Bearer {token}'},
                     params=params)

    if r.status_code == 200:
        data.update(r.json())
    else:
        raise AncileException(f"Request error: {r.json()}")
    return data
Beispiel #3
0
def get_available_rooms(floor, user):
    import requests

    data = {'output': []}
    token = get_token(user)

    headers = {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
    }

    url = "https://graph.microsoft.com/beta/me/findMeetingTimes"
    start, end = get_start_end_time()
    js = get_available_by_floor(floor, start, end)
    print(headers)
    result = requests.post(url=url, headers=headers, json=js)
    available_rooms = list()
    if result.status_code != 200:
        data['output'].append(result.text)
    else:
        msft_resp = result.json()
        for x in msft_resp['meetingTimeSuggestions'][0][
                "attendeeAvailability"]:
            if x["availability"] == "free":
                available_rooms.append(
                    room_by_email(x["attendee"]['emailAddress']['address']))
    data['rooms'] = available_rooms

    return data
Beispiel #4
0
def book_room(room, user):
    import requests
    import json

    data = {'output': []}
    token = get_token(user)

    headers = {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
    }

    url = "https://graph.microsoft.com/beta/me/calendar/events"
    start, end = get_start_end_time()
    room_full = get_room_by_no(room)

    book_json = create_booking_json(user="******",
                                    room=room_full,
                                    time_start=start.isoformat(),
                                    time_end=end.isoformat())
    print(json.dumps(book_json, indent=4))
    print(headers)
    result = requests.post(url=url, headers=headers, json=book_json)
    if result.status_code != 200:
        data['output'].append(result.text)
        return True

    data['booking_result'] = 'success'
    return data
Beispiel #5
0
def get_primary_calendar_metadata(user=None, **kwargs):
    """
    Retrieve primary calendar metadata as an Ancile function.

    :param user: A UserSpecific data object.
    :return: Primary calendar metadata dictionary.
    """
    data = {'output': []}
    token = get_token(user)

    data['calendar'] = _get_primary_metadata(token)
    return data
Beispiel #6
0
def get_last_location(user):
    """
    Make a request to the last location API with the user's access token.

    :param user: A UserSpecific data structure
    :return: The last location information given by the server.
    """
    token = get_token(user)
    data = {'output': []}
    r = requests.get('https://campusdataservices.cs.vassar.edu/api/last_known',
                     headers={'Authorization': f'Bearer {token}'})
    if r.status_code == 200:
        data.update(r.json())
    else:
        raise AncileException(f"Request error: {r.json()}")

    return data
Beispiel #7
0
def get_calendar_events_in_relative_window(user=None,
                                           min_time=0,
                                           max_time=1,
                                           **kwargs):
    """
    Retrieve Google calendar events for the primary calendar that are occurring
    within min_time minutes before now and max_time minutes after now.

    :param user: A UserSpecific data structure.
    :param min_time: The lower bound of the event window, given in minutes
                     before the current moment.
    :param max_time: The upper bound of the event window, given in minutes
                     after the current moment.
    :return: ['events']. Data for all events occurring in the window
                         (now - min, now + max) listed in the user's primary
                         google calendar.
    """
    from datetime import datetime, timedelta, timezone
    import requests

    data = {'output': []}
    token = get_token(user)

    def format_time(unformatted):
        return unformatted.isoformat()

    cal_id = _get_primary_metadata(token)['id']

    now = datetime.now(timezone.utc).astimezone()
    lower = format_time(now - timedelta(minutes=min_time))
    upper = format_time(now + timedelta(minutes=max_time))

    target_url = "https://www.googleapis.com/calendar/v3/calendars/" + \
                 cal_id + "/events?singleEvents=true&timeMin=" + \
                 lower + "&timeMax=" + upper

    r = requests.get(target_url, headers={'Authorization': "Bearer " + token})

    if r.status_code != 200:
        raise AncileException("Request Error")

    data['events'] = r.json()['items']
    return data