Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • zesje/zesje
  • jbweston/grader_app
  • dj2k/zesje
  • MrHug/zesje
  • okaaij/zesje
  • tsoud/zesje
  • pimotte/zesje
  • works-on-my-machine/zesje
  • labay11/zesje
  • reouvenassouly/zesje
  • t.v.aerts/zesje
  • giuseppe.deininger/zesje
12 results
Show changes
Commits on Source (2926)
Showing with 660 additions and 307 deletions
{
"presets":[
"react",
"flow"
"@babel/react",
"@babel/flow",
"@babel/preset-env"
],
"plugins": [
"syntax-dynamic-import",
"transform-class-properties",
"transform-object-rest-spread",
"react-hot-loader/babel"
"@babel/syntax-dynamic-import",
"react-hot-loader/babel",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-object-rest-spread"
],
"env": {
"test": {
"presets":[
[ "env",
[ "@babel/preset-env",
{
"modules": "commonjs"
}
]
],
"plugins": [
"transform-class-properties"
"@babel/plugin-proposal-class-properties"
]
}
}
......
cov.html
data
data-dev
node_modules/
*.Dockerfile
[flake8]
max-line-length = 120
exclude = .git, __pycache__, client/, .venv/, node_modules/ # no need to traverse these directories
extend-ignore = E203,W503
\ No newline at end of file
......@@ -58,6 +58,9 @@ typings/
yarn.lock
package-lock.json
# Yarn cache
.yarn/cache
# dotenv environment variables file
.env
......@@ -89,8 +92,23 @@ build/
# development data
data-dev
# test data
tests/data/submissions
# redis dump
dump.rdb
# webpack analyze data
stats.json
# JetBrains IDE folders
.idea/
# pytest coverage reports
.coverage
cov.xml
cov.html/
tests.xml
#test output
junit.xml
# This base image can be found in 'Dockerfile'
image: zesje/base
# This base image can be found in 'test.Dockerfile'
image: $TEST_IMAGE
stages:
- build-env
- build
- test
# Special hidden job that is merged with JS jobs
.node_modules: &node_modules
# Cache the JS modules that yarn fetches
cache:
untracked: true
paths:
- .yarn-cache
variables:
TEST_IMAGE: ${CI_REGISTRY_IMAGE}/test
build-image:
stage: build-env
when: manual
image:
name: gcr.io/kaniko-project/executor:v1.17.0-debug
entrypoint: [""]
before_script:
- yarn install --cache-folder .yarn-cache
- mkdir -p /kaniko/.docker
- echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
script:
- mkdir docker
- cp test.Dockerfile docker/
- cp environment.yml docker/
- cp package.json docker/
- /kaniko/executor
--context $CI_PROJECT_DIR/docker
--dockerfile $CI_PROJECT_DIR/docker/test.Dockerfile
--destination $TEST_IMAGE
--cache=true
.conda-env: &conda-env
before_script:
- ln -s /yarn/* ./
- if [[ $CI_JOB_NAME != *"py"* ]]; then yarn install; fi
build:
<<: *node_modules
<<: *conda-env
stage: build
script:
- python3 -m compileall zesje
......@@ -27,24 +45,49 @@ build:
- zesje/static
expire_in: 1 week
test_js:
<<: *node_modules
stage: test
script: yarn test:js
test_py:
stage: test
script: yarn test:py
# test_js:
# <<: *conda-env
# stage: test
# script:
# - yarn test:js
# artifacts:
# reports:
# junit: junit.xml
lint_js:
<<: *node_modules
<<: *conda-env
stage: test
allow_failure: true
script:
- yarn lint:js
lint_py:
<<: *conda-env
stage: test
allow_failure: true
script:
- yarn lint:py
test_py:
<<: *conda-env
stage: test
services:
- mysql:8.0
variables:
MYSQL_DATABASE: "course_test"
MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
script:
- echo -e "\nMYSQL_HOST = 'mysql'\nMYSQL_USER = 'root'\nMYSQL_PASSWORD = None" >> zesje_test_cfg.py
- yarn test:py:cov
artifacts:
paths:
- cov.html/
reports:
coverage_report:
coverage_format: cobertura
path: cov.xml
junit: tests.xml
expire_in: 1 week
include:
template: Jobs/SAST.gitlab-ci.yml
Hidde Leistra <hleistra@gmail.com>
Stefan Hugtenburg <s.hugtenburg@gmail.com>
Robin Bijl <r.a.bijl@student.tudelft.nl>
Richard van de Kuilen <richardvdk@live.nl>
<richardvdk@live.nl> <rvdk>
Thomas Roos <thomasroos@live.nl>
Timotei Jugariu <timotei96@gmail.com>
......@@ -6,3 +6,25 @@
* Justin van der Krieken
* Jamy Mahabier
* Nick Cleintuar
* Hugo Kerstens
* Stefan Hugtenburg
* Hidde Leistra
* Pim Otte
* Luc Enthoven
* Otto Kaaij
* Lucas Holten
* Robin Bijl
* Ruben Young On
* Timotei Jugariu
* Richard van de Kuilen
<!--
Execute
git shortlog -s | grep -v "\[bot\]" | sed -e "s/^ *[0-9\t ]*//"| xargs -i sh -c 'grep -q "{}" AUTHORS.md || echo "{}"'
To check if any authors are missing from this list.
If you add any new authors that do not specify a correct name
in their commits, please add them to the `.mailmap` file.
-->
FROM archlinux/base
# A Dockerfile containing the production deployment for Zesje
## Install packages and clear the cache after installation. Yarn is fixed at 1.6.0 untill 1.8.0 is released due to a critical bug.
RUN pacman -Sy --noconfirm nodejs python-pip git libdmtx libsm libxrender libxext gcc libmagick6 imagemagick ghostscript; \
pacman -U --noconfirm https://archive.archlinux.org/packages/y/yarn/yarn-1.6.0-1-any.pkg.tar.xz
FROM mambaorg/micromamba:1.5-jammy
WORKDIR ~
ADD requirements*.txt ./
#ADD package.json .
RUN pip install --no-cache-dir -r requirements.txt -r requirements-dev.txt;
#RUN yarn install; \
# yarn cache clean; \
# rm package.json
USER root
CMD bash
\ No newline at end of file
RUN apt-get update && \
apt-get install -y libdmtx-dev && \
apt-get install -y git supervisor nginx cron
COPY --chown=$MAMBA_USER:$MAMBA_USER environment.yml /tmp/env.yaml
USER $MAMBA_USER
RUN micromamba install -y -n base -f /tmp/env.yaml && \
micromamba clean --all --yes
ARG MAMBA_DOCKERFILE_ACTIVATE=1
USER root
WORKDIR /app
ADD . .
RUN yarn install
RUN yarn build
RUN rm -rf node_modules
ENTRYPOINT ["/usr/local/bin/_entrypoint.sh", "/usr/bin/bash"]
[![coverage report](https://gitlab.kwant-project.org/zesje/zesje/badges/master/coverage.svg)](https://gitlab.kwant-project.org/zesje/zesje/commits/master)
# Welcome to Zesje
Zesje is an online grading system for written exams.
## Running Zesje
### Running Zesje using Docker
Running Zesje using Docker is the easiest method to run Zesje
yourself with minimal technical knowledge required. For this approach
we assume that you already have [Docker](https://www.docker.com/)
installed, cloned the Zesje repository and entered its directory.
First create a volume to store the data:
docker volume create zesje
Then build the Docker image using the following below. Anytime you
update Zesje by pulling the repository you have to run this command again.
docker build -f auto.Dockerfile . -t zesje:auto
Finally, you can run the container to start Zesje using:
docker run -p 8881:80 --volume zesje:/app/data-dev -it zesje:auto
Zesje should be available at http://127.0.0.1:8881. If you get
the error `502 - Bad Gateway` it means that Zesje is still starting.
## Development
### Setting up a development environment
*Zesje currently doesn't support native Windows, but WSL works.*
We recommend using the Conda tool for managing your development
environment. If you already have Anaconda or Miniconda installed,
you may skip this step.
......@@ -13,10 +41,11 @@ Install Miniconda by following the instructions on this page:
https://conda.io/miniconda.html
Create a Conda environment that you will use for installing all
of zesje's dependencies:
Make sure you cloned this repository and enter its directory. Then
create a Conda environment that will automatically install all
of zesje's Python dependencies:
conda create -c conda-forge -n zesje-dev python=3.6 yarn
conda env create # Creates an environment from environment.yml
Then, *activate* the conda environment:
......@@ -29,24 +58,30 @@ Install all of the Javascript dependencies:
yarn install
Install all of the Python dependencies:
pip install -r requirements.txt -r requirements-dev.txt
Unfortunately there is also another dependency that must be installed
manually for now (we are working to bring this dependency into the
Conda ecosystem). You can install this dependency in the following way
on different platforms:
| OS | Command |
|---------------|------------------------------|
| macOS | `brew install libdmtx` |
| Debian/Ubuntu | `sudo apt install libdmtx0a` |
| Arch | `pacman -S libdmtx` |
| Fedora | `dnf install libdmtx` |
| openSUSE | `zypper install libdmtx0` |
| Windows | *not necessary* |
| OS | Command |
| -------------- | ------------------------- |
| macOS | `brew install libdmtx` |
| Debian, Ubuntu | `apt install libdmtx-dev` |
| Arch | `pacman -S libdmtx` |
| Fedora | `dnf install libdmtx` |
| openSUSE | `zypper install libdmtx0` |
#### Setting up MySQL server
If this is the first time that you will run Zesje with MySQL in
development, then run the following command from the Zesje
repository directory:
yarn dev:mysql-init
That's all it needs to create the MySQL files in the data directory,
migrate the database to the last schema and move all your previous data.
### Running a development server
......@@ -58,27 +93,106 @@ to start the development server, which you can access on http://127.0.0.1:8881.
It will automatically reload whenever you change any source files in `client/`
or `zesje/`.
### Running Oauth2 Mock Server
By default, login is disabled during development but it can be enabled by setting `LOGIN_DISABLED = False` in
the [development configuration file](./zesje_dev_cfg.py). You can see the set of supported login providers in
[constants.py](./zesje/constants.py) but take into account that for GitLab and Surf Conext you will need to request
for a valid `CLIENT_ID` and `CLIENT_SECRET`.
In case you only want to test the flow, you can set the provider to `mock` and start the
[mock oauth server](./mock_oauth_server.py) in a different terminal from where you
started the development server by running `yarn dev:oauth`.
### Generate sample data
The script `example_data.py` can be used to create a sample exam that mimics the appearance and behavior of a typical grading process in Zesje. The prototype exam consist on 3 open answer questions per page and 1 multiple choice question per page (excluding the first one). The script partially solves those questions and assigns random feedback to the answered questions while the not answered questions are processed as blank.
The script is called from the command line with the following parameters:
- `-d, --delete` If specified, removes any existing data and creates a new empty database. Otherwise, new exams are added without deleting previous data.
- `--exams (int)` the number of exams to add, default is 1.
- `--pages (int)` the number of pages per exam, default is 3.
- `--students (int)` the number of students per exam, default is 30
- `--graders (int)` the number of graders to add, default is 4.
- `--solve (float)` between 0 and 100, indicates the percentage of questions to answer (including MCQ), default is 90%.
- `--grade (float)` between 0 and 100, indicate the percentage of solved questions to grade (that is, excluding blank answers), default is 60%.
- `--skip-processing` if specified, fakes the pdf processing to reduce time. As a drawback, blanks will not be detected.
- `--multiple-copies (float)` between 0 and 100, indicates how much of the students submit multiple copies, default is 5%
The actual processing of the exam takes a while, specially when the number of students is large.
### Running the tests
You can run the tests by running
yarn test
### Building and running the production version
#### Viewing test coverage
As a test coverage tool for Python tests, `pytest-cov` is used.
To view test coverage, run
yarn test:py:cov
A coverage report is now generated in the terminal, as an XML file, and in HTML format.
The HTML file shows an overview of untested code in red.
##### Viewing coverage in Visual Studio Code
There is a plugin called Coverage Gutter that will highlight which lines of code are covered.
Simply install Coverage Gutter, after which a watch button appears in the colored box at the bottom of your IDE.
When you click watch, green and red lines appear next to the line numbers indicating if the code is covered.
Coverage Gutter uses the XML which is produced by `yarn test:py:cov`, called `cov.xml`. This file should be located in the main folder.
##### Viewing coverage in PyCharm
To view test coverage in PyCharm, run `yarn test:py:cov` to generate the coverage report XML file `cov.xml` if it is not present already.
Next, open up PyCharm and in the top bar go to **Run -> Show Code Coverage Data** (Ctrl + Alt + F6).
Press **+** and add the file `cov.xml` that is in the main project directory.
A code coverage report should now appear in the side bar on the right.
#### Policy errors
If you encounter PolicyErrors related to ImageMagick in any of the previous steps, please
try the instructions listed
[here](https://alexvanderbist.com/posts/2018/fixing-imagick-error-unauthorized) as
a first resort.
### Database modifications
Zesje uses Flask-Migrate and Alembic for database versioning and migration. Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic.
To change something in the database schema, simply add this change to `zesje/database.py`. After that run the following command to prepare a new migration:
yarn dev:prepare-migration
This uses Flask-Migrate to make a new migration script in `migrations/versions` which needs to be reviewed and edited. Please suffix the name of this file with something distinctive and add a short description at the top of the file. To apply the database migration run:
yarn dev:mysql-migrate # (for the development database)
yarn migrate # (for the production database, MySQL must be running)
### Building and running the production version
### Code style
#### Python
Adhere to [PEP8](https://www.python.org/dev/peps/pep-0008/), but use a column width of 120 characters (instead of 79).
If you followed the instructions above, the linter `flake8` is installed in your virtual environment. If you use Visual Studio Code, install the [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) extension and add the following lines to your workspace settings:
If you followed the instructions above, the linter `flake8` and the formatter `black` are installed in your virtual environment. If you use Visual Studio Code, install the [Python](https://marketplace.visualstudio.com/items?itemName=ms-python.python) extension and add the following lines to your workspace settings:
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"[python]": {
"editor.rulers": [120]
"editor.rulers": [120],
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true
},
"black-formatter.args": [
"--line-length=120"
]
If you use Atom, install the [linter-flake8](https://atom.io/packages/linter-flake8) plugin and add the following lines to your config:
......@@ -89,18 +203,17 @@ If you use Atom, install the [linter-flake8](https://atom.io/packages/linter-fla
#### Javascript
Adhere to [StandardJS](https://standardjs.com/).
If you use Visual Studio Code, install the [vscode-standardjs](https://marketplace.visualstudio.com/items?itemName=chenxsan.vscode-standardjs) plugin.
If you use Visual Studio Code, install the [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) plugin.
If you use Atom, install the [linter-js-standard-engine](https://atom.io/packages/linter-js-standard-engine) plugin.
If you use Atom, install the [linter-eslint](https://atom.io/packages/linter-eslint) plugin.
### Adding dependencies
#### Server-side
If you start using a new Python library, be sure to add it to `requirements.txt`. Python libraries for the testing are in `requirements-dev.txt`.
The packages can be installed and updated in your environment by `pip` using
pip install -r requirements.txt -r requirements-dev.txt
If you start using a new Python library, be sure to add it to `environment.yml`.
The packages can be installed and updated in your environment by `conda` using
conda env update
#### Client-side
Yarn keeps track of all the client-side dependancies in `package.json` when you install new packages with `yarn add [packageName]`. Yarn will install and update your packages if your run
......
# A Dockerfile containing everything to run Zesje automatically
FROM continuumio/miniconda3
RUN apt-get update -y && apt-get install -y libdmtx-dev nginx sudo
RUN echo "server { listen 80; location / { proxy_pass http://127.0.0.1:5000; } }" > /etc/nginx/sites-enabled/proxy.conf
RUN rm /etc/nginx/sites-enabled/default
RUN groupadd -r zesje && useradd --no-log-init -r -g zesje zesje
RUN echo 'zesje ALL= NOPASSWD: /usr/sbin/service nginx restart,/bin/chown -R zesje\:zesje /app/data-dev' | sudo EDITOR='tee -a' visudo
WORKDIR /app
COPY . /app
RUN conda env create -n zesje-dev
ENV PATH /opt/conda/envs/zesje-dev/bin:$PATH
RUN yarn install
RUN yarn build
USER zesje
VOLUME /app/data-dev
EXPOSE 80
CMD sudo service nginx restart && \
sudo chown -R zesje:zesje /app/data-dev && \
yarn dev:mysql-init && yarn dev:backend
import sys
import os
from io import BytesIO
from reportlab.pdfgen import canvas
import PIL
from wand.image import Image
from wand.color import Color
from pystrich.datamatrix import DataMatrixEncoder
sys.path.append(os.getcwd())
def generate_datamatrix(exam_id, page_num, copy_num):
data = f'{exam_id}/{copy_num:04d}/{page_num:02d}'
from zesje.pdf_generation import generate_datamatrix # noqa: E402
from zesje.database import token_length # noqa: E402
image_bytes = DataMatrixEncoder(data).get_imagedata(cellsize=2)
return PIL.Image.open(BytesIO(image_bytes))
exam_token = "A" * token_length
copy_num = 1559
page_num = 0
datamatrix = generate_datamatrix(0, 0, 0)
datamatrix_x = datamatrix_y = 0
fontsize = 8
margin = 3
fontsize = 12
datamatrix_x = 0
datamatrix_y = fontsize
datamatrix = generate_datamatrix(0, 0, 0000)
imagesize = (datamatrix.width, 3 + fontsize + datamatrix.height)
datamatrix = generate_datamatrix(exam_token, page_num, copy_num)
imagesize = (datamatrix.width, fontsize + datamatrix.height)
result_pdf = BytesIO()
canv = canvas.Canvas(result_pdf, pagesize=imagesize)
canv.drawInlineImage(datamatrix, 0, 3 + fontsize)
canv.drawInlineImage(datamatrix, datamatrix_x, datamatrix_y)
canv.setFont('Helvetica', fontsize)
canv.drawString(0, 3, f" # 1519")
canv.setFont("Helvetica", fontsize)
canv.drawString(datamatrix_x, datamatrix_y - (fontsize * 0.66), f" # {copy_num}")
canv.showPage()
canv.save()
......@@ -36,7 +37,7 @@ canv.save()
result_pdf.seek(0)
# From https://stackoverflow.com/questions/27826854/python-wand-convert-pdf-to-png-disable-transparent-alpha-channel
with Image(file=result_pdf, resolution=80) as img:
with Image(width=img.width, height=img.height, background=Color("white")) as bg:
with Image(file=result_pdf, resolution=72) as img:
with Image(width=imagesize[0], height=imagesize[1], background=Color("white")) as bg:
bg.composite(img, 0, 0)
bg.save(filename="client/components/barcode_example.png")
import React from 'react'
import Loadable from 'react-loadable'
import loadable from '@loadable/component'
import { hot } from 'react-hot-loader'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import 'bulma/css/bulma.css'
import 'react-bulma-notification/build/css/index.css'
import 'font-awesome/css/font-awesome.css'
import { BrowserRouter as Router, Route, Routes, Navigate, Outlet, useLocation } from 'react-router-dom'
import './App.scss'
import * as api from './api.jsx'
import NavBar from './components/NavBar.jsx'
import ExamRouter from './components/ExamRouter.jsx'
import Footer from './components/Footer.jsx'
import Loading from './views/Loading.jsx'
import HelpModal, { HELP_PAGES } from './components/modals/HelpModal.jsx'
const Home = Loadable({
loader: () => import('./views/Home.jsx'),
loading: Loading
})
const AddExam = Loadable({
loader: () => import('./views/AddExam.jsx'),
loading: Loading
})
const Exam = Loadable({
loader: () => import('./views/Exam.jsx'),
loading: Loading
})
const Submissions = Loadable({
loader: () => import('./views/Submissions.jsx'),
loading: Loading
})
const Students = Loadable({
loader: () => import('./views/Students.jsx'),
loading: Loading
})
const Grade = Loadable({
loader: () => import('./views/Grade.jsx'),
loading: Loading
})
const Graders = Loadable({
loader: () => import('./views/Graders.jsx'),
loading: Loading
})
const Overview = Loadable({
loader: () => import('./views/Overview.jsx'),
loading: Loading
})
const Email = Loadable({
loader: () => import('./views/Email.jsx'),
loading: Loading
})
const Fail = Loadable({
loader: () => import('./views/Fail.jsx'),
loading: Loading
})
const Login = loadable(() => import('./views/Login.jsx'), { fallback: <Loading /> })
const Home = loadable(() => import('./views/Home.jsx'), { fallback: <Loading /> })
const AddExam = loadable(() => import('./views/AddExam.jsx'), { fallback: <Loading /> })
const Graders = loadable(() => import('./views/Graders.jsx'), { fallback: <Loading /> })
const Fail = loadable(() => import('./views/Fail.jsx'), { fallback: <Loading /> })
const nullExam = () => ({
id: null,
name: '',
submissions: [],
problems: [],
widgets: []
})
const NavBarView = (props) => {
const location = useLocation()
class App extends React.Component {
menu = React.createRef();
return props.grader == null
? <Navigate to={{ pathname: '/login', search: `from=${location.pathname}` }} state={{ from: location }} replace />
: <div>
<NavBar
logout={props.logout}
ref={props.menu}
grader={props.grader}
examID={props.examID}
setHelpPage={props.setHelpPage} />
<section className='section'>
<div className='container is-fluid'>
<Outlet />
</div>
</section>
<HelpModal
page={HELP_PAGES[props.helpPage] || { content: null, title: null }}
closeHelp={() => props.setHelpPage({ helpPage: null })}
/>
<Footer />
</div>
}
class App extends React.Component {
state = {
exam: nullExam(),
grader: null
examID: null,
/*
* The id of the current user. An undefined user means that the App has not check the backend for the registrered
* user yet, hence wait for the response before going to the desired url by showing a Home/Welcome screen.
* Instead, a null user means that is not logged in, then go to the Home page through the router.
*/
grader: undefined,
helpPage: null
}
updateExam = (examID) => {
if (examID === null) {
this.setState({ exam: nullExam() })
} else {
api.get('exams/' + examID)
.catch(resp => this.setState({ exam: nullExam() }))
.then(ex => this.setState({ exam: ex }))
}
constructor (props) {
super(props)
this.menu = React.createRef()
}
deleteExam = (examID) => {
return api
.del('exams/' + examID)
.then(() => {
if (this.menu.current) {
this.menu.current.updateExamList()
}
componentDidMount = () => {
api.get('oauth/status').then(status => {
this.setState({
grader: status.grader,
loginProvider: status.provider
})
}
updateSubmission = (index, sub) => {
if (index === undefined) {
api.get('submissions/' + this.state.exam.id)
.then(subs => this.setState({
exam: {
...this.state.exam,
submissions: subs
}
}))
} else {
if (sub) {
if (JSON.stringify(sub) !== JSON.stringify(this.state.exam.submissions[index])) {
let newList = this.state.exam.submissions
newList[index] = sub
this.setState({
exam: {
...this.state.exam,
submissions: newList
}
})
}
}).catch(err => {
if (err.status === 401) {
this.setState({
grader: null,
loginProvider: err.provider
})
} else {
api.get('submissions/' + this.state.exam.id + '/' + this.state.exam.submissions[index].id)
.then(sub => {
if (JSON.stringify(sub) !== JSON.stringify(this.state.exam.submissions[index])) {
let newList = this.state.exam.submissions
newList[index] = sub
this.setState({
exam: {
...this.state.exam,
submissions: newList
}
})
}
})
console.log(err)
}
}
})
}
changeGrader = (grader) => {
this.setState({
grader: grader
})
window.sessionStorage.setItem('graderID', grader.id)
selectExam = (id) => this.setState({ examID: parseInt(id) })
logout = () => api.get('oauth/logout').then(() => this.setState({ grader: null }))
setHelpPage = (helpPage) => this.setState({ helpPage })
updateExamList = () => {
if (this.menu.current) {
this.menu.current.updateExamList()
}
}
render () {
const exam = this.state.exam
const grader = this.state.grader
if (this.state.grader === undefined) return <Loading />
return (
<Router>
<div>
<NavBar exam={exam} updateExam={this.updateExam} grader={grader} changeGrader={this.changeGrader} ref={this.menu} />
<Switch>
<Route exact path='/' component={Home} />
<Route path='/exams/:examID' render={({ match, history }) =>
<Exam
exam={exam}
examID={match.params.examID}
updateExam={this.updateExam}
deleteExam={this.deleteExam}
updateSubmission={this.updateSubmission}
leave={() => history.push('/')} />} />
<Route path='/exams' render={({ history }) =>
<AddExam updateExamList={this.menu.current ? this.menu.current.updateExamList : null} changeURL={history.push} />} />
<Route path='/submissions/:examID' render={({ match }) =>
<Submissions
exam={exam}
urlID={match.params.examID}
updateExam={this.updateExam}
updateSubmission={this.updateSubmission} />} />
<Route path='/students' render={() =>
<Students exam={exam} updateSubmission={this.updateSubmission} />} />
<Route path='/grade' render={() => (
exam.submissions.length && grader
? <Grade exam={exam} graderID={this.state.grader.id}
updateSubmission={this.updateSubmission} updateExam={this.updateExam} />
: <Fail message='No exams uploaded or no grader selected. Please do not bookmark URLs' />
)} />
<Route path='/overview' render={() => (
exam.submissions.length ? <Overview exam={exam} /> : <Fail message='No exams uploaded. Please do not bookmark URLs' />
)} />
<Route path='/email' render={() => (
exam.submissions.length ? <Email exam={exam} /> : <Fail message='No exams uploaded. Please do not bookmark URLs' />
)} />
<Route path='/graders' render={() =>
<Graders updateGraderList={this.menu.current ? this.menu.current.updateGraderList : null} />} />
<Route render={() =>
<Fail message="404. Could not find that page :'(" />} />
</Switch>
<Footer />
</div>
<Routes>
<Route path='login' element={
<Login provider={this.state.loginProvider} grader={this.state.grader} />
} />
<Route path='unauthorized' element={
<Fail message='Your account is not authorized to access this instance of Zesje.' />
}/>
<Route path='*' element={<Fail message="404. Could not find that page :'(" />}/>
<Route path='/' element={
<NavBarView
logout={this.logout}
menu={this.menu}
grader={this.state.grader}
examID={this.state.examID}
setHelpPage={this.setHelpPage}
helpPage={this.state.helpPage} />
}>
<Route index element={<Home />} />
<Route path='exams' element={<Outlet />}>
<Route index element={<AddExam updateExamList={this.updateExamList}/>} />
<Route path=':examID/*' element={
<ExamRouter
selectExam={this.selectExam}
updateExamList={this.updateExamList}
setHelpPage={this.setHelpPage}
/>}
/>
</Route>
<Route path='graders' element={<Graders />} />
</Route>
</Routes>
</Router>
)
}
......
@charset "utf-8";
/* Bulma Switch Control */
@import "~bulma-switch-control/bulma-switch-control";
@import 'bulma-popover/bulma-popover';
@import "bulma/bulma";
$fa-font-path: "~@fortawesome/fontawesome-free/webfonts";
@import "@fortawesome/fontawesome-free/scss/fontawesome";
@import "@fortawesome/fontawesome-free/scss/solid";
@import '@creativebulma/bulma-tooltip/dist/bulma-tooltip.min.css';
.dropzone {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
border-width: 2px;
border-radius: 2px;
border-color: $info;
border-style: dashed;
background-color: #fafafa;
color: $info;
outline: none;
transition: border .24s ease-in-out;
}
.dropzone:focus {
border-color: #2196f3;
}
.dropzone.disabled {
border-color: #eeeeee;
color: #bdbdbd;
opacity: 0.6;
}
.tag.is-circular {
border-radius: 50%;
border-color: $link;
}
.tag.is-circular.is-danger {
border-radius: 50%;
border-color: $danger;
}
.tag.is-squared {
border-radius: 2px;
border-color: $link;
}
// close navbar dropdown automatically
// extracted from: https://github.com/jgthms/bulma/issues/2514#issuecomment-510451361
@media screen and (min-width: 1025px) {
.navbar-item.is-hoverable:hover .navbar-dropdown {
display: block !important;
}
.navbar-item.is-hoverable:focus-within .navbar-dropdown {
display: none;
}
}
.has-tooltip-hidden {
&:after, &:before {
opacity: 0 !important;
display: none !important;
}
}
/* Class that manually sets the z-index of sticky objects with a modal as a child.
Required since the model will inherit the z-index of sticky parents. */
.is-sticky.has-modal {
z-index: 40;
}
......@@ -7,29 +7,31 @@ function _typeof (a) {
function _fetch (method) {
return (endpoint, data) => {
var headers = new window.Headers()
const headers = new window.Headers()
if (_typeof(data) === 'Object') {
headers.append('Content-Type', 'application/json')
data = JSON.stringify(data)
}
return window.fetch('/api/' + endpoint, {
method: method,
method,
credentials: 'same-origin',
body: data,
headers: headers
headers
})
.catch(error =>
console.error('Error: ', error, ' in', method, endpoint, 'with data', data))
.catch(error => console.error('Error: ', error, ' in', method, endpoint, 'with data', data))
.then(resp => {
if (!resp.ok) {
throw resp
} else {
return resp
}
if (!resp.json) throw resp
return resp.json().then(json => {
if (resp.ok) {
return json
} else {
console.error(json)
return Promise.reject(json)
}
})
})
// valid responses always return JSON
.then(r => r.json())
}
}
......
import React from 'react'
class ColorInput extends React.Component {
state = {
editing: true
}
onStartEditing = () => this.setState({ editing: true })
onFinishEditing = () => this.setState({ editing: false })
inputColor = (value) => {
if (this.state.editing) {
return ''
} else if (value) {
return 'is-success'
} else {
return 'is-danger'
}
}
render () {
return (
<input
className={'input ' + this.inputColor(this.props.value)}
onFocus={this.onStartEditing}
onBlur={this.onFinishEditing}
{...this.props}
/>
)
}
}
export default ColorInput
import React from 'react'
const DropzoneContent = () => (
<div className='file has-name is-boxed is-centered'>
<label className='file-label'>
<span className='file-cta'>
<span className='file-icon'>
<i className='fa fa-upload' />
</span>
<span className='file-label'>
Choose a file…
</span>
</span>
</label>
</div>
)
export default DropzoneContent
import React from 'react'
const EmptyPDF = (props) => {
let width
let height
switch (props.format) {
case 'a4':
case 'A4':
default:
width = 595
height = 841
}
return (
<div
style={{
paddingTop: '4rem',
minWidth: (width) + 'px',
minHeight: (height) + 'px',
backgroundColor: 'white'
}}
className={'has-text-centered'}
>
<i className={'fa fa-refresh fa-spin'} />
</div>
)
}
export default EmptyPDF
import React from 'react'
import { Route, Routes, Outlet } from 'react-router-dom'
import loadable from '@loadable/component'
import withRouter from './RouterBinder.jsx'
import * as api from '../api.jsx'
import Loading from '../views/Loading.jsx'
const Exam = loadable(() => import('../views/Exam.jsx'), { fallback: <Loading /> })
const Scans = loadable(() => import('../views/Scans.jsx'), { fallback: <Loading /> })
const Students = loadable(() => import('../views/Students.jsx'), { fallback: <Loading /> })
const Grade = loadable(() => import('../views/Grade.jsx'), { fallback: <Loading /> })
const Overview = loadable(() => import('../views/Overview.jsx'), { fallback: <Loading /> })
const Email = loadable(() => import('../views/Email.jsx'), { fallback: <Loading /> })
const Fail = loadable(() => import('../views/Fail.jsx'), { fallback: <Loading /> })
class ExamRouter extends React.PureComponent {
componentDidMount = () => {
this.props.selectExam(this.props.router.params.examID)
}
componentDidUpdate = (prevProps, prevState) => {
const { examID } = this.props.router.params
if (prevProps.router.params.examID !== examID) {
// sends the selected exam to the navbar
this.props.selectExam(examID)
}
}
deleteExam = (examID) => {
return api
.del('exams/' + examID)
.then(() => {
this.props.updateExamList()
this.props.router.navigate('/', { replace: true })
})
}
render = () => {
const { examID } = this.props.router.params
if (!examID || isNaN(examID)) {
return <Fail message='Invalid exam' />
}
return (
<Routes>
<Route
path='scans' element={<Scans examID={examID} />}
/>
<Route
path='students' element={<Students examID={examID} />}
>
<Route path=':copyNumber' element={<Outlet />} />
</Route>
<Route
path='grade' element={<Grade examID={examID} />}
>
<Route path=':submissionID' element={<Outlet />} />
<Route path=':submissionID/:problemID' element={<Outlet />} />
</Route>
<Route
path='overview' element={<Overview examID={examID} />}
/>
<Route
path='email' element={<Email examID={examID} />}
/>
<Route
path='/' element={
<Exam
examID={examID}
updateExamList={this.props.updateExamList}
deleteExam={this.deleteExam}
setHelpPage={this.props.setHelpPage}
/>}
/>
</Routes>
)
}
}
export default withRouter(ExamRouter)
import React from 'react'
const Hero = (props) => {
const Footer = (props) => {
return (
<footer className='footer'>
<div className='container'>
<div className='content has-text-centered'>
<p>
<strong>Zesje</strong> by <a href='https://gitlab.kwant-project.org/zesje/zesje/blob/master/AUTHORS.md' target='_blank'>the team</a>.
The code is licensed under <a href='https://choosealicense.com/licenses/agpl-3.0/' target='_blank'> AGPLv3 </a>
and available <a href='https://gitlab.kwant-project.org/zesje/zesje/' target='_blank'>here</a>.
<strong>Zesje</strong> by
<a
href='https://gitlab.kwant-project.org/zesje/zesje/blob/master/AUTHORS.md'
target='_blank'
rel="noreferrer"
> the team
</a>.
The code is licensed under
<a href='https://choosealicense.com/licenses/agpl-3.0/' target='_blank' rel="noreferrer"> AGPLv3 </a>
and available
<a href='https://gitlab.kwant-project.org/zesje/zesje/' target='_blank' rel="noreferrer"> here</a>.
<br />
Version {__ZESJE_VERSION__}
</p>
</div>
</div>
......@@ -16,4 +26,4 @@ const Hero = (props) => {
)
}
export default Hero
export default Footer
import React from 'react'
import EmptyPDF from '../components/EmptyPDF.jsx'
import { LoadingPDF, ErrorPDF } from '../components/PDFPlaceholders.jsx'
import { Document, Page } from 'react-pdf/dist/entry.webpack'
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5'
class GeneratedExamPreview extends React.Component {
render = () => {
......@@ -9,13 +9,15 @@ class GeneratedExamPreview extends React.Component {
<Document
file={'/api/exams/' + this.props.examID + '/preview'}
onLoadSuccess={this.props.onPDFLoad}
loading={<EmptyPDF />}
noData={<EmptyPDF />}
loading={<LoadingPDF />}
error={<ErrorPDF />}
noData={<ErrorPDF text='No PDF file specified.' />}
>
<Page
renderAnnotations={false}
renderTextLayer={false}
pageIndex={this.props.page} />
pageIndex={this.props.page}
/>
</Document>
)
}
......