Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
mycampusscript.py 2.50 KiB
import re
import sys
import typing as tg

import bs4
import yaml
import requests

import base as b


usage = """mycampusscript create_multigroup_assgmt config.yaml
  Creates an Sakai 'assignment' entry in a site with separate deadlines per section
"""
site_url_help = """site_url: URL of the MyCampus site's homepage"""
cookies_help = """cookies: a dictionary of cookie names to cookie values
  You need to obtain the following cookies: SAKAI2SESSIONID.  How to do that:
  Log into MyCampus, 
  visit the site where you want to create the multigroup assignment,
  open the developer tools in your browser (in Firefox: F12),
  open the 'network' tab in the developer tools,
  visit the assignment creation form ('Assignments' -> 'Add'),
  select the first requests in the network tab's request list,
  in the panel on the right, select 'Headers' -> 'Request Headers', turn on 'raw' view,
  copy the entire line that starts with "Cookie:" and paste into your config as the value
    for the 'cookies' config parameter; you must enclose it in double quotes.
"""

ASSIGNMENTS_CREATION_FORM_PATH = 'tool/1f8f054a-4e58-4965-8d32-141b236e0023?panel=Main'


StrAnyDict = dict[str, tg.Any]


def main(scriptname: str, cmdname: str, configfile: str):
    with open(configfile, 'rt') as f:
        config = yaml.load(f, Loader=yaml.Loader)
    site_url: str = find_value_or_help(config, 'site_url')
    parse_cookies(config)
    group_ids: str = find_value_or_help(config, 'group_ids')


def find_value_or_help(config: StrAnyDict, key: str) -> tg.Any:
    if key in config:
        return config[key]
    the_help = globals()[f"{key}_help"]
    if callable(the_help):
        !!!
        the_help = ...
    b.critical(the_help)


def parse_cookies(config: StrAnyDict):
    def perhaps_complain(mm):
        if not mm:
            b.critical("config param 'cookies' must have format 'Cookie: \"NAME1=value1; name2=value\"")

    cookiesheader_re = r"Cookie: (.+)"
    mm = re.fullmatch(cookiesheader_re, config['cookies'])
    perhaps_complain(mm)
    cookiepairs = mm.group(1).split("; ")
    result = dict()
    for pair in cookiepairs:
        mm = re.fullmatch(r"(.+?)=(.+)", pair)  # split at the first equals sign
        perhaps_complain(mm)
        result[mm.group(1)] = mm.group(2)
    print(result)
    config['cookies'] = result


if __name__ == '__main__':
    if len(sys.argv) != 2+1 or sys.argv[1] != 'create_multigroup_assgmt':
        print(usage)
    else:
        try:
            main(*sys.argv)
        except b.CritialError:
            pass  # just stop