mirror of
https://gitlab.com/animath/si/plateforme-corres2math.git
synced 2025-07-03 10:42:49 +02:00
Compare commits
109 Commits
6647a284f4
...
improvemen
Author | SHA1 | Date | |
---|---|---|---|
35a197be07
|
|||
d55671efd1
|
|||
bcdbc445c6
|
|||
95a69f35d2
|
|||
eec941c816
|
|||
64d471936f
|
|||
02c977264d
|
|||
8f86ea15c8
|
|||
7628387158
|
|||
bf2feb9c35
|
|||
969e53b712
|
|||
84e149e8c9
|
|||
9e6a3eb1ca
|
|||
1f9f60d880
|
|||
205760f2e9
|
|||
8f742b8e14
|
|||
996d00c7f0
|
|||
8f09ca5553
|
|||
b761670133
|
|||
f2ca4b7446 | |||
3faf1294d8 | |||
dbcf15c4f3 | |||
10115a0419 | |||
833f9147ce | |||
55a727612c | |||
de7f51d8da | |||
c658a9767d | |||
982b61fe03 | |||
ace1dbdc75 | |||
731f8711ff | |||
d3e18a8fbb | |||
ece1e800ab | |||
2e0028c063 | |||
d304c3565c | |||
0fe1f9c348 | |||
9867e5e2a8 | |||
48b34e4362 | |||
10932d1cc5 | |||
02ca1d1efe | |||
b0a3a22f83 | |||
4238e49c11 | |||
c3c2c55aca | |||
cba3e56fb8 | |||
f146ae2dd2 | |||
04dd02b88a | |||
1ddf39f296 | |||
fa368a399a | |||
c35fb4e996 | |||
b6cefc1519 | |||
e73bb2d18b | |||
f422212aea | |||
52763cb75a | |||
aed9f457c3 | |||
6afa1ea40b | |||
e98540a2a8 | |||
7353ecfd5f | |||
0a3fffe21e | |||
bf32c34d4c | |||
c62aa3ebd1 | |||
4181742133 | |||
25756fb2ef | |||
4c25ae2928 | |||
7ae2b152c6 | |||
682ef05110 | |||
4043d04826 | |||
dee2152616 | |||
be17d11581 | |||
c80355f2bc | |||
62b883467c | |||
5fc46e74d2 | |||
61719cae1c | |||
463adc90d6 | |||
a707219a9e | |||
dd1238d44d | |||
7a8d05c58a | |||
4975d4ddb7 | |||
c8029fdd7a | |||
82f8d61eb7 | |||
1392b50db1 | |||
bcca41bfb6 | |||
4f1f4b0783 | |||
2f6a1f6e56 | |||
d0007ee9b2 | |||
0d9c293443 | |||
2a282e366e | |||
c11a40e054 | |||
2895fb88db | |||
4b14d3562f | |||
0ea51f47b3 | |||
0e9afc780c | |||
52c8a836f1 | |||
2273cbfbc6 | |||
95e1c4f821 | |||
e9c56104df | |||
e0f06179a0 | |||
244084a1fd | |||
aa617a4bb6 | |||
fac239111a | |||
9bb638f48d | |||
d8ece66b23 | |||
6d4cd217b2 | |||
8236a9fe14 | |||
971169fe2c | |||
79836f0d94 | |||
3265c1fc1b | |||
09a2947095 | |||
316e4eefc1 | |||
238333a175 | |||
db30b481a3 |
4
.gitignore
vendored
4
.gitignore
vendored
@ -40,5 +40,5 @@ env/
|
||||
venv/
|
||||
db.sqlite3
|
||||
|
||||
# Don't git personal data
|
||||
import_olddb/
|
||||
# Don't git index
|
||||
whoosh_index/
|
||||
|
@ -14,7 +14,7 @@ py39:
|
||||
stage: test
|
||||
image: python:3.9-alpine
|
||||
before_script:
|
||||
- apk add --no-cache libmagic
|
||||
- apk add --no-cache gcc libmagic
|
||||
- pip install tox --no-cache-dir
|
||||
script: tox -e py39
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
FROM python:3-alpine
|
||||
FROM python:3.8-alpine
|
||||
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
ENV DJANGO_ALLOW_ASYNC_UNSAFE 1
|
||||
@ -11,14 +11,12 @@ RUN apk add --no-cache bash
|
||||
RUN mkdir /code
|
||||
WORKDIR /code
|
||||
COPY requirements.txt /code/requirements.txt
|
||||
RUN pip install -r requirements.txt psycopg2-binary sympasoap --no-cache-dir
|
||||
RUN pip install -r requirements.txt --no-cache-dir
|
||||
|
||||
COPY . /code/
|
||||
|
||||
RUN python manage.py collectstatic --noinput && \
|
||||
python manage.py compilemessages && \
|
||||
python manage.py migrate && \
|
||||
python manage.py loaddata initial
|
||||
python manage.py compilemessages
|
||||
|
||||
# Configure nginx
|
||||
RUN mkdir /run/nginx
|
||||
|
674
LICENSE
Normal file
674
LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) 2020 Animath
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) 2020 Animath
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
21
README.md
21
README.md
@ -1,7 +1,7 @@
|
||||
# Plateforme d'inscription des Correspondances des Jeunes Mathématicien·nes
|
||||
# Plateforme des Correspondances des Jeunes Mathématicien·nes
|
||||
|
||||
[](https://gitlab.com/animath/si/plateforme-corres2math/-/commits/django)
|
||||
[](https://gitlab.com/animath/si/plateforme-corres2math/-/commits/django)
|
||||
[](https://gitlab.com/animath/si/plateforme-corres2math/-/commits/master)
|
||||
[](https://gitlab.com/animath/si/plateforme-corres2math/-/commits/master)
|
||||
|
||||
La plateforme des Correspondances des Jeunes Mathématicien·nes est née pour la seconde édition en 2019 de l'action.
|
||||
D'abord codée en PHP, elle a subi une refonte totale en Python, à l'aide du framework Web [Django](https://www.djangoproject.com/).
|
||||
@ -21,8 +21,8 @@ Le plus simple pour installer la plateforme est d'utiliser l'image Docker inclus
|
||||
exposé sur le port 80 avec le serveur Django. Ci-dessous une configuration Docker-Compose, à adapter selon vos besoins :
|
||||
|
||||
```yaml
|
||||
inscription-corres2math:
|
||||
build: ./inscription-corres2math
|
||||
plateforme-corres2math:
|
||||
build: https://gitlab.com/animath/si/plateforme-corres2math.git
|
||||
links:
|
||||
- postgres
|
||||
ports:
|
||||
@ -51,17 +51,20 @@ SMTP_HOST_USER= # Utilisateur du compte SMTP
|
||||
SMTP_HOST_PASSWORD= # Mot de passe du compte SMTP
|
||||
FROM_EMAIL=contact@correspondances-maths.fr # Nom de l'expéditeur des mails
|
||||
SERVER_EMAIL=contact@correspondances-maths.fr # Adresse e-mail expéditrice
|
||||
SYMPA_URL=lists.example.com # Serveur Sympa à utiliser
|
||||
SYMPA_EMAIL= # Adresse e-mail du compte administrateur de Sympa
|
||||
SYMPA_PASSWORD= # Mot de passe du compte administrateur de Sympa
|
||||
SYNAPSE_PASSWORD= # Mot de passe du robot Matrix
|
||||
```
|
||||
|
||||
Si le type de base de données sélectionné est SQLite, la variable `DJANGO_DB_HOST` sera utilisée en guise de chemin vers
|
||||
le fichier de base de données (par défaut, `db.sqlite3`).
|
||||
|
||||
En développement, il est recommandé d'utiliser SQLite pour des raisons de simplicité. Les paramètres de mail ne seront
|
||||
pas utilisés, et les mails qui doivent être envoyés seront envoyés dans la console.
|
||||
pas utilisés, et les mails qui doivent être envoyés seront envoyés dans la console. Les intégrations mail et Matrix
|
||||
seront également désactivées.
|
||||
|
||||
En production, il est recommandé de ne pas utiliser SQLite pour des raisons de performances.
|
||||
|
||||
La dernière différence entre le développment et la production est qu'en développement, chaque modification d'un fichier
|
||||
est détectée et le serveur se relance automatiquement dès lors.
|
||||
|
||||
Une fois le site lancé, le premier compte créé sera un compte administrateur.
|
||||
est détectée et le serveur se relance automatiquement dès lors.
|
@ -1 +1,4 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
default_app_config = 'api.apps.APIConfig'
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers
|
||||
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from unittest.case import skipIf
|
||||
|
||||
from django.conf import settings
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.conf import settings
|
||||
from django.conf.urls import include, url
|
||||
from rest_framework import routers
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from rest_framework.filters import SearchFilter
|
||||
|
@ -1 +1,4 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
default_app_config = 'eastereggs.apps.EastereggsConfig'
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.urls import path
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-21 15:33
|
||||
# Generated by Django 3.1.3 on 2020-11-04 12:05
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
@ -11,8 +11,8 @@ class Migration(migrations.Migration):
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('contenttypes', '0002_remove_content_type_name'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('contenttypes', '0002_remove_content_type_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by BDE ENS Paris-Saclay
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1 +1,4 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
default_app_config = 'participation.apps.ParticipationConfig'
|
||||
|
@ -0,0 +1,49 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.contrib import admin
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from .models import Participation, Phase, Question, Team, Video
|
||||
|
||||
|
||||
@admin.register(Team)
|
||||
class TeamAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'trigram', 'problem', 'valid',)
|
||||
search_fields = ('name', 'trigram',)
|
||||
list_filter = ('participation__problem', 'participation__valid',)
|
||||
|
||||
def problem(self, team):
|
||||
return team.participation.get_problem_display()
|
||||
|
||||
problem.short_description = _('problem number')
|
||||
|
||||
def valid(self, team):
|
||||
return team.participation.valid
|
||||
|
||||
valid.short_description = _('valid')
|
||||
|
||||
|
||||
@admin.register(Participation)
|
||||
class ParticipationAdmin(admin.ModelAdmin):
|
||||
list_display = ('team', 'problem', 'valid',)
|
||||
search_fields = ('team__name', 'team__trigram',)
|
||||
list_filter = ('problem', 'valid',)
|
||||
|
||||
|
||||
@admin.register(Video)
|
||||
class VideoAdmin(admin.ModelAdmin):
|
||||
list_display = ('participation', 'link',)
|
||||
search_fields = ('participation__team__name', 'participation__team__trigram', 'link',)
|
||||
|
||||
|
||||
@admin.register(Question)
|
||||
class QuestionAdmin(admin.ModelAdmin):
|
||||
list_display = ('participation', 'question',)
|
||||
search_fields = ('participation__team__name', 'participation__team__trigram', 'question',)
|
||||
|
||||
|
||||
@admin.register(Phase)
|
||||
class PhaseAdmin(admin.ModelAdmin):
|
||||
list_display = ('phase_number', 'start', 'end',)
|
||||
ordering = ('phase_number', 'start',)
|
||||
|
@ -1,8 +1,14 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.apps import AppConfig
|
||||
from django.db.models.signals import post_save, pre_delete, pre_save
|
||||
|
||||
|
||||
class ParticipationConfig(AppConfig):
|
||||
"""
|
||||
The participation app contains the data about the teams, videos, ...
|
||||
"""
|
||||
name = 'participation'
|
||||
|
||||
def ready(self):
|
||||
|
@ -1,14 +1,22 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import re
|
||||
|
||||
from bootstrap_datepicker_plus import DateTimePickerInput
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
||||
from django.db.models import Q
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from .models import Participation, Phase, Team, Video
|
||||
from .models import Participation, Phase, Question, Team, Video
|
||||
|
||||
|
||||
class TeamForm(forms.ModelForm):
|
||||
"""
|
||||
Form to create a team, with the name and the trigram,
|
||||
and if the team accepts that Animath diffuse the videos.
|
||||
"""
|
||||
def clean_trigram(self):
|
||||
trigram = self.cleaned_data["trigram"].upper()
|
||||
if not re.match("[A-Z]{3}", trigram):
|
||||
@ -21,6 +29,9 @@ class TeamForm(forms.ModelForm):
|
||||
|
||||
|
||||
class JoinTeamForm(forms.ModelForm):
|
||||
"""
|
||||
Form to join a team by the access code.
|
||||
"""
|
||||
def clean_access_code(self):
|
||||
access_code = self.cleaned_data["access_code"]
|
||||
if not Team.objects.filter(access_code=access_code).exists():
|
||||
@ -40,12 +51,18 @@ class JoinTeamForm(forms.ModelForm):
|
||||
|
||||
|
||||
class ParticipationForm(forms.ModelForm):
|
||||
"""
|
||||
Form to update the problem of a team participation.
|
||||
"""
|
||||
class Meta:
|
||||
model = Participation
|
||||
fields = ('problem',)
|
||||
|
||||
|
||||
class RequestValidationForm(forms.Form):
|
||||
"""
|
||||
Form to ask about validation.
|
||||
"""
|
||||
_form_type = forms.CharField(
|
||||
initial="RequestValidationForm",
|
||||
widget=forms.HiddenInput(),
|
||||
@ -58,6 +75,9 @@ class RequestValidationForm(forms.Form):
|
||||
|
||||
|
||||
class ValidateParticipationForm(forms.Form):
|
||||
"""
|
||||
Form to let administrators to accept or refuse a team.
|
||||
"""
|
||||
_form_type = forms.CharField(
|
||||
initial="ValidateParticipationForm",
|
||||
widget=forms.HiddenInput(),
|
||||
@ -70,17 +90,88 @@ class ValidateParticipationForm(forms.Form):
|
||||
|
||||
|
||||
class UploadVideoForm(forms.ModelForm):
|
||||
"""
|
||||
Form to upload a video, for a solution or a synthesis.
|
||||
"""
|
||||
class Meta:
|
||||
model = Video
|
||||
fields = ('link',)
|
||||
|
||||
def clean(self):
|
||||
if Phase.current_phase().phase_number != 1 and self.instance.link:
|
||||
if Phase.current_phase().phase_number != 1 and Phase.current_phase().phase_number != 4 and self.instance.link:
|
||||
self.add_error("link", _("You can't upload your video after the deadline."))
|
||||
return super().clean()
|
||||
|
||||
|
||||
class ReceiveParticipationForm(forms.ModelForm):
|
||||
"""
|
||||
Update the received participation of a participation.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["received_participation"].queryset = Participation.objects.filter(
|
||||
~Q(pk=self.instance.pk) & Q(problem=self.instance.problem, valid=True)
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Participation
|
||||
fields = ('received_participation',)
|
||||
|
||||
|
||||
class SendParticipationForm(forms.ModelForm):
|
||||
"""
|
||||
Update the sent participation of a participation.
|
||||
"""
|
||||
sent_participation = forms.ModelChoiceField(
|
||||
queryset=Participation.objects,
|
||||
label=lambda: _("Send to team"),
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
try:
|
||||
self.fields["sent_participation"].initial = self.instance.sent_participation
|
||||
except ObjectDoesNotExist: # No sent participation
|
||||
pass
|
||||
self.fields["sent_participation"].queryset = Participation.objects.filter(
|
||||
~Q(pk=self.instance.pk) & Q(problem=self.instance.problem, valid=True)
|
||||
)
|
||||
|
||||
def clean(self, commit=True):
|
||||
cleaned_data = super().clean()
|
||||
if "sent_participation" in cleaned_data:
|
||||
participation = cleaned_data["sent_participation"]
|
||||
participation.received_participation = self.instance
|
||||
self.instance = participation
|
||||
return cleaned_data
|
||||
|
||||
class Meta:
|
||||
model = Participation
|
||||
fields = ('sent_participation',)
|
||||
|
||||
|
||||
class QuestionForm(forms.ModelForm):
|
||||
"""
|
||||
Create or update a question.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["question"].widget.attrs.update({"placeholder": _("How did you get the idea to ...?")})
|
||||
|
||||
def clean(self):
|
||||
if Phase.current_phase().phase_number != 2:
|
||||
self.add_error(None, _("You can only create or update a question during the second phase."))
|
||||
return super().clean()
|
||||
|
||||
class Meta:
|
||||
model = Question
|
||||
fields = ('question',)
|
||||
|
||||
|
||||
class PhaseForm(forms.ModelForm):
|
||||
"""
|
||||
Form to update the calendar of a phase.
|
||||
"""
|
||||
class Meta:
|
||||
model = Phase
|
||||
fields = ('start', 'end',)
|
||||
@ -92,10 +183,12 @@ class PhaseForm(forms.ModelForm):
|
||||
def clean(self):
|
||||
# Ensure that dates are in a right order
|
||||
cleaned_data = super().clean()
|
||||
if cleaned_data["end"] <= cleaned_data["start"]:
|
||||
start = cleaned_data["start"]
|
||||
end = cleaned_data["end"]
|
||||
if end <= start:
|
||||
self.add_error("end", _("Start date must be before the end date."))
|
||||
if Phase.objects.filter(phase_number__lt=self.instance.phase_number, end__gt=cleaned_data["start"]).exists():
|
||||
if Phase.objects.filter(phase_number__lt=self.instance.phase_number, end__gt=start).exists():
|
||||
self.add_error("start", _("This phase must start after the previous phases."))
|
||||
if Phase.objects.filter(phase_number__gt=self.instance.phase_number, start__lt=cleaned_data["end"]).exists():
|
||||
if Phase.objects.filter(phase_number__gt=self.instance.phase_number, start__lt=end).exists():
|
||||
self.add_error("end", _("This phase must end after the next phases."))
|
||||
return cleaned_data
|
||||
|
2
apps/participation/management/commands/__init__.py
Normal file
2
apps/participation/management/commands/__init__.py
Normal file
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
@ -0,0 +1,92 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from corres2math.matrix import Matrix, RoomPreset, RoomVisibility
|
||||
from django.core.management import BaseCommand
|
||||
from registration.models import AdminRegistration, Registration
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
def handle(self, *args, **options):
|
||||
Matrix.set_display_name("Bot des Correspondances")
|
||||
|
||||
if not os.getenv("SYNAPSE_PASSWORD"):
|
||||
avatar_uri = "plop"
|
||||
else: # pragma: no cover
|
||||
if not os.path.isfile(".matrix_avatar"):
|
||||
stat_file = os.stat("corres2math/static/logo.png")
|
||||
with open("corres2math/static/logo.png", "rb") as f:
|
||||
resp = Matrix.upload(f, filename="logo.png", content_type="image/png",
|
||||
filesize=stat_file.st_size)[0][0]
|
||||
avatar_uri = resp.content_uri
|
||||
with open(".matrix_avatar", "w") as f:
|
||||
f.write(avatar_uri)
|
||||
Matrix.set_avatar(avatar_uri)
|
||||
|
||||
with open(".matrix_avatar", "r") as f:
|
||||
avatar_uri = f.read().rstrip(" \t\r\n")
|
||||
|
||||
if not async_to_sync(Matrix.resolve_room_alias)("#faq:correspondances-maths.fr"):
|
||||
Matrix.create_room(
|
||||
visibility=RoomVisibility.public,
|
||||
alias="faq",
|
||||
name="FAQ",
|
||||
topic="Posez toutes vos questions ici !",
|
||||
federate=False,
|
||||
preset=RoomPreset.public_chat,
|
||||
)
|
||||
|
||||
if not async_to_sync(Matrix.resolve_room_alias)("#annonces:correspondances-maths.fr"):
|
||||
Matrix.create_room(
|
||||
visibility=RoomVisibility.public,
|
||||
alias="annonces",
|
||||
name="Annonces",
|
||||
topic="Informations importantes des Correspondances",
|
||||
federate=False,
|
||||
preset=RoomPreset.public_chat,
|
||||
)
|
||||
|
||||
if not async_to_sync(Matrix.resolve_room_alias)("#je-cherche-une-equipe:correspondances-maths.fr"):
|
||||
Matrix.create_room(
|
||||
visibility=RoomVisibility.public,
|
||||
alias="je-cherche-une-equipe",
|
||||
name="Je cherche une équipe",
|
||||
topic="Le Tinder des Correspondances",
|
||||
federate=False,
|
||||
preset=RoomPreset.public_chat,
|
||||
)
|
||||
|
||||
if not async_to_sync(Matrix.resolve_room_alias)("#flood:correspondances-maths.fr"):
|
||||
Matrix.create_room(
|
||||
visibility=RoomVisibility.public,
|
||||
alias="flood",
|
||||
name="Flood",
|
||||
topic="Discutez de tout et de rien !",
|
||||
federate=False,
|
||||
preset=RoomPreset.public_chat,
|
||||
)
|
||||
|
||||
Matrix.set_room_avatar("#annonces:correspondances-maths.fr", avatar_uri)
|
||||
Matrix.set_room_avatar("#faq:correspondances-maths.fr", avatar_uri)
|
||||
Matrix.set_room_avatar("#je-cherche-une-equipe:correspondances-maths.fr", avatar_uri)
|
||||
Matrix.set_room_avatar("#flood:correspondances-maths.fr", avatar_uri)
|
||||
|
||||
Matrix.set_room_power_level_event("#annonces:correspondances-maths.fr", "events_default", 50)
|
||||
|
||||
for r in Registration.objects.all():
|
||||
Matrix.invite("#annonces:correspondances-maths.fr", f"@{r.matrix_username}:correspondances-maths.fr")
|
||||
Matrix.invite("#faq:correspondances-maths.fr", f"@{r.matrix_username}:correspondances-maths.fr")
|
||||
Matrix.invite("#je-cherche-une-equipe:correspondances-maths.fr",
|
||||
f"@{r.matrix_username}:correspondances-maths.fr")
|
||||
Matrix.invite("#flood:correspondances-maths.fr", f"@{r.matrix_username}:correspondances-maths.fr")
|
||||
|
||||
for admin in AdminRegistration.objects.all():
|
||||
Matrix.set_room_power_level("#annonces:correspondances-maths.fr",
|
||||
f"@{admin.matrix_username}:correspondances-maths.fr", 95)
|
||||
Matrix.set_room_power_level("#faq:correspondances-maths.fr",
|
||||
f"@{admin.matrix_username}:correspondances-maths.fr", 95)
|
||||
Matrix.set_room_power_level("#flood:correspondances-maths.fr",
|
||||
f"@{admin.matrix_username}:correspondances-maths.fr", 95)
|
43
apps/participation/management/commands/fix_sympa_lists.py
Normal file
43
apps/participation/management/commands/fix_sympa_lists.py
Normal file
@ -0,0 +1,43 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from corres2math.lists import get_sympa_client
|
||||
from django.core.management import BaseCommand
|
||||
from django.db.models import Q
|
||||
from participation.models import Team
|
||||
from registration.models import CoachRegistration, StudentRegistration
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
def handle(self, *args, **options):
|
||||
"""
|
||||
Create Sympa mailing lists and register teams.
|
||||
"""
|
||||
sympa = get_sympa_client()
|
||||
|
||||
sympa.create_list("equipes", "Équipes des Correspondances", "hotline",
|
||||
"Liste de diffusion pour contacter toutes les équipes validées des Correspondances.",
|
||||
"education", raise_error=False)
|
||||
sympa.create_list("equipes-non-valides", "Équipes des Correspondances", "hotline",
|
||||
"Liste de diffusion pour contacter toutes les équipes non-validées des Correspondances.",
|
||||
"education", raise_error=False)
|
||||
|
||||
for problem in range(1, 4):
|
||||
sympa.create_list(f"probleme-{problem}",
|
||||
f"Équipes des Correspondances participant au problème {problem}", "hotline",
|
||||
f"Liste de diffusion pour contacter les équipes participant au problème {problem}"
|
||||
f" des Correspondances.", "education", raise_error=False)
|
||||
|
||||
for team in Team.objects.filter(participation__valid=True).all():
|
||||
team.create_mailing_list()
|
||||
sympa.subscribe(team.email, "equipes", f"Equipe {team.name}", True)
|
||||
sympa.subscribe(team.email, f"probleme-{team.participation.problem}", f"Equipe {team.name}", True)
|
||||
|
||||
for team in Team.objects.filter(Q(participation__valid=False) | Q(participation__valid__isnull=True)).all():
|
||||
team.create_mailing_list()
|
||||
sympa.subscribe(team.email, "equipes-non-valides", f"Equipe {team.name}", True)
|
||||
|
||||
for student in StudentRegistration.objects.filter(team__isnull=False).all():
|
||||
sympa.subscribe(student.user.email, f"equipe-{student.team.trigram.lower()}", True, f"{student}")
|
||||
for coach in CoachRegistration.objects.filter(team__isnull=False).all():
|
||||
sympa.subscribe(coach.user.email, f"equipe-{coach.team.trigram.lower()}", True, f"{coach}")
|
44
apps/participation/management/commands/setup_third_phase.py
Normal file
44
apps/participation/management/commands/setup_third_phase.py
Normal file
@ -0,0 +1,44 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from corres2math.matrix import Matrix, RoomVisibility
|
||||
from django.core.management import BaseCommand
|
||||
from participation.models import Participation
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
def handle(self, *args, **options):
|
||||
for participation in Participation.objects.filter(valid=True).all():
|
||||
for i, question in enumerate(participation.questions.order_by("id").all()):
|
||||
solution_author = participation.received_participation.team
|
||||
alias = f"equipe-{solution_author.trigram.lower()}-question-{i}"
|
||||
room_id = f"#{alias}:correspondances-maths.fr"
|
||||
Matrix.create_room(
|
||||
visibility=RoomVisibility.public,
|
||||
alias=alias,
|
||||
name=f"Solution équipe {solution_author.trigram} - question {i+1}",
|
||||
topic=f"Échange entre l'équipe {solution_author.name} ({solution_author.trigram}) "
|
||||
f"et l'équipe {participation.team.name} ({participation.team.trigram}) "
|
||||
f"autour de la question {i+1} sur le problème {participation.problem}",
|
||||
federate=False,
|
||||
invite=[f"@{registration.matrix_username}:correspondances-maths.fr" for registration in
|
||||
list(participation.team.students.all()) + list(participation.team.coachs.all()) +
|
||||
list(solution_author.students.all()) + list(solution_author.coachs.all())],
|
||||
)
|
||||
Matrix.set_room_power_level_event(room_id, "events_default", 21)
|
||||
for registration in solution_author.students.all():
|
||||
Matrix.set_room_power_level(room_id,
|
||||
f"@{registration.matrix_username}:correspondances-maths.fr", 42)
|
||||
|
||||
Matrix.send_message(room_id, "Bienvenue dans la troisième phase des Correspondances !")
|
||||
Matrix.send_message(room_id, f"L'équipe {participation.team.name} a visionné la vidéo de l'équipe "
|
||||
f"{solution_author.name} sur le problème {participation.problem}, et a posé "
|
||||
"une série de questions.")
|
||||
Matrix.send_message(room_id, "L'équipe ayant composé la vidéo doit maintenant proposer une réponse.")
|
||||
Matrix.send_message(room_id, "Une fois la réponse apportée, vous pourrez ensuite échanger plus "
|
||||
"librement autour de la question, au travers de ce canal.")
|
||||
Matrix.send_message(room_id, "**Question posée :**", formatted_body="<strong>Question posée :</strong>")
|
||||
Matrix.send_message(room_id, question.question,
|
||||
formatted_body=f"<font color=\"#ff0000\">{question.question}</font>")
|
||||
|
||||
# TODO Setup the bot the set the power level of all members of the room to 42
|
@ -1,8 +1,39 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-21 15:51
|
||||
# Generated by Django 3.1.3 on 2020-11-04 12:05
|
||||
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
|
||||
|
||||
def register_phases(apps, _):
|
||||
"""
|
||||
Import the different phases of the action
|
||||
"""
|
||||
Phase = apps.get_model("participation", "phase")
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=1,
|
||||
description="Soumission des vidéos",
|
||||
)
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=2,
|
||||
description="Phase de questions",
|
||||
)
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=3,
|
||||
description="Phase d'échanges entre les équipes",
|
||||
)
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=4,
|
||||
description="Synthèse de l'échange",
|
||||
)
|
||||
|
||||
|
||||
def reverse_phase_registering(apps, _): # pragma: no cover
|
||||
"""
|
||||
Drop all phases in order to unapply this migration.
|
||||
"""
|
||||
Phase = apps.get_model("participation", "phase")
|
||||
Phase.objects.all().delete()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
@ -17,13 +48,34 @@ class Migration(migrations.Migration):
|
||||
name='Participation',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('problem', models.IntegerField(choices=[(1, 'Problem #1'), (2, 'Problem #2'), (3, 'Problem #3'), (4, 'Problem #4')], default=None, null=True, verbose_name='problem number')),
|
||||
('problem', models.IntegerField(choices=[(1, 'Problem #1'), (2, 'Problem #2'), (3, 'Problem #3')], default=None, null=True, verbose_name='problem number')),
|
||||
('valid', models.BooleanField(default=None, help_text='The video got the validation of the administrators.', null=True, verbose_name='valid')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'participation',
|
||||
'verbose_name_plural': 'participations',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Phase',
|
||||
fields=[
|
||||
('phase_number', models.AutoField(primary_key=True, serialize=False, unique=True, verbose_name='phase number')),
|
||||
('description', models.CharField(max_length=255, verbose_name='phase description')),
|
||||
('start', models.DateTimeField(default=django.utils.timezone.now, verbose_name='start date of the given phase')),
|
||||
('end', models.DateTimeField(default=django.utils.timezone.now, verbose_name='end date of the given phase')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'phase',
|
||||
'verbose_name_plural': 'phases',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Question',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('question', models.TextField(verbose_name='question')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Team',
|
||||
fields=[
|
||||
@ -31,6 +83,7 @@ class Migration(migrations.Migration):
|
||||
('name', models.CharField(max_length=255, unique=True, verbose_name='name')),
|
||||
('trigram', models.CharField(help_text='The trigram must be composed of three uppercase letters.', max_length=3, unique=True, validators=[django.core.validators.RegexValidator('[A-Z]{3}')], verbose_name='trigram')),
|
||||
('access_code', models.CharField(help_text='The access code let other people to join the team.', max_length=6, verbose_name='access code')),
|
||||
('grant_animath_access_videos', models.BooleanField(default=False, help_text='Give the authorisation to publish the video on the main website to promote the action.', verbose_name='Grant Animath to publish my video')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'team',
|
||||
@ -43,7 +96,6 @@ class Migration(migrations.Migration):
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('link', models.URLField(help_text='The full video link.', verbose_name='link')),
|
||||
('valid', models.BooleanField(default=None, help_text='The video got the validation of the administrators.', null=True, verbose_name='valid')),
|
||||
('participation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='participation.participation', verbose_name='participation')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'video',
|
||||
@ -54,6 +106,11 @@ class Migration(migrations.Migration):
|
||||
model_name='team',
|
||||
index=models.Index(fields=['trigram'], name='participati_trigram_239255_idx'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='question',
|
||||
name='participation',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='participation.participation', verbose_name='participation'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='participation',
|
||||
name='received_participation',
|
||||
@ -62,16 +119,20 @@ class Migration(migrations.Migration):
|
||||
migrations.AddField(
|
||||
model_name='participation',
|
||||
name='solution',
|
||||
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='participation.video', verbose_name='solution video'),
|
||||
field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_solution', to='participation.video', verbose_name='solution video'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='participation',
|
||||
name='synthesis',
|
||||
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='participation.video', verbose_name='synthesis video'),
|
||||
field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_synthesis', to='participation.video', verbose_name='synthesis video'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='participation',
|
||||
name='team',
|
||||
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='participation.team', verbose_name='team'),
|
||||
),
|
||||
migrations.RunPython(
|
||||
register_phases,
|
||||
reverse_code=reverse_phase_registering,
|
||||
)
|
||||
]
|
||||
|
@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-22 16:21
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('participation', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='team',
|
||||
name='grant_animath_access_videos',
|
||||
field=models.BooleanField(default=False, help_text='Give the authorisation to publish the video on the main website to promote the action.', verbose_name='Grant Animath to publish my video'),
|
||||
),
|
||||
]
|
@ -1,28 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-27 11:09
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('participation', '0002_team_grant_animath_access_videos'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='video',
|
||||
name='participation',
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='participation',
|
||||
name='solution',
|
||||
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation', to='participation.video', verbose_name='solution video'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='participation',
|
||||
name='synthesis',
|
||||
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_synthesis', to='participation.video', verbose_name='synthesis video'),
|
||||
),
|
||||
]
|
@ -1,24 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-27 11:22
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('participation', '0003_auto_20200927_1309'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='participation',
|
||||
name='solution',
|
||||
field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_solution', to='participation.video', verbose_name='solution video'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='participation',
|
||||
name='synthesis',
|
||||
field=models.OneToOneField(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='participation_synthesis', to='participation.video', verbose_name='synthesis video'),
|
||||
),
|
||||
]
|
@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-10-11 13:58
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('participation', '0004_auto_20200927_1322'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='participation',
|
||||
name='valid',
|
||||
field=models.BooleanField(default=None, help_text='The video got the validation of the administrators.', null=True, verbose_name='valid'),
|
||||
),
|
||||
]
|
@ -1,61 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-10-20 10:39
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.utils.timezone
|
||||
|
||||
|
||||
def register_phases(apps, schema_editor):
|
||||
"""
|
||||
Import the different phases of the action
|
||||
"""
|
||||
Phase = apps.get_model("participation", "phase")
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=1,
|
||||
description="Soumission des vidéos",
|
||||
)
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=2,
|
||||
description="Phase de questions",
|
||||
)
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=3,
|
||||
description="Phase d'échanges entre les équipes",
|
||||
)
|
||||
Phase.objects.get_or_create(
|
||||
phase_number=4,
|
||||
description="Synthèse de l'échange",
|
||||
)
|
||||
|
||||
|
||||
def reverse_phase_registering(apps, schema_editor):
|
||||
"""
|
||||
Drop all phases in order to unapply this migration.
|
||||
"""
|
||||
Phase = apps.get_model("participation", "phase")
|
||||
Phase.objects.all().delete()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
('participation', '0005_participation_valid'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Phase',
|
||||
fields=[
|
||||
('phase_number', models.AutoField(primary_key=True, serialize=False, unique=True, verbose_name='phase number')),
|
||||
('description', models.CharField(max_length=255, verbose_name="phase description")),
|
||||
('start', models.DateTimeField(default=django.utils.timezone.now, verbose_name='start date of the given phase')),
|
||||
('end', models.DateTimeField(default=django.utils.timezone.now, verbose_name='end date of the given phase')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'phase',
|
||||
'verbose_name_plural': 'phases',
|
||||
},
|
||||
),
|
||||
migrations.RunPython(
|
||||
register_phases,
|
||||
reverse_phase_registering,
|
||||
),
|
||||
]
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1,25 +1,28 @@
|
||||
import asyncio
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from django.template.loader import render_to_string
|
||||
from nio import RoomVisibility, RoomPreset
|
||||
|
||||
from corres2math.lists import get_sympa_client
|
||||
from corres2math.matrix import Matrix, RoomPreset, RoomVisibility
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.core.validators import RegexValidator
|
||||
from django.db import models
|
||||
from django.db.models import Index
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.crypto import get_random_string
|
||||
from django.utils.text import format_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from corres2math.matrix import Matrix
|
||||
|
||||
|
||||
class Team(models.Model):
|
||||
"""
|
||||
The Team model represents a real team that participates to the Correspondances.
|
||||
This only includes the registration detail.
|
||||
"""
|
||||
name = models.CharField(
|
||||
max_length=255,
|
||||
verbose_name=_("name"),
|
||||
@ -48,9 +51,15 @@ class Team(models.Model):
|
||||
|
||||
@property
|
||||
def email(self):
|
||||
"""
|
||||
:return: The mailing list to contact the team members.
|
||||
"""
|
||||
return f"equipe-{self.trigram.lower()}@{os.getenv('SYMPA_HOST', 'localhost')}"
|
||||
|
||||
def create_mailing_list(self):
|
||||
"""
|
||||
Create a new Sympa mailing list to contact the team.
|
||||
"""
|
||||
get_sympa_client().create_list(
|
||||
f"equipe-{self.trigram.lower()}",
|
||||
f"Équipe {self.name} ({self.trigram})",
|
||||
@ -59,19 +68,35 @@ class Team(models.Model):
|
||||
"education",
|
||||
raise_error=False,
|
||||
)
|
||||
if self.pk and self.participation.valid: # pragma: no cover
|
||||
get_sympa_client().subscribe(self.email, "equipes", False, f"Equipe {self.name}")
|
||||
get_sympa_client().subscribe(self.email, f"probleme-{self.participation.problem}", False,
|
||||
f"Equipe {self.name}")
|
||||
else:
|
||||
get_sympa_client().subscribe(self.email, "equipes-non-valides", False)
|
||||
|
||||
def delete_mailing_list(self):
|
||||
"""
|
||||
Drop the Sympa mailing list, if the team is empty or if the trigram changed.
|
||||
"""
|
||||
if self.participation.valid: # pragma: no cover
|
||||
get_sympa_client().unsubscribe(self.email, "equipes", False)
|
||||
get_sympa_client().unsubscribe(self.email, f"probleme-{self.participation.problem}", False)
|
||||
else:
|
||||
get_sympa_client().unsubscribe(self.email, "equipes-non-valides", False)
|
||||
get_sympa_client().delete_list(f"equipe-{self.trigram}")
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.access_code:
|
||||
# if the team got created, generate the access code, create the contact mailing list
|
||||
# and create a dedicated Matrix room.
|
||||
self.access_code = get_random_string(6)
|
||||
self.create_mailing_list()
|
||||
|
||||
Matrix.create_room(
|
||||
visibility=RoomVisibility.private,
|
||||
name=f"#équipe-{self.trigram.lower()}",
|
||||
alias=f"team-{self.trigram.lower()}",
|
||||
alias=f"equipe-{self.trigram.lower()}",
|
||||
topic=f"Discussion de l'équipe {self.name}",
|
||||
preset=RoomPreset.private_chat,
|
||||
)
|
||||
@ -93,6 +118,10 @@ class Team(models.Model):
|
||||
|
||||
|
||||
class Participation(models.Model):
|
||||
"""
|
||||
The Participation model contains all data that are related to the participation:
|
||||
chosen problem, validity status, videos,...
|
||||
"""
|
||||
team = models.OneToOneField(
|
||||
Team,
|
||||
on_delete=models.CASCADE,
|
||||
@ -100,7 +129,7 @@ class Participation(models.Model):
|
||||
)
|
||||
|
||||
problem = models.IntegerField(
|
||||
choices=[(i, format_lazy(_("Problem #{problem:d}"), problem=i)) for i in range(1, 5)],
|
||||
choices=[(i, format_lazy(_("Problem #{problem:d}"), problem=i)) for i in range(1, 4)],
|
||||
null=True,
|
||||
default=None,
|
||||
verbose_name=_("problem number"),
|
||||
@ -152,6 +181,9 @@ class Participation(models.Model):
|
||||
|
||||
|
||||
class Video(models.Model):
|
||||
"""
|
||||
The Video model only contains a link and a validity status.
|
||||
"""
|
||||
link = models.URLField(
|
||||
verbose_name=_("link"),
|
||||
help_text=_("The full video link."),
|
||||
@ -166,23 +198,38 @@ class Video(models.Model):
|
||||
|
||||
@property
|
||||
def participation(self):
|
||||
"""
|
||||
Retrives the participation that is associated to this video,
|
||||
whatever it is a solution or a synthesis.
|
||||
"""
|
||||
try:
|
||||
# If this is a solution
|
||||
return self.participation_solution
|
||||
except ObjectDoesNotExist:
|
||||
# If this is a synthesis
|
||||
return self.participation_synthesis
|
||||
|
||||
@property
|
||||
def platform(self):
|
||||
"""
|
||||
According to the link, retrieve the platform that is used to upload the video.
|
||||
"""
|
||||
if "youtube.com" in self.link or "youtu.be" in self.link:
|
||||
return "youtube"
|
||||
return "unknown"
|
||||
|
||||
@property
|
||||
def youtube_code(self):
|
||||
"""
|
||||
If the video is uploaded on Youtube, search in the URL the video code.
|
||||
"""
|
||||
return re.compile("(https?://|)(www\\.|)(youtube\\.com/watch\\?v=|youtu\\.be/)([a-zA-Z0-9-_]*)?.*?")\
|
||||
.match("https://www.youtube.com/watch?v=73nsrixx7eI").group(4)
|
||||
.match(self.link).group(4)
|
||||
|
||||
def as_iframe(self):
|
||||
"""
|
||||
Generate the HTML code to embed the video in an iframe, according to the type of the host platform.
|
||||
"""
|
||||
if self.platform == "youtube":
|
||||
return render_to_string("participation/youtube_iframe.html", context=dict(youtube_code=self.youtube_code))
|
||||
return None
|
||||
@ -196,7 +243,29 @@ class Video(models.Model):
|
||||
verbose_name_plural = _("videos")
|
||||
|
||||
|
||||
class Question(models.Model):
|
||||
"""
|
||||
Question to ask to the team that sent a solution.
|
||||
"""
|
||||
participation = models.ForeignKey(
|
||||
Participation,
|
||||
on_delete=models.CASCADE,
|
||||
verbose_name=_("participation"),
|
||||
related_name="questions",
|
||||
)
|
||||
|
||||
question = models.TextField(
|
||||
verbose_name=_("question"),
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return self.question
|
||||
|
||||
|
||||
class Phase(models.Model):
|
||||
"""
|
||||
The Phase model corresponds to the dates of the phase.
|
||||
"""
|
||||
phase_number = models.AutoField(
|
||||
primary_key=True,
|
||||
unique=True,
|
||||
@ -219,14 +288,15 @@ class Phase(models.Model):
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def current_phase(cls):
|
||||
def current_phase(cls) -> "Phase":
|
||||
"""
|
||||
Retrieve the current phase of this day
|
||||
"""
|
||||
qs = Phase.objects.filter(start__lte=timezone.now(), end__gte=timezone.now())
|
||||
if qs.exists():
|
||||
return qs.get()
|
||||
qs = Phase.objects.order_by("phase_number").all()
|
||||
if timezone.now() < qs.first().start:
|
||||
return qs.first()
|
||||
return qs.last()
|
||||
qs = Phase.objects.filter(start__lte=timezone.now()).order_by("phase_number").all()
|
||||
return qs.last() if qs.exists() else None
|
||||
|
||||
def __str__(self):
|
||||
return _("Phase {phase_number:d} starts on {start:%Y-%m-%d %H:%M} and ends on {end:%Y-%m-%d %H:%M}")\
|
||||
|
@ -1,9 +1,15 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from haystack import indexes
|
||||
|
||||
from .models import Participation, Team, Video
|
||||
|
||||
|
||||
class TeamIndex(indexes.ModelSearchIndex, indexes.Indexable):
|
||||
"""
|
||||
Index all teams by their name and trigram.
|
||||
"""
|
||||
text = indexes.NgramField(document=True, use_template=True)
|
||||
|
||||
class Meta:
|
||||
@ -11,6 +17,9 @@ class TeamIndex(indexes.ModelSearchIndex, indexes.Indexable):
|
||||
|
||||
|
||||
class ParticipationIndex(indexes.ModelSearchIndex, indexes.Indexable):
|
||||
"""
|
||||
Index all participations by their team name and team trigram.
|
||||
"""
|
||||
text = indexes.NgramField(document=True, use_template=True)
|
||||
|
||||
class Meta:
|
||||
@ -18,6 +27,9 @@ class ParticipationIndex(indexes.ModelSearchIndex, indexes.Indexable):
|
||||
|
||||
|
||||
class VideoIndex(indexes.ModelSearchIndex, indexes.Indexable):
|
||||
"""
|
||||
Index all teams by their team name and team trigram.
|
||||
"""
|
||||
text = indexes.NgramField(document=True, use_template=True)
|
||||
|
||||
class Meta:
|
||||
|
@ -1,22 +1,36 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from corres2math.lists import get_sympa_client
|
||||
from participation.models import Participation, Team, Video
|
||||
|
||||
|
||||
def create_team_participation(instance, **_):
|
||||
def create_team_participation(instance, created, **_):
|
||||
"""
|
||||
When a team got created, create an associated team and create Video objects.
|
||||
"""
|
||||
participation = Participation.objects.get_or_create(team=instance)[0]
|
||||
if not participation.solution:
|
||||
participation.solution = Video.objects.create()
|
||||
if not participation.synthesis:
|
||||
participation.synthesis = Video.objects.create()
|
||||
participation.save()
|
||||
if not created:
|
||||
participation.team.create_mailing_list()
|
||||
|
||||
|
||||
def update_mailing_list(instance: Team, **_):
|
||||
"""
|
||||
When a team name or trigram got updated, update mailing lists and Matrix rooms
|
||||
"""
|
||||
if instance.pk:
|
||||
old_team = Team.objects.get(pk=instance.pk)
|
||||
if old_team.name != instance.name or old_team.trigram != instance.trigram:
|
||||
# TODO Rename Matrix room
|
||||
# Delete old mailing list, create a new one
|
||||
old_team.delete_mailing_list()
|
||||
instance.create_mailing_list()
|
||||
# Subscribe all team members in the mailing list
|
||||
for student in instance.students.all():
|
||||
get_sympa_client().subscribe(student.user.email, f"equipe-{instance.trigram.lower()}", False,
|
||||
f"{student.user.first_name} {student.user.last_name}")
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
import django_tables2 as tables
|
||||
@ -39,6 +42,9 @@ class TeamTable(tables.Table):
|
||||
attrs = {
|
||||
'class': 'table table condensed table-striped',
|
||||
}
|
||||
row_attrs = {
|
||||
'class': lambda record: '' if record.participation.solution.link else 'bg-warning',
|
||||
}
|
||||
model = Team
|
||||
fields = ('name', 'trigram', 'problem',)
|
||||
template_name = 'django_tables2/bootstrap4.html'
|
||||
@ -72,19 +78,17 @@ class ParticipationTable(tables.Table):
|
||||
|
||||
|
||||
class VideoTable(tables.Table):
|
||||
participationname = tables.LinkColumn(
|
||||
participation_name = tables.LinkColumn(
|
||||
'participation:participation_detail',
|
||||
args=[tables.A("participation__pk")],
|
||||
verbose_name=lambda: _("name").capitalize(),
|
||||
accessor=tables.A("participation__team__name"),
|
||||
)
|
||||
|
||||
def render_participationname(self, record):
|
||||
return record.participation.team.name
|
||||
|
||||
class Meta:
|
||||
attrs = {
|
||||
'class': 'table table condensed table-striped',
|
||||
}
|
||||
model = Team
|
||||
fields = ('participationname', 'link',)
|
||||
fields = ('participation_name', 'link',)
|
||||
template_name = 'django_tables2/bootstrap4.html'
|
||||
|
39
apps/participation/templates/participation/chat.html
Normal file
39
apps/participation/templates/participation/chat.html
Normal file
@ -0,0 +1,39 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="alert alert-warning">
|
||||
{% blocktrans trimmed %}
|
||||
The chat is located on the dedicated Matrix server:
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
|
||||
<div class="alert text-center">
|
||||
<a class="btn btn-success" href="https://element.correspondances-maths.fr/#/room/#faq:correspondances-maths.fr" target="_blank">
|
||||
<i class="fas fa-server"></i> {% trans "Access to the Matrix server" %}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-info">
|
||||
<p>
|
||||
{% blocktrans trimmed %}
|
||||
To connect to the server, you can select "Log in", then use your credentials of this platform to connect
|
||||
with the central authentication server, then you must trust the connection between the Matrix account and the
|
||||
platform. Finally, you will be able to access to the chat platform.
|
||||
{% endblocktrans %}
|
||||
</p>
|
||||
|
||||
<p>
|
||||
{% blocktrans trimmed %}
|
||||
You will be invited in some basic rooms. You must confirm the invitations to join channels.
|
||||
{% endblocktrans %}
|
||||
</p>
|
||||
|
||||
<p>
|
||||
{% blocktrans trimmed %}
|
||||
If you have any trouble, don't hesitate to contact us :)
|
||||
{% endblocktrans %}
|
||||
</p>
|
||||
</div>
|
||||
{% endblock %}
|
@ -13,7 +13,9 @@ Bonjour {{ user.registration }},
|
||||
L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer
|
||||
au {{ team.participation.get_problem_display }} des Correspondances des Jeunes Mathématicien·ne·s.
|
||||
Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe :
|
||||
<a href="{% url "participation:team_detail" pk=team.pk %}">{% url "participation:team_detail" pk=team.pk %}</a>
|
||||
<a href="https://{{ domain }}{% url "participation:team_detail" pk=team.pk %}">
|
||||
https://{{ domain }}{% url "participation:team_detail" pk=team.pk %}
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
|
@ -3,7 +3,7 @@ Bonjour {{ user.registration }},
|
||||
L'équipe « {{ team.name }} » ({{ team.trigram }}) vient de demander à valider son équipe pour participer
|
||||
au {{ team.participation.get_problem_display }} des Correspondances des Jeunes Mathématicien·ne·s.
|
||||
Vous pouvez décider d'accepter ou de refuser l'équipe en vous rendant sur la page de l'équipe :
|
||||
{% url "participation:team_detail" pk=team.pk %}
|
||||
https://{{ domain }}{% url "participation:team_detail" pk=team.pk %}
|
||||
|
||||
Cordialement,
|
||||
|
||||
|
@ -21,7 +21,7 @@
|
||||
<dl class="row">
|
||||
{% trans "No video sent" as novideo %}
|
||||
<dt class="col-sm-2">{% trans "Proposed solution:" %}</dt>
|
||||
<dd class="col-sm-10"><a href="{{ participation.solution.link|default:"#" }}" target="_blank">
|
||||
<dd class="col-sm-10"><a href="{{ participation.solution.link|default:"#" }}"{% if participation.solution.link %} target="_blank"{% endif %}>
|
||||
{{ participation.solution.link|default:novideo }}</a>
|
||||
{% if current_phase.phase_number == 1 or participation.solution.link == "" %}
|
||||
<button class="btn btn-primary" data-toggle="modal" data-target="#uploadSolutionModal">{% trans "Upload" %}</button>
|
||||
@ -35,23 +35,269 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if user.registration.is_admin or current_phase.phase_number >= 2 %}
|
||||
<hr>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="card bg-light shadow">
|
||||
<div class="card-header text-center">
|
||||
<h4>{% trans "Sent solution" %}</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<dl class="row">
|
||||
<dt class="col-xl-5 text-right">{% trans "Team that received your solution:" %}</dt>
|
||||
<dd class="col-md-5">{{ participation.sent_participation.team|default:any }}</dd>
|
||||
{% if user.registration.is_admin %}
|
||||
<dd class="col-xs-2">
|
||||
<button class="btn btn-primary" data-toggle="modal" data-target="#defineSentParticipationModal">{% trans "Change" %}</button>
|
||||
</dd>
|
||||
{% endif %}
|
||||
</dl>
|
||||
|
||||
{% if current_phase.phase_number == 2 %}
|
||||
<div class="alert alert-info">
|
||||
{% blocktrans trimmed %}
|
||||
The mentioned team received your video. They are now watching your video,
|
||||
and formulating questions. You would be able to exchange with the other phase during
|
||||
the next phase.
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
{% elif current_phase.phase_number == 3 %}
|
||||
<div class="alert alert-info">
|
||||
{% blocktrans trimmed with user_id=user.pk %}
|
||||
The other team sent you questions about your solution. Your are now able to answer them,
|
||||
then to exchange freely with the other team. You can click on the Chat button, or to
|
||||
connect to your dedicated Matrix account:
|
||||
<code>@corres2math_{{ user_id }}:correspondances-maths.fr</code>.
|
||||
You can use your own Matrix client, or use the dedicated Element client:
|
||||
<a href="https://element.correspondances-maths.fr">element.correpondances-maths.fr</a>
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
{% elif current_phase.phase_number == 4 %}
|
||||
<dl class="row">
|
||||
<dt class="col-xl-5 text-right">{% trans "Synthesis from the other team:" %}</dt>
|
||||
<dd class="col-sm-7"><a href="{{ participation.received_participation.synthesis.link|default:"#" }}"{% if participation.received_participation.synthesis.link %} target="_blank"{% endif %}>
|
||||
{{ participation.received_participation.synthesis.link|default:novideo }}</a>
|
||||
{% if participation.received_participation.synthesis.link %}
|
||||
<button class="btn btn-info" data-toggle="modal" data-target="#displayOtherSynthesisModal">{% trans "Display" %}</button>
|
||||
{% endif %}
|
||||
</dd>
|
||||
</dl>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="card bg-light shadow">
|
||||
<div class="card-header text-center">
|
||||
<h4>{% trans "Received solution" %}</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<dl class="row">
|
||||
<dt class="col-xl-5 text-right">{% trans "Team that sent you their solution:" %}</dt>
|
||||
<dd class="col-md-5">{{ participation.received_participation.team|default:any }}</dd>
|
||||
{% if user.registration.is_admin %}
|
||||
<dd class="col-xs-2">
|
||||
<button class="btn btn-primary" data-toggle="modal" data-target="#defineReceivedParticipationModal">{% trans "Change" %}</button>
|
||||
</dd>
|
||||
{% endif %}
|
||||
|
||||
<dt class="col-xl-5 text-right">{% trans "Proposed solution:" %}</dt>
|
||||
<dd class="col-sm-7"><a href="{{ participation.received_participation.solution.link|default:"#" }}"{% if participation.received_participation.solution.link %} target="_blank"{% endif %}>
|
||||
{{ participation.received_participation.solution.link|default:novideo }}</a>
|
||||
{% if participation.received_participation.solution.link %}
|
||||
<button class="btn btn-info" data-toggle="modal" data-target="#displayOtherSolutionModal">{% trans "Display" %}</button>
|
||||
{% endif %}
|
||||
</dd>
|
||||
|
||||
{% if current_phase.phase_number == 2 %}
|
||||
<div class="alert alert-info">
|
||||
{% blocktrans trimmed %}
|
||||
You received a solution about the same problem that you treated from another team.
|
||||
You are now encouraged to see the video, then to ask from 3 to 6 questions about the video.
|
||||
After that, you will be invited to exchange with the other team about the solution.
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
|
||||
{% for question in participation.questions.all %}
|
||||
<dd class="col-md-9 text-truncate">{{ question.question }}</dd>
|
||||
<dd class="col-md-3">
|
||||
<button class="btn btn-primary" data-toggle="modal" data-target="#updateQuestion{{ forloop.counter }}Modal">{% trans "Change" %}</button>
|
||||
</dd>
|
||||
<hr>
|
||||
{% endfor %}
|
||||
|
||||
{% if user.registration.participates %}
|
||||
<button class="btn btn-success" data-toggle="modal" data-target="#addQuestionModal">
|
||||
<i class="fas fa-plus-circle"></i> {% trans "Add a question" %}
|
||||
</button>
|
||||
{% endif %}
|
||||
{% elif current_phase.phase_number == 3 %}
|
||||
<div class="alert alert-info">
|
||||
{% blocktrans trimmed with user_id=user.pk %}
|
||||
You sent your questions to the other team about their solution. When they answer to
|
||||
your questions, you will be able to exchange freely with the other team.
|
||||
You can click on the Chat button, or to connect to your dedicated Matrix account:
|
||||
<code>@corres2math_{{ user_id }}:correspondances-maths.fr</code>.
|
||||
You can use your own Matrix client, or use the dedicated Element client:
|
||||
<a href="https://element.correspondances-maths.fr">element.correpondances-maths.fr</a>
|
||||
{% endblocktrans %}
|
||||
</div>
|
||||
{% elif current_phase.phase_number == 4 %}
|
||||
<div id="solution-container">
|
||||
<dl class="row">
|
||||
{% trans "No video sent" as novideo %}
|
||||
<dt class="col-sm-5 text-right">{% trans "Your synthesis of the exchange:" %}</dt>
|
||||
<dd class="col-sm-7"><a href="{{ participation.synthesis.link|default:"#" }}"{% if participation.synthesis.link %} target="_blank"{% endif %}>
|
||||
{{ participation.synthesis.link|default:novideo }}</a>
|
||||
<button class="btn btn-primary" data-toggle="modal" data-target="#uploadSynthesisModal">{% trans "Upload" %}</button>
|
||||
{% if participation.synthesis.link %}
|
||||
<button class="btn btn-info" data-toggle="modal" data-target="#displaySynthesisModal">{% trans "Display" %}</button>
|
||||
{% endif %}
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
{% endif %}
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if user.registration.is_admin %}
|
||||
{% trans "Define received video" as modal_title %}
|
||||
{% trans "Update" as modal_button %}
|
||||
{% url "participation:participation_receive_participation" pk=participation.pk as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="defineReceivedParticipation" %}
|
||||
|
||||
{% trans "Define team that receives your video" as modal_title %}
|
||||
{% trans "Update" as modal_button %}
|
||||
{% url "participation:participation_send_participation" pk=participation.pk as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="defineSentParticipation" %}
|
||||
{% endif %}
|
||||
|
||||
{% trans "Upload video" as modal_title %}
|
||||
{% trans "Upload" as modal_button %}
|
||||
{% url "participation:upload_video" pk=participation.solution_id as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="uploadSolution" %}
|
||||
|
||||
{% trans "Display solution" as modal_title %}
|
||||
{% trans "This video platform is not supported yet." as unsupported_platform %}
|
||||
{% include "base_modal.html" with modal_id="displaySolution" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.solution.as_iframe|default:unsupported_platform %}
|
||||
|
||||
|
||||
{% if user.registration.is_admin or current_phase.phase_number >= 2 %}
|
||||
{% if participation.received_participation.solution.link %}
|
||||
{% trans "Display solution" as modal_title %}
|
||||
{% trans "This video platform is not supported yet." as unsupported_platform %}
|
||||
{% include "base_modal.html" with modal_id="displayOtherSolution" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.received_participation.solution.as_iframe|default:unsupported_platform %}
|
||||
{% endif %}
|
||||
|
||||
{% if current_phase.phase_number == 2 %}
|
||||
{% trans "Add question" as modal_title %}
|
||||
{% trans "Add" as modal_button %}
|
||||
{% url "participation:add_question" pk=participation.pk as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="addQuestion" modal_button_type="success" %}
|
||||
{% endif %}
|
||||
|
||||
{% for question in participation.questions.all %}
|
||||
{% with number_str=forloop.counter|stringformat:"d"%}
|
||||
{% with modal_id="updateQuestion"|add:number_str %}
|
||||
{% trans "Delete" as delete %}
|
||||
{% with extra_modal_button='<button class="btn btn-danger" type="button" data-dismiss="modal" data-toggle="modal" data-target="#deleteQuestion'|add:number_str|add:'Modal">'|add:delete|add:"</button>"|safe %}
|
||||
{% trans "Update question" as modal_title %}
|
||||
{% trans "Update" as modal_button %}
|
||||
{% url "participation:update_question" pk=question.pk as modal_action %}
|
||||
{% include "base_modal.html" %}
|
||||
{% endwith %}
|
||||
{% endwith %}
|
||||
|
||||
{% with modal_id="deleteQuestion"|add:number_str %}
|
||||
{% trans "Delete question" as modal_title %}
|
||||
{% trans "Delete" as modal_button %}
|
||||
{% url "participation:delete_question" pk=question.pk as modal_action %}
|
||||
{% include "base_modal.html" with modal_button_type="danger" %}
|
||||
{% endwith %}
|
||||
{% endwith %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
{% if current_phase.phase_number >= 4 %}
|
||||
{% if participation.received_participation.synthesis.link %}
|
||||
{% trans "Display synthesis" as modal_title %}
|
||||
{% trans "This video platform is not supported yet." as unsupported_platform %}
|
||||
{% include "base_modal.html" with modal_id="displayOtherSynthesis" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.received_participation.synthesis.as_iframe|default:unsupported_platform %}
|
||||
{% endif %}
|
||||
|
||||
{% trans "Upload video" as modal_title %}
|
||||
{% trans "Upload" as modal_button %}
|
||||
{% url "participation:upload_video" pk=participation.synthesis_id as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="uploadSynthesis" %}
|
||||
|
||||
{% if participation.synthesis.link %}
|
||||
{% trans "Display synthesis" as modal_title %}
|
||||
{% trans "This video platform is not supported yet." as unsupported_platform %}
|
||||
{% include "base_modal.html" with modal_id="displaySynthesis" modal_action="" modal_button="" modal_additional_class="modal-lg" modal_content=participation.synthesis.as_iframe|default:unsupported_platform %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block extrajavascript %}
|
||||
<script>
|
||||
$(document).ready(function() {
|
||||
{% if user.registration.is_admin %}
|
||||
$('button[data-target="#defineReceivedParticipationModal"]').click(function() {
|
||||
let modalBody = $("#defineReceivedParticipationModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:participation_receive_participation" pk=participation.pk %} #form-content");
|
||||
});
|
||||
|
||||
$('button[data-target="#defineSentParticipationModal"]').click(function() {
|
||||
let modalBody = $("#defineSentParticipationModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:participation_send_participation" pk=participation.pk %} #form-content");
|
||||
});
|
||||
{% endif %}
|
||||
|
||||
{% if current_phase.phase_number == 2 %}
|
||||
$('button[data-target="#addQuestionModal"]').click(function() {
|
||||
let modalBody = $("#addQuestionModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:add_question" pk=participation.pk %} #form-content");
|
||||
});
|
||||
{% endif %}
|
||||
|
||||
{% for question in participation.questions.all %}
|
||||
$('button[data-target="#updateQuestion{{ forloop.counter }}Modal"]').click(function() {
|
||||
let modalBody = $("#updateQuestion{{ forloop.counter }}Modal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:update_question" pk=question.pk %} #form-content");
|
||||
});
|
||||
|
||||
{% if current_phase.phase_number == 2 %}
|
||||
$('button[data-target="#deleteQuestion{{ forloop.counter }}Modal"]').click(function() {
|
||||
let modalBody = $("#deleteQuestion{{ forloop.counter }}Modal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:delete_question" pk=question.pk %} #form-content");
|
||||
});
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
$('button[data-target="#uploadSolutionModal"]').click(function() {
|
||||
let modalBody = $("#uploadSolutionModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:upload_video" pk=participation.solution_id %} #form-content");
|
||||
});
|
||||
|
||||
{% if current_phase.phase_number == 4 %}
|
||||
$('button[data-target="#uploadSynthesisModal"]').click(function() {
|
||||
let modalBody = $("#uploadSynthesisModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:upload_video" pk=participation.synthesis_id %} #form-content");
|
||||
});
|
||||
{% endif %}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
@ -0,0 +1,17 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load crispy_forms_filters i18n %}
|
||||
|
||||
{% block content %}
|
||||
<form method="post">
|
||||
<div id="form-content">
|
||||
<div class="alert alert-danger">
|
||||
{% trans "Are you sure you want to delete this question?" %}
|
||||
</div>
|
||||
{% csrf_token %}
|
||||
{{ form|crispy }}
|
||||
</div>
|
||||
<button class="btn btn-danger" type="submit">{% trans "Delete" %}</button>
|
||||
</form>
|
||||
{% endblock content %}
|
||||
|
@ -0,0 +1,14 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load crispy_forms_filters i18n %}
|
||||
|
||||
{% block content %}
|
||||
<form method="post">
|
||||
<div id="form-content">
|
||||
{% csrf_token %}
|
||||
{{ form|crispy }}
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">{% trans "Send" %}</button>
|
||||
</form>
|
||||
{% endblock content %}
|
||||
|
@ -0,0 +1,14 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load crispy_forms_filters i18n %}
|
||||
|
||||
{% block content %}
|
||||
<form method="post">
|
||||
<div id="form-content">
|
||||
{% csrf_token %}
|
||||
{{ form|crispy }}
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">{% trans "Update" %}</button>
|
||||
</form>
|
||||
{% endblock content %}
|
||||
|
@ -0,0 +1,14 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load crispy_forms_filters i18n %}
|
||||
|
||||
{% block content %}
|
||||
<form method="post">
|
||||
<div id="form-content">
|
||||
{% csrf_token %}
|
||||
{{ form|crispy }}
|
||||
</div>
|
||||
<button class="btn btn-primary" type="submit">{% trans "Update" %}</button>
|
||||
</form>
|
||||
{% endblock content %}
|
||||
|
13
apps/participation/templates/participation/team_list.html
Normal file
13
apps/participation/templates/participation/team_list.html
Normal file
@ -0,0 +1,13 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load django_tables2 i18n %}
|
||||
|
||||
{% block contenttitle %}
|
||||
<h1>{% trans "All teams" %}</h1>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div id="form-content">
|
||||
{% render_table table %}
|
||||
</div>
|
||||
{% endblock %}
|
2
apps/participation/templatetags/__init__.py
Normal file
2
apps/participation/templatetags/__init__.py
Normal file
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
15
apps/participation/templatetags/calendar.py
Normal file
15
apps/participation/templatetags/calendar.py
Normal file
@ -0,0 +1,15 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django import template
|
||||
|
||||
from ..models import Phase
|
||||
|
||||
|
||||
def current_phase(nb):
|
||||
phase = Phase.current_phase()
|
||||
return phase is not None and phase.phase_number == nb
|
||||
|
||||
|
||||
register = template.Library()
|
||||
register.filter("current_phase", current_phase)
|
@ -1,13 +1,28 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.contrib.sites.models import Site
|
||||
from django.core.management import call_command
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from registration.models import StudentRegistration
|
||||
from django.utils import timezone
|
||||
from registration.models import CoachRegistration, StudentRegistration
|
||||
|
||||
from .models import Team
|
||||
from .models import Participation, Phase, Question, Team
|
||||
|
||||
|
||||
class TestStudentParticipation(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.superuser = User.objects.create_superuser(
|
||||
username="admin",
|
||||
email="admin@example.com",
|
||||
password="toto1234",
|
||||
)
|
||||
|
||||
self.user = User.objects.create(
|
||||
first_name="Toto",
|
||||
last_name="Toto",
|
||||
@ -27,13 +42,99 @@ class TestStudentParticipation(TestCase):
|
||||
access_code="azerty",
|
||||
grant_animath_access_videos=True,
|
||||
)
|
||||
self.question = Question.objects.create(participation=self.team.participation,
|
||||
question="Pourquoi l'existence précède l'essence ?")
|
||||
self.client.force_login(self.user)
|
||||
|
||||
# TODO Remove these lines
|
||||
str(self.team)
|
||||
str(self.team.participation)
|
||||
self.second_user = User.objects.create(
|
||||
first_name="Lalala",
|
||||
last_name="Lalala",
|
||||
email="lalala@example.com",
|
||||
password="lalala",
|
||||
)
|
||||
StudentRegistration.objects.create(
|
||||
user=self.second_user,
|
||||
student_class=11,
|
||||
school="Moon",
|
||||
give_contact_to_animath=True,
|
||||
email_confirmed=True,
|
||||
)
|
||||
self.second_team = Team.objects.create(
|
||||
name="Poor team",
|
||||
trigram="FFF",
|
||||
access_code="qwerty",
|
||||
grant_animath_access_videos=True,
|
||||
)
|
||||
|
||||
self.coach = User.objects.create(
|
||||
first_name="Coach",
|
||||
last_name="Coach",
|
||||
email="coach@example.com",
|
||||
password="coach",
|
||||
)
|
||||
CoachRegistration.objects.create(user=self.coach)
|
||||
|
||||
def test_admin_pages(self):
|
||||
"""
|
||||
Load Django-admin pages.
|
||||
"""
|
||||
self.client.force_login(self.superuser)
|
||||
|
||||
# Test team pages
|
||||
response = self.client.get(reverse("admin:index") + "participation/team/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"participation/team/{self.team.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.get(reverse("admin:index") +
|
||||
f"r/{ContentType.objects.get_for_model(Team).id}/"
|
||||
f"{self.team.pk}/")
|
||||
self.assertRedirects(response, "http://" + Site.objects.get().domain +
|
||||
str(self.team.get_absolute_url()), 302, 200)
|
||||
|
||||
# Test participation pages
|
||||
self.team.participation.valid = True
|
||||
self.team.participation.save()
|
||||
response = self.client.get(reverse("admin:index") + "participation/participation/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"participation/participation/{self.team.participation.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.get(reverse("admin:index") +
|
||||
f"r/{ContentType.objects.get_for_model(Participation).id}/"
|
||||
f"{self.team.participation.pk}/")
|
||||
self.assertRedirects(response, "http://" + Site.objects.get().domain +
|
||||
str(self.team.participation.get_absolute_url()), 302, 200)
|
||||
|
||||
# Test video pages
|
||||
response = self.client.get(reverse("admin:index") + "participation/video/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"participation/video/{self.team.participation.solution.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Test question pages
|
||||
response = self.client.get(reverse("admin:index") + "participation/question/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"participation/question/{self.question.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Test phase pages
|
||||
response = self.client.get(reverse("admin:index") + "participation/phase/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index") + "participation/phase/1/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_create_team(self):
|
||||
"""
|
||||
Try to create a team.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:create_team"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -59,8 +160,12 @@ class TestStudentParticipation(TestCase):
|
||||
trigram="TET",
|
||||
grant_animath_access_videos=False,
|
||||
))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_join_team(self):
|
||||
"""
|
||||
Try to join an existing team.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:join_team"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -83,11 +188,24 @@ class TestStudentParticipation(TestCase):
|
||||
))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_team_list(self):
|
||||
"""
|
||||
Test to display the list of teams.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:team_list"))
|
||||
self.assertTrue(response.status_code, 200)
|
||||
|
||||
def test_no_myteam_redirect_noteam(self):
|
||||
"""
|
||||
Test redirection.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:my_team_detail"))
|
||||
self.assertTrue(response.status_code, 200)
|
||||
|
||||
def test_team_detail(self):
|
||||
"""
|
||||
Try to display the information of a team.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
@ -97,10 +215,171 @@ class TestStudentParticipation(TestCase):
|
||||
response = self.client.get(reverse("participation:team_detail", args=(self.team.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_update_team(self):
|
||||
# Can't see other teams
|
||||
self.second_user.registration.team = self.second_team
|
||||
self.second_user.registration.save()
|
||||
self.client.force_login(self.second_user)
|
||||
response = self.client.get(reverse("participation:team_detail", args=(self.team.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_request_validate_team(self):
|
||||
"""
|
||||
The team ask for validation.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
second_user = User.objects.create(
|
||||
first_name="Blublu",
|
||||
last_name="Blublu",
|
||||
email="blublu@example.com",
|
||||
password="blublu",
|
||||
)
|
||||
StudentRegistration.objects.create(
|
||||
user=second_user,
|
||||
student_class=12,
|
||||
school="Jupiter",
|
||||
give_contact_to_animath=True,
|
||||
email_confirmed=True,
|
||||
team=self.team,
|
||||
photo_authorization="authorization/photo/mai-linh",
|
||||
)
|
||||
|
||||
third_user = User.objects.create(
|
||||
first_name="Zupzup",
|
||||
last_name="Zupzup",
|
||||
email="zupzup@example.com",
|
||||
password="zupzup",
|
||||
)
|
||||
StudentRegistration.objects.create(
|
||||
user=third_user,
|
||||
student_class=10,
|
||||
school="Sun",
|
||||
give_contact_to_animath=False,
|
||||
email_confirmed=True,
|
||||
team=self.team,
|
||||
photo_authorization="authorization/photo/yohann",
|
||||
)
|
||||
|
||||
self.client.force_login(self.superuser)
|
||||
# Admin users can't ask for validation
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="RequestValidationForm",
|
||||
engagement=True,
|
||||
))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
self.client.force_login(self.user)
|
||||
|
||||
self.assertIsNone(self.team.participation.valid)
|
||||
|
||||
resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,)))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
self.assertFalse(resp.context["can_validate"])
|
||||
# Can't validate
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="RequestValidationForm",
|
||||
engagement=True,
|
||||
))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
self.user.registration.photo_authorization = "authorization/photo/ananas"
|
||||
self.user.registration.save()
|
||||
|
||||
resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,)))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
self.assertFalse(resp.context["can_validate"])
|
||||
|
||||
self.team.participation.problem = 2
|
||||
self.team.participation.save()
|
||||
|
||||
resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,)))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
self.assertTrue(resp.context["can_validate"])
|
||||
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="RequestValidationForm",
|
||||
engagement=True,
|
||||
))
|
||||
self.assertRedirects(resp, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200)
|
||||
self.team.participation.refresh_from_db()
|
||||
self.assertFalse(self.team.participation.valid)
|
||||
self.assertIsNotNone(self.team.participation.valid)
|
||||
|
||||
# Team already asked for validation
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="RequestValidationForm",
|
||||
engagement=True,
|
||||
))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
def test_validate_team(self):
|
||||
"""
|
||||
A team asked for validation. Try to validate it.
|
||||
"""
|
||||
self.team.participation.valid = False
|
||||
self.team.participation.save()
|
||||
|
||||
# No right to do that
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="ValidateParticipationForm",
|
||||
message="J'ai 4 ans",
|
||||
validate=True,
|
||||
))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
self.client.force_login(self.superuser)
|
||||
|
||||
resp = self.client.get(reverse("participation:team_detail", args=(self.team.pk,)))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="ValidateParticipationForm",
|
||||
message="Woops I didn't said anything",
|
||||
))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
# Test invalidate team
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="ValidateParticipationForm",
|
||||
message="Wsh nope",
|
||||
invalidate=True,
|
||||
))
|
||||
self.assertRedirects(resp, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200)
|
||||
self.team.participation.refresh_from_db()
|
||||
self.assertIsNone(self.team.participation.valid)
|
||||
|
||||
# Team did not ask validation
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="ValidateParticipationForm",
|
||||
message="Bienvenue ça va être trop cool",
|
||||
validate=True,
|
||||
))
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
|
||||
self.team.participation.valid = False
|
||||
self.team.participation.save()
|
||||
|
||||
# Test validate team
|
||||
resp = self.client.post(reverse("participation:team_detail", args=(self.team.pk,)), data=dict(
|
||||
_form_type="ValidateParticipationForm",
|
||||
message="Bienvenue ça va être trop cool",
|
||||
validate=True,
|
||||
))
|
||||
self.assertRedirects(resp, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200)
|
||||
self.team.participation.refresh_from_db()
|
||||
self.assertTrue(self.team.participation.valid)
|
||||
|
||||
def test_update_team(self):
|
||||
"""
|
||||
Try to update team information.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
self.coach.registration.team = self.team
|
||||
self.coach.registration.save()
|
||||
|
||||
response = self.client.get(reverse("participation:update_team", args=(self.team.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -122,14 +401,54 @@ class TestStudentParticipation(TestCase):
|
||||
self.assertRedirects(response, reverse("participation:team_detail", args=(self.team.pk,)), 302, 200)
|
||||
self.assertTrue(Team.objects.filter(trigram="BBB", participation__problem=3).exists())
|
||||
|
||||
def test_no_myparticipation_redirect_nomyparticipation(self):
|
||||
response = self.client.get(reverse("participation:my_participation_detail"))
|
||||
self.assertTrue(response.status_code, 200)
|
||||
def test_leave_team(self):
|
||||
"""
|
||||
A user is in a team, and leaves it.
|
||||
"""
|
||||
# User is not in a team
|
||||
response = self.client.post(reverse("participation:team_leave"))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_participation_detail(self):
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
# Team is valid
|
||||
self.team.participation.valid = True
|
||||
self.team.participation.save()
|
||||
response = self.client.post(reverse("participation:team_leave"))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
# Unauthenticated users are redirected to login page
|
||||
self.client.logout()
|
||||
response = self.client.get(reverse("participation:team_leave"))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:team_leave"), 302, 200)
|
||||
|
||||
self.client.force_login(self.user)
|
||||
|
||||
self.team.participation.valid = None
|
||||
self.team.participation.save()
|
||||
|
||||
response = self.client.post(reverse("participation:team_leave"))
|
||||
self.assertRedirects(response, reverse("index"), 302, 200)
|
||||
self.user.registration.refresh_from_db()
|
||||
self.assertIsNone(self.user.registration.team)
|
||||
self.assertFalse(Team.objects.filter(pk=self.team.pk).exists())
|
||||
|
||||
def test_no_myparticipation_redirect_nomyparticipation(self):
|
||||
"""
|
||||
Ensure a permission denied when we search my team participation when we are in no team.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:my_participation_detail"))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_participation_detail(self):
|
||||
"""
|
||||
Try to display the detail of a team participation.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
# Can't see the participation if it is not valid
|
||||
response = self.client.get(reverse("participation:my_participation_detail"))
|
||||
self.assertRedirects(response,
|
||||
reverse("participation:participation_detail", args=(self.team.participation.pk,)),
|
||||
@ -145,7 +464,17 @@ class TestStudentParticipation(TestCase):
|
||||
response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Can't see other participations
|
||||
self.second_user.registration.team = self.second_team
|
||||
self.second_user.registration.save()
|
||||
self.client.force_login(self.second_user)
|
||||
response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_upload_video(self):
|
||||
"""
|
||||
Try to send a solution video link.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
@ -167,8 +496,221 @@ class TestStudentParticipation(TestCase):
|
||||
response = self.client.get(reverse("participation:participation_detail", args=(self.team.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Set the second phase
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=i - 2),
|
||||
end=timezone.now() + timedelta(days=i - 1))
|
||||
self.assertEqual(Phase.current_phase().phase_number, 2)
|
||||
|
||||
class TestAdminForbidden(TestCase):
|
||||
# Can't update the link during the second phase
|
||||
response = self.client.post(reverse("participation:upload_video", args=(self.team.participation.solution.pk,)),
|
||||
data=dict(link="https://youtube.com/watch?v=73nsrixx7eI"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_questions(self):
|
||||
"""
|
||||
Ensure that creating/updating/deleting a question is working.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
self.team.participation.valid = True
|
||||
self.team.participation.save()
|
||||
|
||||
response = self.client.get(reverse("participation:add_question", args=(self.team.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# We are not in second phase
|
||||
response = self.client.post(reverse("participation:add_question", args=(self.team.participation.pk,)),
|
||||
data=dict(question="I got censored!"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Set the second phase
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=i - 2),
|
||||
end=timezone.now() + timedelta(days=i - 1))
|
||||
self.assertEqual(Phase.current_phase().phase_number, 2)
|
||||
|
||||
# Create a question
|
||||
response = self.client.post(reverse("participation:add_question", args=(self.team.participation.pk,)),
|
||||
data=dict(question="I asked a question!"))
|
||||
self.assertRedirects(response, reverse("participation:participation_detail",
|
||||
args=(self.team.participation.pk,)), 302, 200)
|
||||
qs = Question.objects.filter(participation=self.team.participation, question="I asked a question!")
|
||||
self.assertTrue(qs.exists())
|
||||
question = qs.get()
|
||||
|
||||
# Update a question
|
||||
response = self.client.get(reverse("participation:update_question", args=(question.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.post(reverse("participation:update_question", args=(question.pk,)), data=dict(
|
||||
question="The question changed!",
|
||||
))
|
||||
self.assertRedirects(response, reverse("participation:participation_detail",
|
||||
args=(self.team.participation.pk,)), 302, 200)
|
||||
question.refresh_from_db()
|
||||
self.assertEqual(question.question, "The question changed!")
|
||||
|
||||
# Delete the question
|
||||
response = self.client.get(reverse("participation:delete_question", args=(question.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.post(reverse("participation:delete_question", args=(question.pk,)))
|
||||
self.assertRedirects(response, reverse("participation:participation_detail",
|
||||
args=(self.team.participation.pk,)), 302, 200)
|
||||
self.assertFalse(Question.objects.filter(pk=question.pk).exists())
|
||||
|
||||
# Non-authenticated users are redirected to login page
|
||||
self.client.logout()
|
||||
response = self.client.get(reverse("participation:add_question", args=(self.team.participation.pk,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" +
|
||||
reverse("participation:add_question", args=(self.team.participation.pk,)), 302, 200)
|
||||
response = self.client.get(reverse("participation:update_question", args=(self.question.pk,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" +
|
||||
reverse("participation:update_question", args=(self.question.pk,)), 302, 200)
|
||||
response = self.client.get(reverse("participation:delete_question", args=(self.question.pk,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" +
|
||||
reverse("participation:delete_question", args=(self.question.pk,)), 302, 200)
|
||||
|
||||
def test_current_phase(self):
|
||||
"""
|
||||
Ensure that the current phase is the good one.
|
||||
"""
|
||||
# We are before the beginning
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=2 * i),
|
||||
end=timezone.now() + timedelta(days=2 * i + 1))
|
||||
self.assertEqual(Phase.current_phase(), None)
|
||||
|
||||
# We are after the end
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() - timedelta(days=2 * i),
|
||||
end=timezone.now() - timedelta(days=2 * i + 1))
|
||||
self.assertEqual(Phase.current_phase().phase_number, Phase.objects.count())
|
||||
|
||||
# First phase
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=i - 1),
|
||||
end=timezone.now() + timedelta(days=i))
|
||||
self.assertEqual(Phase.current_phase().phase_number, 1)
|
||||
|
||||
# Second phase
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=i - 2),
|
||||
end=timezone.now() + timedelta(days=i - 1))
|
||||
self.assertEqual(Phase.current_phase().phase_number, 2)
|
||||
|
||||
# Third phase
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=i - 3),
|
||||
end=timezone.now() + timedelta(days=i - 2))
|
||||
self.assertEqual(Phase.current_phase().phase_number, 3)
|
||||
|
||||
# Fourth phase
|
||||
for i in range(1, 5):
|
||||
Phase.objects.filter(phase_number=i).update(start=timezone.now() + timedelta(days=i - 4),
|
||||
end=timezone.now() + timedelta(days=i - 3))
|
||||
self.assertEqual(Phase.current_phase().phase_number, 4)
|
||||
|
||||
response = self.client.get(reverse("participation:calendar"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("participation:update_phase", args=(4,)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
response = self.client.post(reverse("participation:update_phase", args=(4,)), data=dict(
|
||||
start=timezone.now(),
|
||||
end=timezone.now() + timedelta(days=3),
|
||||
))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
self.client.force_login(self.superuser)
|
||||
response = self.client.get(reverse("participation:update_phase", args=(4,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.post(reverse("participation:update_phase", args=(4,)), data=dict(
|
||||
start=timezone.now(),
|
||||
end=timezone.now() + timedelta(days=3),
|
||||
))
|
||||
self.assertRedirects(response, reverse("participation:calendar"), 302, 200)
|
||||
fourth_phase = Phase.objects.get(phase_number=4)
|
||||
self.assertEqual((fourth_phase.end - fourth_phase.start).days, 3)
|
||||
|
||||
# First phase must be before the other phases
|
||||
response = self.client.post(reverse("participation:update_phase", args=(1,)), data=dict(
|
||||
start=timezone.now() + timedelta(days=8),
|
||||
end=timezone.now() + timedelta(days=9),
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Fourth phase must be after the other phases
|
||||
response = self.client.post(reverse("participation:update_phase", args=(4,)), data=dict(
|
||||
start=timezone.now() - timedelta(days=9),
|
||||
end=timezone.now() - timedelta(days=8),
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# End must be after start
|
||||
response = self.client.post(reverse("participation:update_phase", args=(4,)), data=dict(
|
||||
start=timezone.now() + timedelta(days=3),
|
||||
end=timezone.now(),
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Unauthenticated user can't update the calendar
|
||||
self.client.logout()
|
||||
response = self.client.get(reverse("participation:calendar"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.get(reverse("participation:update_phase", args=(2,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" +
|
||||
reverse("participation:update_phase", args=(2,)), 302, 200)
|
||||
|
||||
def test_forbidden_access(self):
|
||||
"""
|
||||
Load personal pages and ensure that these are protected.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
|
||||
resp = self.client.get(reverse("participation:team_detail", args=(self.second_team.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:update_team", args=(self.second_team.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:team_authorizations", args=(self.second_team.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:participation_detail", args=(self.second_team.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:upload_video",
|
||||
args=(self.second_team.participation.solution.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:upload_video",
|
||||
args=(self.second_team.participation.synthesis.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:add_question", args=(self.second_team.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
question = Question.objects.create(participation=self.second_team.participation,
|
||||
question=self.question.question)
|
||||
resp = self.client.get(reverse("participation:update_question", args=(question.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
resp = self.client.get(reverse("participation:delete_question", args=(question.pk,)))
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
|
||||
def test_cover_matrix(self):
|
||||
"""
|
||||
Load matrix scripts, to cover them and ensure that they can run.
|
||||
"""
|
||||
self.user.registration.team = self.team
|
||||
self.user.registration.save()
|
||||
self.second_user.registration.team = self.second_team
|
||||
self.second_user.registration.save()
|
||||
self.team.participation.valid = True
|
||||
self.team.participation.received_participation = self.second_team.participation
|
||||
self.team.participation.save()
|
||||
|
||||
call_command('fix_matrix_channels')
|
||||
call_command('setup_third_phase')
|
||||
|
||||
|
||||
class TestAdmin(TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.user = User.objects.create_superuser(
|
||||
username="admin@example.com",
|
||||
@ -177,22 +719,135 @@ class TestAdminForbidden(TestCase):
|
||||
)
|
||||
self.client.force_login(self.user)
|
||||
|
||||
self.team1 = Team.objects.create(
|
||||
name="Toto",
|
||||
trigram="TOT",
|
||||
)
|
||||
self.team1.participation.valid = True
|
||||
self.team1.participation.problem = 1
|
||||
self.team1.participation.save()
|
||||
|
||||
self.team2 = Team.objects.create(
|
||||
name="Bliblu",
|
||||
trigram="BIU",
|
||||
)
|
||||
self.team2.participation.valid = True
|
||||
self.team2.participation.problem = 1
|
||||
self.team2.participation.save()
|
||||
|
||||
self.team3 = Team.objects.create(
|
||||
name="Zouplop",
|
||||
trigram="ZPL",
|
||||
)
|
||||
self.team3.participation.valid = True
|
||||
self.team3.participation.problem = 1
|
||||
self.team3.participation.save()
|
||||
|
||||
self.other_team = Team.objects.create(
|
||||
name="I am different",
|
||||
trigram="IAD",
|
||||
)
|
||||
self.other_team.participation.valid = True
|
||||
self.other_team.participation.problem = 2
|
||||
self.other_team.participation.save()
|
||||
|
||||
def test_research(self):
|
||||
"""
|
||||
Try to search some things.
|
||||
"""
|
||||
call_command("rebuild_index", "--noinput", "--verbosity", 0)
|
||||
|
||||
response = self.client.get(reverse("haystack_search") + "?q=" + self.team1.name)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.context["object_list"])
|
||||
|
||||
response = self.client.get(reverse("haystack_search") + "?q=" + self.team2.trigram)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.context["object_list"])
|
||||
|
||||
def test_set_received_video(self):
|
||||
"""
|
||||
Try to define the received video of a participation.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:participation_receive_participation",
|
||||
args=(self.team1.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.post(reverse("participation:participation_receive_participation",
|
||||
args=(self.team1.participation.pk,)),
|
||||
data=dict(received_participation=self.team2.participation.pk))
|
||||
self.assertRedirects(response, reverse("participation:participation_detail",
|
||||
args=(self.team1.participation.pk,)), 302, 200)
|
||||
|
||||
response = self.client.get(reverse("participation:participation_receive_participation",
|
||||
args=(self.team1.participation.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.post(reverse("participation:participation_send_participation",
|
||||
args=(self.team1.participation.pk,)),
|
||||
data=dict(sent_participation=self.team3.participation.pk))
|
||||
self.assertRedirects(response, reverse("participation:participation_detail",
|
||||
args=(self.team1.participation.pk,)), 302, 200)
|
||||
|
||||
self.team1.participation.refresh_from_db()
|
||||
self.team2.participation.refresh_from_db()
|
||||
self.team3.participation.refresh_from_db()
|
||||
|
||||
self.assertEqual(self.team1.participation.received_participation.pk, self.team2.participation.pk)
|
||||
self.assertEqual(self.team1.participation.sent_participation.pk, self.team3.participation.pk)
|
||||
self.assertEqual(self.team2.participation.sent_participation.pk, self.team1.participation.pk)
|
||||
self.assertEqual(self.team3.participation.received_participation.pk, self.team1.participation.pk)
|
||||
|
||||
# The other team didn't work on the same problem
|
||||
response = self.client.post(reverse("participation:participation_receive_participation",
|
||||
args=(self.team1.participation.pk,)),
|
||||
data=dict(received_participation=self.other_team.participation.pk))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.post(reverse("participation:participation_send_participation",
|
||||
args=(self.team1.participation.pk,)),
|
||||
data=dict(sent_participation=self.other_team.participation.pk))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_create_team_forbidden(self):
|
||||
"""
|
||||
Ensure that an admin can't create a team.
|
||||
"""
|
||||
response = self.client.post(reverse("participation:create_team"), data=dict(
|
||||
name="Test team",
|
||||
trigram="TES",
|
||||
grant_animath_access_videos=False,
|
||||
))
|
||||
self.assertTrue(response.status_code, 200)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_join_team_forbidden(self):
|
||||
"""
|
||||
Ensure that an admin can't join a team.
|
||||
"""
|
||||
team = Team.objects.create(name="Test", trigram="TES")
|
||||
|
||||
response = self.client.post(reverse("participation:join_team"), data=dict(
|
||||
access_code=team.access_code,
|
||||
))
|
||||
self.assertTrue(response.status_code, 200)
|
||||
self.assertTrue(response.status_code, 403)
|
||||
|
||||
def test_leave_team_forbidden(self):
|
||||
"""
|
||||
Ensure that an admin can't leave a team.
|
||||
"""
|
||||
response = self.client.get(reverse("participation:team_leave"))
|
||||
self.assertTrue(response.status_code, 403)
|
||||
|
||||
def test_my_team_forbidden(self):
|
||||
"""
|
||||
Ensure that an admin can't access to "My team".
|
||||
"""
|
||||
response = self.client.get(reverse("participation:my_team_detail"))
|
||||
self.assertTrue(response.status_code, 200)
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_my_participation_forbidden(self):
|
||||
"""
|
||||
Ensure that an admin can't access to "My participation".
|
||||
"""
|
||||
response = self.client.get(reverse("participation:my_participation_detail"))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
@ -1,8 +1,13 @@
|
||||
from django.urls import path
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from .views import CalendarView, CreateTeamView, JoinTeamView, MyParticipationDetailView, MyTeamDetailView, \
|
||||
ParticipationDetailView, PhaseUpdateView, TeamAuthorizationsView, TeamDetailView, TeamLeaveView, TeamUpdateView, \
|
||||
UploadVideoView
|
||||
from django.urls import path
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
from .views import CalendarView, CreateQuestionView, CreateTeamView, DeleteQuestionView, JoinTeamView, \
|
||||
MyParticipationDetailView, MyTeamDetailView, ParticipationDetailView, PhaseUpdateView, \
|
||||
SetParticipationReceiveParticipationView, SetParticipationSendParticipationView, TeamAuthorizationsView, \
|
||||
TeamDetailView, TeamLeaveView, TeamListView, TeamUpdateView, UpdateQuestionView, UploadVideoView
|
||||
|
||||
|
||||
app_name = "participation"
|
||||
@ -10,6 +15,7 @@ app_name = "participation"
|
||||
urlpatterns = [
|
||||
path("create_team/", CreateTeamView.as_view(), name="create_team"),
|
||||
path("join_team/", JoinTeamView.as_view(), name="join_team"),
|
||||
path("teams/", TeamListView.as_view(), name="team_list"),
|
||||
path("team/", MyTeamDetailView.as_view(), name="my_team_detail"),
|
||||
path("team/<int:pk>/", TeamDetailView.as_view(), name="team_detail"),
|
||||
path("team/<int:pk>/update/", TeamUpdateView.as_view(), name="update_team"),
|
||||
@ -18,6 +24,14 @@ urlpatterns = [
|
||||
path("detail/", MyParticipationDetailView.as_view(), name="my_participation_detail"),
|
||||
path("detail/<int:pk>/", ParticipationDetailView.as_view(), name="participation_detail"),
|
||||
path("detail/upload-video/<int:pk>/", UploadVideoView.as_view(), name="upload_video"),
|
||||
path("detail/<int:pk>/receive-participation/", SetParticipationReceiveParticipationView.as_view(),
|
||||
name="participation_receive_participation"),
|
||||
path("detail/<int:pk>/send-participation/", SetParticipationSendParticipationView.as_view(),
|
||||
name="participation_send_participation"),
|
||||
path("detail/<int:pk>/add-question/", CreateQuestionView.as_view(), name="add_question"),
|
||||
path("update-question/<int:pk>/", UpdateQuestionView.as_view(), name="update_question"),
|
||||
path("delete-question/<int:pk>/", DeleteQuestionView.as_view(), name="delete_question"),
|
||||
path("calendar/", CalendarView.as_view(), name="calendar"),
|
||||
path("calendar/<int:pk>/", PhaseUpdateView.as_view(), name="update_phase"),
|
||||
path("chat/", TemplateView.as_view(template_name="participation/chat.html"), name="chat")
|
||||
]
|
||||
|
@ -1,34 +1,40 @@
|
||||
import asyncio
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from io import BytesIO
|
||||
from zipfile import ZipFile
|
||||
|
||||
from django.shortcuts import redirect
|
||||
from django.views.generic.base import TemplateView
|
||||
|
||||
from corres2math.lists import get_sympa_client
|
||||
from corres2math.matrix import Matrix
|
||||
from corres2math.views import AdminMixin
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.contrib.sites.models import Site
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.mail import send_mail
|
||||
from django.db import transaction
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import redirect
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import CreateView, DetailView, FormView, RedirectView, UpdateView
|
||||
from django.views.generic import CreateView, DeleteView, DetailView, FormView, RedirectView, TemplateView, UpdateView
|
||||
from django.views.generic.edit import FormMixin, ProcessFormView
|
||||
from django_tables2 import SingleTableView
|
||||
from magic import Magic
|
||||
from registration.models import AdminRegistration
|
||||
|
||||
from .forms import JoinTeamForm, ParticipationForm, PhaseForm, RequestValidationForm, TeamForm, UploadVideoForm,\
|
||||
ValidateParticipationForm
|
||||
from .models import Participation, Phase, Team, Video
|
||||
from .tables import CalendarTable
|
||||
from .forms import JoinTeamForm, ParticipationForm, PhaseForm, QuestionForm, \
|
||||
ReceiveParticipationForm, RequestValidationForm, SendParticipationForm, TeamForm, \
|
||||
UploadVideoForm, ValidateParticipationForm
|
||||
from .models import Participation, Phase, Question, Team, Video
|
||||
from .tables import CalendarTable, TeamTable
|
||||
|
||||
|
||||
class CreateTeamView(LoginRequiredMixin, CreateView):
|
||||
"""
|
||||
Display the page to create a team for new users.
|
||||
"""
|
||||
|
||||
model = Team
|
||||
form_class = TeamForm
|
||||
extra_context = dict(title=_("Create team"))
|
||||
@ -36,6 +42,8 @@ class CreateTeamView(LoginRequiredMixin, CreateView):
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if not user.is_authenticated:
|
||||
return super().handle_no_permission()
|
||||
registration = user.registration
|
||||
if not registration.participates:
|
||||
raise PermissionDenied(_("You don't participate, so you can't create a team."))
|
||||
@ -45,15 +53,25 @@ class CreateTeamView(LoginRequiredMixin, CreateView):
|
||||
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
"""
|
||||
When a team is about to be created, the user automatically
|
||||
joins the team, a mailing list got created and the user is
|
||||
automatically subscribed to this mailing list, and finally
|
||||
a Matrix room is created and the user is invited in this room.
|
||||
"""
|
||||
ret = super().form_valid(form)
|
||||
# The user joins the team
|
||||
user = self.request.user
|
||||
registration = user.registration
|
||||
registration.team = form.instance
|
||||
registration.save()
|
||||
|
||||
# Subscribe the user mail address to the team mailing list
|
||||
get_sympa_client().subscribe(user.email, f"equipe-{form.instance.trigram.lower()}", False,
|
||||
f"{user.first_name} {user.last_name}")
|
||||
|
||||
Matrix.invite(f"#team-{form.instance.trigram.lower()}:correspondances-maths.fr",
|
||||
# Invite the user in the team Matrix room
|
||||
Matrix.invite(f"#equipe-{form.instance.trigram.lower()}:correspondances-maths.fr",
|
||||
f"@{user.registration.matrix_username}:correspondances-maths.fr")
|
||||
return ret
|
||||
|
||||
@ -62,6 +80,9 @@ class CreateTeamView(LoginRequiredMixin, CreateView):
|
||||
|
||||
|
||||
class JoinTeamView(LoginRequiredMixin, FormView):
|
||||
"""
|
||||
Participants can join a team with the access code of the team.
|
||||
"""
|
||||
model = Team
|
||||
form_class = JoinTeamForm
|
||||
extra_context = dict(title=_("Join team"))
|
||||
@ -69,6 +90,8 @@ class JoinTeamView(LoginRequiredMixin, FormView):
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if not user.is_authenticated:
|
||||
return super().handle_no_permission()
|
||||
registration = user.registration
|
||||
if not registration.participates:
|
||||
raise PermissionDenied(_("You don't participate, so you can't create a team."))
|
||||
@ -78,16 +101,25 @@ class JoinTeamView(LoginRequiredMixin, FormView):
|
||||
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
"""
|
||||
When a user joins a team, the user is automatically subscribed to
|
||||
the team mailing list,the user is invited in the team Matrix room.
|
||||
"""
|
||||
self.object = form.instance
|
||||
ret = super().form_valid(form)
|
||||
|
||||
# Join the team
|
||||
user = self.request.user
|
||||
registration = user.registration
|
||||
registration.team = form.instance
|
||||
registration.save()
|
||||
|
||||
# Subscribe to the team mailing list
|
||||
get_sympa_client().subscribe(user.email, f"equipe-{form.instance.trigram.lower()}", False,
|
||||
f"{user.first_name} {user.last_name}")
|
||||
|
||||
Matrix.invite(f"#team-{form.instance.trigram.lower()}:correspondances-maths.fr",
|
||||
# Invite the user in the team Matrix room
|
||||
Matrix.invite(f"#equipe-{form.instance.trigram.lower()}:correspondances-maths.fr",
|
||||
f"@{user.registration.matrix_username}:correspondances-maths.fr")
|
||||
return ret
|
||||
|
||||
@ -95,7 +127,20 @@ class JoinTeamView(LoginRequiredMixin, FormView):
|
||||
return reverse_lazy("participation:team_detail", args=(self.object.pk,))
|
||||
|
||||
|
||||
class TeamListView(AdminMixin, SingleTableView):
|
||||
"""
|
||||
Display the whole list of teams
|
||||
"""
|
||||
model = Team
|
||||
table_class = TeamTable
|
||||
ordering = ('participation__problem', 'trigram',)
|
||||
|
||||
|
||||
class MyTeamDetailView(LoginRequiredMixin, RedirectView):
|
||||
"""
|
||||
Redirect to the detail of the team in which the user is.
|
||||
"""
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
user = self.request.user
|
||||
registration = user.registration
|
||||
@ -107,12 +152,17 @@ class MyTeamDetailView(LoginRequiredMixin, RedirectView):
|
||||
|
||||
|
||||
class TeamDetailView(LoginRequiredMixin, FormMixin, ProcessFormView, DetailView):
|
||||
"""
|
||||
Display the detail of a team.
|
||||
"""
|
||||
model = Team
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
self.object = self.get_object()
|
||||
if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"]:
|
||||
# Ensure that the user is an admin or a member of the team
|
||||
if user.registration.is_admin or user.registration.participates and \
|
||||
user.registration.team and user.registration.team.pk == kwargs["pk"]:
|
||||
return super().get(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
@ -120,8 +170,11 @@ class TeamDetailView(LoginRequiredMixin, FormMixin, ProcessFormView, DetailView)
|
||||
context = super().get_context_data(**kwargs)
|
||||
|
||||
team = self.get_object()
|
||||
context["title"] = _("Detail of team {trigram}").format(trigram=self.object.trigram)
|
||||
context["request_validation_form"] = RequestValidationForm(self.request.POST or None)
|
||||
context["validation_form"] = ValidateParticipationForm(self.request.POST or None)
|
||||
# A team is complete when there are at least 3 members that have sent their photo authorization
|
||||
# and confirmed their email address
|
||||
context["can_validate"] = team.students.count() >= 3 and \
|
||||
all(r.email_confirmed for r in team.students.all()) and \
|
||||
all(r.photo_authorization for r in team.students.all()) and \
|
||||
@ -136,67 +189,94 @@ class TeamDetailView(LoginRequiredMixin, FormMixin, ProcessFormView, DetailView)
|
||||
return RequestValidationForm
|
||||
elif self.request.POST["_form_type"] == "ValidateParticipationForm":
|
||||
return ValidateParticipationForm
|
||||
return None
|
||||
|
||||
def form_valid(self, form):
|
||||
self.object = self.get_object()
|
||||
if isinstance(form, RequestValidationForm):
|
||||
if not self.request.user.registration.participates:
|
||||
form.add_error(None, _("You don't participate, so you can't request the validation of the team."))
|
||||
return self.form_invalid(form)
|
||||
if self.object.participation.valid is not None:
|
||||
form.add_error(None, _("The validation of the team is already done or pending."))
|
||||
return self.form_invalid(form)
|
||||
|
||||
self.object.participation.valid = False
|
||||
self.object.participation.save()
|
||||
|
||||
for admin in AdminRegistration.objects.all():
|
||||
mail_context = dict(user=admin.user, team=self.object)
|
||||
mail_plain = render_to_string("participation/mails/request_validation.txt", mail_context)
|
||||
mail_html = render_to_string("participation/mails/request_validation.html", mail_context)
|
||||
admin.user.email_user("[Corres2math] Validation d'équipe", mail_plain, html_message=mail_html)
|
||||
return self.handle_request_validation(form)
|
||||
elif isinstance(form, ValidateParticipationForm):
|
||||
if not self.request.user.registration.is_admin:
|
||||
form.add_error(None, _("You are not an administrator."))
|
||||
return self.form_invalid(form)
|
||||
elif self.object.participation.valid is not False:
|
||||
form.add_error(None, _("This team has no pending validation."))
|
||||
return self.form_invalid(form)
|
||||
return self.handle_validate_participation(form)
|
||||
|
||||
if "validate" in self.request.POST:
|
||||
self.object.participation.valid = True
|
||||
self.object.participation.save()
|
||||
mail_context = dict(team=self.object, message=form.cleaned_data["message"])
|
||||
mail_plain = render_to_string("participation/mails/team_validated.txt", mail_context)
|
||||
mail_html = render_to_string("participation/mails/team_validated.html", mail_context)
|
||||
send_mail("[Corres2math] Équipe validée", mail_plain, None, [self.object.email], html_message=mail_html)
|
||||
elif "invalidate" in self.request.POST:
|
||||
self.object.participation.valid = None
|
||||
self.object.participation.save()
|
||||
mail_context = dict(team=self.object, message=form.cleaned_data["message"])
|
||||
mail_plain = render_to_string("participation/mails/team_not_validated.txt", mail_context)
|
||||
mail_html = render_to_string("participation/mails/team_not_validated.html", mail_context)
|
||||
send_mail("[Corres2math] Équipe non validée", mail_plain, None, [self.object.email],
|
||||
html_message=mail_html)
|
||||
else:
|
||||
form.add_error(None, _("You must specify if you validate the registration or not."))
|
||||
return self.form_invalid(form)
|
||||
def handle_request_validation(self, form):
|
||||
"""
|
||||
A team requests to be validated
|
||||
"""
|
||||
if not self.request.user.registration.participates:
|
||||
form.add_error(None, _("You don't participate, so you can't request the validation of the team."))
|
||||
return self.form_invalid(form)
|
||||
if self.object.participation.valid is not None:
|
||||
form.add_error(None, _("The validation of the team is already done or pending."))
|
||||
return self.form_invalid(form)
|
||||
if not self.get_context_data()["can_validate"]:
|
||||
form.add_error(None, _("The team can't be validated: missing email address confirmations, "
|
||||
"photo authorizations, people or the chosen problem is not set."))
|
||||
return self.form_invalid(form)
|
||||
|
||||
return super().form_invalid(form)
|
||||
self.object.participation.valid = False
|
||||
self.object.participation.save()
|
||||
|
||||
for admin in AdminRegistration.objects.all():
|
||||
mail_context = dict(user=admin.user, team=self.object, domain=Site.objects.first().domain)
|
||||
mail_plain = render_to_string("participation/mails/request_validation.txt", mail_context)
|
||||
mail_html = render_to_string("participation/mails/request_validation.html", mail_context)
|
||||
admin.user.email_user("[Corres2math] Validation d'équipe", mail_plain, html_message=mail_html)
|
||||
return super().form_valid(form)
|
||||
|
||||
def handle_validate_participation(self, form):
|
||||
"""
|
||||
An admin validates the team (or not)
|
||||
"""
|
||||
if not self.request.user.registration.is_admin:
|
||||
form.add_error(None, _("You are not an administrator."))
|
||||
return self.form_invalid(form)
|
||||
elif self.object.participation.valid is not False:
|
||||
form.add_error(None, _("This team has no pending validation."))
|
||||
return self.form_invalid(form)
|
||||
|
||||
if "validate" in self.request.POST:
|
||||
self.object.participation.valid = True
|
||||
self.object.participation.save()
|
||||
mail_context = dict(team=self.object, message=form.cleaned_data["message"])
|
||||
mail_plain = render_to_string("participation/mails/team_validated.txt", mail_context)
|
||||
mail_html = render_to_string("participation/mails/team_validated.html", mail_context)
|
||||
send_mail("[Corres2math] Équipe validée", mail_plain, None, [self.object.email], html_message=mail_html)
|
||||
|
||||
get_sympa_client().subscribe(self.object.email, "equipes", False, f"Equipe {self.object.name}")
|
||||
get_sympa_client().unsubscribe(self.object.email, "equipes-non-valides", False)
|
||||
get_sympa_client().subscribe(self.object.email, f"probleme-{self.object.participation.problem}", False,
|
||||
f"Equipe {self.object.name}")
|
||||
elif "invalidate" in self.request.POST:
|
||||
self.object.participation.valid = None
|
||||
self.object.participation.save()
|
||||
mail_context = dict(team=self.object, message=form.cleaned_data["message"])
|
||||
mail_plain = render_to_string("participation/mails/team_not_validated.txt", mail_context)
|
||||
mail_html = render_to_string("participation/mails/team_not_validated.html", mail_context)
|
||||
send_mail("[Corres2math] Équipe non validée", mail_plain, None, [self.object.email],
|
||||
html_message=mail_html)
|
||||
else:
|
||||
form.add_error(None, _("You must specify if you validate the registration or not."))
|
||||
return self.form_invalid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_success_url(self):
|
||||
return self.request.path
|
||||
|
||||
|
||||
class TeamUpdateView(LoginRequiredMixin, UpdateView):
|
||||
"""
|
||||
Update the detail of a team
|
||||
"""
|
||||
model = Team
|
||||
form_class = TeamForm
|
||||
template_name = "participation/update_team.html"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"]:
|
||||
if not user.is_authenticated:
|
||||
return super().handle_no_permission()
|
||||
if user.registration.is_admin or user.registration.participates and \
|
||||
user.registration.team and \
|
||||
user.registration.team.pk == kwargs["pk"]:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
@ -204,6 +284,7 @@ class TeamUpdateView(LoginRequiredMixin, UpdateView):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["participation_form"] = ParticipationForm(data=self.request.POST or None,
|
||||
instance=self.object.participation)
|
||||
context["title"] = _("Update team {trigram}").format(trigram=self.object.trigram)
|
||||
return context
|
||||
|
||||
@transaction.atomic
|
||||
@ -220,10 +301,15 @@ class TeamUpdateView(LoginRequiredMixin, UpdateView):
|
||||
|
||||
|
||||
class TeamAuthorizationsView(LoginRequiredMixin, DetailView):
|
||||
"""
|
||||
Get as a ZIP archive all the authorizations that are sent
|
||||
"""
|
||||
model = Team
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if not user.is_authenticated:
|
||||
return super().handle_no_permission()
|
||||
if user.registration.is_admin or user.registration.participates and user.registration.team.pk == kwargs["pk"]:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
@ -247,29 +333,43 @@ class TeamAuthorizationsView(LoginRequiredMixin, DetailView):
|
||||
|
||||
|
||||
class TeamLeaveView(LoginRequiredMixin, TemplateView):
|
||||
"""
|
||||
A team member leaves a team
|
||||
"""
|
||||
template_name = "participation/team_leave.html"
|
||||
extra_context = dict(title=_("Leave team"))
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return self.handle_no_permission()
|
||||
if not request.user.registration.team:
|
||||
if not request.user.registration.participates or not request.user.registration.team:
|
||||
raise PermissionDenied(_("You are not in a team."))
|
||||
if request.user.registration.team.participation.valid is not None:
|
||||
if request.user.registration.team.participation.valid:
|
||||
raise PermissionDenied(_("The team is already validated or the validation is pending."))
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
@transaction.atomic()
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""
|
||||
When the team is left, the user is unsubscribed from the team mailing list
|
||||
and kicked from the team room.
|
||||
"""
|
||||
team = request.user.registration.team
|
||||
request.user.registration.team = None
|
||||
request.user.registration.save()
|
||||
get_sympa_client().unsubscribe(request.user.email, f"equipe-{team.trigram.lower()}", False)
|
||||
Matrix.kick(f"#equipe-{team.trigram.lower()}:correspondances-maths.fr",
|
||||
f"@{request.user.registration.matrix_username}:correspondances-maths.fr",
|
||||
"Équipe quittée")
|
||||
if team.students.count() + team.coachs.count() == 0:
|
||||
team.delete()
|
||||
return redirect(reverse_lazy("index"))
|
||||
|
||||
|
||||
class MyParticipationDetailView(LoginRequiredMixin, RedirectView):
|
||||
"""
|
||||
Redirects to the detail view of the participation of the team.
|
||||
"""
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
user = self.request.user
|
||||
registration = user.registration
|
||||
@ -281,13 +381,19 @@ class MyParticipationDetailView(LoginRequiredMixin, RedirectView):
|
||||
|
||||
|
||||
class ParticipationDetailView(LoginRequiredMixin, DetailView):
|
||||
"""
|
||||
Display detail about the participation of a team, and manage the video submission.
|
||||
"""
|
||||
model = Participation
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if not user.is_authenticated:
|
||||
return super().handle_no_permission()
|
||||
if not self.get_object().valid:
|
||||
raise PermissionDenied(_("The team is not validated yet."))
|
||||
if user.registration.is_admin or user.registration.participates \
|
||||
and user.registration.team.participation \
|
||||
and user.registration.team.participation.pk == kwargs["pk"]:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
@ -301,13 +407,126 @@ class ParticipationDetailView(LoginRequiredMixin, DetailView):
|
||||
return context
|
||||
|
||||
|
||||
class SetParticipationReceiveParticipationView(AdminMixin, UpdateView):
|
||||
"""
|
||||
Define the solution that a team will receive.
|
||||
"""
|
||||
model = Participation
|
||||
form_class = ReceiveParticipationForm
|
||||
template_name = "participation/receive_participation_form.html"
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("participation:participation_detail", args=(self.kwargs["pk"],))
|
||||
|
||||
|
||||
class SetParticipationSendParticipationView(AdminMixin, UpdateView):
|
||||
"""
|
||||
Define the team where the solution will be sent.
|
||||
"""
|
||||
model = Participation
|
||||
form_class = SendParticipationForm
|
||||
template_name = "participation/send_participation_form.html"
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("participation:participation_detail", args=(self.kwargs["pk"],))
|
||||
|
||||
|
||||
class CreateQuestionView(LoginRequiredMixin, CreateView):
|
||||
"""
|
||||
Ask a question to another team.
|
||||
"""
|
||||
participation: Participation
|
||||
model = Question
|
||||
form_class = QuestionForm
|
||||
extra_context = dict(title=_("Create question"))
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not request.user.is_authenticated:
|
||||
return self.handle_no_permission()
|
||||
self.participation = Participation.objects.get(pk=kwargs["pk"])
|
||||
if request.user.registration.is_admin or \
|
||||
request.user.registration.participates and \
|
||||
self.participation.valid and \
|
||||
request.user.registration.team.pk == self.participation.team_id:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
def form_valid(self, form):
|
||||
form.instance.participation = self.participation
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("participation:participation_detail", args=(self.participation.pk,))
|
||||
|
||||
|
||||
class UpdateQuestionView(LoginRequiredMixin, UpdateView):
|
||||
"""
|
||||
Edit a question.
|
||||
"""
|
||||
model = Question
|
||||
form_class = QuestionForm
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
if not request.user.is_authenticated:
|
||||
return self.handle_no_permission()
|
||||
if request.user.registration.is_admin or \
|
||||
request.user.registration.participates and \
|
||||
self.object.participation.valid and \
|
||||
request.user.registration.team.pk == self.object.participation.team_id:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
def form_valid(self, form):
|
||||
if not self.request.user.registration.is_admin and Phase.current_phase().phase_number != 2:
|
||||
form.add_error(None, _("You can update your questions now."))
|
||||
return self.form_invalid(form)
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("participation:participation_detail", args=(self.object.participation.pk,))
|
||||
|
||||
|
||||
class DeleteQuestionView(LoginRequiredMixin, DeleteView):
|
||||
"""
|
||||
Remove a question.
|
||||
"""
|
||||
model = Question
|
||||
extra_context = dict(title=_("Delete question"))
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
if not request.user.is_authenticated:
|
||||
return self.handle_no_permission()
|
||||
if request.user.registration.is_admin or \
|
||||
request.user.registration.participates and \
|
||||
self.object.participation.valid and \
|
||||
request.user.registration.team.pk == self.object.participation.team_id:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
def delete(self, request, *args, **kwargs):
|
||||
if not request.user.registration.is_admin and Phase.current_phase().phase_number != 2:
|
||||
raise PermissionDenied(_("You can update your questions now."))
|
||||
return super().delete(request, *args, **kwargs)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("participation:participation_detail", args=(self.object.participation.pk,))
|
||||
|
||||
|
||||
class UploadVideoView(LoginRequiredMixin, UpdateView):
|
||||
"""
|
||||
Upload a solution video for a team.
|
||||
"""
|
||||
model = Video
|
||||
form_class = UploadVideoForm
|
||||
template_name = "participation/upload_video.html"
|
||||
extra_context = dict(title=_("Upload video"))
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if not user.is_authenticated:
|
||||
return super().handle_no_permission()
|
||||
if user.registration.is_admin or user.registration.participates \
|
||||
and user.registration.team.participation.pk == self.get_object().participation.pk:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
@ -318,13 +537,21 @@ class UploadVideoView(LoginRequiredMixin, UpdateView):
|
||||
|
||||
|
||||
class CalendarView(SingleTableView):
|
||||
"""
|
||||
Display the calendar of the action.
|
||||
"""
|
||||
table_class = CalendarTable
|
||||
model = Phase
|
||||
extra_context = dict(title=_("Calendar"))
|
||||
|
||||
|
||||
class PhaseUpdateView(AdminMixin, UpdateView):
|
||||
"""
|
||||
Update a phase of the calendar, if we have sufficient rights.
|
||||
"""
|
||||
model = Phase
|
||||
form_class = PhaseForm
|
||||
extra_context = dict(title=_("Calendar update"))
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("participation:calendar")
|
||||
|
@ -1 +1,4 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
default_app_config = 'registration.apps.RegistrationConfig'
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.contrib import admin
|
||||
from polymorphic.admin import PolymorphicChildModelAdmin, PolymorphicParentModelAdmin
|
||||
|
||||
|
@ -1,12 +1,23 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.apps import AppConfig
|
||||
from django.db.models.signals import post_save, pre_save
|
||||
|
||||
|
||||
class RegistrationConfig(AppConfig):
|
||||
"""
|
||||
Registration app contains the detail about users only.
|
||||
"""
|
||||
name = 'registration'
|
||||
|
||||
def ready(self):
|
||||
from registration.signals import set_username, send_email_link, create_admin_registration
|
||||
from registration.signals import create_admin_registration, invite_to_public_rooms, \
|
||||
set_username, send_email_link
|
||||
pre_save.connect(set_username, "auth.User")
|
||||
pre_save.connect(send_email_link, "auth.User")
|
||||
post_save.connect(create_admin_registration, "auth.User")
|
||||
post_save.connect(invite_to_public_rooms, "registration.Registration")
|
||||
post_save.connect(invite_to_public_rooms, "registration.StudentRegistration")
|
||||
post_save.connect(invite_to_public_rooms, "registration.CoachRegistration")
|
||||
post_save.connect(invite_to_public_rooms, "registration.AdminRegistration")
|
||||
|
@ -1,7 +1,10 @@
|
||||
from cas_server.auth import DjangoAuthUser
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from cas_server.auth import DjangoAuthUser # pragma: no cover
|
||||
|
||||
|
||||
class CustomAuthUser(DjangoAuthUser):
|
||||
class CustomAuthUser(DjangoAuthUser): # pragma: no cover
|
||||
"""
|
||||
Override Django Auth User model to define a custom Matrix username.
|
||||
"""
|
||||
|
@ -13,5 +13,14 @@
|
||||
"single_log_out": true,
|
||||
"single_log_out_callback": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"model": "cas_server.replaceattributname",
|
||||
"pk": 1,
|
||||
"fields": {
|
||||
"name": "display_name",
|
||||
"replace": "",
|
||||
"service_pattern": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django import forms
|
||||
from django.contrib.auth.forms import UserCreationForm
|
||||
from django.contrib.auth.models import User
|
||||
@ -9,6 +12,11 @@ from .models import AdminRegistration, CoachRegistration, StudentRegistration
|
||||
|
||||
|
||||
class SignupForm(UserCreationForm):
|
||||
"""
|
||||
Signup form to registers participants and coaches
|
||||
They can choose the role at the registration.
|
||||
"""
|
||||
|
||||
role = forms.ChoiceField(
|
||||
label=lambda: _("role").capitalize(),
|
||||
choices=lambda: [
|
||||
@ -17,6 +25,15 @@ class SignupForm(UserCreationForm):
|
||||
],
|
||||
)
|
||||
|
||||
def clean_email(self):
|
||||
"""
|
||||
Ensure that the email address is unique.
|
||||
"""
|
||||
email = self.data["email"]
|
||||
if User.objects.filter(email=email).exists():
|
||||
self.add_error("email", _("This email address is already used."))
|
||||
return email
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["first_name"].required = True
|
||||
@ -29,6 +46,10 @@ class SignupForm(UserCreationForm):
|
||||
|
||||
|
||||
class UserForm(forms.ModelForm):
|
||||
"""
|
||||
Replace the default user form to require the first name, last name and the email.
|
||||
The username is always equal to the email.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields["first_name"].required = True
|
||||
@ -41,17 +62,26 @@ class UserForm(forms.ModelForm):
|
||||
|
||||
|
||||
class StudentRegistrationForm(forms.ModelForm):
|
||||
"""
|
||||
A student can update its class, its school and if it allows Animath to contact him/her later.
|
||||
"""
|
||||
class Meta:
|
||||
model = StudentRegistration
|
||||
fields = ('student_class', 'school', 'give_contact_to_animath',)
|
||||
fields = ('team', 'student_class', 'school', 'give_contact_to_animath', 'email_confirmed',)
|
||||
|
||||
|
||||
class PhotoAuthorizationForm(forms.ModelForm):
|
||||
"""
|
||||
Form to send a photo authorization.
|
||||
"""
|
||||
def clean_photo_authorization(self):
|
||||
file = self.files["photo_authorization"]
|
||||
if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]:
|
||||
raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file."))
|
||||
return self.cleaned_data["photo_authorization"]
|
||||
if "photo_authorization" in self.files:
|
||||
file = self.files["photo_authorization"]
|
||||
if file.size > 2e6:
|
||||
raise ValidationError(_("The uploaded file size must be under 2 Mo."))
|
||||
if file.content_type not in ["application/pdf", "image/png", "image/jpeg"]:
|
||||
raise ValidationError(_("The uploaded file must be a PDF, PNG of JPEG file."))
|
||||
return self.cleaned_data["photo_authorization"]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
@ -63,12 +93,18 @@ class PhotoAuthorizationForm(forms.ModelForm):
|
||||
|
||||
|
||||
class CoachRegistrationForm(forms.ModelForm):
|
||||
"""
|
||||
A coach can tell its professional activity.
|
||||
"""
|
||||
class Meta:
|
||||
model = CoachRegistration
|
||||
fields = ('professional_activity', 'give_contact_to_animath',)
|
||||
fields = ('team', 'professional_activity', 'give_contact_to_animath', 'email_confirmed',)
|
||||
|
||||
|
||||
class AdminRegistrationForm(forms.ModelForm):
|
||||
"""
|
||||
Admins can tell everything they want.
|
||||
"""
|
||||
class Meta:
|
||||
model = AdminRegistration
|
||||
fields = ('role', 'give_contact_to_animath',)
|
||||
fields = ('role', 'give_contact_to_animath', 'email_confirmed',)
|
||||
|
@ -1,8 +1,9 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-21 15:51
|
||||
# Generated by Django 3.1.3 on 2020-11-04 12:05
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import registration.models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
@ -11,8 +12,8 @@ class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('contenttypes', '0002_remove_content_type_name'),
|
||||
('participation', '0001_initial'),
|
||||
('contenttypes', '0002_remove_content_type_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
@ -21,8 +22,8 @@ class Migration(migrations.Migration):
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('give_contact_to_animath', models.BooleanField(default=False, verbose_name='Grant Animath to contact me in the future about other actions')),
|
||||
('email_confirmed', models.BooleanField(default=False, verbose_name='email confirmed')),
|
||||
('polymorphic_ctype', models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='polymorphic_registration.registration_set+', to='contenttypes.contenttype')),
|
||||
('team', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, to='participation.team', verbose_name='team')),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user')),
|
||||
],
|
||||
options={
|
||||
@ -42,24 +43,14 @@ class Migration(migrations.Migration):
|
||||
},
|
||||
bases=('registration.registration',),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='CoachRegistration',
|
||||
fields=[
|
||||
('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.registration')),
|
||||
('professional_activity', models.TextField(verbose_name='professional activity')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'coach registration',
|
||||
'verbose_name_plural': 'coach registrations',
|
||||
},
|
||||
bases=('registration.registration',),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='StudentRegistration',
|
||||
fields=[
|
||||
('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.registration')),
|
||||
('student_class', models.IntegerField(choices=[(12, '12th grade'), (11, '11th grade'), (10, '10th grade or lower')], verbose_name='student class')),
|
||||
('school', models.CharField(max_length=255, verbose_name='school')),
|
||||
('photo_authorization', models.FileField(blank=True, default='', upload_to=registration.models.get_random_filename, verbose_name='photo authorization')),
|
||||
('team', models.ForeignKey(default=None, blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='students', to='participation.team', verbose_name='team')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'student registration',
|
||||
@ -67,4 +58,17 @@ class Migration(migrations.Migration):
|
||||
},
|
||||
bases=('registration.registration',),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='CoachRegistration',
|
||||
fields=[
|
||||
('registration_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='registration.registration')),
|
||||
('professional_activity', models.TextField(verbose_name='professional activity')),
|
||||
('team', models.ForeignKey(default=None, blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='coachs', to='participation.team', verbose_name='team')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'coach registration',
|
||||
'verbose_name_plural': 'coach registrations',
|
||||
},
|
||||
bases=('registration.registration',),
|
||||
),
|
||||
]
|
||||
|
@ -1,29 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-21 17:48
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('participation', '0001_initial'),
|
||||
('registration', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='registration',
|
||||
name='team',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='coachregistration',
|
||||
name='team',
|
||||
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='coachs', to='participation.team', verbose_name='team'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='studentregistration',
|
||||
name='team',
|
||||
field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='students', to='participation.team', verbose_name='team'),
|
||||
),
|
||||
]
|
@ -1,18 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-22 16:56
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('registration', '0002_auto_20200921_1948'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='registration',
|
||||
name='email_confirmed',
|
||||
field=models.BooleanField(default=False, verbose_name='email confirmed'),
|
||||
),
|
||||
]
|
@ -1,19 +0,0 @@
|
||||
# Generated by Django 3.1.1 on 2020-09-24 20:36
|
||||
|
||||
from django.db import migrations, models
|
||||
import registration.models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('registration', '0003_registration_email_confirmed'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='studentregistration',
|
||||
name='photo_authorization',
|
||||
field=models.FileField(blank=True, default='', upload_to=registration.models.get_random_filename, verbose_name='photo authorization'),
|
||||
),
|
||||
]
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from corres2math.tokens import email_validation_token
|
||||
from django.contrib.sites.models import Site
|
||||
from django.db import models
|
||||
@ -11,6 +14,11 @@ from polymorphic.models import PolymorphicModel
|
||||
|
||||
|
||||
class Registration(PolymorphicModel):
|
||||
"""
|
||||
Registrations store extra content that are not asked in the User Model.
|
||||
This is specific to the role of the user, see StudentRegistration,
|
||||
ClassRegistration or AdminRegistration..
|
||||
"""
|
||||
user = models.OneToOneField(
|
||||
"auth.User",
|
||||
on_delete=models.CASCADE,
|
||||
@ -28,6 +36,10 @@ class Registration(PolymorphicModel):
|
||||
)
|
||||
|
||||
def send_email_validation_link(self):
|
||||
"""
|
||||
The account got created or the email got changed.
|
||||
Send an email that contains a link to validate the address.
|
||||
"""
|
||||
subject = "[Corres2math] " + str(_("Activate your Correspondances account"))
|
||||
token = email_validation_token.make_token(self.user)
|
||||
uid = urlsafe_base64_encode(force_bytes(self.user.pk))
|
||||
@ -49,11 +61,11 @@ class Registration(PolymorphicModel):
|
||||
self.user.email_user(subject, message, html_message=html)
|
||||
|
||||
@property
|
||||
def type(self):
|
||||
def type(self): # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
def form_class(self):
|
||||
def form_class(self): # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@ -84,11 +96,16 @@ def get_random_filename(instance, filename):
|
||||
|
||||
|
||||
class StudentRegistration(Registration):
|
||||
"""
|
||||
Specific registration for students.
|
||||
They have a team, a student class and a school.
|
||||
"""
|
||||
team = models.ForeignKey(
|
||||
"participation.Team",
|
||||
related_name="students",
|
||||
on_delete=models.PROTECT,
|
||||
null=True,
|
||||
blank=True,
|
||||
default=None,
|
||||
verbose_name=_("team"),
|
||||
)
|
||||
@ -129,11 +146,16 @@ class StudentRegistration(Registration):
|
||||
|
||||
|
||||
class CoachRegistration(Registration):
|
||||
"""
|
||||
Specific registration for coaches.
|
||||
They have a team and a professional activity.
|
||||
"""
|
||||
team = models.ForeignKey(
|
||||
"participation.Team",
|
||||
related_name="coachs",
|
||||
on_delete=models.PROTECT,
|
||||
null=True,
|
||||
blank=True,
|
||||
default=None,
|
||||
verbose_name=_("team"),
|
||||
)
|
||||
@ -157,6 +179,10 @@ class CoachRegistration(Registration):
|
||||
|
||||
|
||||
class AdminRegistration(Registration):
|
||||
"""
|
||||
Specific registration for admins.
|
||||
They have a field to justify they status.
|
||||
"""
|
||||
role = models.TextField(
|
||||
verbose_name=_("role of the administrator"),
|
||||
)
|
||||
|
@ -1,9 +1,15 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from haystack import indexes
|
||||
|
||||
from .models import Registration
|
||||
|
||||
|
||||
class RegistrationIndex(indexes.ModelSearchIndex, indexes.Indexable):
|
||||
"""
|
||||
Registrations are indexed by the user detail.
|
||||
"""
|
||||
text = indexes.NgramField(document=True, use_template=True)
|
||||
|
||||
class Meta:
|
||||
|
@ -1,14 +1,25 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from corres2math.lists import get_sympa_client
|
||||
from corres2math.matrix import Matrix
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from .models import AdminRegistration, Registration
|
||||
|
||||
|
||||
def set_username(instance, **_):
|
||||
"""
|
||||
Ensure that the user username is always equal to the user email address.
|
||||
"""
|
||||
instance.username = instance.email
|
||||
|
||||
|
||||
def send_email_link(instance, **_):
|
||||
"""
|
||||
If the email address got changed, send a new validation link
|
||||
and update the registration status in the team mailing list.
|
||||
"""
|
||||
if instance.pk:
|
||||
old_instance = User.objects.get(pk=instance.pk)
|
||||
if old_instance.email != instance.email:
|
||||
@ -25,5 +36,21 @@ def send_email_link(instance, **_):
|
||||
|
||||
|
||||
def create_admin_registration(instance, **_):
|
||||
"""
|
||||
When a super user got created through console,
|
||||
ensure that an admin registration is created.
|
||||
"""
|
||||
if instance.is_superuser:
|
||||
AdminRegistration.objects.get_or_create(user=instance)
|
||||
|
||||
|
||||
def invite_to_public_rooms(instance: Registration, created: bool, **_):
|
||||
"""
|
||||
When a user got registered, automatically invite the Matrix user into public rooms.
|
||||
"""
|
||||
if not created:
|
||||
Matrix.invite("#annonces:correspondances-maths.fr", f"@{instance.matrix_username}:correspondances-maths.fr")
|
||||
Matrix.invite("#faq:correspondances-maths.fr", f"@{instance.matrix_username}:correspondances-maths.fr")
|
||||
Matrix.invite("#je-cherche-une-equip:correspondances-maths.fr",
|
||||
f"@{instance.matrix_username}:correspondances-maths.fr")
|
||||
Matrix.invite("#flood:correspondances-maths.fr", f"@{instance.matrix_username}:correspondances-maths.fr")
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
import django_tables2 as tables
|
||||
|
||||
@ -5,6 +8,9 @@ from .models import Registration
|
||||
|
||||
|
||||
class RegistrationTable(tables.Table):
|
||||
"""
|
||||
Table of all registrations.
|
||||
"""
|
||||
last_name = tables.LinkColumn(
|
||||
'registration:user_detail',
|
||||
args=[tables.A("user_id")],
|
||||
|
@ -19,7 +19,11 @@ SPDX-License-Identifier: GPL-3.0-or-later
|
||||
</p>
|
||||
{% else %}
|
||||
<p>
|
||||
{% trans "The link was invalid. The token may have expired. Please send us an email to activate your account." %}
|
||||
{% if user.is_authenticated and user.registration.email_confirmed %}
|
||||
{% trans "The link was invalid. The token may have expired, or your account is already activated. However, your account seems to be already valid." %}
|
||||
{% else %}
|
||||
{% trans "The link was invalid. The token may have expired, or your account is already activated. Please send us an email to activate your account." %}
|
||||
{% endif %}
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
7
apps/registration/templates/registration/user_list.html
Normal file
7
apps/registration/templates/registration/user_list.html
Normal file
@ -0,0 +1,7 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% load django_tables2 %}
|
||||
|
||||
{% block content %}
|
||||
{% render_table table %}
|
||||
{% endblock %}
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django import template
|
||||
from django_tables2 import Table
|
||||
from participation.models import Participation, Team, Video
|
||||
@ -9,6 +12,7 @@ from ..tables import RegistrationTable
|
||||
|
||||
def search_table(results):
|
||||
model_class = results[0].object.__class__
|
||||
table_class = Table
|
||||
if issubclass(model_class, Registration):
|
||||
table_class = RegistrationTable
|
||||
elif issubclass(model_class, Team):
|
||||
@ -17,8 +21,6 @@ def search_table(results):
|
||||
table_class = ParticipationTable
|
||||
elif issubclass(model_class, Video):
|
||||
table_class = VideoTable
|
||||
else:
|
||||
table_class = Table
|
||||
return table_class([result.object for result in results], prefix=model_class._meta.model_name)
|
||||
|
||||
|
||||
|
@ -1,18 +1,62 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from datetime import timedelta
|
||||
import os
|
||||
|
||||
from corres2math.tokens import email_validation_token
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.contrib.sites.models import Site
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.core.management import call_command
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from django.utils.encoding import force_bytes
|
||||
from django.utils.http import urlsafe_base64_encode
|
||||
from participation.models import Phase, Team
|
||||
|
||||
from .models import CoachRegistration, Registration, StudentRegistration
|
||||
from .models import AdminRegistration, CoachRegistration, StudentRegistration
|
||||
|
||||
|
||||
class TestIndexPage(TestCase):
|
||||
def test_index(self) -> None:
|
||||
"""
|
||||
Display the index page, without any right.
|
||||
"""
|
||||
response = self.client.get(reverse("index"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_not_authenticated(self):
|
||||
"""
|
||||
Try to load some pages without being authenticated.
|
||||
"""
|
||||
response = self.client.get(reverse("registration:reset_admin"))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("registration:reset_admin"), 302, 200)
|
||||
|
||||
User.objects.create()
|
||||
response = self.client.get(reverse("registration:user_detail", args=(1,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("registration:user_detail", args=(1,)))
|
||||
|
||||
Team.objects.create()
|
||||
response = self.client.get(reverse("participation:team_detail", args=(1,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:team_detail", args=(1,)))
|
||||
response = self.client.get(reverse("participation:update_team", args=(1,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:update_team", args=(1,)))
|
||||
response = self.client.get(reverse("participation:create_team"))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:create_team"))
|
||||
response = self.client.get(reverse("participation:join_team"))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:join_team"))
|
||||
response = self.client.get(reverse("participation:team_authorizations", args=(1,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next="
|
||||
+ reverse("participation:team_authorizations", args=(1,)))
|
||||
response = self.client.get(reverse("participation:participation_detail", args=(1,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next="
|
||||
+ reverse("participation:participation_detail", args=(1,)))
|
||||
response = self.client.get(reverse("participation:upload_video", args=(1,)))
|
||||
self.assertRedirects(response, reverse("login") + "?next=" + reverse("participation:upload_video", args=(1,)))
|
||||
|
||||
|
||||
class TestRegistration(TestCase):
|
||||
def setUp(self) -> None:
|
||||
@ -29,22 +73,50 @@ class TestRegistration(TestCase):
|
||||
CoachRegistration.objects.create(user=self.coach, professional_activity="Teacher")
|
||||
|
||||
def test_admin_pages(self):
|
||||
"""
|
||||
Check that admin pages are rendering successfully.
|
||||
"""
|
||||
response = self.client.get(reverse("admin:index") + "registration/registration/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"registration/registration/{self.user.registration.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.get(reverse("admin:index") +
|
||||
f"r/{ContentType.objects.get_for_model(AdminRegistration).id}/"
|
||||
f"{self.user.registration.pk}/")
|
||||
self.assertRedirects(response, "http://" + Site.objects.get().domain +
|
||||
str(self.user.registration.get_absolute_url()), 302, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"registration/registration/{self.student.registration.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.get(reverse("admin:index") +
|
||||
f"r/{ContentType.objects.get_for_model(StudentRegistration).id}/"
|
||||
f"{self.student.registration.pk}/")
|
||||
self.assertRedirects(response, "http://" + Site.objects.get().domain +
|
||||
str(self.student.registration.get_absolute_url()), 302, 200)
|
||||
|
||||
response = self.client.get(reverse("admin:index")
|
||||
+ f"registration/registration/{self.coach.registration.pk}/change/")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
response = self.client.get(reverse("admin:index") +
|
||||
f"r/{ContentType.objects.get_for_model(CoachRegistration).id}/"
|
||||
f"{self.coach.registration.pk}/")
|
||||
self.assertRedirects(response, "http://" + Site.objects.get().domain +
|
||||
str(self.coach.registration.get_absolute_url()), 302, 200)
|
||||
|
||||
def test_registration(self):
|
||||
"""
|
||||
Ensure that the signup form is working successfully.
|
||||
"""
|
||||
# After first phase
|
||||
response = self.client.get(reverse("registration:signup"))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
Phase.objects.filter(phase_number__gte=2).update(start=timezone.now() + timedelta(days=1),
|
||||
end=timezone.now() + timedelta(days=2))
|
||||
|
||||
response = self.client.get(reverse("registration:signup"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -73,6 +145,20 @@ class TestRegistration(TestCase):
|
||||
self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200)
|
||||
self.assertTrue(User.objects.filter(email="toto@example.com").exists())
|
||||
|
||||
# Email is already used
|
||||
response = self.client.post(reverse("registration:signup"), data=dict(
|
||||
last_name="Toto",
|
||||
first_name="Toto",
|
||||
email="toto@example.com",
|
||||
password1="azertyuiopazertyuiop",
|
||||
password2="azertyuiopazertyuiop",
|
||||
role="participant",
|
||||
student_class=12,
|
||||
school="God",
|
||||
give_contact_to_animath=False,
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.get(reverse("registration:email_validation_sent"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -109,6 +195,9 @@ class TestRegistration(TestCase):
|
||||
self.assertRedirects(response, reverse("registration:email_validation_sent"), 302, 200)
|
||||
|
||||
def test_login(self):
|
||||
"""
|
||||
With a registered user, try to log in
|
||||
"""
|
||||
response = self.client.get(reverse("login"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -127,13 +216,34 @@ class TestRegistration(TestCase):
|
||||
self.assertRedirects(response, reverse("index"), 302, 200)
|
||||
|
||||
def test_user_detail(self):
|
||||
"""
|
||||
Load a user detail page.
|
||||
"""
|
||||
response = self.client.get(reverse("registration:my_account_detail"))
|
||||
self.assertRedirects(response, reverse("registration:user_detail", args=(self.user.pk,)))
|
||||
|
||||
response = self.client.get(reverse("registration:user_detail", args=(self.user.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_user_list(self):
|
||||
"""
|
||||
Display the list of all users.
|
||||
"""
|
||||
response = self.client.get(reverse("registration:user_list"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_update_user(self):
|
||||
"""
|
||||
Update the user information, for each type of user.
|
||||
"""
|
||||
# To test the modification of mailing lists
|
||||
from participation.models import Team
|
||||
self.student.registration.team = Team.objects.create(
|
||||
name="toto",
|
||||
trigram="TOT",
|
||||
)
|
||||
self.student.registration.save()
|
||||
|
||||
for user, data in [(self.user, dict(role="Bot")),
|
||||
(self.student, dict(student_class=11, school="Sky")),
|
||||
(self.coach, dict(professional_activity="God"))]:
|
||||
@ -145,6 +255,8 @@ class TestRegistration(TestCase):
|
||||
last_name="Name",
|
||||
email="new_" + user.email,
|
||||
give_contact_to_animath=True,
|
||||
email_confirmed=True,
|
||||
team_id="",
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
@ -153,6 +265,8 @@ class TestRegistration(TestCase):
|
||||
last_name="Name",
|
||||
email="new_" + user.email,
|
||||
give_contact_to_animath=True,
|
||||
email_confirmed=True,
|
||||
team_id="",
|
||||
)
|
||||
response = self.client.post(reverse("registration:update_user", args=(user.pk,)), data=data)
|
||||
self.assertRedirects(response, reverse("registration:user_detail", args=(user.pk,)), 302, 200)
|
||||
@ -162,6 +276,9 @@ class TestRegistration(TestCase):
|
||||
self.assertEqual(user.first_name, "Changed")
|
||||
|
||||
def test_upload_photo_authorization(self):
|
||||
"""
|
||||
Try to upload a photo authorization.
|
||||
"""
|
||||
response = self.client.get(reverse("registration:upload_user_photo_authorization",
|
||||
args=(self.student.registration.pk,)))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
@ -173,6 +290,14 @@ class TestRegistration(TestCase):
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
# Don't send too large files
|
||||
response = self.client.post(reverse("registration:upload_user_photo_authorization",
|
||||
args=(self.student.registration.pk,)), data=dict(
|
||||
photo_authorization=SimpleUploadedFile("file.pdf", content=int(0).to_bytes(2000001, "big"),
|
||||
content_type="application/pdf"),
|
||||
))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
response = self.client.post(reverse("registration:upload_user_photo_authorization",
|
||||
args=(self.student.registration.pk,)), data=dict(
|
||||
photo_authorization=open("corres2math/static/Autorisation de droit à l'image - majeur.pdf", "rb"),
|
||||
@ -194,9 +319,77 @@ class TestRegistration(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response["content-type"], "application/zip")
|
||||
|
||||
# Do it twice, ensure that the previous authorization got deleted
|
||||
old_authoratization = self.student.registration.photo_authorization.path
|
||||
response = self.client.post(reverse("registration:upload_user_photo_authorization",
|
||||
args=(self.student.registration.pk,)), data=dict(
|
||||
photo_authorization=open("corres2math/static/Autorisation de droit à l'image - majeur.pdf", "rb"),
|
||||
))
|
||||
self.assertRedirects(response, reverse("registration:user_detail", args=(self.student.pk,)), 302, 200)
|
||||
self.assertFalse(os.path.isfile(old_authoratization))
|
||||
|
||||
self.student.registration.refresh_from_db()
|
||||
self.student.registration.photo_authorization.delete()
|
||||
|
||||
def test_string_render(self):
|
||||
# TODO These string field tests will be removed when used in a template
|
||||
self.assertRaises(NotImplementedError, lambda: Registration().type)
|
||||
self.assertRaises(NotImplementedError, lambda: Registration().form_class)
|
||||
def test_user_detail_forbidden(self):
|
||||
"""
|
||||
Create a new user and ensure that it can't see the detail of another user.
|
||||
"""
|
||||
self.client.force_login(self.coach)
|
||||
|
||||
response = self.client.get(reverse("registration:user_detail", args=(self.user.pk,)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
response = self.client.get(reverse("registration:update_user", args=(self.user.pk,)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
response = self.client.get(reverse("registration:upload_user_photo_authorization", args=(self.user.pk,)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
response = self.client.get(reverse("photo_authorization", args=("inexisting-authorization",)))
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
with open("media/authorization/photo/example", "w") as f:
|
||||
f.write("I lost the game.")
|
||||
self.student.registration.photo_authorization = "authorization/photo/example"
|
||||
self.student.registration.save()
|
||||
response = self.client.get(reverse("photo_authorization", args=("example",)))
|
||||
self.assertEqual(response.status_code, 403)
|
||||
os.remove("media/authorization/photo/example")
|
||||
|
||||
def test_impersonate(self):
|
||||
"""
|
||||
Admin can impersonate other people to act as them.
|
||||
"""
|
||||
response = self.client.get(reverse("registration:user_impersonate", args=(0x7ffff42ff,)))
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
# Impersonate student account
|
||||
response = self.client.get(reverse("registration:user_impersonate", args=(self.student.pk,)))
|
||||
self.assertRedirects(response, reverse("registration:user_detail", args=(self.student.pk,)), 302, 200)
|
||||
self.assertEqual(self.client.session["_fake_user_id"], self.student.id)
|
||||
|
||||
# Reset admin view
|
||||
response = self.client.get(reverse("registration:reset_admin"))
|
||||
self.assertRedirects(response, reverse("index"), 302, 200)
|
||||
self.assertFalse("_fake_user_id" in self.client.session)
|
||||
|
||||
def test_research(self):
|
||||
"""
|
||||
Try to search some things.
|
||||
"""
|
||||
call_command("rebuild_index", "--noinput", "-v", 0)
|
||||
|
||||
response = self.client.get(reverse("haystack_search") + "?q=" + self.user.email)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.context["object_list"])
|
||||
|
||||
response = self.client.get(reverse("haystack_search") + "?q=" +
|
||||
str(self.coach.registration.professional_activity))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.context["object_list"])
|
||||
|
||||
response = self.client.get(reverse("haystack_search") + "?q=" +
|
||||
self.student.registration.get_student_class_display())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.context["object_list"])
|
||||
|
@ -1,7 +1,10 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.urls import path
|
||||
|
||||
from .views import MyAccountDetailView, ResetAdminView, SignupView, UserDetailView, UserImpersonateView, \
|
||||
UserResendValidationEmailView, UserUpdateView, UserUploadPhotoAuthorizationView, UserValidateView, \
|
||||
UserListView, UserResendValidationEmailView, UserUpdateView, UserUploadPhotoAuthorizationView, UserValidateView, \
|
||||
UserValidationEmailSentView
|
||||
|
||||
app_name = "registration"
|
||||
@ -18,5 +21,6 @@ urlpatterns = [
|
||||
path("user/<int:pk>/upload-photo-authorization/", UserUploadPhotoAuthorizationView.as_view(),
|
||||
name="upload_user_photo_authorization"),
|
||||
path("user/<int:pk>/impersonate/", UserImpersonateView.as_view(), name="user_impersonate"),
|
||||
path("user/list/", UserListView.as_view(), name="user_list"),
|
||||
path("reset-admin/", ResetAdminView.as_view(), name="reset_admin"),
|
||||
]
|
||||
|
@ -1,6 +1,10 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
|
||||
from corres2math.tokens import email_validation_token
|
||||
from corres2math.views import AdminMixin
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.contrib.auth.models import User
|
||||
@ -12,16 +16,32 @@ from django.urls import reverse_lazy
|
||||
from django.utils.http import urlsafe_base64_decode
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import CreateView, DetailView, RedirectView, TemplateView, UpdateView, View
|
||||
from django_tables2 import SingleTableView
|
||||
from magic import Magic
|
||||
from participation.models import Phase
|
||||
|
||||
from .forms import CoachRegistrationForm, PhotoAuthorizationForm, SignupForm, StudentRegistrationForm, UserForm
|
||||
from .models import StudentRegistration
|
||||
from .models import Registration, StudentRegistration
|
||||
from .tables import RegistrationTable
|
||||
|
||||
|
||||
class SignupView(CreateView):
|
||||
"""
|
||||
Signup, as a participant or a coach.
|
||||
"""
|
||||
model = User
|
||||
form_class = SignupForm
|
||||
template_name = "registration/signup.html"
|
||||
extra_context = dict(title=_("Sign up"))
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
"""
|
||||
The signup view is available only during the first phase.
|
||||
"""
|
||||
current_phase = Phase.current_phase()
|
||||
if not current_phase or current_phase.phase_number >= 2:
|
||||
raise PermissionDenied(_("You can't register now."))
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data()
|
||||
@ -29,6 +49,11 @@ class SignupView(CreateView):
|
||||
context["student_registration_form"] = StudentRegistrationForm(self.request.POST or None)
|
||||
context["coach_registration_form"] = CoachRegistrationForm(self.request.POST or None)
|
||||
|
||||
del context["student_registration_form"].fields["team"]
|
||||
del context["student_registration_form"].fields["email_confirmed"]
|
||||
del context["coach_registration_form"].fields["team"]
|
||||
del context["coach_registration_form"].fields["email_confirmed"]
|
||||
|
||||
return context
|
||||
|
||||
@transaction.atomic
|
||||
@ -38,6 +63,8 @@ class SignupView(CreateView):
|
||||
registration_form = StudentRegistrationForm(self.request.POST)
|
||||
else:
|
||||
registration_form = CoachRegistrationForm(self.request.POST)
|
||||
del registration_form.fields["team"]
|
||||
del registration_form.fields["email_confirmed"]
|
||||
|
||||
if not registration_form.is_valid():
|
||||
return self.form_invalid(form)
|
||||
@ -59,7 +86,7 @@ class UserValidateView(TemplateView):
|
||||
"""
|
||||
title = _("Email validation")
|
||||
template_name = 'registration/email_validation_complete.html'
|
||||
extra_context = {"title": _("Validate email")}
|
||||
extra_context = dict(title=_("Validate email"))
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
"""
|
||||
@ -109,7 +136,7 @@ class UserValidationEmailSentView(TemplateView):
|
||||
Display the information that the validation link has been sent.
|
||||
"""
|
||||
template_name = 'registration/email_validation_email_sent.html'
|
||||
extra_context = {"title": _('Email validation email sent')}
|
||||
extra_context = dict(title=_('Email validation email sent'))
|
||||
|
||||
|
||||
class UserResendValidationEmailView(LoginRequiredMixin, DetailView):
|
||||
@ -117,7 +144,7 @@ class UserResendValidationEmailView(LoginRequiredMixin, DetailView):
|
||||
Rensend the email validation link.
|
||||
"""
|
||||
model = User
|
||||
extra_context = {"title": _("Resend email validation link")}
|
||||
extra_context = dict(title=_("Resend email validation link"))
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
user = self.get_object()
|
||||
@ -126,23 +153,50 @@ class UserResendValidationEmailView(LoginRequiredMixin, DetailView):
|
||||
|
||||
|
||||
class MyAccountDetailView(LoginRequiredMixin, RedirectView):
|
||||
"""
|
||||
Redirect to our own profile detail page.
|
||||
"""
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
return reverse_lazy("registration:user_detail", args=(self.request.user.pk,))
|
||||
|
||||
|
||||
class UserDetailView(LoginRequiredMixin, DetailView):
|
||||
"""
|
||||
Display the detail about a user.
|
||||
"""
|
||||
|
||||
model = User
|
||||
context_object_name = "user_object"
|
||||
template_name = "registration/user_detail.html"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
if not user.is_authenticated:
|
||||
return self.handle_no_permission()
|
||||
# Only an admin or the concerned user can see the information
|
||||
if not user.registration.is_admin and user.pk != kwargs["pk"]:
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["title"] = _("Detail of user {user}").format(user=str(self.object.registration))
|
||||
return context
|
||||
|
||||
|
||||
class UserListView(AdminMixin, SingleTableView):
|
||||
"""
|
||||
Display the list of all registered users.
|
||||
"""
|
||||
model = Registration
|
||||
table_class = RegistrationTable
|
||||
template_name = "registration/user_list.html"
|
||||
|
||||
|
||||
class UserUpdateView(LoginRequiredMixin, UpdateView):
|
||||
"""
|
||||
Update the detail about a user and its registration.
|
||||
"""
|
||||
model = User
|
||||
form_class = UserForm
|
||||
template_name = "registration/update_user.html"
|
||||
@ -156,8 +210,13 @@ class UserUpdateView(LoginRequiredMixin, UpdateView):
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
user = self.get_object()
|
||||
context["title"] = _("Update user {user}").format(user=str(self.object.registration))
|
||||
context["registration_form"] = user.registration.form_class(data=self.request.POST or None,
|
||||
instance=self.object.registration)
|
||||
if not self.request.user.registration.is_admin:
|
||||
if "team" in context["registration_form"].fields:
|
||||
del context["registration_form"].fields["team"]
|
||||
del context["registration_form"].fields["email_confirmed"]
|
||||
return context
|
||||
|
||||
@transaction.atomic
|
||||
@ -165,6 +224,11 @@ class UserUpdateView(LoginRequiredMixin, UpdateView):
|
||||
user = form.instance
|
||||
registration_form = user.registration.form_class(data=self.request.POST or None,
|
||||
instance=self.object.registration)
|
||||
if not self.request.user.registration.is_admin:
|
||||
if "team" in registration_form.fields:
|
||||
del registration_form.fields["team"]
|
||||
del registration_form.fields["email_confirmed"]
|
||||
|
||||
if not registration_form.is_valid():
|
||||
return self.form_invalid(form)
|
||||
|
||||
@ -176,9 +240,13 @@ class UserUpdateView(LoginRequiredMixin, UpdateView):
|
||||
|
||||
|
||||
class UserUploadPhotoAuthorizationView(LoginRequiredMixin, UpdateView):
|
||||
"""
|
||||
A participant can send its photo authorization.
|
||||
"""
|
||||
model = StudentRegistration
|
||||
form_class = PhotoAuthorizationForm
|
||||
template_name = "registration/upload_photo_authorization.html"
|
||||
extra_context = dict(title=_("Upload photo authorization"))
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
user = request.user
|
||||
@ -198,6 +266,9 @@ class UserUploadPhotoAuthorizationView(LoginRequiredMixin, UpdateView):
|
||||
|
||||
|
||||
class PhotoAuthorizationView(LoginRequiredMixin, View):
|
||||
"""
|
||||
Display the sent photo authorization.
|
||||
"""
|
||||
def get(self, request, *args, **kwargs):
|
||||
filename = kwargs["filename"]
|
||||
path = f"media/authorization/photo/{filename}"
|
||||
@ -207,25 +278,27 @@ class PhotoAuthorizationView(LoginRequiredMixin, View):
|
||||
user = request.user
|
||||
if not user.registration.is_admin and user.pk != student.user.pk:
|
||||
raise PermissionDenied
|
||||
# Guess mime type of the file
|
||||
mime = Magic(mime=True)
|
||||
mime_type = mime.from_file(path)
|
||||
ext = mime_type.split("/")[1].replace("jpeg", "jpg")
|
||||
# Replace file name
|
||||
true_file_name = _("Photo authorization of {student}.{ext}").format(student=str(student), ext=ext)
|
||||
return FileResponse(open(path, "rb"), content_type=mime_type, filename=true_file_name)
|
||||
|
||||
|
||||
class UserImpersonateView(LoginRequiredMixin, RedirectView):
|
||||
"""
|
||||
An administrator can log in through this page as someone else, and act as this other person.
|
||||
"""
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
"""
|
||||
An administrator can log in through this page as someone else, and act as this other person.
|
||||
"""
|
||||
if self.request.user.registration.is_admin:
|
||||
if not User.objects.filter(pk=kwargs["pk"]).exists():
|
||||
raise Http404
|
||||
session = request.session
|
||||
session["admin"] = request.user.pk
|
||||
session["_fake_user_id"] = kwargs["pk"]
|
||||
return redirect(request.path)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
@ -243,4 +316,4 @@ class ResetAdminView(LoginRequiredMixin, View):
|
||||
return self.handle_no_permission()
|
||||
if "_fake_user_id" in request.session:
|
||||
del request.session["_fake_user_id"]
|
||||
return redirect(request.GET.get("path", "/"))
|
||||
return redirect(request.GET.get("path", reverse_lazy("index")))
|
||||
|
@ -3,3 +3,6 @@
|
||||
* * * * * cd /code && python manage.py send_mail -c 1
|
||||
* * * * * cd /code && python manage.py retry_deferred -c 1
|
||||
0 0 * * * cd /code && python manage.py purge_mail_log 7 -c 1
|
||||
|
||||
# Rebuild search index
|
||||
0 * * * * cd /code && python manage.py update_index -v 0
|
||||
|
@ -0,0 +1,2 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
"""
|
||||
ASGI config for corres2math project.
|
||||
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
|
||||
_client = None
|
||||
@ -6,7 +9,7 @@ _client = None
|
||||
def get_sympa_client():
|
||||
global _client
|
||||
if _client is None:
|
||||
if os.getenv("SYMPA_PASSWORD", None) is not None:
|
||||
if os.getenv("SYMPA_PASSWORD", None) is not None: # pragma: no cover
|
||||
from sympasoap import Client
|
||||
_client = Client("https://" + os.getenv("SYMPA_URL"))
|
||||
_client.login(os.getenv("SYMPA_EMAIL"), os.getenv("SYMPA_PASSWORD"))
|
||||
|
@ -1,52 +1,393 @@
|
||||
import asyncio
|
||||
from typing import Any, Dict, Optional, Union
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from enum import Enum
|
||||
import os
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from nio import AsyncClient, RoomCreateError, RoomCreateResponse, RoomInviteError, RoomInviteResponse, RoomPreset, \
|
||||
RoomVisibility, RoomResolveAliasResponse
|
||||
|
||||
|
||||
class Matrix:
|
||||
"""
|
||||
Utility class to manage interaction with the Matrix homeserver.
|
||||
This log in the @corres2mathbot account (must be created before).
|
||||
The access token is then stored.
|
||||
All is done with this bot account, that is a server administrator.
|
||||
Tasks are normally asynchronous, but for compatibility we make
|
||||
them synchronous.
|
||||
"""
|
||||
_token = None
|
||||
_device_id = None
|
||||
|
||||
@classmethod
|
||||
async def _get_client(cls) -> AsyncClient:
|
||||
# TODO Store
|
||||
async def _get_client(cls): # pragma: no cover
|
||||
"""
|
||||
Retrieve the bot account.
|
||||
If not logged, log in and store access token.
|
||||
"""
|
||||
if not os.getenv("SYNAPSE_PASSWORD"):
|
||||
return FakeMatrixClient()
|
||||
|
||||
from nio import AsyncClient
|
||||
client = AsyncClient("https://correspondances-maths.fr", "@corres2mathbot:correspondances-maths.fr")
|
||||
await client.login("toto1234")
|
||||
client.user_id = "@corres2mathbot:correspondances-maths.fr"
|
||||
|
||||
if os.path.isfile(".matrix_token"):
|
||||
with open(".matrix_device", "r") as f:
|
||||
cls._device_id = f.read().rstrip(" \t\r\n")
|
||||
client.device_id = cls._device_id
|
||||
with open(".matrix_token", "r") as f:
|
||||
cls._token = f.read().rstrip(" \t\r\n")
|
||||
client.access_token = cls._token
|
||||
return client
|
||||
|
||||
await client.login(password=os.getenv("SYNAPSE_PASSWORD"), device_name="Plateforme")
|
||||
cls._token = client.access_token
|
||||
cls._device_id = client.device_id
|
||||
with open(".matrix_token", "w") as f:
|
||||
f.write(cls._token)
|
||||
with open(".matrix_device", "w") as f:
|
||||
f.write(cls._device_id)
|
||||
return client
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def set_display_name(cls, name: str):
|
||||
"""
|
||||
Set the display name of the bot account.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
return await client.set_displayname(name)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def set_avatar(cls, avatar_url: str): # pragma: no cover
|
||||
"""
|
||||
Set the display avatar of the bot account.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
return await client.set_avatar(avatar_url)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def upload(
|
||||
cls,
|
||||
data_provider,
|
||||
content_type: str = "application/octet-stream",
|
||||
filename: str = None,
|
||||
encrypt: bool = False,
|
||||
monitor=None,
|
||||
filesize: int = None,
|
||||
): # pragma: no cover
|
||||
"""
|
||||
Upload a file to the content repository.
|
||||
|
||||
Returns a tuple containing:
|
||||
|
||||
- Either a `UploadResponse` if the request was successful, or a
|
||||
`UploadError` if there was an error with the request
|
||||
|
||||
- A dict with file decryption info if encrypt is ``True``,
|
||||
else ``None``.
|
||||
Args:
|
||||
data_provider (Callable, SynchronousFile, AsyncFile): A function
|
||||
returning the data to upload or a file object. File objects
|
||||
must be opened in binary mode (``mode="r+b"``). Callables
|
||||
returning a path string, Path, async iterable or aiofiles
|
||||
open binary file object allow the file data to be read in an
|
||||
asynchronous and lazy way (without reading the entire file
|
||||
into memory). Returning a synchronous iterable or standard
|
||||
open binary file object will still allow the data to be read
|
||||
lazily, but not asynchronously.
|
||||
|
||||
The function will be called again if the upload fails
|
||||
due to a server timeout, in which case it must restart
|
||||
from the beginning.
|
||||
Callables receive two arguments: the total number of
|
||||
429 "Too many request" errors that occured, and the total
|
||||
number of server timeout exceptions that occured, thus
|
||||
cleanup operations can be performed for retries if necessary.
|
||||
|
||||
content_type (str): The content MIME type of the file,
|
||||
e.g. "image/png".
|
||||
Defaults to "application/octet-stream", corresponding to a
|
||||
generic binary file.
|
||||
Custom values are ignored if encrypt is ``True``.
|
||||
|
||||
filename (str, optional): The file's original name.
|
||||
|
||||
encrypt (bool): If the file's content should be encrypted,
|
||||
necessary for files that will be sent to encrypted rooms.
|
||||
Defaults to ``False``.
|
||||
|
||||
monitor (TransferMonitor, optional): If a ``TransferMonitor``
|
||||
object is passed, it will be updated by this function while
|
||||
uploading.
|
||||
From this object, statistics such as currently
|
||||
transferred bytes or estimated remaining time can be gathered
|
||||
while the upload is running as a task; it also allows
|
||||
for pausing and cancelling.
|
||||
|
||||
filesize (int, optional): Size in bytes for the file to transfer.
|
||||
If left as ``None``, some servers might refuse the upload.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
return await client.upload(data_provider, content_type, filename, encrypt, monitor, filesize) \
|
||||
if not isinstance(client, FakeMatrixClient) else None, None
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def create_room(
|
||||
cls,
|
||||
visibility: RoomVisibility = RoomVisibility.private,
|
||||
alias: Optional[str] = None,
|
||||
name: Optional[str] = None,
|
||||
topic: Optional[str] = None,
|
||||
room_version: Optional[str] = None,
|
||||
federate: bool = True,
|
||||
is_direct: bool = False,
|
||||
preset: Optional[RoomPreset] = None,
|
||||
visibility=None,
|
||||
alias=None,
|
||||
name=None,
|
||||
topic=None,
|
||||
room_version=None,
|
||||
federate=True,
|
||||
is_direct=False,
|
||||
preset=None,
|
||||
invite=(),
|
||||
initial_state=(),
|
||||
power_level_override: Optional[Dict[str, Any]] = None,
|
||||
) -> Union[RoomCreateResponse, RoomCreateError]:
|
||||
resp: Union[RoomCreateResponse, RoomCreateError]
|
||||
power_level_override=None,
|
||||
):
|
||||
"""
|
||||
Create a new room.
|
||||
|
||||
Returns either a `RoomCreateResponse` if the request was successful or
|
||||
a `RoomCreateError` if there was an error with the request.
|
||||
|
||||
Args:
|
||||
visibility (RoomVisibility): whether to have the room published in
|
||||
the server's room directory or not.
|
||||
Defaults to ``RoomVisibility.private``.
|
||||
|
||||
alias (str, optional): The desired canonical alias local part.
|
||||
For example, if set to "foo" and the room is created on the
|
||||
"example.com" server, the room alias will be
|
||||
"#foo:example.com".
|
||||
|
||||
name (str, optional): A name to set for the room.
|
||||
|
||||
topic (str, optional): A topic to set for the room.
|
||||
|
||||
room_version (str, optional): The room version to set.
|
||||
If not specified, the homeserver will use its default setting.
|
||||
If a version not supported by the homeserver is specified,
|
||||
a 400 ``M_UNSUPPORTED_ROOM_VERSION`` error will be returned.
|
||||
|
||||
federate (bool): Whether to allow users from other homeservers from
|
||||
joining the room. Defaults to ``True``.
|
||||
Cannot be changed later.
|
||||
|
||||
is_direct (bool): If this should be considered a
|
||||
direct messaging room.
|
||||
If ``True``, the server will set the ``is_direct`` flag on
|
||||
``m.room.member events`` sent to the users in ``invite``.
|
||||
Defaults to ``False``.
|
||||
|
||||
preset (RoomPreset, optional): The selected preset will set various
|
||||
rules for the room.
|
||||
If unspecified, the server will choose a preset from the
|
||||
``visibility``: ``RoomVisibility.public`` equates to
|
||||
``RoomPreset.public_chat``, and
|
||||
``RoomVisibility.private`` equates to a
|
||||
``RoomPreset.private_chat``.
|
||||
|
||||
invite (list): A list of user id to invite to the room.
|
||||
|
||||
initial_state (list): A list of state event dicts to send when
|
||||
the room is created.
|
||||
For example, a room could be made encrypted immediatly by
|
||||
having a ``m.room.encryption`` event dict.
|
||||
|
||||
power_level_override (dict): A ``m.room.power_levels content`` dict
|
||||
to override the default.
|
||||
The dict will be applied on top of the generated
|
||||
``m.room.power_levels`` event before it is sent to the room.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
return await client.room_create(
|
||||
visibility, alias, name, topic, room_version, federate, is_direct, preset, invite, initial_state,
|
||||
power_level_override)
|
||||
|
||||
@classmethod
|
||||
async def resolve_room_alias(cls, room_alias: str) -> str:
|
||||
async def resolve_room_alias(cls, room_alias: str):
|
||||
"""
|
||||
Resolve a room alias to a room ID.
|
||||
Return None if the alias does not exist.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
resp: RoomResolveAliasResponse = await client.room_resolve_alias(room_alias)
|
||||
return resp.room_id
|
||||
resp = await client.room_resolve_alias(room_alias)
|
||||
return resp.room_id if resp and hasattr(resp, "room_id") else None
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def invite(cls, room_id: str, user_id: str) -> Union[RoomInviteResponse, RoomInviteError]:
|
||||
async def invite(cls, room_id: str, user_id: str):
|
||||
"""
|
||||
Invite a user to a room.
|
||||
|
||||
Returns either a `RoomInviteResponse` if the request was successful or
|
||||
a `RoomInviteError` if there was an error with the request.
|
||||
|
||||
Args:
|
||||
room_id (str): The room id of the room that the user will be
|
||||
invited to.
|
||||
user_id (str): The user id of the user that should be invited.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
if room_id.startswith("#"):
|
||||
room_id = await cls.resolve_room_alias(room_id)
|
||||
return await client.room_invite(room_id, user_id)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def send_message(cls, room_id: str, body: str, formatted_body: str = None,
|
||||
msgtype: str = "m.text", html: bool = True):
|
||||
"""
|
||||
Send a message to a room.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
if room_id.startswith("#"):
|
||||
room_id = await cls.resolve_room_alias(room_id)
|
||||
content = {
|
||||
"msgtype": msgtype,
|
||||
"body": body,
|
||||
"formatted_body": formatted_body or body,
|
||||
}
|
||||
if html:
|
||||
content["format"] = "org.matrix.custom.html"
|
||||
return await client.room_send(
|
||||
room_id=room_id,
|
||||
message_type="m.room.message",
|
||||
content=content,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def kick(cls, room_id: str, user_id: str, reason: str = None):
|
||||
"""
|
||||
Kick a user from a room, or withdraw their invitation.
|
||||
|
||||
Kicking a user adjusts their membership to "leave" with an optional
|
||||
reason.
|
||||
²
|
||||
Returns either a `RoomKickResponse` if the request was successful or
|
||||
a `RoomKickError` if there was an error with the request.
|
||||
|
||||
Args:
|
||||
room_id (str): The room id of the room that the user will be
|
||||
kicked from.
|
||||
user_id (str): The user_id of the user that should be kicked.
|
||||
reason (str, optional): A reason for which the user is kicked.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
if room_id.startswith("#"):
|
||||
room_id = await cls.resolve_room_alias(room_id)
|
||||
return await client.room_kick(room_id, user_id, reason)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def set_room_power_level(cls, room_id: str, user_id: str, power_level: int): # pragma: no cover
|
||||
"""
|
||||
Put a given power level to a user in a certain room.
|
||||
|
||||
Returns either a `RoomPutStateResponse` if the request was successful or
|
||||
a `RoomPutStateError` if there was an error with the request.
|
||||
|
||||
Args:
|
||||
room_id (str): The room id of the room where the power level
|
||||
of the user should be updated.
|
||||
user_id (str): The user_id of the user which power level should
|
||||
be updated.
|
||||
power_level (int): The target power level to give.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
if isinstance(client, FakeMatrixClient):
|
||||
return None
|
||||
|
||||
if room_id.startswith("#"):
|
||||
room_id = await cls.resolve_room_alias(room_id)
|
||||
resp = await client.room_get_state_event(room_id, "m.room.power_levels")
|
||||
content = resp.content
|
||||
content["users"][user_id] = power_level
|
||||
return await client.room_put_state(room_id, "m.room.power_levels", content=content, state_key=resp.state_key)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def set_room_power_level_event(cls, room_id: str, event: str, power_level: int): # pragma: no cover
|
||||
"""
|
||||
Define the minimal power level to have to send a certain event type
|
||||
in a given room.
|
||||
|
||||
Returns either a `RoomPutStateResponse` if the request was successful or
|
||||
a `RoomPutStateError` if there was an error with the request.
|
||||
|
||||
Args:
|
||||
room_id (str): The room id of the room where the power level
|
||||
of the event should be updated.
|
||||
event (str): The event name which minimal power level should
|
||||
be updated.
|
||||
power_level (int): The target power level to give.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
if isinstance(client, FakeMatrixClient):
|
||||
return None
|
||||
|
||||
if room_id.startswith("#"):
|
||||
room_id = await cls.resolve_room_alias(room_id)
|
||||
resp = await client.room_get_state_event(room_id, "m.room.power_levels")
|
||||
content = resp.content
|
||||
if event.startswith("m."):
|
||||
content["events"][event] = power_level
|
||||
else:
|
||||
content[event] = power_level
|
||||
return await client.room_put_state(room_id, "m.room.power_levels", content=content, state_key=resp.state_key)
|
||||
|
||||
@classmethod
|
||||
@async_to_sync
|
||||
async def set_room_avatar(cls, room_id: str, avatar_uri: str):
|
||||
"""
|
||||
Define the avatar of a room.
|
||||
|
||||
Returns either a `RoomPutStateResponse` if the request was successful or
|
||||
a `RoomPutStateError` if there was an error with the request.
|
||||
|
||||
Args:
|
||||
room_id (str): The room id of the room where the avatar
|
||||
should be changed.
|
||||
avatar_uri (str): The internal avatar URI to apply.
|
||||
"""
|
||||
client = await cls._get_client()
|
||||
if room_id.startswith("#"):
|
||||
room_id = await cls.resolve_room_alias(room_id)
|
||||
return await client.room_put_state(room_id, "m.room.avatar", content={
|
||||
"url": avatar_uri
|
||||
}, state_key="")
|
||||
|
||||
|
||||
if os.getenv("SYNAPSE_PASSWORD"): # pragma: no cover
|
||||
from nio import RoomVisibility, RoomPreset
|
||||
RoomVisibility = RoomVisibility
|
||||
RoomPreset = RoomPreset
|
||||
else:
|
||||
# When running tests, faking matrix-nio classes to don't include the module
|
||||
class RoomVisibility(Enum):
|
||||
private = 'private'
|
||||
public = 'public'
|
||||
|
||||
class RoomPreset(Enum):
|
||||
private_chat = "private_chat"
|
||||
trusted_private_chat = "trusted_private_chat"
|
||||
public_chat = "public_chat"
|
||||
|
||||
|
||||
class FakeMatrixClient:
|
||||
"""
|
||||
Simulate a Matrix client to run tests, if no Matrix homeserver is connected.
|
||||
"""
|
||||
|
||||
def __getattribute__(self, item):
|
||||
async def func(*_, **_2):
|
||||
return None
|
||||
return func
|
||||
|
@ -1,9 +1,10 @@
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import AnonymousUser, User
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from threading import local
|
||||
|
||||
from django.contrib.sessions.backends.db import SessionStore
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import AnonymousUser, User
|
||||
|
||||
USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
|
||||
SESSION_ATTR_NAME = getattr(settings, 'LOCAL_SESSION_ATTR_NAME', '_current_session')
|
||||
@ -22,19 +23,13 @@ def get_current_user() -> User:
|
||||
return getattr(_thread_locals, USER_ATTR_NAME, None)
|
||||
|
||||
|
||||
def get_current_session() -> SessionStore:
|
||||
return getattr(_thread_locals, SESSION_ATTR_NAME, None)
|
||||
|
||||
|
||||
def get_current_ip() -> str:
|
||||
return getattr(_thread_locals, IP_ATTR_NAME, None)
|
||||
|
||||
|
||||
def get_current_authenticated_user():
|
||||
current_user = get_current_user()
|
||||
if isinstance(current_user, AnonymousUser):
|
||||
return None
|
||||
return current_user
|
||||
return None if isinstance(current_user, AnonymousUser) else current_user
|
||||
|
||||
|
||||
class SessionMiddleware(object):
|
||||
@ -50,10 +45,7 @@ class SessionMiddleware(object):
|
||||
request.user = User.objects.get(pk=request.session["_fake_user_id"])
|
||||
|
||||
user = request.user
|
||||
if 'HTTP_X_REAL_IP' in request.META:
|
||||
ip = request.META.get('HTTP_X_REAL_IP')
|
||||
else:
|
||||
ip = request.META.get('REMOTE_ADDR')
|
||||
ip = request.META.get('HTTP_X_REAL_IP' if 'HTTP_X_REAL_IP' in request.META else 'REMOTE_ADDR')
|
||||
|
||||
_set_current_user_and_ip(user, request.session, ip)
|
||||
response = self.get_response(request)
|
||||
@ -62,7 +54,7 @@ class SessionMiddleware(object):
|
||||
return response
|
||||
|
||||
|
||||
class TurbolinksMiddleware(object):
|
||||
class TurbolinksMiddleware(object): # pragma: no cover
|
||||
"""
|
||||
Send the `Turbolinks-Location` header in response to a visit that was redirected,
|
||||
and Turbolinks will replace the browser's topmost history entry.
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
"""
|
||||
Django settings for corres2math project.
|
||||
|
||||
@ -52,15 +55,12 @@ INSTALLED_APPS = [
|
||||
|
||||
'bootstrap_datepicker_plus',
|
||||
'crispy_forms',
|
||||
'django_extensions',
|
||||
'django_tables2',
|
||||
'haystack',
|
||||
'logs',
|
||||
'mailer',
|
||||
'polymorphic',
|
||||
'rest_framework',
|
||||
'rest_framework.authtoken',
|
||||
'cas_server',
|
||||
|
||||
'api',
|
||||
'eastereggs',
|
||||
@ -68,6 +68,13 @@ INSTALLED_APPS = [
|
||||
'participation',
|
||||
]
|
||||
|
||||
if "test" not in sys.argv: # pragma: no cover
|
||||
INSTALLED_APPS += [
|
||||
'cas_server',
|
||||
'django_extensions',
|
||||
'mailer',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
@ -89,8 +96,7 @@ LOGIN_REDIRECT_URL = "index"
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [os.path.join(BASE_DIR, 'templates')]
|
||||
,
|
||||
'DIRS': [os.path.join(BASE_DIR, 'corres2math/templates')],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
@ -196,7 +202,7 @@ HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
|
||||
|
||||
_db_type = os.getenv('DJANGO_DB_TYPE', 'sqlite').lower()
|
||||
|
||||
if _db_type == 'mysql' or _db_type.startswith('postgres') or _db_type == 'psql':
|
||||
if _db_type == 'mysql' or _db_type.startswith('postgres') or _db_type == 'psql': # pragma: no cover
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.mysql' if _db_type == 'mysql' else 'django.db.backends.postgresql_psycopg2',
|
||||
@ -215,7 +221,7 @@ else:
|
||||
}
|
||||
}
|
||||
|
||||
if os.getenv("CORRES2MATH_STAGE", "dev") == "prod":
|
||||
from .settings_prod import *
|
||||
if os.getenv("CORRES2MATH_STAGE", "dev") == "prod": # pragma: no cover
|
||||
from .settings_prod import * # noqa: F401,F403
|
||||
else:
|
||||
from .settings_dev import *
|
||||
from .settings_dev import * # noqa: F401,F403
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
|
||||
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
|
||||
# Break it, fix it!
|
||||
|
40
corres2math/templates/about.html
Normal file
40
corres2math/templates/about.html
Normal file
@ -0,0 +1,40 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block contenttitle %}
|
||||
<h1>À propos</h1>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<p>
|
||||
La plateforme d'inscription des Correspondances des Jeunes Mathématiciennes a été développée entre 2019 et 2021
|
||||
par Yohann D'ANELLO, bénévole pour l'association Animath. Elle est vouée à être utilisée par les participants
|
||||
pour intéragir avec les organisateurs et les autres participants.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
La plateforme est développée avec le framework <a href="https://www.djangoproject.com/">Django</a> et le code
|
||||
source est accessible librement sur <a href="https://gitlab.com/animath/si/plateforme-corres2math">Gitlab</a>.
|
||||
Le code est distribué sous la licence <a href="https://www.gnu.org/licenses/gpl-3.0.html">GNU GPL v3</a>,
|
||||
qui vous autorise à consulter le code, à le partager, à réutiliser des parties du code et à contribuer.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Le site principal présent sur <a href="https://inscription.correspondances-maths.fr/">https://inscription.correspondances-maths.fr</a>
|
||||
est hébergé chez <a href="https://www.scaleway.com/fr/">Scaleway</a>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Les données collectées par cette plateforme sont utilisées uniquement dans le cadre des Correspondances et sont
|
||||
détruites dès l'action touche à sa fin, soit au plus tard 1 an après le début de l'action. Sur autorisation
|
||||
explicite, des informations de contact peuvent être conservées afin d'être tenu au courant des actions futures
|
||||
de l'association Animath. Aucune information personnelle n'est collectée à votre insu. Aucune information
|
||||
personnelle n'est cédée à des tiers.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Pour toute demande ou réclammation, merci de nous contacter à l'adresse
|
||||
<a target="_blank" href="mailto:contact@correspondances-maths.fr">
|
||||
contact@correspondances-maths.fr
|
||||
</a>.
|
||||
</p>
|
||||
{% endblock %}
|
@ -1,4 +1,4 @@
|
||||
{% load static i18n static %}
|
||||
{% load static i18n static calendar %}
|
||||
|
||||
<!DOCTYPE html>
|
||||
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}
|
||||
@ -70,7 +70,14 @@
|
||||
<a href="#" class="nav-link" data-toggle="modal" data-target="#calendarModal"><i class="fas fa-calendar"></i> {% trans "Calendar" %}</a>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% if user.is_authenticated and user.registration.participates %}
|
||||
{% if user.is_authenticated and user.registration.is_admin %}
|
||||
<li class="nav-item active">
|
||||
<a href="{% url "registration:user_list" %}" class="nav-link"><i class="fas fa-user"></i> {% trans "Users" %}</a>
|
||||
</li>
|
||||
<li class="nav-item active">
|
||||
<a href="#" class="nav-link" data-toggle="modal" data-target="#teamsModal"><i class="fas fa-users"></i> {% trans "Teams" %}</a>
|
||||
</li>
|
||||
{% elif user.is_authenticated and user.registration.participates %}
|
||||
{% if not user.registration.team %}
|
||||
<li class="nav-item active">
|
||||
<a href="#" class="nav-link" data-toggle="modal" data-target="#createTeamModal">
|
||||
@ -96,8 +103,8 @@
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<li class="nav-item active">
|
||||
<a class="nav-link" href="https://www.helloasso.com/associations/animath/formulaires/5/widget"><i
|
||||
class="fas fa-hand-holding-heart"></i> {% trans "Make a gift" %}</a>
|
||||
<a class="nav-link" href="{% url "participation:chat" %}">
|
||||
<i class="fas fa-comments"></i> {% trans "Chat" %}</a>
|
||||
</li>
|
||||
{% if user.admin %}
|
||||
<li class="nav-item active">
|
||||
@ -122,9 +129,11 @@
|
||||
</li>
|
||||
{% endif %}
|
||||
{% if not user.is_authenticated %}
|
||||
<li class="nav-item active">
|
||||
<a class="nav-link" href="{% url "registration:signup" %}"><i class="fas fa-user-plus"></i> {% trans "Register" %}</a>
|
||||
</li>
|
||||
{% if 1|current_phase %}
|
||||
<li class="nav-item active">
|
||||
<a class="nav-link" href="{% url "registration:signup" %}"><i class="fas fa-user-plus"></i> {% trans "Register" %}</a>
|
||||
</li>
|
||||
{% endif %}
|
||||
<li class="nav-item active">
|
||||
<a class="nav-link" href="#" data-toggle="modal" data-target="#loginModal">
|
||||
<i class="fas fa-sign-in-alt"></i> {% trans "Log in" %}
|
||||
@ -150,6 +159,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
{% block fullcontent %}
|
||||
<div class="{% block containertype %}container{% endblock %} my-3">
|
||||
{% block contenttitle %}{% endblock %}
|
||||
{% if user.is_authenticated and not user.registration.email_confirmed %}
|
||||
@ -171,6 +181,7 @@
|
||||
{% endblock content %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
</main>
|
||||
|
||||
<footer class="bg-light text-primary mt-auto py-2">
|
||||
@ -181,7 +192,7 @@
|
||||
class="form-inline">
|
||||
<span class="text-muted mr-1">
|
||||
<a target="_blank" href="mailto:contact@correspondances-maths.fr"
|
||||
class="text-muted">{% trans "Contact us" %}</a> —
|
||||
class="text-muted"><i class="fas fa-envelope"></i> {% trans "Contact us" %}</a>
|
||||
</span>
|
||||
{% csrf_token %}
|
||||
<select title="language" name="language"
|
||||
@ -196,10 +207,15 @@
|
||||
{{ lang_name }} ({{ lang_code }})
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</select>
|
||||
<noscript>
|
||||
<input type="submit">
|
||||
</noscript>
|
||||
</noscript>
|
||||
<a target="_blank" class="text-muted" href="{% url "about" %}">{% trans "About" %}</a> —
|
||||
<a target="_blank" class="text-muted"
|
||||
href="https://gitlab.com/animath/si/plateforme-corres2math">
|
||||
<i class="fab fa-gitlab"></i>
|
||||
</a>
|
||||
</form>
|
||||
</div>
|
||||
<div class="col text-right">
|
||||
@ -214,21 +230,28 @@
|
||||
|
||||
{% trans "Calendar" as modal_title %}
|
||||
{% include "base_modal.html" with modal_id="calendar" modal_additional_class="modal-lg" %}
|
||||
{% trans "Search results" as modal_title %}
|
||||
{% include "base_modal.html" with modal_id="search" modal_form_method="get" modal_additional_class="modal-lg" %}
|
||||
{% trans "Log in" as modal_title %}
|
||||
{% trans "Log in" as modal_button %}
|
||||
{% url "login" as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="login" %}
|
||||
|
||||
{% if user.is_authenticated %}
|
||||
{% trans "All teams" as modal_title %}
|
||||
{% include "base_modal.html" with modal_id="teams" modal_additional_class="modal-lg" %}
|
||||
|
||||
{% trans "Search results" as modal_title %}
|
||||
{% include "base_modal.html" with modal_id="search" modal_form_method="get" modal_additional_class="modal-lg" %}
|
||||
|
||||
{% trans "Join team" as modal_title %}
|
||||
{% trans "Join" as modal_button %}
|
||||
{% url "participation:join_team" as modal_action %}
|
||||
|
||||
{% include "base_modal.html" with modal_id="joinTeam" %}
|
||||
{% trans "Create team" as modal_title %}
|
||||
{% trans "Create" as modal_button %}
|
||||
{% url "participation:create_team" as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="createTeam" modal_button_type="success" %}
|
||||
{% else %}
|
||||
{% trans "Log in" as modal_title %}
|
||||
{% trans "Log in" as modal_button %}
|
||||
{% url "login" as modal_action %}
|
||||
{% include "base_modal.html" with modal_id="login" %}
|
||||
{% endif %}
|
||||
|
||||
<script>
|
||||
@ -241,26 +264,39 @@
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:calendar" %} #form-content")
|
||||
});
|
||||
$('button[data-target="#searchModal"]').click(function() {
|
||||
let modalBody = $("#searchModal div.modal-body");
|
||||
let q = encodeURI($("#search-term").val());
|
||||
modalBody.load("{% url "haystack_search" %}?q=" + q + " #search-results");
|
||||
});
|
||||
{% if user.is_authenticated and user.registration.is_admin %}
|
||||
$('a[data-target="#teamsModal"]').click(function() {
|
||||
let modalBody = $("#teamsModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:team_list" %} #form-content")
|
||||
});
|
||||
$('button[data-target="#searchModal"]').click(function() {
|
||||
let modalBody = $("#searchModal div.modal-body");
|
||||
let q = encodeURI($("#search-term").val());
|
||||
modalBody.load("{% url "haystack_search" %}?q=" + q + " #search-results");
|
||||
});
|
||||
{% endif %}
|
||||
|
||||
{% if not user.is_authenticated %}
|
||||
$('a[data-target="#loginModal"]').click(function() {
|
||||
let modalBody = $("#loginModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "login" %} #form-content")
|
||||
});
|
||||
$('a[data-target="#createTeamModal"]').click(function() {
|
||||
let modalBody = $("#createTeamModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:create_team" %} #form-content");
|
||||
});
|
||||
$('a[data-target="#joinTeamModal"]').click(function() {
|
||||
let modalBody = $("#joinTeamModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:join_team" %} #form-content");
|
||||
});
|
||||
let modalBody = $("#loginModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "login" %} #form-content")
|
||||
});
|
||||
{% endif %}
|
||||
|
||||
{% if user.is_authenticated and user.registration.participates and not user.registration.team %}
|
||||
$('a[data-target="#createTeamModal"]').click(function() {
|
||||
let modalBody = $("#createTeamModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:create_team" %} #form-content");
|
||||
});
|
||||
$('a[data-target="#joinTeamModal"]').click(function() {
|
||||
let modalBody = $("#joinTeamModal div.modal-body");
|
||||
if (!modalBody.html().trim())
|
||||
modalBody.load("{% url "participation:join_team" %} #form-content");
|
||||
});
|
||||
{% endif %}
|
||||
});
|
||||
</script>
|
||||
|
@ -12,6 +12,7 @@
|
||||
</div>
|
||||
<div class="modal-body">{{ modal_content }}</div>
|
||||
<div class="modal-footer">
|
||||
{{ extra_modal_button }}
|
||||
{% if modal_button %}
|
||||
<button type="submit" class="btn btn-{{ modal_button_type|default:"primary" }}">{{ modal_button }}</button>
|
||||
{% endif %}
|
80
corres2math/templates/index.html
Normal file
80
corres2math/templates/index.html
Normal file
@ -0,0 +1,80 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<div>
|
||||
|
||||
<div class="jumbotron bg-white">
|
||||
<div class="row">
|
||||
<h1 class="display-3">
|
||||
Bienvenue sur le site d'inscription aux <a href="https://correspondances-maths.fr/" target="_blank">
|
||||
Correspondances des Jeunes Mathématicien·ne·s</a> !
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row jumbotron bg-white">
|
||||
<div class="col-sm">
|
||||
<h3>
|
||||
Tu souhaites participer aux Correspondances ?
|
||||
<br/>
|
||||
Ton équipe est déjà formée ?
|
||||
</h3>
|
||||
</div>
|
||||
<div class="col-sm text-right">
|
||||
<div class="btn-group-vertical">
|
||||
<a class="btn btn-primary btn-lg" href="{% url "registration:signup" %}" role="button">Inscris-toi maintenant !</a>
|
||||
<a class="btn btn-light btn-lg" href="{% url "login" %}" role="button">J'ai déjà un compte</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-danger">
|
||||
Avertissement : certains rencontrent des difficultés à recevoir les mails automatiques. Merci de vérifier
|
||||
régulièrement votre boîte spam, et à nous contacter en cas de problème.
|
||||
</div>
|
||||
|
||||
<div class="jumbotron">
|
||||
<h5 class="display-4">Comment ça marche ?</h5>
|
||||
<p>
|
||||
Pour participer aux Correspondances, il suffit de créer un compte sur la rubrique <strong><a href="{% url "registration:signup" %}">Inscription</a></strong>.
|
||||
Vous devrez ensuite confirmer votre adresse e-mail.
|
||||
</p>
|
||||
|
||||
<p class="text-justify">
|
||||
Vous pouvez accéder à votre compte via la rubrique <strong><a href="{% url "login" %}">Connexion</a></strong>.
|
||||
Une fois connecté, vous pourrez créer une équipe ou en rejoindre une déjà créée par l'un de vos camarades
|
||||
via un code d'accès qui vous aura été transmis. Vous serez ensuite invité à soumettre une autorisation de droit à l'image,
|
||||
indispensable au bon déroulement des Correspondances. Une fois que votre équipe comporte au moins 3 participants (maximum 5)
|
||||
et un encadrant, vous pourrez demander à valider votre équipe pour être apte à travailler sur le problème de votre choix.
|
||||
</p>
|
||||
|
||||
<h2>Je ne trouve pas d'équipe, aidez-moi !</h2>
|
||||
|
||||
<p class="text-justify">
|
||||
En ayant créé un compte sur cette plateforme, vous créez également un compte sur la plateforme de chat dédiée
|
||||
aux Correspondances, basée sur le protocole <a href="https://matrix.org/">Matrix</a> et le client
|
||||
<a href="https://element.io">Element</a>. Cette interface de chat vous permet de communiquer avec les membres
|
||||
de votre équipe, mais surtout de pouvoir échanger durant la troisième phase des Correspondances, et
|
||||
également de poser vos questions en cas de besoin.
|
||||
</p>
|
||||
|
||||
<p class="text-justify">
|
||||
Ce chat contient également un salon <code>#je-cherche-une-equipe</code> où vous pouvez crier à l'aide pour trouver
|
||||
une équipe, ou compléter la votre s'il vous manque des participants. C'est un petit coin auprès du feu, un parc à
|
||||
jeu où vous pouvez descendre en toboggan (en le désinfectant après utilisation), ne cherchez pas à être trop formel.
|
||||
</p>
|
||||
|
||||
<h2>J'ai une question</h2>
|
||||
|
||||
<p class="text-justify">
|
||||
Pour toute question, vous pouvez soit la poser dans <code>#faq</code> dans l'onglet chat comme indiqué ci-dessus, soit nous
|
||||
contacter par mail à l'adresse <a href="mailto:contact@correspondances-maths.fr">contact@correspondances-maths.fr</a>.
|
||||
</p>
|
||||
|
||||
<div class="alert alert-warning">
|
||||
<strong>Attention aux dates !</strong> Si vous ne finalisez pas votre inscription dans le délai indiqué, vous
|
||||
ne pourrez malheureusement pas participer aux Correspondances.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
{% endblock %}
|
@ -6,7 +6,6 @@
|
||||
<h2>{% trans "Search" %}</h2>
|
||||
|
||||
<form>
|
||||
{% csrf_token %}
|
||||
{{ form|crispy }}
|
||||
<button type="submit" class="btn btn-primary">{% trans "Search" %}</button>
|
||||
</form>
|
27
corres2math/tests.py
Normal file
27
corres2math/tests.py
Normal file
@ -0,0 +1,27 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import os
|
||||
|
||||
from django.core.handlers.asgi import ASGIHandler
|
||||
from django.core.handlers.wsgi import WSGIHandler
|
||||
from django.test import TestCase
|
||||
|
||||
|
||||
class TestLoadModules(TestCase):
|
||||
"""
|
||||
Load modules that are not used in development mode in order to increase coverage.
|
||||
"""
|
||||
def test_asgi(self):
|
||||
from corres2math import asgi
|
||||
self.assertTrue(isinstance(asgi.application, ASGIHandler))
|
||||
|
||||
def test_wsgi(self):
|
||||
from corres2math import wsgi
|
||||
self.assertTrue(isinstance(wsgi.application, WSGIHandler))
|
||||
|
||||
def test_load_production_settings(self):
|
||||
os.putenv("CORRES2MATH_STAGE", "prod")
|
||||
os.putenv("DJANGO_DB_TYPE", "postgres")
|
||||
from corres2math import settings_prod
|
||||
self.assertFalse(settings_prod.DEBUG)
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.contrib.auth.tokens import PasswordResetTokenGenerator
|
||||
|
||||
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
"""corres2math URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
@ -13,9 +16,10 @@ Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.contrib import admin
|
||||
from django.urls import path, include
|
||||
from django.views.defaults import bad_request, permission_denied, page_not_found, server_error
|
||||
from django.urls import include, path
|
||||
from django.views.defaults import bad_request, page_not_found, permission_denied, server_error
|
||||
from django.views.generic import TemplateView
|
||||
from registration.views import PhotoAuthorizationView
|
||||
|
||||
@ -23,6 +27,7 @@ from .views import AdminSearchView
|
||||
|
||||
urlpatterns = [
|
||||
path('', TemplateView.as_view(template_name="index.html"), name='index'),
|
||||
path('about/', TemplateView.as_view(template_name="about.html"), name='about'),
|
||||
path('i18n/', include('django.conf.urls.i18n')),
|
||||
path('admin/doc/', include('django.contrib.admindocs.urls')),
|
||||
path('admin/', admin.site.urls, name="admin"),
|
||||
@ -35,11 +40,14 @@ urlpatterns = [
|
||||
|
||||
path('media/authorization/photo/<str:filename>/', PhotoAuthorizationView.as_view(), name='photo_authorization'),
|
||||
|
||||
path('cas/', include('cas_server.urls', namespace="cas_server")),
|
||||
|
||||
path('', include('eastereggs.urls')),
|
||||
]
|
||||
|
||||
if 'cas_server' in settings.INSTALLED_APPS: # pragma: no cover
|
||||
urlpatterns += [
|
||||
path('cas/', include('cas_server.urls', namespace="cas_server")),
|
||||
]
|
||||
|
||||
handler400 = bad_request
|
||||
handler403 = permission_denied
|
||||
handler404 = page_not_found
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from haystack.generic_views import SearchView
|
||||
|
@ -1,3 +1,6 @@
|
||||
# Copyright (C) 2020 by Animath
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
"""
|
||||
WSGI config for corres2math project.
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user