Skip to content

Commit

Permalink
Merge pull request #107 from pennlabs/wharton
Browse files Browse the repository at this point in the history
integrated wharton endpoint
  • Loading branch information
ezwang authored Feb 24, 2019
2 parents ce9e2be + 0d80b42 commit 9bfb967
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 4 deletions.
105 changes: 102 additions & 3 deletions penn/wharton.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import re
import requests
import datetime

from bs4 import BeautifulSoup
from .base import APIError


BASE_URL = "https://apps.wharton.upenn.edu/gsr"


Expand Down Expand Up @@ -46,8 +47,42 @@ def get_reservations(self, sessionid):
reservations.append(reservation)
return reservations

def book_reservation(self, sessionid, roomid, start, end):
""" Book a reservation given the session id, the room id as an integer, and the start and end time as datetimes. """
duration = int((end - start).seconds / 60)
booking_url = "{}/reserve/{}/{}/?d={}".format(BASE_URL, roomid, start.strftime("%Y-%m-%dT%H:%M:%S-05:00"), duration)
resp = requests.get(booking_url, cookies={"sessionid": sessionid})
resp.raise_for_status()

csrfheader = re.search(r"csrftoken=(.*?);", resp.headers["Set-Cookie"]).group(1)
csrftoken = re.search(r"<input name=\"csrfmiddlewaretoken\" type=\"hidden\" value=\"(.*?)\"/>", resp.content.decode("utf8")).group(1)

start_string = start.strftime("%I:%M %p")
if start_string[0] == "0":
start_string = start_string[1:]

resp = requests.post(
booking_url,
cookies={"sessionid": sessionid, "csrftoken": csrfheader},
headers={"Referer": booking_url},
data={
"csrfmiddlewaretoken": csrftoken,
"room": roomid,
"start_time": start_string,
"end_time": end.strftime("%a %b %d %H:%M:%S %Y"),
"date": start.strftime("%B %d, %Y")
}
)
resp.raise_for_status()
content = resp.content.decode("utf8")
if "errorlist" in content:
error_msg = re.search(r"class=\"errorlist\"><li>(.*?)</li>", content).group(1)
return {"success": False, "error": error_msg}

return {"success": True}

def delete_booking(self, sessionid, booking_id):
"""Deletes a Wharton GSR Booking for a given booking and session id"""
""" Deletes a Wharton GSR Booking for a given booking and session id. """
url = "{}{}{}/".format(BASE_URL, "/delete/", booking_id)
cookies = dict(sessionid=sessionid)

Expand Down Expand Up @@ -78,4 +113,68 @@ def delete_booking(self, sessionid, booking_id):
except resp2.exceptions.HTTPError as error:
raise APIError("Server Error: {}".format(error))

return "success"
return {"success": True}

def get_wharton_gsrs(self, sessionid, date):
""" Make a request to retrieve Wharton GSR listings. """
if date:
date += " 05:00"
else:
date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%S")
resp = requests.get('https://apps.wharton.upenn.edu/gsr/api/app/grid_view/', params={
'search_time': date
}, cookies={
'sessionid': sessionid
})
if resp.status_code == 200:
return resp.json()
else:
raise APIError('Remote server returned status code {}.'.format(resp.status_code))

def switch_format(self, gsr):
""" Convert the Wharton GSR format into the studyspaces API format. """
if "error" in gsr:
return gsr
rooms = {
"cid": 1,
"name": "Huntsman Hall",
"rooms": []
}

for time in gsr["times"]:
for entry in time:
entry["name"] = "GSR " + entry["room_number"]
del entry["room_number"]
start_time_str = entry["start_time"]
end_time = datetime.datetime.strptime(start_time_str[:-6], '%Y-%m-%dT%H:%M:%S') + datetime.timedelta(minutes=30)
end_time_str = end_time.strftime("%Y-%m-%dT%H:%M:%S") + "-05:00"
time = {
"available": not entry["reserved"],
"start": entry["start_time"],
"end": end_time_str,
}
exists = False
for room in rooms["rooms"]:
if room["name"] == entry["name"]:
room["times"].append(time)
exists = True
if not exists:
del entry["booked_by_user"]
del entry["building"]
if "reservation_id" in entry:
del entry["reservation_id"]
entry["lid"] = 1
entry["capacity"] = 5
entry["room_id"] = entry["id"]
del entry["id"]
entry["times"] = [time]
del entry["reserved"]
del entry["end_time"]
del entry["start_time"]
rooms["rooms"].append(entry)
return {"categories": [rooms]}

def get_wharton_gsrs_formatted(self, sessionid):
""" Return the wharton GSR listing formatted in studyspaces format. """
gsrs = self.get_wharton_gsrs(sessionid, None)
return self.switch_format(gsrs)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
url='https://github.com/pennlabs/penn-sdk-python',
author='Penn Labs',
author_email='[email protected]',
version='1.8',
version='1.8.1',
packages=['penn'],
license='MIT',
package_data={
Expand Down

0 comments on commit 9bfb967

Please sign in to comment.