INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Returns True if students can unregister from course
|
def allow_unregister(self, plugin_override=True):
""" Returns True if students can unregister from course """
vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister)
return vals[0] if len(vals) and plugin_override else self._allow_unregister
|
Return the name of this course
|
def get_name(self, language):
""" Return the name of this course """
return self.gettext(language, self._name) if self._name else ""
|
Returns the course description
|
def get_description(self, language):
"""Returns the course description """
description = self.gettext(language, self._description) if self._description else ''
return ParsableText(description, "rst", self._translations.get(language, gettext.NullTranslations()))
|
Return a tuple of lists ([common_tags], [anti_tags], [organisational_tags]) all tags of all tasks of this course
Since this is an heavy procedure, we use a cache to cache results. Cache should be updated when a task is modified.
|
def get_all_tags(self):
"""
Return a tuple of lists ([common_tags], [anti_tags], [organisational_tags]) all tags of all tasks of this course
Since this is an heavy procedure, we use a cache to cache results. Cache should be updated when a task is modified.
"""
if self._all_tags_cache != None:
return self._all_tags_cache
tag_list_common = set()
tag_list_misconception = set()
tag_list_org = set()
tasks = self.get_tasks()
for id, task in tasks.items():
for tag in task.get_tags()[0]:
tag_list_common.add(tag)
for tag in task.get_tags()[1]:
tag_list_misconception.add(tag)
for tag in task.get_tags()[2]:
tag_list_org.add(tag)
tag_list_common = natsorted(tag_list_common, key=lambda y: y.get_name().lower())
tag_list_misconception = natsorted(tag_list_misconception, key=lambda y: y.get_name().lower())
tag_list_org = natsorted(tag_list_org, key=lambda y: y.get_name().lower())
self._all_tags_cache = (list(tag_list_common), list(tag_list_misconception), list(tag_list_org))
return self._all_tags_cache
|
Computes and cache two list containing all tags name sorted by natural order on name
|
def get_all_tags_names_as_list(self, admin=False, language="en"):
""" Computes and cache two list containing all tags name sorted by natural order on name """
if admin:
if self._all_tags_cache_list_admin != {} and language in self._all_tags_cache_list_admin:
return self._all_tags_cache_list_admin[language] #Cache hit
else:
if self._all_tags_cache_list != {} and language in self._all_tags_cache_list:
return self._all_tags_cache_list[language] #Cache hit
#Cache miss, computes everything
s_stud = set()
s_admin = set()
(common, _, org) = self.get_all_tags()
for tag in common + org:
# Is tag_name_with_translation correct by doing that like that ?
tag_name_with_translation = self.gettext(language, tag.get_name()) if tag.get_name() else ""
s_admin.add(tag_name_with_translation)
if tag.is_visible_for_student():
s_stud.add(tag_name_with_translation)
self._all_tags_cache_list_admin[language] = natsorted(s_admin, key=lambda y: y.lower())
self._all_tags_cache_list[language] = natsorted(s_stud, key=lambda y: y.lower())
if admin:
return self._all_tags_cache_list_admin[language]
return self._all_tags_cache_list[language]
|
This build a dict for fast retrive tasks id based on organisational tags. The form of the dict is:
{ 'org_tag_1': ['task_id', 'task_id', ...],
'org_tag_2' : ['task_id', 'task_id', ...],
... }
|
def get_organisational_tags_to_task(self):
""" This build a dict for fast retrive tasks id based on organisational tags. The form of the dict is:
{ 'org_tag_1': ['task_id', 'task_id', ...],
'org_tag_2' : ['task_id', 'task_id', ...],
... }
"""
if self._organisational_tags_to_task != {}:
return self._organisational_tags_to_task
for taskid, task in self.get_tasks().items():
for tag in task.get_tags()[2]:
self._organisational_tags_to_task.setdefault(tag.get_name(), []).append(taskid)
return self._organisational_tags_to_task
|
Force the cache refreshing
|
def update_all_tags_cache(self):
""" Force the cache refreshing """
self._all_tags_cache = None
self._all_tags_cache_list = {}
self._all_tags_cache_list_admin = {}
self._organisational_tags_to_task = {}
self.get_all_tags()
self.get_all_tags_names_as_list()
self.get_organisational_tags_to_task()
|
Init the webdav app
|
def get_app(config):
""" Init the webdav app """
mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost'))
database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')]
# Create the FS provider
if "tasks_directory" not in config:
raise RuntimeError("WebDav access is only supported if INGInious is using a local filesystem to access tasks")
fs_provider = LocalFSProvider(config["tasks_directory"])
course_factory, task_factory = create_factories(fs_provider, {}, None, WebAppCourse, WebAppTask)
user_manager = UserManager(MongoStore(database, 'sessions'), database, config.get('superadmins', []))
config = dict(wsgidav_app.DEFAULT_CONFIG)
config["provider_mapping"] = {"/": INGIniousFilesystemProvider(course_factory, task_factory)}
config["domaincontroller"] = INGIniousDAVDomainController(user_manager, course_factory)
config["verbose"] = 0
app = wsgidav_app.WsgiDAVApp(config)
return app
|
Resolve a relative url to the appropriate realm name.
|
def getDomainRealm(self, inputURL, environ):
"""Resolve a relative url to the appropriate realm name."""
# we don't get the realm here, its already been resolved in
# request_resolver
if inputURL.startswith("/"):
inputURL = inputURL[1:]
parts = inputURL.split("/")
return parts[0]
|
Returns True if this username is valid for the realm, False otherwise.
|
def isRealmUser(self, realmname, username, environ):
"""Returns True if this username is valid for the realm, False otherwise."""
try:
course = self.course_factory.get_course(realmname)
ok = self.user_manager.has_admin_rights_on_course(course, username=username)
return ok
except:
return False
|
Return the password for the given username for the realm.
Used for digest authentication.
|
def getRealmUserPassword(self, realmname, username, environ):
"""Return the password for the given username for the realm.
Used for digest authentication.
"""
return self.user_manager.get_user_api_key(username, create=True)
|
Returns True if this username/password pair is valid for the realm,
False otherwise. Used for basic authentication.
|
def authDomainUser(self, realmname, username, password, environ):
"""Returns True if this username/password pair is valid for the realm,
False otherwise. Used for basic authentication."""
try:
apikey = self.user_manager.get_user_api_key(username, create=None)
return apikey is not None and password == apikey
except:
return False
|
Return info dictionary for path.
See DAVProvider.getResourceInst()
|
def getResourceInst(self, path, environ):
"""Return info dictionary for path.
See DAVProvider.getResourceInst()
"""
self._count_getResourceInst += 1
fp = self._locToFilePath(path)
if not os.path.exists(fp):
return None
if os.path.isdir(fp):
return FolderResource(path, environ, fp)
return FileResource(path, environ, fp)
|
GET request
|
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
return self.page(course)
|
POST request
|
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course, __ = self.get_course_and_check_rights(courseid, None, False)
data = web.input()
if "remove" in data:
try:
if data["type"] == "all":
aggregations = list(self.database.aggregations.find({"courseid": courseid}))
for aggregation in aggregations:
aggregation["students"] = []
for group in aggregation["groups"]:
group["students"] = []
self.database.aggregations.replace_one({"_id": aggregation["_id"]}, aggregation)
else:
self.user_manager.course_unregister_user(course, data["username"])
except:
pass
elif "register" in data:
try:
self.user_manager.course_register_user(course, data["username"].strip(), '', True)
except:
pass
return self.page(course)
|
Get all data and display the page
|
def page(self, course, error="", post=False):
""" Get all data and display the page """
users = sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course, False)).items()),
key=lambda k: k[1][0] if k[1] is not None else "")
users = OrderedDict(sorted(list(self.user_manager.get_users_info(course.get_staff()).items()),
key=lambda k: k[1][0] if k[1] is not None else "") + users)
user_data = OrderedDict([(username, {
"username": username, "realname": user[0] if user is not None else "",
"email": user[1] if user is not None else "", "total_tasks": 0,
"task_grades": {"answer": 0, "match": 0}, "task_succeeded": 0, "task_tried": 0, "total_tries": 0,
"grade": 0, "url": self.submission_url_generator(username)}) for username, user in users.items()])
for username, data in self.user_manager.get_course_caches(list(users.keys()), course).items():
user_data[username].update(data if data is not None else {})
if "csv" in web.input():
return make_csv(user_data)
return self.template_helper.get_renderer().course_admin.student_list(course, list(user_data.values()), error, post)
|
GET request
|
def GET_AUTH(self, submissionid): # pylint: disable=arguments-differ
""" GET request """
course, task, submission = self.fetch_submission(submissionid)
return self.page(course, task, submission)
|
Get all data and display the page
|
def page(self, course, task, submission):
""" Get all data and display the page """
submission = self.submission_manager.get_input_from_submission(submission)
submission = self.submission_manager.get_feedback_from_submission(
submission,
show_everything=True,
translation=self.app._translations.get(self.user_manager.session_language(), gettext.NullTranslations())
)
to_display = {
problem.get_id(): {
"id": problem.get_id(),
"name": problem.get_name(self.user_manager.session_language()),
"defined": True
} for problem in task.get_problems()
}
to_display.update({
pid: {
"id": pid,
"name": pid,
"defined": False
} for pid in (set(submission["input"]) - set(to_display))
})
return self.template_helper.get_renderer().course_admin.submission(course, task, submission, to_display.values())
|
Edit a task
|
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" Edit a task """
if not id_checker(taskid):
raise Exception("Invalid task id")
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
try:
task_data = self.task_factory.get_task_descriptor_content(courseid, taskid)
except:
task_data = None
if task_data is None:
task_data = {}
environments = self.containers
current_filetype = None
try:
current_filetype = self.task_factory.get_task_descriptor_extension(courseid, taskid)
except:
pass
available_filetypes = self.task_factory.get_available_task_file_extensions()
additional_tabs = self.plugin_manager.call_hook('task_editor_tab', course=course, taskid=taskid,
task_data=task_data, template_helper=self.template_helper)
return self.template_helper.get_renderer().course_admin.task_edit(
course,
taskid,
self.task_factory.get_problem_types(),
task_data,
environments,
task_data.get('problems',{}),
self.contains_is_html(task_data),
current_filetype,
available_filetypes,
AccessibleTime,
CourseTaskFiles.get_task_filelist(self.task_factory, courseid, taskid),
additional_tabs
)
|
Detect if the problem has at least one "xyzIsHTML" key
|
def contains_is_html(cls, data):
""" Detect if the problem has at least one "xyzIsHTML" key """
for key, val in data.items():
if isinstance(key, str) and key.endswith("IsHTML"):
return True
if isinstance(val, (OrderedDict, dict)) and cls.contains_is_html(val):
return True
return False
|
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od["problem[q0][a]"]=1
>>> od["problem[q0][b][c]"]=2
>>> od["problem[q1][first]"]=1
>>> od["problem[q1][second]"]=2
>>> AdminCourseEditTask.dict_from_prefix("problem",od)
OrderedDict([('q0', OrderedDict([('a', 1), ('b', OrderedDict([('c', 2)]))])), ('q1', OrderedDict([('first', 1), ('second', 2)]))])
|
def dict_from_prefix(cls, prefix, dictionary):
"""
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od["problem[q0][a]"]=1
>>> od["problem[q0][b][c]"]=2
>>> od["problem[q1][first]"]=1
>>> od["problem[q1][second]"]=2
>>> AdminCourseEditTask.dict_from_prefix("problem",od)
OrderedDict([('q0', OrderedDict([('a', 1), ('b', OrderedDict([('c', 2)]))])), ('q1', OrderedDict([('first', 1), ('second', 2)]))])
"""
o_dictionary = OrderedDict()
for key, val in dictionary.items():
if key.startswith(prefix):
o_dictionary[key[len(prefix):].strip()] = val
dictionary = o_dictionary
if len(dictionary) == 0:
return None
elif len(dictionary) == 1 and "" in dictionary:
return dictionary[""]
else:
return_dict = OrderedDict()
for key, val in dictionary.items():
ret = re.search(r"^\[([^\]]+)\](.*)$", key)
if ret is None:
continue
return_dict[ret.group(1)] = cls.dict_from_prefix("[{}]".format(ret.group(1)), dictionary)
return return_dict
|
Parses a problem, modifying some data
|
def parse_problem(self, problem_content):
""" Parses a problem, modifying some data """
del problem_content["@order"]
return self.task_factory.get_problem_types().get(problem_content["type"]).parse_problem(problem_content)
|
Wipe the data associated to the taskid from DB
|
def wipe_task(self, courseid, taskid):
""" Wipe the data associated to the taskid from DB"""
submissions = self.database.submissions.find({"courseid": courseid, "taskid": taskid})
for submission in submissions:
for key in ["input", "archive"]:
if key in submission and type(submission[key]) == bson.objectid.ObjectId:
self.submission_manager.get_gridfs().delete(submission[key])
self.database.aggregations.remove({"courseid": courseid, "taskid": taskid})
self.database.user_tasks.remove({"courseid": courseid, "taskid": taskid})
self.database.submissions.remove({"courseid": courseid, "taskid": taskid})
self._logger.info("Task %s/%s wiped.", courseid, taskid)
|
Edit a task
|
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" Edit a task """
if not id_checker(taskid) or not id_checker(courseid):
raise Exception("Invalid course/task id")
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
data = web.input(task_file={})
# Delete task ?
if "delete" in data:
self.task_factory.delete_task(courseid, taskid)
if data.get("wipe", False):
self.wipe_task(courseid, taskid)
raise web.seeother(self.app.get_homepath() + "/admin/"+courseid+"/tasks")
# Else, parse content
try:
try:
task_zip = data.get("task_file").file
except:
task_zip = None
del data["task_file"]
problems = self.dict_from_prefix("problem", data)
limits = self.dict_from_prefix("limits", data)
#Tags
tags = self.dict_from_prefix("tags", data)
if tags is None:
tags = {}
tags = OrderedDict(sorted(tags.items(), key=lambda item: item[0])) # Sort by key
# Repair tags
for k in tags:
tags[k]["visible"] = ("visible" in tags[k]) # Since unckecked checkboxes are not present here, we manually add them to avoid later errors
tags[k]["type"] = int(tags[k]["type"])
if not "id" in tags[k]:
tags[k]["id"] = "" # Since textinput is disabled when the tag is organisational, the id field is missing. We add it to avoid Keys Errors
if tags[k]["type"] == 2:
tags[k]["id"] = "" # Force no id if organisational tag
# Remove uncompleted tags (tags with no name or no id)
for k in list(tags.keys()):
if (tags[k]["id"] == "" and tags[k]["type"] != 2) or tags[k]["name"] == "":
del tags[k]
# Find duplicate ids. Return an error if some tags use the same id.
for k in tags:
if tags[k]["type"] != 2: # Ignore organisational tags since they have no id.
count = 0
id = str(tags[k]["id"])
if (" " in id):
return json.dumps({"status": "error", "message": _("You can not use spaces in the tag id field.")})
if not id_checker(id):
return json.dumps({"status": "error", "message": _("Invalid tag id: {}").format(id)})
for k2 in tags:
if tags[k2]["type"] != 2 and tags[k2]["id"] == id:
count = count+1
if count > 1:
return json.dumps({"status": "error", "message": _("Some tags have the same id! The id of a tag must be unique.")})
data = {key: val for key, val in data.items() if
not key.startswith("problem")
and not key.startswith("limits")
and not key.startswith("tags")
and not key.startswith("/")}
del data["@action"]
# Determines the task filetype
if data["@filetype"] not in self.task_factory.get_available_task_file_extensions():
return json.dumps({"status": "error", "message": _("Invalid file type: {}").format(str(data["@filetype"]))})
file_ext = data["@filetype"]
del data["@filetype"]
# Parse and order the problems (also deletes @order from the result)
if problems is None:
data["problems"] = OrderedDict([])
else:
data["problems"] = OrderedDict([(key, self.parse_problem(val))
for key, val in sorted(iter(problems.items()), key=lambda x: int(x[1]['@order']))])
# Task limits
data["limits"] = limits
data["tags"] = OrderedDict(sorted(tags.items(), key=lambda x: x[1]['type']))
if "hard_time" in data["limits"] and data["limits"]["hard_time"] == "":
del data["limits"]["hard_time"]
# Weight
try:
data["weight"] = float(data["weight"])
except:
return json.dumps({"status": "error", "message": _("Grade weight must be a floating-point number")})
# Groups
if "groups" in data:
data["groups"] = True if data["groups"] == "true" else False
# Submision storage
if "store_all" in data:
try:
stored_submissions = data["stored_submissions"]
data["stored_submissions"] = 0 if data["store_all"] == "true" else int(stored_submissions)
except:
return json.dumps(
{"status": "error", "message": _("The number of stored submission must be positive!")})
if data["store_all"] == "false" and data["stored_submissions"] <= 0:
return json.dumps({"status": "error", "message": _("The number of stored submission must be positive!")})
del data['store_all']
# Submission limits
if "submission_limit" in data:
if data["submission_limit"] == "none":
result = {"amount": -1, "period": -1}
elif data["submission_limit"] == "hard":
try:
result = {"amount": int(data["submission_limit_hard"]), "period": -1}
except:
return json.dumps({"status": "error", "message": _("Invalid submission limit!")})
else:
try:
result = {"amount": int(data["submission_limit_soft_0"]), "period": int(data["submission_limit_soft_1"])}
except:
return json.dumps({"status": "error", "message": _("Invalid submission limit!")})
del data["submission_limit_hard"]
del data["submission_limit_soft_0"]
del data["submission_limit_soft_1"]
data["submission_limit"] = result
# Accessible
if data["accessible"] == "custom":
data["accessible"] = "{}/{}/{}".format(data["accessible_start"], data["accessible_soft_end"], data["accessible_end"])
elif data["accessible"] == "true":
data["accessible"] = True
else:
data["accessible"] = False
del data["accessible_start"]
del data["accessible_end"]
del data["accessible_soft_end"]
# Checkboxes
if data.get("responseIsHTML"):
data["responseIsHTML"] = True
# Network grading
data["network_grading"] = "network_grading" in data
except Exception as message:
return json.dumps({"status": "error", "message": _("Your browser returned an invalid form ({})").format(message)})
# Get the course
try:
course = self.course_factory.get_course(courseid)
except:
return json.dumps({"status": "error", "message": _("Error while reading course's informations")})
# Get original data
try:
orig_data = self.task_factory.get_task_descriptor_content(courseid, taskid)
data["order"] = orig_data["order"]
except:
pass
task_fs = self.task_factory.get_task_fs(courseid, taskid)
task_fs.ensure_exists()
# Call plugins and return the first error
plugin_results = self.plugin_manager.call_hook('task_editor_submit', course=course, taskid=taskid,
task_data=data, task_fs=task_fs)
# Retrieve the first non-null element
error = next(filter(None, plugin_results), None)
if error is not None:
return error
try:
WebAppTask(course, taskid, data, task_fs, None, self.plugin_manager, self.task_factory.get_problem_types())
except Exception as message:
return json.dumps({"status": "error", "message": _("Invalid data: {}").format(str(message))})
if task_zip:
try:
zipfile = ZipFile(task_zip)
except Exception:
return json.dumps({"status": "error", "message": _("Cannot read zip file. Files were not modified")})
with tempfile.TemporaryDirectory() as tmpdirname:
try:
zipfile.extractall(tmpdirname)
except Exception:
return json.dumps(
{"status": "error", "message": _("There was a problem while extracting the zip archive. Some files may have been modified")})
task_fs.copy_to(tmpdirname)
self.task_factory.delete_all_possible_task_files(courseid, taskid)
self.task_factory.update_task_descriptor_content(courseid, taskid, data, force_extension=file_ext)
course.update_all_tags_cache()
return json.dumps({"status": "ok"})
|
Display main course list page
|
def GET(self): # pylint: disable=arguments-differ
""" Display main course list page """
if not self.app.welcome_page:
raise web.seeother("/courselist")
return self.show_page(self.app.welcome_page)
|
Display main course list page
|
def POST(self): # pylint: disable=arguments-differ
""" Display main course list page """
if not self.app.welcome_page:
raise web.seeother("/courselist")
return self.show_page(self.app.welcome_page)
|
GET request
|
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
username = self.user_manager.session_username()
error = False
change = False
msg = ""
data = web.input()
if self.user_manager.has_staff_rights_on_course(course):
raise web.notfound()
elif not self.user_manager.course_is_open_to_user(course, lti=False):
return self.template_helper.get_renderer().course_unavailable()
elif "register_group" in data:
change = True
if course.can_students_choose_group() and course.use_classrooms():
aggregation = self.database.aggregations.find_one({"courseid": course.get_id(), "students": username})
if int(data["register_group"]) >= 0 and (len(aggregation["groups"]) > int(data["register_group"])):
group = aggregation["groups"][int(data["register_group"])]
if group["size"] > len(group["students"]):
for index, group in enumerate(aggregation["groups"]):
if username in group["students"]:
aggregation["groups"][index]["students"].remove(username)
aggregation["groups"][int(data["register_group"])]["students"].append(username)
self.database.aggregations.replace_one({"courseid": course.get_id(), "students": username}, aggregation)
self._logger.info("User %s registered to group %s/%s/%s", username, courseid, aggregation["description"], data["register_group"])
else:
error = True
msg = _("Couldn't register to the specified group.")
elif course.can_students_choose_group():
aggregation = self.database.aggregations.find_one(
{"courseid": course.get_id(), "students": username})
if aggregation is not None:
aggregation["students"].remove(username)
for index, group in enumerate(aggregation["groups"]):
if username in group["students"]:
aggregation["groups"][index]["students"].remove(username)
self.database.aggregations.replace_one({"courseid": course.get_id(), "students": username}, aggregation)
# Add student in the classroom and unique group
self.database.aggregations.find_one_and_update({"_id": ObjectId(data["register_group"])},
{"$push": {"students": username}})
new_aggregation = self.database.aggregations.find_one_and_update({"_id": ObjectId(data["register_group"])},
{"$push": {"groups.0.students": username}})
if new_aggregation is None:
error = True
msg = _("Couldn't register to the specified group.")
else:
self._logger.info("User %s registered to team %s/%s", username, courseid, aggregation["description"])
else:
error = True
msg = _("You are not allowed to change group.")
elif "unregister_group" in data:
change = True
if course.can_students_choose_group():
aggregation = self.database.aggregations.find_one({"courseid": course.get_id(), "students": username, "groups.students": username})
if aggregation is not None:
for index, group in enumerate(aggregation["groups"]):
if username in group["students"]:
aggregation["groups"][index]["students"].remove(username)
self.database.aggregations.replace_one({"courseid": course.get_id(), "students": username}, aggregation)
self._logger.info("User %s unregistered from group/team %s/%s", username, courseid, aggregation["description"])
else:
error = True
msg = _("You're not registered in a group.")
else:
error = True
msg = _("You are not allowed to change group.")
tasks = course.get_tasks()
last_submissions = self.submission_manager.get_user_last_submissions(5, {"courseid": courseid, "taskid": {"$in": list(tasks.keys())}})
for submission in last_submissions:
submission["taskname"] = tasks[submission['taskid']].get_name(self.user_manager.session_language())
aggregation = self.user_manager.get_course_user_aggregation(course)
aggregations = self.user_manager.get_course_aggregations(course)
users = self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course))
if course.use_classrooms():
mygroup = None
for index, group in enumerate(aggregation["groups"]):
if self.user_manager.session_username() in group["students"]:
mygroup = group
mygroup["index"] = index + 1
return self.template_helper.get_renderer().classroom(course, last_submissions, aggregation, users,
mygroup, msg, error, change)
else:
return self.template_helper.get_renderer().team(course, last_submissions, aggregations, users,
aggregation, msg, error)
|
A wrapper that remove all exceptions raised from hooks
|
def _exception_free_callback(self, callback, *args, **kwargs):
""" A wrapper that remove all exceptions raised from hooks """
try:
return callback(*args, **kwargs)
except Exception:
self._logger.exception("An exception occurred while calling a hook! ",exc_info=True)
return None
|
Add a new hook that can be called with the call_hook function.
`prio` is the priority. Higher priority hooks are called before lower priority ones.
This function does not enforce a particular order between hooks with the same priorities.
|
def add_hook(self, name, callback, prio=0):
""" Add a new hook that can be called with the call_hook function.
`prio` is the priority. Higher priority hooks are called before lower priority ones.
This function does not enforce a particular order between hooks with the same priorities.
"""
hook_list = self._hooks.get(name, [])
add = (lambda *args, **kwargs: self._exception_free_callback(callback, *args, **kwargs)), -prio
pos = bisect.bisect_right(list(x[1] for x in hook_list), -prio)
hook_list[pos:pos] = [add]
self._hooks[name] = hook_list
|
Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)
|
def call_hook(self, name, **kwargs):
""" Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)"""
return [y for y in [x(**kwargs) for x, _ in self._hooks.get(name, [])] if y is not None]
|
Call all hooks registered with this name. Each hook receives as arguments the return value of the
previous hook call, or the initial params for the first hook. As such, each hook must return a dictionary
with the received (eventually modified) args. Returns the modified args.
|
def call_hook_recursive(self, name, **kwargs):
""" Call all hooks registered with this name. Each hook receives as arguments the return value of the
previous hook call, or the initial params for the first hook. As such, each hook must return a dictionary
with the received (eventually modified) args. Returns the modified args."""
for x, _ in self._hooks.get(name, []):
out = x(**kwargs)
if out is not None: #ignore already reported failure
kwargs = out
return kwargs
|
Check if an input for a task is consistent. Return true if this is case, false else
|
def input_is_consistent(self, task_input, default_allowed_extension, default_max_size):
""" Check if an input for a task is consistent. Return true if this is case, false else """
for problem in self._problems:
if not problem.input_is_consistent(task_input, default_allowed_extension, default_max_size):
return False
return True
|
Return the limits of this task
|
def get_limits(self):
""" Return the limits of this task """
vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits)
return vals[0] if len(vals) else self._limits
|
Return True if the grading container should have access to the network
|
def allow_network_access_grading(self):
""" Return True if the grading container should have access to the network """
vals = self._hook_manager.call_hook('task_network_grading', course=self.get_course(), task=self, default=self._network_grading)
return vals[0] if len(vals) else self._network_grading
|
Verify the answers in task_input. Returns six values
1st: True the input is **currently** valid. (may become invalid after running the code), False else
2nd: True if the input needs to be run in the VM, False else
3rd: Main message, as a list (that can be join with \n or <br/> for example)
4th: Problem specific message, as a dictionnary (tuple of result/text)
5th: Number of subproblems that (already) contain errors. <= Number of subproblems
6th: Number of errors in MCQ problems. Not linked to the number of subproblems
|
def check_answer(self, task_input, language):
"""
Verify the answers in task_input. Returns six values
1st: True the input is **currently** valid. (may become invalid after running the code), False else
2nd: True if the input needs to be run in the VM, False else
3rd: Main message, as a list (that can be join with \n or <br/> for example)
4th: Problem specific message, as a dictionnary (tuple of result/text)
5th: Number of subproblems that (already) contain errors. <= Number of subproblems
6th: Number of errors in MCQ problems. Not linked to the number of subproblems
"""
valid = True
need_launch = False
main_message = []
problem_messages = {}
error_count = 0
multiple_choice_error_count = 0
for problem in self._problems:
problem_is_valid, problem_main_message, problem_s_messages, problem_mc_error_count = problem.check_answer(task_input, language)
if problem_is_valid is None:
need_launch = True
elif problem_is_valid == False:
error_count += 1
valid = False
if problem_main_message is not None:
main_message.append(problem_main_message)
if problem_s_messages is not None:
problem_messages[problem.get_id()] = (("success" if problem_is_valid else "failed"), problem_s_messages)
multiple_choice_error_count += problem_mc_error_count
return valid, need_launch, main_message, problem_messages, error_count, multiple_choice_error_count
|
Creates a new instance of the right class for a given problem.
|
def _create_task_problem(self, problemid, problem_content, task_problem_types):
"""Creates a new instance of the right class for a given problem."""
# Basic checks
if not id_checker(problemid):
raise Exception("Invalid problem _id: " + problemid)
if problem_content.get('type', "") not in task_problem_types:
raise Exception("Invalid type for problem " + problemid)
return task_problem_types.get(problem_content.get('type', ""))(self, problemid, problem_content, self._translations)
|
Init logging
:param log_level: An integer representing the log level or a string representing one
|
def init_logging(log_level=logging.DEBUG):
"""
Init logging
:param log_level: An integer representing the log level or a string representing one
"""
logging.root.handlers = [] # remove possible side-effects from other libs
logger = logging.getLogger("inginious")
logger.setLevel(log_level)
ch = logging.StreamHandler()
ch.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)
|
Displays the link to the scoreboards on the course page, if the plugin is activated for this course
|
def course_menu(course, template_helper):
""" Displays the link to the scoreboards on the course page, if the plugin is activated for this course """
scoreboards = course.get_descriptor().get('scoreboard', [])
if scoreboards != []:
return str(template_helper.get_custom_renderer('frontend/plugins/scoreboard', layout=False).course_menu(course))
else:
return None
|
Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards
|
def task_menu(course, task, template_helper):
""" Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards """
scoreboards = course.get_descriptor().get('scoreboard', [])
try:
tolink = []
for sid, scoreboard in enumerate(scoreboards):
if task.get_id() in scoreboard["content"]:
tolink.append((sid, scoreboard["name"]))
if tolink:
return str(template_helper.get_custom_renderer('frontend/plugins/scoreboard', layout=False).task_menu(course, tolink))
return None
except:
return None
|
Init the plugin.
Available configuration in configuration.yaml:
::
- plugin_module: "inginious.frontend.plugins.scoreboard"
Available configuration in course.yaml:
::
- scoreboard: #you can define multiple scoreboards
- content: "taskid1" #creates a scoreboard for taskid1
name: "Scoreboard task 1"
- content: ["taskid2", "taskid3"] #creates a scoreboard for taskid2 and taskid3 (sum of both score is taken as overall score)
name: "Scoreboard for task 2 and 3"
- content: {"taskid4": 2, "taskid5": 3} #creates a scoreboard where overall score is 2*score of taskid4 + 3*score of taskid5
name: "Another scoreboard"
reverse: True #reverse the score (less is better)
|
def init(plugin_manager, _, _2, _3):
"""
Init the plugin.
Available configuration in configuration.yaml:
::
- plugin_module: "inginious.frontend.plugins.scoreboard"
Available configuration in course.yaml:
::
- scoreboard: #you can define multiple scoreboards
- content: "taskid1" #creates a scoreboard for taskid1
name: "Scoreboard task 1"
- content: ["taskid2", "taskid3"] #creates a scoreboard for taskid2 and taskid3 (sum of both score is taken as overall score)
name: "Scoreboard for task 2 and 3"
- content: {"taskid4": 2, "taskid5": 3} #creates a scoreboard where overall score is 2*score of taskid4 + 3*score of taskid5
name: "Another scoreboard"
reverse: True #reverse the score (less is better)
"""
page_pattern_course = r'/scoreboard/([a-z0-9A-Z\-_]+)'
page_pattern_scoreboard = r'/scoreboard/([a-z0-9A-Z\-_]+)/([0-9]+)'
plugin_manager.add_page(page_pattern_course, ScoreBoardCourse)
plugin_manager.add_page(page_pattern_scoreboard, ScoreBoard)
plugin_manager.add_hook('course_menu', course_menu)
plugin_manager.add_hook('task_menu', task_menu)
|
GET request
|
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
scoreboards = course.get_descriptor().get('scoreboard', [])
try:
names = {i: val["name"] for i, val in enumerate(scoreboards)}
except:
raise web.notfound("Invalid configuration")
if len(names) == 0:
raise web.notfound()
return self.template_helper.get_custom_renderer('frontend/plugins/scoreboard').main(course, names)
|
GET request
|
def GET_AUTH(self, courseid, scoreboardid): # pylint: disable=arguments-differ
""" GET request """
course = self.course_factory.get_course(courseid)
scoreboards = course.get_descriptor().get('scoreboard', [])
try:
scoreboardid = int(scoreboardid)
scoreboard_name = scoreboards[scoreboardid]["name"]
scoreboard_content = scoreboards[scoreboardid]["content"]
scoreboard_reverse = bool(scoreboards[scoreboardid].get('reverse', False))
except:
raise web.notfound()
# Convert scoreboard_content
if isinstance(scoreboard_content, str):
scoreboard_content = OrderedDict([(scoreboard_content, 1)])
if isinstance(scoreboard_content, list):
scoreboard_content = OrderedDict([(entry, 1) for entry in scoreboard_content])
if not isinstance(scoreboard_content, OrderedDict):
scoreboard_content = OrderedDict(iter(scoreboard_content.items()))
# Get task names
task_names = {}
for taskid in scoreboard_content:
try:
task_names[taskid] = course.get_task(taskid).get_name(self.user_manager.session_language())
except:
raise web.notfound("Unknown task id "+taskid)
# Get all submissions
results = self.database.submissions.find({
"courseid": courseid,
"taskid": {"$in": list(scoreboard_content.keys())},
"custom.score": {"$exists": True},
"result": "success"
}, ["taskid", "username", "custom.score"])
# Get best results per users(/group)
result_per_user = {}
users = set()
for submission in results:
# Be sure we have a list
if not isinstance(submission["username"], list):
submission["username"] = [submission["username"]]
submission["username"] = tuple(submission["username"])
if submission["username"] not in result_per_user:
result_per_user[submission["username"]] = {}
if submission["taskid"] not in result_per_user[submission["username"]]:
result_per_user[submission["username"]][submission["taskid"]] = submission["custom"]["score"]
else:
# keep best score
current_score = result_per_user[submission["username"]][submission["taskid"]]
new_score = submission["custom"]["score"]
task_reversed = scoreboard_reverse != (scoreboard_content[submission["taskid"]] < 0)
if task_reversed and current_score > new_score:
result_per_user[submission["username"]][submission["taskid"]] = new_score
elif not task_reversed and current_score < new_score:
result_per_user[submission["username"]][submission["taskid"]] = new_score
for user in submission["username"]:
users.add(user)
# Get user names
users_realname = {}
for username, userinfo in self.user_manager.get_users_info(list(users)).items():
users_realname[username] = userinfo[0] if userinfo else username
# Compute overall result per user, and sort them
overall_result_per_user = {}
for key, val in result_per_user.items():
total = 0
solved = 0
for taskid, coef in scoreboard_content.items():
if taskid in val:
total += val[taskid]*coef
solved += 1
overall_result_per_user[key] = {"total": total, "solved": solved}
sorted_users = list(overall_result_per_user.keys())
sorted_users = sorted(sorted_users, key=sort_func(overall_result_per_user, scoreboard_reverse))
# Compute table
table = []
# Header
if len(scoreboard_content) == 1:
header = ["", "Student(s)", "Score"]
emphasized_columns = [2]
else:
header = ["", "Student(s)", "Solved", "Total score"] + [task_names[taskid] for taskid in list(scoreboard_content.keys())]
emphasized_columns = [2, 3]
# Lines
old_score = ()
rank = 0
for user in sorted_users:
# Increment rank if needed, and display it
line = []
if old_score != (overall_result_per_user[user]["solved"], overall_result_per_user[user]["total"]):
rank += 1
old_score = (overall_result_per_user[user]["solved"], overall_result_per_user[user]["total"])
line.append(rank)
else:
line.append("")
# Users
line.append(",".join(sorted([users_realname[u] for u in user])))
if len(scoreboard_content) == 1:
line.append(overall_result_per_user[user]["total"])
else:
line.append(overall_result_per_user[user]["solved"])
line.append(overall_result_per_user[user]["total"])
for taskid in scoreboard_content:
line.append(result_per_user[user].get(taskid, ""))
table.append(line)
renderer = self.template_helper.get_custom_renderer('frontend/plugins/scoreboard')
return renderer.scoreboard(course, scoreboardid, scoreboard_name, header, table, emphasized_columns)
|
Fixes a bug in web.py. See #208. PR is waiting to be merged upstream at https://github.com/webpy/webpy/pull/419
TODO: remove me once PR is merged upstream.
|
def fix_webpy_cookies():
"""
Fixes a bug in web.py. See #208. PR is waiting to be merged upstream at https://github.com/webpy/webpy/pull/419
TODO: remove me once PR is merged upstream.
"""
try:
web.webapi.parse_cookies('a="test"') # make the bug occur
except NameError:
# monkeypatch web.py
SimpleCookie.iteritems = SimpleCookie.items
web.webapi.Cookie = namedtuple('Cookie', ['SimpleCookie', 'CookieError'])(SimpleCookie, CookieError)
web.webapi.parse_cookies('a="test"')
|
Get the available student and tutor lists for classroom edition
|
def get_user_lists(self, course, classroomid):
""" Get the available student and tutor lists for classroom edition"""
tutor_list = course.get_staff()
# Determine if user is grouped or not in the classroom
student_list = list(self.database.classrooms.aggregate([
{"$match": {"_id": ObjectId(classroomid)}},
{"$unwind": "$students"},
{"$project": {
"students": 1,
"grouped": {
"$anyElementTrue": {
"$map": {
"input": "$groups.students",
"as": "group",
"in": {
"$anyElementTrue": {
"$map": {
"input": "$$group",
"as": "groupmember",
"in": {"$eq": ["$$groupmember", "$students"]}
}
}
}
}
}
}
}}
]))
student_list = dict([(student["students"], student) for student in student_list])
other_students = [entry['students'] for entry in list(self.database.classrooms.aggregate([
{"$match": {"courseid": course.get_id(), "_id": {"$ne": ObjectId(classroomid)}}},
{"$unwind": "$students"},
{"$project": {"_id": 0, "students": 1}}
]))]
users_info = self.user_manager.get_users_info(other_students + list(student_list.keys()) + tutor_list)
# Order the non-registered students
other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val)))
return student_list, tutor_list, other_students, users_info
|
Update classroom and returns a list of errored students
|
def update_classroom(self, course, classroomid, new_data):
""" Update classroom and returns a list of errored students"""
student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid)
# Check tutors
new_data["tutors"] = [tutor for tutor in map(str.strip, new_data["tutors"]) if tutor in tutor_list]
students, groups, errored_students = [], [], []
new_data["students"] = map(str.strip, new_data["students"])
# Check the students
for student in new_data["students"]:
if student in student_list:
students.append(student)
else:
if student in other_students:
# Remove user from the other classroom
self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "groups.students": student},
{"$pull": {"groups.$.students": student, "students": student}})
self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}})
students.append(student)
else:
# Check if user can be registered
user_info = self.user_manager.get_user_info(student)
if user_info is None or student in tutor_list:
errored_students.append(student)
else:
students.append(student)
removed_students = [student for student in student_list if student not in new_data["students"]]
self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "default": True},
{"$push": {"students": {"$each": removed_students}}})
new_data["students"] = students
# Check the groups
for group in new_data["groups"]:
group["students"] = [student for student in map(str.strip, group["students"]) if student in new_data["students"]]
if len(group["students"]) <= group["size"]:
groups.append(group)
new_data["groups"] = groups
classroom = self.database.classrooms.find_one_and_update(
{"_id": ObjectId(classroomid)},
{"$set": {"description": new_data["description"],
"students": students, "tutors": new_data["tutors"],
"groups": groups}}, return_document=ReturnDocument.AFTER)
return classroom, errored_students
|
Edit a classroom
|
def GET_AUTH(self, courseid, classroomid): # pylint: disable=arguments-differ
""" Edit a classroom """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)
if course.is_lti():
raise web.notfound()
student_list, tutor_list, other_students, users_info = self.get_user_lists(course, classroomid)
classroom = self.database.classrooms.find_one({"_id": ObjectId(classroomid), "courseid": courseid})
if classroom:
return self.template_helper.get_renderer().course_admin.edit_classroom(course, student_list, tutor_list, other_students, users_info,
classroom, "", False)
else:
raise web.notfound()
|
Edit a classroom
|
def POST_AUTH(self, courseid, classroomid): # pylint: disable=arguments-differ
""" Edit a classroom """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)
if course.is_lti():
raise web.notfound()
error = False
data = web.input(tutors=[], groups=[], classroomfile={})
if "delete" in data:
# Get the classroom
classroom = self.database.classrooms.find_one({"_id": ObjectId(classroomid), "courseid": courseid})
if classroom is None:
msg = _("Classroom not found.")
error = True
elif classroom['default']:
msg = _("You can't remove your default classroom.")
error = True
else:
self.database.classrooms.find_one_and_update({"courseid": courseid, "default": True},
{"$push": {
"students": {"$each": classroom["students"]}
}})
self.database.classrooms.delete_one({"_id": ObjectId(classroomid)})
raise web.seeother(self.app.get_homepath() + "/admin/" + courseid + "/classrooms")
else:
try:
if "upload" in data:
new_data = custom_yaml.load(data["classroomfile"].file)
else:
# Prepare classroom-like data structure from input
new_data = {"description": data["description"], "tutors": data["tutors"], "students": [], "groups": []}
for index, groupstr in enumerate(data["groups"]):
group = json.loads(groupstr)
new_data["students"].extend(group["students"])
if index != 0:
new_data["groups"].append(group)
classroom, errored_students = self.update_classroom(course, classroomid, new_data)
student_list, tutor_list, other_students, users_info = self.get_user_lists(course, classroom["_id"])
if len(errored_students) > 0:
msg = _("Changes couldn't be applied for following students :") + "<ul>"
for student in errored_students:
msg += "<li>" + student + "</li>"
msg += "</ul>"
error = True
else:
msg = _("Classroom updated.")
except:
classroom = self.database.classrooms.find_one({"_id": ObjectId(classroomid), "courseid": courseid})
student_list, tutor_list, other_students, users_info = self.get_user_lists(course, classroom["_id"])
msg = _('An error occurred while parsing the data.')
error = True
return self.template_helper.get_renderer().course_admin.edit_classroom(course, student_list, tutor_list, other_students, users_info,
classroom, msg, error)
|
Returns parsed text
|
def parse(self, debug=False):
"""Returns parsed text"""
if self._parsed is None:
try:
if self._mode == "html":
self._parsed = self.html(self._content, self._show_everything, self._translation)
else:
self._parsed = self.rst(self._content, self._show_everything, self._translation, debug=debug)
except Exception as e:
if debug:
raise BaseException("Parsing failed") from e
else:
self._parsed = self._translation.gettext("<b>Parsing failed</b>: <pre>{}</pre>").format(html.escape(self._content))
return self._parsed
|
Parses HTML
|
def html(cls, string, show_everything=False, translation=gettext.NullTranslations()): # pylint: disable=unused-argument
"""Parses HTML"""
out, _ = tidylib.tidy_fragment(string)
return out
|
Parses reStructuredText
|
def rst(cls, string, show_everything=False, translation=gettext.NullTranslations(), initial_header_level=3, debug=False):
"""Parses reStructuredText"""
overrides = {
'initial_header_level': initial_header_level,
'doctitle_xform': False,
'syntax_highlight': 'none',
'force_show_hidden_until': show_everything,
'translation': translation,
'math_output': 'MathJax'
}
if debug:
overrides['halt_level'] = 2
overrides['traceback'] = True
parts = core.publish_parts(source=string, writer=_CustomHTMLWriter(), settings_overrides=overrides)
return parts['body_pre_docinfo'] + parts['fragment']
|
POST request
|
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course, __ = self.get_course_and_check_rights(courseid)
data = web.input(task=[])
if "task" in data:
# Change tasks order
for index, taskid in enumerate(data["task"]):
try:
task = self.task_factory.get_task_descriptor_content(courseid, taskid)
task["order"] = index
self.task_factory.update_task_descriptor_content(courseid, taskid, task)
except:
pass
return self.page(course)
|
Get all data and display the page
|
def page(self, course):
""" Get all data and display the page """
data = list(self.database.user_tasks.aggregate(
[
{
"$match":
{
"courseid": course.get_id(),
"username": {"$in": self.user_manager.get_course_registered_users(course, False)}
}
},
{
"$group":
{
"_id": "$taskid",
"viewed": {"$sum": 1},
"attempted": {"$sum": {"$cond": [{"$ne": ["$tried", 0]}, 1, 0]}},
"attempts": {"$sum": "$tried"},
"succeeded": {"$sum": {"$cond": ["$succeeded", 1, 0]}}
}
}
]))
# Load tasks and verify exceptions
files = self.task_factory.get_readable_tasks(course)
output = {}
errors = []
for task in files:
try:
output[task] = course.get_task(task)
except Exception as inst:
errors.append({"taskid": task, "error": str(inst)})
tasks = OrderedDict(sorted(list(output.items()), key=lambda t: (t[1].get_order(), t[1].get_id())))
# Now load additional informations
result = OrderedDict()
for taskid in tasks:
result[taskid] = {"name": tasks[taskid].get_name(self.user_manager.session_language()), "viewed": 0, "attempted": 0, "attempts": 0, "succeeded": 0,
"url": self.submission_url_generator(taskid)}
for entry in data:
if entry["_id"] in result:
result[entry["_id"]]["viewed"] = entry["viewed"]
result[entry["_id"]]["attempted"] = entry["attempted"]
result[entry["_id"]]["attempts"] = entry["attempts"]
result[entry["_id"]]["succeeded"] = entry["succeeded"]
if "csv" in web.input():
return make_csv(result)
return self.template_helper.get_renderer().course_admin.task_list(course, result, errors)
|
Edit a task
|
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" Edit a task """
if not id_checker(taskid):
raise Exception("Invalid task id")
self.get_course_and_check_rights(courseid, allow_all_staff=False)
request = web.input()
if request.get("action") == "download" and request.get('path') is not None:
return self.action_download(courseid, taskid, request.get('path'))
elif request.get("action") == "delete" and request.get('path') is not None:
return self.action_delete(courseid, taskid, request.get('path'))
elif request.get("action") == "rename" and request.get('path') is not None and request.get('new_path') is not None:
return self.action_rename(courseid, taskid, request.get('path'), request.get('new_path'))
elif request.get("action") == "create" and request.get('path') is not None:
return self.action_create(courseid, taskid, request.get('path'))
elif request.get("action") == "edit" and request.get('path') is not None:
return self.action_edit(courseid, taskid, request.get('path'))
else:
return self.show_tab_file(courseid, taskid)
|
Upload or modify a file
|
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ
""" Upload or modify a file """
if not id_checker(taskid):
raise Exception("Invalid task id")
self.get_course_and_check_rights(courseid, allow_all_staff=False)
request = web.input(file={})
if request.get("action") == "upload" and request.get('path') is not None and request.get('file') is not None:
return self.action_upload(courseid, taskid, request.get('path'), request.get('file'))
elif request.get("action") == "edit_save" and request.get('path') is not None and request.get('content') is not None:
return self.action_edit_save(courseid, taskid, request.get('path'), request.get('content'))
else:
return self.show_tab_file(courseid, taskid)
|
Return the file tab
|
def show_tab_file(self, courseid, taskid, error=None):
""" Return the file tab """
return self.template_helper.get_renderer(False).course_admin.edit_tabs.files(
self.course_factory.get_course(courseid), taskid, self.get_task_filelist(self.task_factory, courseid, taskid), error)
|
Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files.
It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, String CompleteName)
|
def get_task_filelist(cls, task_factory, courseid, taskid):
""" Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files.
It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, String CompleteName)
"""
task_fs = task_factory.get_task_fs(courseid, taskid)
if not task_fs.exists():
return []
tmp_out = {}
entries = task_fs.list(True, True, True)
for entry in entries:
if os.path.splitext(entry)[0] == "task" and os.path.splitext(entry)[1][1:] in task_factory.get_available_task_file_extensions():
continue
data = entry.split("/")
is_directory = False
if data[-1] == "":
is_directory = True
data = data[0:len(data)-1]
cur_pos = 0
tree_pos = tmp_out
while cur_pos != len(data):
if data[cur_pos] not in tree_pos:
tree_pos[data[cur_pos]] = {} if is_directory or cur_pos != len(data) - 1 else None
tree_pos = tree_pos[data[cur_pos]]
cur_pos += 1
def recur_print(current, level, current_name):
iteritems = sorted(current.items())
# First, the files
recur_print.flattened += [(level, False, f, current_name+"/"+f) for f, t in iteritems if t is None]
# Then, the dirs
for name, sub in iteritems:
if sub is not None:
recur_print.flattened.append((level, True, name, current_name+"/"+name+"/"))
recur_print(sub, level + 1, current_name + "/" + name)
recur_print.flattened = []
recur_print(tmp_out, 0, '')
return recur_print.flattened
|
Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed
|
def verify_path(self, courseid, taskid, path, new_path=False):
""" Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed """
task_fs = self.task_factory.get_task_fs(courseid, taskid)
# verify that the dir exists
if not task_fs.exists():
return None
# all path given to this part of the application must start with a "/", let's remove it
if not path.startswith("/"):
return None
path = path[1:len(path)]
if ".." in path:
return None
if task_fs.exists(path) == new_path:
return None
# do not allow touching the task.* file
if os.path.splitext(path)[0] == "task" and os.path.splitext(path)[1][1:] in \
self.task_factory.get_available_task_file_extensions():
return None
# do not allow hidden dir/files
if path != ".":
for i in path.split(os.path.sep):
if i.startswith("."):
return None
return path
|
Edit a file
|
def action_edit(self, courseid, taskid, path):
""" Edit a file """
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
return "Internal error"
try:
content = self.task_factory.get_task_fs(courseid, taskid).get(wanted_path).decode("utf-8")
return json.dumps({"content": content})
except:
return json.dumps({"error": "not-readable"})
|
Save an edited file
|
def action_edit_save(self, courseid, taskid, path, content):
""" Save an edited file """
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
return json.dumps({"error": True})
try:
self.task_factory.get_task_fs(courseid, taskid).put(wanted_path, content.encode("utf-8"))
return json.dumps({"ok": True})
except:
return json.dumps({"error": True})
|
Upload a file
|
def action_upload(self, courseid, taskid, path, fileobj):
""" Upload a file """
# the path is given by the user. Let's normalize it
path = path.strip()
if not path.startswith("/"):
path = "/" + path
wanted_path = self.verify_path(courseid, taskid, path, True)
if wanted_path is None:
return self.show_tab_file(courseid, taskid, _("Invalid new path"))
task_fs = self.task_factory.get_task_fs(courseid, taskid)
try:
task_fs.put(wanted_path, fileobj.file.read())
except:
return self.show_tab_file(courseid, taskid, _("An error occurred while writing the file"))
return self.show_tab_file(courseid, taskid)
|
Delete a file or a directory
|
def action_create(self, courseid, taskid, path):
""" Delete a file or a directory """
# the path is given by the user. Let's normalize it
path = path.strip()
if not path.startswith("/"):
path = "/" + path
want_directory = path.endswith("/")
wanted_path = self.verify_path(courseid, taskid, path, True)
if wanted_path is None:
return self.show_tab_file(courseid, taskid, _("Invalid new path"))
task_fs = self.task_factory.get_task_fs(courseid, taskid)
if want_directory:
task_fs.from_subfolder(wanted_path).ensure_exists()
else:
task_fs.put(wanted_path, b"")
return self.show_tab_file(courseid, taskid)
|
Delete a file or a directory
|
def action_rename(self, courseid, taskid, path, new_path):
""" Delete a file or a directory """
# normalize
path = path.strip()
new_path = new_path.strip()
if not path.startswith("/"):
path = "/" + path
if not new_path.startswith("/"):
new_path = "/" + new_path
old_path = self.verify_path(courseid, taskid, path)
if old_path is None:
return self.show_tab_file(courseid, taskid, _("Internal error"))
wanted_path = self.verify_path(courseid, taskid, new_path, True)
if wanted_path is None:
return self.show_tab_file(courseid, taskid, _("Invalid new path"))
try:
self.task_factory.get_task_fs(courseid, taskid).move(old_path, wanted_path)
return self.show_tab_file(courseid, taskid)
except:
return self.show_tab_file(courseid, taskid, _("An error occurred while moving the files"))
|
Delete a file or a directory
|
def action_delete(self, courseid, taskid, path):
""" Delete a file or a directory """
# normalize
path = path.strip()
if not path.startswith("/"):
path = "/" + path
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
return self.show_tab_file(courseid, taskid, _("Internal error"))
# special case: cannot delete current directory of the task
if "/" == wanted_path:
return self.show_tab_file(courseid, taskid, _("Internal error"))
try:
self.task_factory.get_task_fs(courseid, taskid).delete(wanted_path)
return self.show_tab_file(courseid, taskid)
except:
return self.show_tab_file(courseid, taskid, _("An error occurred while deleting the files"))
|
Download a file or a directory
|
def action_download(self, courseid, taskid, path):
""" Download a file or a directory """
wanted_path = self.verify_path(courseid, taskid, path)
if wanted_path is None:
raise web.notfound()
task_fs = self.task_factory.get_task_fs(courseid, taskid)
(method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path)
if method == "local":
web.header('Content-Type', mimetype_or_none)
return file_or_url
elif method == "url":
raise web.redirect(file_or_url)
else:
raise web.notfound()
|
Load JSON or YAML depending on the file extension. Returns a dict
|
def load_json_or_yaml(file_path):
""" Load JSON or YAML depending on the file extension. Returns a dict """
with open(file_path, "r") as f:
if os.path.splitext(file_path)[1] == ".json":
return json.load(f)
else:
return inginious.common.custom_yaml.load(f)
|
Load JSON or YAML depending on the file extension. Returns a dict
|
def loads_json_or_yaml(file_path, content):
""" Load JSON or YAML depending on the file extension. Returns a dict """
if os.path.splitext(file_path)[1] == ".json":
return json.loads(content)
else:
return inginious.common.custom_yaml.load(content)
|
Write JSON or YAML depending on the file extension.
|
def write_json_or_yaml(file_path, content):
""" Write JSON or YAML depending on the file extension. """
with codecs.open(file_path, "w", "utf-8") as f:
f.write(get_json_or_yaml(file_path, content))
|
Generate JSON or YAML depending on the file extension.
|
def get_json_or_yaml(file_path, content):
""" Generate JSON or YAML depending on the file extension. """
if os.path.splitext(file_path)[1] == ".json":
return json.dumps(content, sort_keys=False, indent=4, separators=(',', ': '))
else:
return inginious.common.custom_yaml.dump(content)
|
:param fileobj: a file object
:return: a hash of the file content
|
def hash_file(fileobj):
"""
:param fileobj: a file object
:return: a hash of the file content
"""
hasher = hashlib.md5()
buf = fileobj.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = fileobj.read(65536)
return hasher.hexdigest()
|
:param directory: directory in which the function list the files
:return: dict in the form {file: (hash of the file, stat of the file)}
|
def directory_content_with_hash(directory):
"""
:param directory: directory in which the function list the files
:return: dict in the form {file: (hash of the file, stat of the file)}
"""
output = {}
for root, _, filenames in os.walk(directory):
for filename in filenames:
p = os.path.join(root, filename)
file_stat = os.stat(p)
with open(p, 'rb') as f:
output[os.path.relpath(p, directory)] = (hash_file(f), file_stat.st_mode)
return output
|
:param from_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash
:param to_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash
:return: a tuple containing two list: the files that should be uploaded to "to_directory" and the files that should be removed from "to_directory"
|
def directory_compare_from_hash(from_directory, to_directory):
"""
:param from_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash
:param to_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash
:return: a tuple containing two list: the files that should be uploaded to "to_directory" and the files that should be removed from "to_directory"
"""
from_directory = dict([(os.path.normpath(path), (filehash, stat)) for path, (filehash, stat) in from_directory.items()])
to_directory = dict([(os.path.normpath(path), (filehash, stat)) for path, (filehash, stat) in to_directory.items()])
to_upload = []
to_delete = []
for path, (filehash, stat) in from_directory.items():
if not path in to_directory or to_directory[path] != (filehash, stat):
to_upload.append(path)
for path in to_directory:
if path not in from_directory:
to_delete.append(path)
return (to_upload, to_delete)
|
Init the session. Preserves potential LTI information.
|
def _set_session(self, username, realname, email, language):
""" Init the session. Preserves potential LTI information. """
self._session.loggedin = True
self._session.email = email
self._session.username = username
self._session.realname = realname
self._session.language = language
self._session.token = None
if "lti" not in self._session:
self._session.lti = None
|
Destroy the session
|
def _destroy_session(self):
""" Destroy the session """
self._session.loggedin = False
self._session.email = None
self._session.username = None
self._session.realname = None
self._session.token = None
self._session.lti = None
|
Creates an LTI cookieless session. Returns the new session id
|
def create_lti_session(self, user_id, roles, realname, email, course_id, task_id, consumer_key, outcome_service_url,
outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label):
""" Creates an LTI cookieless session. Returns the new session id"""
self._destroy_session() # don't forget to destroy the current session (cleans the threaded dict from web.py)
self._session.load('') # creates a new cookieless session
session_id = self._session.session_id
self._session.lti = {
"email": email,
"username": user_id,
"realname": realname,
"roles": roles,
"task": (course_id, task_id),
"outcome_service_url": outcome_service_url,
"outcome_result_id": outcome_result_id,
"consumer_key": consumer_key,
"context_title": context_title,
"context_label": context_label,
"tool_description": tool_desc,
"tool_name": tool_name,
"tool_url": tool_url
}
return session_id
|
Authenticate the user in database
:param username: Username/Login
:param password: User password
:return: Returns a dict represrnting the user
|
def auth_user(self, username, password):
"""
Authenticate the user in database
:param username: Username/Login
:param password: User password
:return: Returns a dict represrnting the user
"""
password_hash = hashlib.sha512(password.encode("utf-8")).hexdigest()
user = self._database.users.find_one(
{"username": username, "password": password_hash, "activate": {"$exists": False}})
return user if user is not None and self.connect_user(username, user["realname"], user["email"], user["language"]) else None
|
Opens a session for the user
:param username: Username
:param realname: User real name
:param email: User email
|
def connect_user(self, username, realname, email, language):
"""
Opens a session for the user
:param username: Username
:param realname: User real name
:param email: User email
"""
self._database.users.update_one({"email": email}, {"$set": {"realname": realname, "username": username, "language": language}},
upsert=True)
self._logger.info("User %s connected - %s - %s - %s", username, realname, email, web.ctx.ip)
self._set_session(username, realname, email, language)
return True
|
Disconnects the user currently logged-in
:param ip_addr: the ip address of the client, that will be logged
|
def disconnect_user(self):
"""
Disconnects the user currently logged-in
:param ip_addr: the ip address of the client, that will be logged
"""
if self.session_logged_in():
self._logger.info("User %s disconnected - %s - %s - %s", self.session_username(), self.session_realname(), self.session_email(), web.ctx.ip)
self._destroy_session()
|
:param usernames: a list of usernames
:return: a dict, in the form {username: val}, where val is either None if the user cannot be found, or a tuple (realname, email)
|
def get_users_info(self, usernames):
"""
:param usernames: a list of usernames
:return: a dict, in the form {username: val}, where val is either None if the user cannot be found, or a tuple (realname, email)
"""
retval = {username: None for username in usernames}
remaining_users = usernames
infos = self._database.users.find({"username": {"$in": remaining_users}})
for info in infos:
retval[info["username"]] = (info["realname"], info["email"])
return retval
|
Get the API key of a given user.
API keys are generated on demand.
:param username:
:param create: Create the API key if none exists yet
:return: the API key assigned to the user, or None if none exists and create is False.
|
def get_user_api_key(self, username, create=True):
"""
Get the API key of a given user.
API keys are generated on demand.
:param username:
:param create: Create the API key if none exists yet
:return: the API key assigned to the user, or None if none exists and create is False.
"""
retval = self._database.users.find_one({"username": username}, {"apikey": 1})
if "apikey" not in retval and create:
apikey = self.generate_api_key()
self._database.users.update_one({"username": username}, {"$set": {"apikey": apikey}})
elif "apikey" not in retval:
apikey = None
else:
apikey = retval["apikey"]
return apikey
|
:param username:
:return: a tuple (realname, email) if the user can be found, None else
|
def get_user_info(self, username):
"""
:param username:
:return: a tuple (realname, email) if the user can be found, None else
"""
info = self.get_users_info([username])
return info[username] if info is not None else None
|
:param username: List of username for which we want info. If usernames is None, data from all users will be returned.
:param course: A Course object
:return:
Returns data of the specified users for a specific course. users is a list of username.
The returned value is a dict:
::
{"username": {"task_tried": 0, "total_tries": 0, "task_succeeded": 0, "task_grades":{"task_1": 100.0, "task_2": 0.0, ...}}}
Note that only the task already seen at least one time will be present in the dict task_grades.
|
def get_course_caches(self, usernames, course):
"""
:param username: List of username for which we want info. If usernames is None, data from all users will be returned.
:param course: A Course object
:return:
Returns data of the specified users for a specific course. users is a list of username.
The returned value is a dict:
::
{"username": {"task_tried": 0, "total_tries": 0, "task_succeeded": 0, "task_grades":{"task_1": 100.0, "task_2": 0.0, ...}}}
Note that only the task already seen at least one time will be present in the dict task_grades.
"""
match = {"courseid": course.get_id()}
if usernames is not None:
match["username"] = {"$in": usernames}
tasks = course.get_tasks()
taskids = tasks.keys()
match["taskid"] = {"$in": list(taskids)}
data = list(self._database.user_tasks.aggregate(
[
{"$match": match},
{"$group": {
"_id": "$username",
"task_tried": {"$sum": {"$cond": [{"$ne": ["$tried", 0]}, 1, 0]}},
"total_tries": {"$sum": "$tried"},
"task_succeeded": {"$addToSet": {"$cond": ["$succeeded", "$taskid", False]}},
"task_grades": {"$addToSet": {"taskid": "$taskid", "grade": "$grade"}}
}}
]))
student_visible_taskids = [taskid for taskid, task in tasks.items() if task.get_accessible_time().after_start()]
course_staff = course.get_staff()
retval = {username: {"task_succeeded": 0, "task_grades": [], "grade": 0} for username in usernames}
for result in data:
username = result["_id"]
visible_tasks = student_visible_taskids if username not in course_staff else taskids
result["task_succeeded"] = len(set(result["task_succeeded"]).intersection(visible_tasks))
result["task_grades"] = {dg["taskid"]: dg["grade"] for dg in result["task_grades"] if dg["taskid"] in visible_tasks}
total_weight = 0
grade = 0
for task_id in visible_tasks:
total_weight += tasks[task_id].get_grading_weight()
grade += result["task_grades"].get(task_id, 0.0) * tasks[task_id].get_grading_weight()
result["grade"] = round(grade / total_weight) if total_weight > 0 else 0
retval[username] = result
return retval
|
Shorthand for get_task_caches([username], courseid, taskid)[username]
|
def get_task_cache(self, username, courseid, taskid):
"""
Shorthand for get_task_caches([username], courseid, taskid)[username]
"""
return self.get_task_caches([username], courseid, taskid)[username]
|
:param usernames: List of username for which we want info. If usernames is None, data from all users will be returned.
:param courseid: the course id
:param taskid: the task id
:return: A dict in the form:
::
{
"username": {
"courseid": courseid,
"taskid": taskid,
"tried": 0,
"succeeded": False,
"grade": 0.0
}
}
|
def get_task_caches(self, usernames, courseid, taskid):
"""
:param usernames: List of username for which we want info. If usernames is None, data from all users will be returned.
:param courseid: the course id
:param taskid: the task id
:return: A dict in the form:
::
{
"username": {
"courseid": courseid,
"taskid": taskid,
"tried": 0,
"succeeded": False,
"grade": 0.0
}
}
"""
match = {"courseid": courseid, "taskid": taskid}
if usernames is not None:
match["username"] = {"$in": usernames}
data = self._database.user_tasks.find(match)
retval = {username: None for username in usernames}
for result in data:
username = result["username"]
del result["username"]
del result["_id"]
retval[username] = result
return retval
|
Set in the database that the user has viewed this task
|
def user_saw_task(self, username, courseid, taskid):
""" Set in the database that the user has viewed this task """
self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid},
{"$setOnInsert": {"username": username, "courseid": courseid, "taskid": taskid,
"tried": 0, "succeeded": False, "grade": 0.0, "submissionid": None, "state": ""}},
upsert=True)
|
Update stats with a new submission
|
def update_user_stats(self, username, task, submission, result_str, grade, state, newsub):
""" Update stats with a new submission """
self.user_saw_task(username, submission["courseid"], submission["taskid"])
if newsub:
old_submission = self._database.user_tasks.find_one_and_update(
{"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$inc": {"tried": 1, "tokens.amount": 1}})
# Check if the submission is the default download
set_default = task.get_evaluate() == 'last' or \
(task.get_evaluate() == 'student' and old_submission is None) or \
(task.get_evaluate() == 'best' and old_submission.get('grade', 0.0) <= grade)
if set_default:
self._database.user_tasks.find_one_and_update(
{"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
{"$set": {"succeeded": result_str == "success", "grade": grade, "state": state, "submissionid": submission['_id']}})
else:
old_submission = self._database.user_tasks.find_one(
{"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]})
if task.get_evaluate() == 'best': # if best, update cache consequently (with best submission)
def_sub = list(self._database.submissions.find({
"username": username, "courseid": task.get_course_id(),
"taskid": task.get_id(), "status": "done"}
).sort([("grade", pymongo.DESCENDING), ("submitted_on", pymongo.DESCENDING)]).limit(1))
if len(def_sub) > 0:
self._database.user_tasks.find_one_and_update(
{"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
{"$set": {
"succeeded": def_sub[0]["result"] == "success",
"grade": def_sub[0]["grade"],
"state": def_sub[0]["state"],
"submissionid": def_sub[0]['_id']
}})
elif old_submission["submissionid"] == submission["_id"]: # otherwise, update cache if needed
self._database.user_tasks.find_one_and_update(
{"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
{"$set": {
"succeeded": submission["result"] == "success",
"grade": submission["grade"],
"state": submission["state"]
}})
|
Returns true if the task is visible by the user
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
- True to indicate the user is in a LTI session
- False to indicate the user is not in a LTI session
- "auto" to enable the check and take the information from the current session
|
def task_is_visible_by_user(self, task, username=None, lti=None):
""" Returns true if the task is visible by the user
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
- True to indicate the user is in a LTI session
- False to indicate the user is not in a LTI session
- "auto" to enable the check and take the information from the current session
"""
if username is None:
username = self.session_username()
return (self.course_is_open_to_user(task.get_course(), username, lti) and task.get_accessible_time().after_start()) or \
self.has_staff_rights_on_course(task.get_course(), username)
|
returns true if the user can submit his work for this task
:param only_check : only checks for 'groups', 'tokens', or None if all checks
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
- True to indicate the user is in a LTI session
- False to indicate the user is not in a LTI session
- "auto" to enable the check and take the information from the current session
|
def task_can_user_submit(self, task, username=None, only_check=None, lti=None):
""" returns true if the user can submit his work for this task
:param only_check : only checks for 'groups', 'tokens', or None if all checks
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
- True to indicate the user is in a LTI session
- False to indicate the user is not in a LTI session
- "auto" to enable the check and take the information from the current session
"""
if username is None:
username = self.session_username()
# Check if course access is ok
course_registered = self.course_is_open_to_user(task.get_course(), username, lti)
# Check if task accessible to user
task_accessible = task.get_accessible_time().is_open()
# User has staff rights ?
staff_right = self.has_staff_rights_on_course(task.get_course(), username)
# Check for group
aggregation = self._database.aggregations.find_one(
{"courseid": task.get_course_id(), "groups.students": self.session_username()},
{"groups": {"$elemMatch": {"students": self.session_username()}}})
if not only_check or only_check == 'groups':
group_filter = (aggregation is not None and task.is_group_task()) or not task.is_group_task()
else:
group_filter = True
students = aggregation["groups"][0]["students"] if (aggregation is not None and task.is_group_task()) else [self.session_username()]
# Check for token availability
enough_tokens = True
timenow = datetime.now()
submission_limit = task.get_submission_limit()
if not only_check or only_check == 'tokens':
if submission_limit == {"amount": -1, "period": -1}:
# no token limits
enough_tokens = True
else:
# select users with a cache for this particular task
user_tasks = list(self._database.user_tasks.find({"courseid": task.get_course_id(),
"taskid": task.get_id(),
"username": {"$in": students}}))
# verify that they all can submit
def check_tokens_for_user_task(user_task):
token_dict = user_task.get("tokens", {"amount": 0, "date": datetime.fromtimestamp(0)})
tokens_ok = token_dict.get("amount", 0) < submission_limit["amount"]
date_limited = submission_limit["period"] > 0
need_reset = token_dict.get("date", datetime.fromtimestamp(0)) < timenow - timedelta(hours=submission_limit["period"])
if date_limited and need_reset:
# time limit for the tokens is reached; reset the tokens
self._database.user_tasks.find_one_and_update(user_task, {"$set": {"tokens": {"amount": 0, "date": datetime.now()}}})
return True
elif tokens_ok:
return True
else:
return False
enough_tokens = reduce(lambda old,user_task: old and check_tokens_for_user_task(user_task), user_tasks, True)
return (course_registered and task_accessible and group_filter and enough_tokens) or staff_right
|
Returns a list of the course aggregations
|
def get_course_aggregations(self, course):
""" Returns a list of the course aggregations"""
return natsorted(list(self._database.aggregations.find({"courseid": course.get_id()})), key=lambda x: x["description"])
|
Returns the classroom whose username belongs to
:param course: a Course object
:param username: The username of the user that we want to register. If None, uses self.session_username()
:return: the classroom description
|
def get_course_user_aggregation(self, course, username=None):
""" Returns the classroom whose username belongs to
:param course: a Course object
:param username: The username of the user that we want to register. If None, uses self.session_username()
:return: the classroom description
"""
if username is None:
username = self.session_username()
return self._database.aggregations.find_one({"courseid": course.get_id(), "students": username})
|
Register a user to the course
:param course: a Course object
:param username: The username of the user that we want to register. If None, uses self.session_username()
:param password: Password for the course. Needed if course.is_password_needed_for_registration() and force != True
:param force: Force registration
:return: True if the registration succeeded, False else
|
def course_register_user(self, course, username=None, password=None, force=False):
"""
Register a user to the course
:param course: a Course object
:param username: The username of the user that we want to register. If None, uses self.session_username()
:param password: Password for the course. Needed if course.is_password_needed_for_registration() and force != True
:param force: Force registration
:return: True if the registration succeeded, False else
"""
if username is None:
username = self.session_username()
user_info = self._database.users.find_one({"username":username})
# Do not continue registering the user in the course if username is empty.
if not username:
return False
if not force:
if not course.is_registration_possible(user_info):
return False
if course.is_password_needed_for_registration() and course.get_registration_password() != password:
return False
if self.course_is_user_registered(course, username):
return False # already registered?
aggregation = self._database.aggregations.find_one({"courseid": course.get_id(), "default": True})
if aggregation is None:
self._database.aggregations.insert({"courseid": course.get_id(), "description": "Default classroom",
"students": [username], "tutors": [], "groups": [], "default": True})
else:
self._database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True},
{"$push": {"students": username}})
self._logger.info("User %s registered to course %s", username, course.get_id())
return True
|
Unregister a user to the course
:param course: a Course object
:param username: The username of the user that we want to unregister. If None, uses self.session_username()
|
def course_unregister_user(self, course, username=None):
"""
Unregister a user to the course
:param course: a Course object
:param username: The username of the user that we want to unregister. If None, uses self.session_username()
"""
if username is None:
username = self.session_username()
# Needed if user belongs to a group
self._database.aggregations.find_one_and_update(
{"courseid": course.get_id(), "groups.students": username},
{"$pull": {"groups.$.students": username, "students": username}})
# If user doesn't belong to a group, will ensure correct deletion
self._database.aggregations.find_one_and_update(
{"courseid": course.get_id(), "students": username},
{"$pull": {"students": username}})
self._logger.info("User %s unregistered from course %s", username, course.get_id())
|
Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
- True to indicate the user is in a LTI session
- False to indicate the user is not in a LTI session
- "auto" to enable the check and take the information from the current session
:return: True if the user can access the course, False else
|
def course_is_open_to_user(self, course, username=None, lti=None):
"""
Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user is currently in a LTI session or not.
- None to ignore the check
- True to indicate the user is in a LTI session
- False to indicate the user is not in a LTI session
- "auto" to enable the check and take the information from the current session
:return: True if the user can access the course, False else
"""
if username is None:
username = self.session_username()
if lti == "auto":
lti = self.session_lti_info() is not None
if self.has_staff_rights_on_course(course, username):
return True
if not course.get_accessibility().is_open() or (not self.course_is_user_registered(course, username) and not course.allow_preview()):
return False
if lti and course.is_lti() != lti:
return False
if lti is False and course.is_lti():
return not course.lti_send_back_grade()
return True
|
Checks if a user is registered
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:return: True if the user is registered, False else
|
def course_is_user_registered(self, course, username=None):
"""
Checks if a user is registered
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:return: True if the user is registered, False else
"""
if username is None:
username = self.session_username()
if self.has_staff_rights_on_course(course, username):
return True
return self._database.aggregations.find_one({"students": username, "courseid": course.get_id()}) is not None
|
Get all the users registered to a course
:param course: a Course object
:param with_admins: include admins?
:return: a list of usernames that are registered to the course
|
def get_course_registered_users(self, course, with_admins=True):
"""
Get all the users registered to a course
:param course: a Course object
:param with_admins: include admins?
:return: a list of usernames that are registered to the course
"""
l = [entry['students'] for entry in list(self._database.aggregations.aggregate([
{"$match": {"courseid": course.get_id()}},
{"$unwind": "$students"},
{"$project": {"_id": 0, "students": 1}}
]))]
if with_admins:
return list(set(l + course.get_staff()))
else:
return l
|
:param username: the username. If None, the username of the currently logged in user is taken
:return: True if the user is superadmin, False else
|
def user_is_superadmin(self, username=None):
"""
:param username: the username. If None, the username of the currently logged in user is taken
:return: True if the user is superadmin, False else
"""
if username is None:
username = self.session_username()
return username in self._superadmins
|
Check if a user can be considered as having admin rights for a course
:type course: webapp.custom.courses.WebAppCourse
:param username: the username. If None, the username of the currently logged in user is taken
:param include_superadmins: Boolean indicating if superadmins should be taken into account
:return: True if the user has admin rights, False else
|
def has_admin_rights_on_course(self, course, username=None, include_superadmins=True):
"""
Check if a user can be considered as having admin rights for a course
:type course: webapp.custom.courses.WebAppCourse
:param username: the username. If None, the username of the currently logged in user is taken
:param include_superadmins: Boolean indicating if superadmins should be taken into account
:return: True if the user has admin rights, False else
"""
if username is None:
username = self.session_username()
return (username in course.get_admins()) or (include_superadmins and self.user_is_superadmin(username))
|
Check if a user can be considered as having staff rights for a course
:type course: webapp.custom.courses.WebAppCourse
:param username: the username. If None, the username of the currently logged in user is taken
:param include_superadmins: Boolean indicating if superadmins should be taken into account
:return: True if the user has staff rights, False else
|
def has_staff_rights_on_course(self, course, username=None, include_superadmins=True):
"""
Check if a user can be considered as having staff rights for a course
:type course: webapp.custom.courses.WebAppCourse
:param username: the username. If None, the username of the currently logged in user is taken
:param include_superadmins: Boolean indicating if superadmins should be taken into account
:return: True if the user has staff rights, False else
"""
if username is None:
username = self.session_username()
return (username in course.get_staff()) or (include_superadmins and self.user_is_superadmin(username))
|
Get the accessible time of this task
|
def get_accessible_time(self, plugin_override=True):
""" Get the accessible time of this task """
vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible)
return vals[0] if len(vals) and plugin_override else self._accessible
|
Returns a string containing the deadline for this task
|
def get_deadline(self):
""" Returns a string containing the deadline for this task """
if self.get_accessible_time().is_always_accessible():
return _("No deadline")
elif self.get_accessible_time().is_never_accessible():
return _("It's too late")
else:
# Prefer to show the soft deadline rather than the hard one
return self.get_accessible_time().get_soft_end_date().strftime("%d/%m/%Y %H:%M:%S")
|
Get the context(description) of this task
|
def get_context(self, language):
""" Get the context(description) of this task """
context = self.gettext(language, self._context) if self._context else ""
vals = self._hook_manager.call_hook('task_context', course=self.get_course(), task=self, default=context)
return ParsableText(vals[0], "rst", self._translations.get(language, gettext.NullTranslations())) if len(vals) \
else ParsableText(context, "rst", self._translations.get(language, gettext.NullTranslations()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.