Skip to content
Snippets Groups Projects
Commit 34ce1757 authored by tuhe's avatar tuhe
Browse files

Initial commit refresh-token + put calendar event preliminary; api not stable

parent 46e8d5ad
No related branches found
No related tags found
No related merge requests found
File added
File added
import pickle
import diskcache
import requests
from diskcache import Cache
import os
"""
Links
API:
"""
def whoami(lc):
url = "https://testdtu.brightspace.com/d2l/api/lp/1.36/users/whoami"
payload = {}
headers = {
'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjRkZTk0ZWViLTU0NDctNDk4ZC1iMmNhLTU4NDg5MTU3OWI3YSIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE2NjUxNTc5MTYsImV4cCI6MTY2NTE2MTUxNiwiaXNzIjoiaHR0cHM6Ly9hcGkuYnJpZ2h0c3BhY2UuY29tL2F1dGgiLCJhdWQiOiJodHRwczovL2FwaS5icmlnaHRzcGFjZS5jb20vYXV0aC90b2tlbiIsInN1YiI6IjMzOTciLCJ0ZW5hbnRpZCI6ImVmYTdjODJhLWExYzItNGZjOC1hZTgyLTgwOGJhNzhjZDkxYyIsImF6cCI6IjQ4MDFhNDc3LTExYzctNGNmYy04NzMyLTczNmYwNDE1NzhiZSIsInNjb3BlIjoiY29yZToqOioiLCJqdGkiOiJjNGVhOTRhZi0xODdmLTQ3MzEtOGZmMy1lM2RkOWJhN2ZlMTIifQ.ngh5rHtFro4DWf6mcYSPoRV4LyadE7QJfNeeLRbosrPC2rwrW-00kX1oHqnrFLnWeIw9wNpeXfwM8UwYUxWvmwPcSGS6TI8d7I5gAb3Lqq6PEGHUfvho577scU2s_Lubi0RG_VTfaoNxggzFbvDlCzJom9EXWwbxGuLGk49OxtLile1_bX0kit8zOJhFoOGPjiO-GSvH5Qi4tvjYoowrBkTIyYD6Jw81ET_q2uTHaB15kWpMTl2uHeED-aRWivtX_rfTnFq3Wed3SmAPdS5Tb9g46hURKwq11O_ubGjqFbtQCsY9bIJpH5GShUURoQvWsTlqSqEyr7zgzc0wlMXwVQ'
}
headers = lc.headers
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
return response
pass
class LearnConfig:
server = "testdtu.brightspace.com/"
lp_version = "1.36"
headers = {
'Authorization': 'Bearer bla-bla'
}
def get_header(self):
headers = {
# cc = Cache(directory="cache")
'Authorization': f"Bearer {self.cc['access_token']}"
}
return headers
def isodate(self, date):
d = date.isoformat()
return d.split(".")[0] + ".000Z"
orgunitId = "8407"
def is_token_valid(self):
response = whoami(self)
json = response.json()
if "FirstName" in json:
print("Hello there", json['FirstName'])
return True
print("Authentication failed")
print(json)
return False
def __init__(self):
cc = Cache(directory= os.path.join( os.path.dirname(__file__), "cache") )
self.cc = cc
while True:
if "access_token" in cc:
print("is there")
# Try to connect...
self.token = cc.get("access_token")
self.headers['Authorization'] = f"Bearer {self.token}"
if self.is_token_valid():
print("Got a new token!")
a = 234
break
else:
del cc['access_token']
print("The token sucks.")
continue
else:
if "refresh_token" in cc:
url = "https://auth.brightspace.com/core/connect/token"
refresh_token = cc['refresh_token']
# refresh_token = "rt.eu-west-1.SAmtMKD3oe094NV6Yc4F8UuROyRdHMJRz_XwpiYtwfI"
self.client_id = "4801a477-11c7-4cfc-8732-736f041578be"
self.client_secret = "niLXYwe9f_pQe2RzvZ8LtYE6Ls6DSiZ_0IeTCPhx4_8"
payload=f'grant_type=refresh_token&refresh_token={refresh_token}&client_id={self.client_id}&client_secret={self.client_secret}&scope=core%3A*%3A*'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
cc['refresh_token'] = response.json()['refresh_token']
cc['access_token'] = response.json()['access_token']
print("Authentication success.")
break
# url = "https://auth.brightspace.com/core/connect/token"
#
# payload = 'grant_type=refresh_token&refresh_token=rt.eu-west-1.QLXytJ-TREfofv9xzbDcBEiEivw-_rogaSmS8XetScg&client_id=4801a477-11c7-4cfc-8732-736f041578be&client_secret=niLXYwe9f_pQe2RzvZ8LtYE6Ls6DSiZ_0IeTCPhx4_8&scope=core%3A*%3A*'
# headers = {
# 'Content-Type': 'application/x-www-form-urlencoded'
# }
#
# response = requests.request("POST", url, headers=headers, data=payload)
#
# print(response.text)
#
#
# print(response.text)
else:
s = input("Please give me a refresh token")
cc['refresh_token'] = s
print("Saved refresh token", s)
print("no it is not there")
a = 234
print("Phew! Authentication completed.")
# load refresh token file.
# test if login possible with current token.
# pkl.get
# rt.eu-west-1.tN5byZD8n0KHSowkDC2NnElZx0J0BJgIz57Fmj-ZhKs
pass
if __name__ == '__main__':
print("Hello world")
c = LearnConfig()
import datetime
import json
import requests
from learn_config import LearnConfig
def get_calendar_events(lc):
""" https://{{server}}d2l/api/le/{{lp_version}}/{{orgunitId}}/calendar/events/ """
# def whoami(lc):
url = f"https://{lc.server}d2l/api/le/{lc.lp_version}/{lc.orgunitId}/calendar/events/"
payload = {}
# headers = {
# 'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjRkZTk0ZWViLTU0NDctNDk4ZC1iMmNhLTU4NDg5MTU3OWI3YSIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE2NjUxNTc5MTYsImV4cCI6MTY2NTE2MTUxNiwiaXNzIjoiaHR0cHM6Ly9hcGkuYnJpZ2h0c3BhY2UuY29tL2F1dGgiLCJhdWQiOiJodHRwczovL2FwaS5icmlnaHRzcGFjZS5jb20vYXV0aC90b2tlbiIsInN1YiI6IjMzOTciLCJ0ZW5hbnRpZCI6ImVmYTdjODJhLWExYzItNGZjOC1hZTgyLTgwOGJhNzhjZDkxYyIsImF6cCI6IjQ4MDFhNDc3LTExYzctNGNmYy04NzMyLTczNmYwNDE1NzhiZSIsInNjb3BlIjoiY29yZToqOioiLCJqdGkiOiJjNGVhOTRhZi0xODdmLTQ3MzEtOGZmMy1lM2RkOWJhN2ZlMTIifQ.ngh5rHtFro4DWf6mcYSPoRV4LyadE7QJfNeeLRbosrPC2rwrW-00kX1oHqnrFLnWeIw9wNpeXfwM8UwYUxWvmwPcSGS6TI8d7I5gAb3Lqq6PEGHUfvho577scU2s_Lubi0RG_VTfaoNxggzFbvDlCzJom9EXWwbxGuLGk49OxtLile1_bX0kit8zOJhFoOGPjiO-GSvH5Qi4tvjYoowrBkTIyYD6Jw81ET_q2uTHaB15kWpMTl2uHeED-aRWivtX_rfTnFq3Wed3SmAPdS5Tb9g46hURKwq11O_ubGjqFbtQCsY9bIJpH5GShUURoQvWsTlqSqEyr7zgzc0wlMXwVQ'
# }
# headers = lc.headers
response = requests.request("GET", url, headers=lc.headers, data=payload)
print(response.text)
return response
pass
def put_calendar_event(lc, start_date, end_date, title="Lecture", description="Do some stuff today", location_name="Auditorim 666"):
"""
[{'CalendarEventId': 131048,
'OrgUnitId': 8407,
'CreatorUserId': 3397,
'Title': 'This even is a lecture! feel free to drop dead. ',
'Description': 'Oy veh.',
'CalendarEventViewUrl': 'https://testdtu.brightspace.com/d2l/le/calendar/8407/event/146759/detailsview',
'IsAllDayEvent': False,
'GroupId': None,
'StartDateTime': '2022-10-26T23:00:00.000Z',
'EndDateTime': '2022-10-27T01:00:00.000Z',
'IsRecurring': False,
'RecurrenceInfo': None,
'StartDay': None,
'EndDay': None,
'LocationId': None,
'LocationName': 'Auditorium',
'OrgUnitName': 'Tue Herlau- Sandbox',
'OrgUnitCode': 'OFFERING-SANDBOX-92378',
'IsAssociatedWithEntity': False,
'AssociatedEntity': None,
'HasVisibilityRestrictions': False,
'VisibilityRestrictions': {'Type': 1,
'Range': None,
'HiddenRangeUnitType': None,
'StartDate': None,
'EndDate': None},
'Presenters': []}]
"""
url = f"https://testdtu.brightspace.com/d2l/api/le/{lc.lp_version}/{lc.orgunitId}/calendar/event/"
payload = json.dumps({
"Title": title, # "Today's Special 666b",
"Description": description, # "<p>Soup <b>is relly good</p><p>and also healthy</p>",
"StartDateTime": lc.isodate(start_date), # "2019-05-02T20:00:00.000Z",
"EndDateTime": lc.isodate(end_date), # "2019-05-02T20:30:00.000Z",
"StartDay": None,
"EndDay": None,
"GroupId": None,
"RecurrenceInfo": None,
"LocationId": None,
"LocationName": location_name,
"AssociatedEntity": None,
"VisibilityRestrictions": {
"Type": 1,
"Range": None,
"HiddenRangeUnitType": None,
"StartDate": None,
"EndDate": None
}
})
headers = lc.get_header()
headers['Content-Type'] = 'application/json'
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
if __name__ == '__main__':
lc = LearnConfig()
get_calendar_events(lc)
from datetime import datetime, timedelta
put_calendar_event(lc, start_date=datetime.now(), end_date=datetime.now() + timedelta(hours=2), title="Do stuff for lecture 4", description="<p><b>MORE</b></p>", location_name="Room 022")
# Cartoon elk: https://community.desire2learn.com/d2l/home/14841
"""
I will just copy the required information in again:
Client ID
4801a477-11c7-4cfc-8732-736f041578be
Client Secret
niLXYwe9f_pQe2RzvZ8LtYE6Ls6DSiZ_0IeTCPhx4_8
Description
Redirect URI
https://localhost:3434/redirecturi
Access Token Lifetime (seconds)
3600
Scope
core:*:*
ACCESS CODE (learn)
tuhe / G(..)(!60 optional).
"""
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment