Skip to content
Snippets Groups Projects
Commit c041eb43 authored by magnus2142's avatar magnus2142
Browse files

Merge branch 'main' into magnus_feature_module-skeleton

parents 5657149f d61c36d1
No related branches found
No related tags found
No related merge requests found
...@@ -34,3 +34,7 @@ to run the tests: ...@@ -34,3 +34,7 @@ to run the tests:
### 5. Run the tests ### 5. Run the tests
`python -m pytest test` `python -m pytest test`
### 6. Setup the bbcli script inside the root of the project
`pip install --editable .` **OR** `pip3 install --editable .`
from .AuthorizationService import *
\ No newline at end of file
from datetime import datetime
def check_valid_key(obj, key) -> bool:
# print("the keys are", obj.keys())
if key not in obj.keys():
print(f'The key: \"{key}\" is not in the object')
return False
else:
return True
def check_response(response) -> bool:
invalid_statuscodes = [401, 403, 404]
if response.status_code in invalid_statuscodes:
print(response.json()['status'])
print(response.json()['message'])
return False
else:
return True
def check_valid_date(cookies) -> bool:
tmp = cookies['BbRouter']
start = int(tmp.find('expires')) + len('expires') + 1
end = int(tmp.find(','))
timestmp = int(tmp[start : end])
print(timestmp)
expires = datetime.fromtimestamp(timestmp)
now = datetime.now()
if expires >= now:
return True
else:
return False
...@@ -5,6 +5,9 @@ __app_name__ = "bbcli" ...@@ -5,6 +5,9 @@ __app_name__ = "bbcli"
__version__ = "0.1.0" __version__ = "0.1.0"
# from .endpoints import * # from .endpoints import *
from .Node import * from .Node import *
from .Utils.utils import *
from .Services import login
# from endpoints import get_user, get_course, get_assignments, get_course_contents
( (
SUCCESS, SUCCESS,
......
"""RP To-Do entry point script.""" from bbcli import __app_name__
# rptodo/__main__.py from .cli import entry_point
from bbcli import cli, __app_name__
def main(): def main():
cli.app(prog_name=__app_name__) entry_point()
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
from typing import Optional from typing import Optional
import typer from pkg_resources import EntryPoint
from bbcli import __app_name__, __version__, endpoints # import typer
from bbcli import __app_name__, __version__
from bbcli.endpoints import get_user, get_course, get_course_contents, get_assignments
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from datetime import datetime from bbcli import check_valid_date
import click
from bbcli.Services import AuthorizationService from bbcli.Services import AuthorizationService
app = typer.Typer() @click.group()
app.add_typer(endpoints.app, name='endpoints', help='Call the endpoints') def entry_point():
authorize_user()
pass
entry_point.add_command(get_user)
entry_point.add_command(get_course)
entry_point.add_command(get_course_contents)
entry_point.add_command(get_assignments)
# app = typer.Typer()
# app.add_typer(endpoints.app, name='endpoints', help='Call the endpoints')
load_dotenv() load_dotenv()
cookies = {'BbRouter' : os.getenv("BB_ROUTER")} cookies = {'BbRouter' : os.getenv("BB_ROUTER")}
headers = {'X-Blackboard-XSRF': os.getenv('XSRF')} headers = {'X-Blackboard-XSRF': os.getenv('XSRF')}
def check_valid_date() -> bool: # def _version_callback(value: bool) -> None:
tmp = cookies['BbRouter'] # if value:
start = int(tmp.find('expires')) + len('expires') + 1 # typer.echo(f'{__app_name__} v{__version__}')
end = int(tmp.find(',')) # raise typer.Exit()
timestmp = int(tmp[start : end])
print(timestmp) # @app.callback()
expires = datetime.fromtimestamp(timestmp) # def main(
now = datetime.now() # version: Optional[bool] = typer.Option(
if expires >= now: # None,
return True # '--version',
else: # '-v',
return False # help='Show the applications version and exit.',
# callback=_version_callback,
def _version_callback(value: bool) -> None: # is_eager=True,
if value: # )
typer.echo(f'{__app_name__} v{__version__}') # ) -> None:
raise typer.Exit() # if check_valid_date(cookies) == False:
# AuthorizationService.login()
@app.callback() # # load_dotenv()
def main( # # cookies['BbRouter'] = os.getenv("BB_ROUTER")
version: Optional[bool] = typer.Option( # # headers['X-Blackboard-XSRF'] = os.getenv("XSRF")
None, # return
'--version',
'-v',
help='Show the applications version and exit.',
callback=_version_callback,
is_eager=True,
)
) -> None:
if check_valid_date() == False:
AuthorizationService.login()
# load_dotenv()
# cookies['BbRouter'] = os.getenv("BB_ROUTER")
# headers['X-Blackboard-XSRF'] = os.getenv("XSRF")
return
#----- AUTHORIZATION MODULE -----# #----- AUTHORIZATION MODULE -----#
@app.command(name='login', help='Authorize the user.') # @app.command(name='login', help='Authorize the user.')
def authorize_user(): def authorize_user():
AuthorizationService.login() if check_valid_date(cookies) == False:
AuthorizationService.login()
#----- COURSE MODULE -----# #----- COURSE MODULE -----#
@app.command(name='course') # @app.command(name='course')
def course( # def course(
course_id: Optional[str] = typer.Argument(None, help='The id of the course you want.'), # course_id: Optional[str] = typer.Argument(None, help='The id of the course you want.'),
favorites: bool = typer.Option(False, help='List only your favorite courses.')): # favorites: bool = typer.Option(False, help='List only your favorite courses.')):
if course_id != None and favorites == False: # if course_id != None and favorites == False:
# CODE FOR GETTING SPESIFIC COURSE # # CODE FOR GETTING SPESIFIC COURSE
print('getting spesific course...') # print('getting spesific course...')
elif course_id != None and favorites == True: # elif course_id != None and favorites == True:
# CODE FOR GETTING SPESIFIC FAVORITE COURSE # # CODE FOR GETTING SPESIFIC FAVORITE COURSE
print('getting spesific favorite course...') # print('getting spesific favorite course...')
else: # else:
# CODE FOR GETTING ALL COURSES # # CODE FOR GETTING ALL COURSES
print('getting all courses...') # print('getting all courses...')
\ No newline at end of file \ No newline at end of file
...@@ -2,87 +2,92 @@ import requests ...@@ -2,87 +2,92 @@ import requests
#from requests.auth import HTTPBasicAuth #from requests.auth import HTTPBasicAuth
# import json # import json
# import pprint # import pprint
import typer
import bbcli.cli as cli import bbcli.cli as cli
#from string_builder import StringBuilder #from string_builder import StringBuilder
import click import click
from typing import Optional # from typing import Optional
from dotenv import load_dotenv # from dotenv import load_dotenv
# from anytree import Node, RenderTree # from anytree import Node, RenderTree
import os import os
app = typer.Typer() from bbcli import check_response
base_url = 'https://ntnu.blackboard.com/learn/api/public/v1/' base_url = 'https://ntnu.blackboard.com/learn/api/public/v1/'
@app.command(name='get-user') @click.command(name='get-user')
def get_user(user_name: str = typer.Argument('', help='Name of the user'))-> None: @click.argument('user_name', default='')
def get_user(user_name: str):
''' '''
Get the user Get the user
Specify the user_name as an option, or else it will use the default user_name Specify the user_name as an option, or else it will use the default user_name
''' '''
if user_name == '': if user_name == '':
user_name = typer.prompt("What is your user name?") user_name = click.prompt("What is your user name?")
url = f'{base_url}users?userName={user_name}' url = f'{base_url}users?userName={user_name}'
x = requests.get( response = requests.get(
url, url,
cookies=cli.cookies cookies=cli.cookies
) )
if check_response(response) == False:
return
else:
data = response.json()['results'][0]
fn = data['name']['given']
sn = data['name']['family']
id = data['studentId']
data = x.json()['results'][0] click.echo(f'Name of the student: {fn} {sn}')
fn = data['name']['given'] click.echo(f'The student id: {id}')
sn = data['name']['family']
id = data['studentId']
typer.echo(f'Name of the student: {fn} {sn}')
typer.echo(f'The student id: {id}')
@app.command(name='get-course') @click.command(name='get-course')
def get_course(course_id: str = typer.Argument('', help='Id of the course')): @click.argument('course_id', default='IDATT2900')
def get_course(course_id: str):
''' '''
Get the course Get the course
''' '''
if course_id == '': if course_id == '':
course_id = typer.prompt("What is the course id?") course_id = click.prompt("What is the course id?")
url = f'{base_url}courses?courseId={course_id}' url = f'{base_url}courses?courseId={course_id}'
x = requests.get( response = requests.get(
url, url,
cookies=cli.cookies) cookies=cli.cookies)
data = x.json()['results'][0] if check_response(response) == False:
name = data['name'] return
course_url = data['externalAccessUrl'] else:
typer.echo(name) data = response.json()['results'][0]
typer.echo(f'URL for the course: {course_url}') name = data['name']
course_url = data['externalAccessUrl']
@app.command(name='get-course-contents') click.echo(name)
def get_course_contents(course_id: str = '_27251_1'): click.echo(f'URL for the course: {course_url}')
@click.command(name='get-course-contents')
@click.argument('course_id', default='_27251_1')
def get_course_contents(course_id: str):
''' '''
Get the course contents Get the course contents
''' '''
url = f'{base_url}courses/{course_id}/contents' url = f'{base_url}courses/{course_id}/contents'
typer.echo(url) click.echo(url)
x = requests.get(url, cookies=cli.cookies) response = requests.get(url, cookies=cli.cookies)
data = x.json()['results'] if check_response(response) == False:
typer.echo('Mapper:') return
map = dict() else:
for i in range(len(data)): data = response.json()['results']
title = data[i]['title'] click.echo('Mapper:')
map[i+1] = data[i]['id'] map = dict()
typer.echo(f'{i+1} {title}') for i in range(len(data)):
# idx = typer.prompt("Open a folder by pressing a number: ") title = data[i]['title']
typer.echo(map) map[i+1] = data[i]['id']
# for d in data: click.echo(f'{i+1} {title}')
# typer.echo(d['title']) click.echo(map)
def get_children(worklist, url, acc, count: int = 0): def get_children(worklist, url, acc, count: int = 0):
count = count + 1 count = count + 1
typer.echo(f'kommer hit: {count}') click.echo(f'kommer hit: {count}')
# print("The acc is: ", acc)
key = 'hasChildren' key = 'hasChildren'
if len(worklist) == 0: if len(worklist) == 0:
return acc return acc
...@@ -90,11 +95,8 @@ def get_children(worklist, url, acc, count: int = 0): ...@@ -90,11 +95,8 @@ def get_children(worklist, url, acc, count: int = 0):
data = worklist.pop() data = worklist.pop()
id = data['id'] id = data['id']
old = f'{url}/{id}/children' old = f'{url}/{id}/children'
# typer.echo(url)
response = requests.get(old, cookies = cli.cookies) response = requests.get(old, cookies = cli.cookies)
if response.status_code == 403 or response.status_code == 404: if check_response(response) == False:
typer.echo(response.json()['status'])
typer.echo(response.json()['message'])
return acc return acc
else: else:
child = response.json()['results'] child = response.json()['results']
...@@ -103,26 +105,29 @@ def get_children(worklist, url, acc, count: int = 0): ...@@ -103,26 +105,29 @@ def get_children(worklist, url, acc, count: int = 0):
worklist.append(child[i]) worklist.append(child[i])
else: else:
acc.append(child[i]) acc.append(child[i])
# parent = worklist.pop()
return get_children(worklist, url, acc, count) return get_children(worklist, url, acc, count)
@app.command(name='get-assignments') @click.command(name='get-assignments')
def get_assignments(course_id: str = typer.Argument('_27251_1', help='The course id')): @click.argument('course_id', default='_27251_1')
def get_assignments(course_id: str):
''' '''
Get the assignments Get the assignments
''' '''
url = f'{base_url}courses/{course_id}/contents' url = f'{base_url}courses/{course_id}/contents'
x = requests.get(url, cookies=cli.cookies) response = requests.get(url, cookies=cli.cookies)
data = x.json()['results'] if check_response(response) == False:
root = data[8] return
# root = Node(data[8]) else:
worklist = [root] data = response.json()['results']
res = get_children(worklist, url, []) root = data[8]
# root = Node(data[8])
for i in res: worklist = [root]
print(i['title']) res = get_children(worklist, url, [])
for i in res:
print(i['title'])
......
setup.py 0 → 100644
from setuptools import setup
setup(
name='cli',
# version='0.1.0',
# py_modules=['yourscript'],
install_requires=[
'Click',
],
entry_points={
'console_scripts': [
'bb=bbcli.__main__:main', # the cli() function runs inside the bbcli.py. cli is the command that is used to run the command
],
},
)
\ No newline at end of file
home = /usr/bin home = /Library/Frameworks/Python.framework/Versions/3.9/bin
include-system-site-packages = false include-system-site-packages = false
version = 3.8.10 version = 3.9.10
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