First push
This commit is contained in:
parent
95468bd21a
commit
0126ff3a1d
20
.gitea/workflows/build.yaml
Normal file
20
.gitea/workflows/build.yaml
Normal file
@ -0,0 +1,20 @@
|
||||
name: Build and push image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
Build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install
|
||||
run: curl -fsSL get.docker.com | bash
|
||||
- name: Clone
|
||||
run: git clone https://git.tgj.services/thatguyjack/game-server-docker.git .
|
||||
- name: Login
|
||||
run: echo "${{ secrets.DOCKERHUB_TOKEN }}" | docker login git.tgj.services -u thatguyjack --password-stdin
|
||||
- name: Buildx Container
|
||||
run: docker buildx create --name buildx --driver=docker-container
|
||||
- name: Build ACC
|
||||
run: docker buildx build --builder=buildx --platform=linux/amd64,linux/arm64 ./ACC -t git.tgj.services/thatguyjack/ACC:latest --push
|
38
ACC/Dockerfile
Normal file
38
ACC/Dockerfile
Normal file
@ -0,0 +1,38 @@
|
||||
FROM debian:11.5-slim
|
||||
|
||||
RUN apt-get update && \
|
||||
DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -y wine python3-pip && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN sudo add-apt-repository multiverse
|
||||
RUN sudo apt install software-properties-common
|
||||
RUN sudo dpkg --add-architecture i386
|
||||
RUN sudo apt update
|
||||
RUN sudo apt install lib32gcc-s1 steamcmd
|
||||
|
||||
|
||||
RUN mkdir -p /server
|
||||
RUN steamcmd +@sSteamCmdForcePlatformType windows +force_install_dir ~/server +app_update 1430110 +quit
|
||||
|
||||
RUN mkdir -p /accservermanager /data
|
||||
|
||||
WORKDIR /accservermanager
|
||||
|
||||
RUN useradd -ms /bin/bash someuser && \
|
||||
chown -R someuser:someuser /accservermanager /data
|
||||
|
||||
USER someuser
|
||||
VOLUME /data
|
||||
|
||||
COPY ./requirements.txt .
|
||||
RUN pip3 install --user --no-cache-dir -r requirements.txt
|
||||
|
||||
ENV WINEARCH=win64 \
|
||||
WINEDEBUG=-all
|
||||
RUN wineboot --init
|
||||
|
||||
COPY . /accservermanager
|
||||
|
||||
EXPOSE 9231/udp 9232/tcp 8000/tcp
|
||||
CMD ["python3", "manage.py", "runserver", "--insecure", "0.0.0.0:8000"]
|
674
ACC/LICENSE
Normal file
674
ACC/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) <year> <name of author>
|
||||
|
||||
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) <year> <name of author>
|
||||
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>.
|
84
ACC/README.md
Normal file
84
ACC/README.md
Normal file
@ -0,0 +1,84 @@
|
||||
Small web project to manage Assetto Corsa Competizione servers, build on Django.
|
||||
Allows to manage multiple configs and multiple server instances. Works in Linux and in Windows, dunno about OSX.
|
||||
|
||||
Currently, the web-app consists of two sub-apps
|
||||
* cfgs: Basically creates an autogenerated view from ACCs event.json, navigating through the object. Allows to create and edit multiple configurations, they are stored in the folder 'local_settings.CONFIGS'.
|
||||
* instances: Start a new ACC server instance or stop/delete running instances. Each instance uses a copy of the ACC 'server' directory, which is placed in the folder 'local_settings.INSTANCES'.
|
||||
|
||||
|
||||
## Development
|
||||
```bash
|
||||
git clone https://github.com/gotzl/accservermanager.git
|
||||
cd accservermanager/
|
||||
# Configure the things in accservermanager/local_settings.py, ie the path to your ACC server files
|
||||
python manage.py migrate
|
||||
python manage.py createsuperuser
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
Now you should be able to access the service at localhost:8000.
|
||||
|
||||
|
||||
## Dependencies
|
||||
```bash
|
||||
pip3 install -r requirements.txt # --user
|
||||
```
|
||||
Windows users might want to follow the official Django install instructions.
|
||||
|
||||
|
||||
## Deployment
|
||||
Follow the development instructions to deploy the app, should be good enough for our purposes...
|
||||
|
||||
Alternatively, I've created a docker image which uses wine to run the ACC server. No modifications to the local_settings.py are necessary in this case.
|
||||
|
||||
```bash
|
||||
# Create a volume (if you didn't already create one)
|
||||
docker volume create accservermanager-data
|
||||
# fire up a container
|
||||
docker run -d --name accservermanager \
|
||||
-e SECRET_KEY=RANDOM_SEQUENCE \
|
||||
-v accservermanager-data:/data \
|
||||
-v PATH_TO_ACC/server:/server \
|
||||
-p 8000:8000 -p 9231:9231/udp -p 9232:9232/tcp \
|
||||
gotzl/accservermanager
|
||||
# initiate the app and create a manager user (only neccessary at the very first start)
|
||||
docker exec -i -t accservermanager python3 manage.py migrate
|
||||
docker exec -i -t accservermanager python3 manage.py createsuperuser
|
||||
```
|
||||
|
||||
After login, you can add more users with djangos admin pages (...:8000/admin).
|
||||
|
||||
If you want to allow connections to the server from anywhere, use `-e ALLOWED_HOSTS='["*"]'`. This should only be used behind a proxy!
|
||||
|
||||
Note: The build-in django webserver only serves static files in debug mode. Therefore, either set `DEBUG=True`, or use `python manage.py runserver --insecure` (this is what's done in the docker image) or collect static files with `python3 manage.py collectstatic` and let s.t. else serve these files.
|
||||
|
||||
To make docker work with the last release of accServer.exe `ignorePrematureDisconnects` must be setted to `0`
|
||||
|
||||
Car skins: The folder `PATH_TO_ACC/server/cars` will be symlinked into the instance environment (if it exists).
|
||||
|
||||
## Persistence
|
||||
All relevant data will be placed insided the 'local_settings.DATA_DIR' folder. In case of docker the folder is persisted outside of the container using a docker volume.
|
||||
This means you can delete and rebuild your container without needing to restore your settings manually.
|
||||
|
||||
|
||||
## Compose example
|
||||
```bash
|
||||
version: '2'
|
||||
|
||||
services:
|
||||
acc:
|
||||
image: gotzl/accservermanager
|
||||
volumes:
|
||||
- /acc/server:/server
|
||||
- accservermanager-data:/data
|
||||
environment:
|
||||
# - ALLOWED_HOSTS=["*"]
|
||||
- SECRET_KEY=
|
||||
ports:
|
||||
- 9232:9232/tcp
|
||||
- 9231:9231/udp
|
||||
- 8000:8000
|
||||
|
||||
volumes:
|
||||
accservermanager-data:
|
||||
```
|
0
ACC/accservermanager/__init__.py
Normal file
0
ACC/accservermanager/__init__.py
Normal file
20
ACC/accservermanager/local_settings.py
Normal file
20
ACC/accservermanager/local_settings.py
Normal file
@ -0,0 +1,20 @@
|
||||
import os
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
# SECRET_KEY = # create a key with eg 'openssl rand -base64 32', one may also put it directly here
|
||||
|
||||
# Default is to only accept connections from localhost.
|
||||
# If you feel save and you're behind a proxy, use ALLOWED_HOSTS = ["*"] to allow connections from everywhere.
|
||||
# ALLOWED_HOSTS = []
|
||||
|
||||
# The ACC server exe, in case of linux, wine is used to execute the binary
|
||||
WINE_PATH = os.getenv('WINE_PATH', 'wine') # defaults to 'wine', windows: just set to empty string ""
|
||||
ACC_SERVER_PATH = os.getenv('ACC_SERVER_PATH', 'accServer.exe') # defaults to 'accServer.exe'
|
||||
ACCEXEC = [i for i in [WINE_PATH, ACC_SERVER_PATH] if i] # Omit WINE_PATH if empty
|
||||
|
||||
ACCSERVER = os.getenv('ACCSERVER', '/server') # defaults to '/server', windows: 'C:\\PATH\\TO\\ACC\\server'
|
||||
|
||||
# Directory where configs and instances are placed
|
||||
# (docker: this folder is mounted from the host via a docker volume)
|
||||
DATA_DIR = os.getenv('DATA_DIR', '/data') # defaults to /data, s.t. like '/tmp/accserver-data' or 'C:\\Users\\someuser\\accserver-data'
|
||||
CONFIGS = os.path.join(DATA_DIR, 'configs')
|
||||
INSTANCES = os.path.join(DATA_DIR, 'instances')
|
82
ACC/accservermanager/messages.json
Normal file
82
ACC/accservermanager/messages.json
Normal file
@ -0,0 +1,82 @@
|
||||
{
|
||||
"adminPassword": "Password to elevate via \"Server admin commands\"",
|
||||
"allowAutoDQ": "If set to 0, the server won\u2019t automatically disqualify drivers, and instead hand out Stop&Go (30s) penalties. This way a server admin / race director has 3 laps time to review the incident, and either use /dq or /clear based on his judgement.",
|
||||
"ambientTemp": "Sets the baseline ambient temperature in \u00b0C, see \"Race weekend simulation\" (ServerAdminHandbook)",
|
||||
"carGroup": "Defines the car group for this server. Possible values are "FreeForAll", "GT3", "GT4", "GTC", "TCX" where \"FreeForAll\" will allow any driver to join with any car (that he defined as Primary Car). GT3, GT4, GTC, TCX will restrict this server to GT3, GT4, Cup-like (Porsche Cup, Lamborghini ST, Ferrari CHL) and TCX (BMW M2) entries",
|
||||
"centralEntryListPath": "Can override the default entryList path \"cfg/entrylist.json\", so multiple ACC servers on the machine can use the same entrylist (and custom car files). Set a full path like \"C:/customEntryListSeriesA/\", where the entrylist is stored. Attention: The path seperators have to be slashes (/), backslashes (\\) will not work.",
|
||||
"cloudLevel": "Sets the baseline cloud level, see \"Race weekend simulation\" (ServerAdminHandbook). Has large impact on the cloud levels and rain chances. Values (0.0, 0.1, \u2026. 1.0)",
|
||||
"customCar": "If set to a filename, the car, team and appearance will be used no matter what the user chose (Exception: overrideCarModelForCustomCar). This is useful for leagues and events, where we want consistent car appearance and the chosen car model for the corresponding driver/team. The custom car file has to be located in a \"cars\" folder next to the entrylist.json (also works for centralEntryListPath). Leave blank (\"\", =default) to let the user chose the car via car selection UI.",
|
||||
"dayOfWeekend": "Race day (1 = Friday, 2 = Saturday, 3 = Sunday) \u2013 relevant to the grip and weather simulation.",
|
||||
"defaultGridPosition": "If set to a value of 1 or greater, this car will obtain this grid position if a race starts without any qualifying session <img src=\"ServerAdminHandbook-28_1.jpg\"/>",
|
||||
"disableAutoClutch": "Forces the equivalent assist option to \"off\"",
|
||||
"disableAutoEngineStart": "Forces the equivalent assist option to \"off\"",
|
||||
"disableAutoGear": "Forces the equivalent assist option to \"off\"",
|
||||
"disableAutoLights": "Forces the equivalent assist option to \"off\"",
|
||||
"disableAutoPitLimiter": "Forces the equivalent assist option to \"off\"",
|
||||
"disableAutoWiper": "Forces the equivalent assist option to \"off\" ",
|
||||
"disableAutosteer": "Disables the steering aid that is only available for gamepad controllers. Unlike SC, this works inside the physics and does not allow unrealistic driving behaviour \u2013 except that this is a very strong aid with superhuman feeling for grip and high reaction speed. There is a built-in penalty that should balance the driving performance in most cases, and give an incentive to learn not to use the driving aid. Default: 0",
|
||||
"disableIdealLine": "Forces the equivalent assist option to \"off\"",
|
||||
"driverCategory": "Bronze/Silver/Gold/Platinum category, if \"overrideDriverInfo\" is set to 1. See \"Driver Category list\" (ServerAdminHandbook) for values",
|
||||
"driverStintTimeSec": "Defines the maximum time a driver can stay out without getting a penalty. Can be used to balance fuel efficient cars in endurance races. The stint time resets in the pitlane, no real stop is required. -1 will disable the stint times. driverStintTimeSec and maxTotalDrivingTime are interdependent features, make sure both are set or off.",
|
||||
"drivers": "List of drivers, see table in ServerAdminHandbook. Must at least contain one driver with the SteamId",
|
||||
"dumpEntryList": "Will save an entry list at the end of any Qualifying session. This can be a quick way to collect a starting point to build an entry list, and is a way to save the defaultGridPositions which can be used to run a race without Qualifying session and predefined grid. Also see the corresponding admin command.",
|
||||
"dumpLeaderboards": "If set to 1, any session will write down the result leaderboard in a \"results\" folder (must be manually created). See \"Session results\" (ServerAdminHandbook)",
|
||||
"entries": "List of entries, see table in ServerAdminHandbook",
|
||||
"firstName": "First name of the driver, if \"overrideDriverInfo\" is set to 1",
|
||||
"forceEntryList": "Will reject drivers that are not in the entry list. Default is 0, which allows the partial definition of entries in a \"normal\" server configuration. Cannot be used on public servers.",
|
||||
"forcedCarModel": "If not set to -1: user cannot join with a different car, see \"Car model list\" (ServerAdminHandbook) for the values",
|
||||
"formationLapType": "Toggles the formation lap type that is permanently used on this server: 3 \u2013 default formation lap with position control and UI 0 \u2013 old limiter lap 1 \u2013 free (replaces /manual start), only usable for private servers",
|
||||
"hourOfDay": "Session starting hour of the day (values 0 - 23)",
|
||||
"ignorePrematureDisconnects": "Removes a (very good) fix where users can randomly lose the connection. There is no sane reason to turn this off. 1 \u2013 default: less arbitrary connections lost 0 \u2013 more timeouts, but strict disconnection of anyone who appears inactive for 5 seconds. Can be useful on unsupported platforms where TCP sockets act differently",
|
||||
"isFixedConditionQualification": "Experimental/not supported: if set to 1, the server will take the rain, cloud, temperature, rain levels literally and make sure whatever is set up never changes. Daytime transitions still happen visually, but do not affect the temperatures or road wetness. Also rubber/grip is always the same. This is intended to be used for private league qualification servers only. weatherRandomness has to be set to 0, otherwise isFixedConditionQualification will be completely disabled.",
|
||||
"isMandatoryPitstopRefuellingRequired": "Defines if a mandatory pitstop requires refuelling.",
|
||||
"isMandatoryPitstopSwapDriverRequired": "Defines if a mandatory pitstop requires a driver swap. Will only be effective for cars in driver swap situations; even in a mixed field this will be skipped for cars with a team size of 1 driver.",
|
||||
"isMandatoryPitstopTyreChangeRequired": "Defines if a mandatory pitstop requires changing tyres.",
|
||||
"isRaceLocked": "If set to 0, the server will allow joining during a race session. Is not useful in \"Public Multiplayer\", as the user-server matching will ignore ongoing race sessions.",
|
||||
"isRefuellingAllowedInRace": "Defines if refuelling is allowed during the race pitstops.",
|
||||
"isRefuellingTimeFixed": "If set to true, any refuelling will take the same amount of time. If turned off, refuelling will consume time linear to the amount refuelled. Very useful setting to balance fuel efficient cars, especially if combined with other features.",
|
||||
"isServerAdmin": "If set to 1, that user will be automatically elevated to server admin when he joins.",
|
||||
"lanDiscovery": "Defines if the server will listen to LAN discovery requests. Can be turned off for dedicated servers.",
|
||||
"lastName": "Last name of the driver, if \"overrideDriverInfo\" is set to 1",
|
||||
"leagueServerIP": "Declares the server IP which will return ALL existing ACC servers on during a \"LAN Server\" search.",
|
||||
"mandatoryPitstopCount": "Defines the basic mandatory pit stops. If the value is greater zero, any car that did not execute the mandatory pitstops will be disqualified at the end of the race. The necessary actions can be further configured using the \"isMandatoryPitstopXYRequired\" properties. A value of zero disables the feature.",
|
||||
"maxCarSlots": "Replaces \"maxClientsOverride\" and \"spectatorSlots\". Defines the amount of car slots the server can occupy; this value is overridden if the pit count of the track is lower, or with 30 for public MP. The gap between maxCarSlots and maxConnections defines how many spectators or other irregular connections (ie entry list entries) can be on the server.",
|
||||
"maxConnections": "Replaces \"maxClients\". The maximum amount of connections a server will accept at a time. If you own the hardware server, you can just set any high number you want. If you rented a 16 or 24 slot server, your Hosting Provider probably has set this here and doesn\u2019t give you write-access to this configuration file.",
|
||||
"maxDriversCount": "In driver swap situations, set this to the maximum number of drivers on a car. When an entry has fewer drivers than maxDriversCount, maxTotalDrivingTime is automatically compensated so that those "smaller" entries are also able to complete the race Example: 3H race length, 65 minutes driverStintTimeSec and 65 minutes maxTotalDrivingTime will result in 65 minutes of maxTotalDrivingTime for entries of 3 and 105 (!) minutes for entries of 2.",
|
||||
"maxTotalDrivingTime": "Restricts the maximum driving time for a single driver. Is only useful for driver swap situations and allows to enforce a minimum driving time for each driver (IRL this is used to make sure mixed teams like Pro/Am have a fair distributions of the slower drivers). -1 disables the feature. driverStintTimeSec and maxTotalDrivingTime are interdependent features, make sure both are set or off. Will set the maximum driving time for the team size defined by \"maxDriversCount\", always make sure both are set.",
|
||||
"metaData": "A user defined string that will be transferred to the result outputs.",
|
||||
"overrideCarModelForCustomCar": "If customCar is used, this setting will apply the car model configured if the value is set to 1 (which is the default). If set to 0, all values except the carModel are applied, so the user is free to pick a car but while team name and appearance will be applied.",
|
||||
"overrideDriverInfo": "If set to 1, the driver\u2019s name and category will be overridden by what is setup in the entry list. If set to 0, it\u2019s up to the client joining.",
|
||||
"password": "Password required to enter this server. If a password is set, the server is declared \"Private Multiplayer\".",
|
||||
"pitWindowLengthSec": "Defines a pit window at the middle of the race. Obviously covers the Sprint series format. -1 will disable the pit window. Use this combined with a mandatoryPitstopCount = 1.",
|
||||
"playerID": "Steam64 Id for this client; Add a \"S\" in the front",
|
||||
"postQualySeconds": "The time after the last driver is finished (or the sessionOverTimeSeconds passed) in Q sessions and the race start. Should not be set to 0, otherwise grid spawning is not secure.",
|
||||
"postRaceSeconds": "Additional time after the race ended for everyone, before the next race weekend starts.",
|
||||
"preRaceWaitingTimeSeconds": "Preparation time before a race. Cannot be less than 30s.",
|
||||
"publicIP": "Explicitly defines the public IP address this server is listening to. Useful if the backend is connected via a different gateway (for example the AWS Accelerator IP). If the publicIP is used, the server has to respond to an additional handshake, or it will immediately shutdown on backend connect.",
|
||||
"qualifyStandingType": "1 = fastest lap, 2 = average lap (running Endurance mode for multiple Q sessions) . Use 1, averaging Qualy is not yet officially supported.",
|
||||
"raceNumber": "The preferred race number if set, -1 if the driver may decide by picking his car. Values 1 - 998",
|
||||
"racecraftRatingRequirement": "Defines the Racecraft Rating (RC) that a user must have to join this server (values -1, 0, \u2026. 99)",
|
||||
"rain": "If weather randomness is off, defines the static rain level. With dynamic weather, it defines the expected rain level, dependent on weatherRandomness. Values (0.0, 0.1, \u2026. 1.0) ",
|
||||
"randomizeTrackWhenEmpty": "If set to 1, the server will change to a random track when the last drivers leaves (which causes a reset to FP1). The \"track\" property will only define the default state for the first session.",
|
||||
"registerToLobby": "When 0, this server won\u2019t register to the backend. Is useful for LAN sessions. If 0, the server is declared \"Private Multiplayer\". See serverList.json to learn how to bypass the backend\u2019s server list and discover servers not listed.",
|
||||
"safetyRatingRequirement": "Defines the Safety Rating (SA) that a user must have to join this server (values -1, 0, \u2026. 99)",
|
||||
"serverName": "The server name displayed in the ACC UI pages",
|
||||
"sessionDurationMinutes": "Session duration in minutes",
|
||||
"sessionOverTimeSeconds": "Time after that a session is forcibly closing after the timer reached 0:00. Something like 107% of the expected laptime is recommended (careful: default 2 minutes does not properly cover tracks like Spa or Silverstone).",
|
||||
"sessionType": "Race session type: P, Q, R for (P)ractice, (Q)ualy, (R)ace",
|
||||
"sessions": "A list of session objects, see table in ServerAdminHandbook",
|
||||
"shortFormationLap": "Toggles the short and long formation lap. Long formation is only usable on private servers.",
|
||||
"shortName": "Short name of the driver, if \"overrideDriverInfo\" is set to 1",
|
||||
"simracerWeatherConditions": "Experimental/not supported: if set to 1, this will limit the maximum rain/wetness to roughly 2/3 of the maximum values, translating to something between medium and heavy rain. It may be useful if you feel forced to run very low cloudLevel and weatherRandomness values just to avoid thunderstorm; however high levels (0.4+ clouds combined with 5+ randomness) will still result in quite serious conditions.",
|
||||
"spectatorPassword": "Password to enter the server as spectator. Must be different to \"password\" if both is set.",
|
||||
"stabilityControlLevelMax": "Set\u2019s the maximum % of SC that can be used. In case a client has a higher SC set than allowed by the server, he will only run what is allowed (25% in this example). Obviously setting this property to 0 removes all SC, including mouse and keyboard users. The Stability Control is an artificial driving aid that allows the car to act out of the physics boundaries, and highly recommended to overcome input methods like Keyboards, Gamepads and Mouse steering. However, there is a built-in effect that makes the SC performance inferior, so in theory using (and relying) on SC is already more than enough penalty, and the way to improve performance is to practice driving without. Default: 100",
|
||||
"tcpPort": "ACC clients will use this port to establish a connection to the server",
|
||||
"timeMultiplier": "Rate at which the session time advances in realtime. Values 0, 1, \u2026 24 ",
|
||||
"track": "The track we run, see \"Track name list\". Setting a wrong value will also print out the available track keys in the log. With the 1.8 update the \"open\" (ServerAdminHandbook) season was introduced, replacing 2018-2020 variants of the track",
|
||||
"trackMedalsRequirement": "Defines the amount of track medals that a user has to have for the given track (values 0, 1, 2, 3)",
|
||||
"trackTemp": "Obsolete: Track temperatures are always simulated based on ambient temperature, sun angle, clouds and other aspects.",
|
||||
"tyreSetCount": "Experimental/not supported: Can be used to reduce the amount of tyre sets any car entry has for the entire weekend. Please note that it is necessary to force cars to remain in the server, or drastically reduced tyre sets will be ineffective, as rejoining will reset the tyre sets.",
|
||||
"udpPort": "Connected clients will use this Port to stream the car positions and is used for the ping test. In case you never see your server getting a ping value, this indicates that the udpPort is not accessible",
|
||||
"weatherRandomness": "Sets the dynamic weather level, see \"Race weekend simulation\" (ServerAdminHandbook). 0 = static weather; 1-4 fairly realistic weather; 5-7 more sensational"
|
||||
}
|
290
ACC/accservermanager/settings.py
Normal file
290
ACC/accservermanager/settings.py
Normal file
@ -0,0 +1,290 @@
|
||||
"""
|
||||
Django settings for accservermanager project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 2.1.2.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/2.1/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/2.1/ref/settings/
|
||||
"""
|
||||
|
||||
import os, json
|
||||
|
||||
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django_bootstrap5',
|
||||
'django_bootstrap_breadcrumbs',
|
||||
'django_tables2',
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'cfgs',
|
||||
'instances',
|
||||
'results',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'accservermanager.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': ['templates'],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.debug',
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'accservermanager.wsgi.application'
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/2.1/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/2.1/howto/static-files/
|
||||
|
||||
STATIC_ROOT = os.path.join(BASE_DIR,'static')
|
||||
STATIC_URL = '/static/'
|
||||
|
||||
|
||||
LOGIN_REDIRECT_URL = '/cfgs'
|
||||
LOGOUT_REDIRECT_URL = '/cfgs'
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True if os.getenv('DEBUG', 'False').lower() == 'true' else False
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = os.environ['SECRET_KEY'] \
|
||||
if 'SECRET_KEY' in os.environ else None # create a key with eg 'openssl rand -base64 32', one may also put it directly here
|
||||
|
||||
ALLOWED_HOSTS = json.loads(os.environ['ALLOWED_HOSTS']) \
|
||||
if 'ALLOWED_HOSTS' in os.environ else []
|
||||
|
||||
CSRF_TRUSTED_ORIGINS = json.loads(os.environ['CSRF_TRUSTED_ORIGINS']) \
|
||||
if 'CSRF_TRUSTED_ORIGINS' in os.environ else []
|
||||
|
||||
ALLOW_SAME_PORTS = True if os.getenv('ALLOW_SAME_PORTS','False').lower() == 'true' else False
|
||||
|
||||
try:
|
||||
from accservermanager.local_settings import *
|
||||
except ImportError:
|
||||
raise Exception("A local_settings.py file is required to run this project")
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(DATA_DIR, 'db.sqlite3'),
|
||||
}
|
||||
}
|
||||
|
||||
# list of acc server files that are copied to the instance, make sure they are found
|
||||
SERVER_FILES = [
|
||||
'accServer.exe',
|
||||
'cfg/configuration.json',
|
||||
'cfg/settings.json',
|
||||
'cfg/assistRules.json',
|
||||
]
|
||||
for f in SERVER_FILES:
|
||||
if not os.path.isfile(os.path.join(ACCSERVER, f)):
|
||||
raise Exception('Cannot find required server file: %s.'%f)
|
||||
|
||||
# session template used in case no session is present
|
||||
SESSION_TEMPLATE = {
|
||||
"hourOfDay": 14,
|
||||
"dayOfWeekend": 2,
|
||||
"timeMultiplier": 1,
|
||||
"sessionType": "R",
|
||||
"sessionDurationMinutes": 10
|
||||
}
|
||||
|
||||
EVENT_RULES_TEMPLATE = {
|
||||
"qualifyStandingType": 1,
|
||||
"pitWindowLengthSec": -1,
|
||||
"driverStintTimeSec": -1,
|
||||
"mandatoryPitstopCount": 0,
|
||||
"maxTotalDrivingTime": -1,
|
||||
"maxDriversCount": 1,
|
||||
"isRefuellingAllowedInRace": True,
|
||||
"isRefuellingTimeFixed": False,
|
||||
"isMandatoryPitstopRefuellingRequired": False,
|
||||
"isMandatoryPitstopTyreChangeRequired": False,
|
||||
"isMandatoryPitstopSwapDriverRequired": False,
|
||||
"tyreSetCount": 50
|
||||
}
|
||||
|
||||
# list of available tracks
|
||||
TRACKS = [
|
||||
('barcelona', 'Catalunya (Barcelona)'),
|
||||
('brands_hatch', 'Brands Hatch'),
|
||||
('hungaroring', 'Hungaroring'),
|
||||
('misano', 'Misano'),
|
||||
('monza', 'Monza'),
|
||||
('nurburgring', 'Nurburgring GP'),
|
||||
('paul_ricard', 'Paul Ricard'),
|
||||
('silverstone', 'Silverstone'),
|
||||
('spa', 'Spa-Francorchamps'),
|
||||
('zolder', 'Zolder'),
|
||||
('zandvoort', 'Zandvoort'),
|
||||
('kyalami', 'Kyalami'),
|
||||
('laguna_seca', 'Laguna Seca'),
|
||||
('mount_panorama', 'Mount Panaorama'),
|
||||
('suzuka', 'Suzuka'),
|
||||
('imola', 'Imola'),
|
||||
('oulton_park', 'Oulton_park'),
|
||||
('donington', 'Donington'),
|
||||
('snetterton', 'Snetterton'),
|
||||
# American Track Pack
|
||||
('cota', 'Circuit of the Americas (DLC)'),
|
||||
('indianapolis', 'Indianapolis Motor Speedway (DLC)'),
|
||||
('watkins_glen', 'Watkins Glen International (DLC)'),
|
||||
('valencia', 'Circuit de la Comunitat Valenciana Ricardo Tormo (DLC)'),
|
||||
]
|
||||
|
||||
|
||||
CAR_MODEL_TYPES = (
|
||||
(0, 'Porsche 911 (991) GT3 R'),
|
||||
(1, 'Mercedes-AMG GT3'),
|
||||
(2, 'Ferrari 488 GT3'),
|
||||
(3, 'Audi R8 LMS'),
|
||||
(4, 'Lamborghini Huracán GT3'),
|
||||
(5, 'McLaren 650S GT3'),
|
||||
(6, 'Nissan GT-R Nismo GT3 (2018)'),
|
||||
(7, 'BMW M6 GT3'),
|
||||
(8, 'Bentley Continental GT3 (2018)'),
|
||||
(9, 'Porsche 911.2 GT3 Cup'),
|
||||
(10, 'Nissan GT-R Nismo GT3 (2017)'),
|
||||
(11, 'Bentley Continental GT3 (2016)'),
|
||||
(12, 'Aston Martin Racing V12 Vantage GT3'),
|
||||
(13, 'Lamborghini Gallardo R-EX'),
|
||||
(14, 'Jaguar G3'),
|
||||
(15, 'Lexus RC F GT3'),
|
||||
(16, 'Lamborghini Huracan Evo (2019)'),
|
||||
(17, 'Honda/Acura NSX GT3'),
|
||||
(18, 'Lamborghini Huracán Super Trofeo (2015)'),
|
||||
(19, 'Audi R8 LMS Evo (2019)'),
|
||||
(20, 'AMR V8 Vantage (2019)'),
|
||||
(21, 'Honda NSX Evo (2019)'),
|
||||
(22, 'McLaren 720S GT3 (Special)'),
|
||||
(23, 'Porsche 911 II GT3 R (2019)'),
|
||||
(24, 'Ferrari 488 GT3 Evo 2020'),
|
||||
(25, 'Mercedes-AMG GT3 2020'),
|
||||
(26, 'Ferrari 488 Challenge Evo'),
|
||||
(27, 'BMW M2 CS Racing'),
|
||||
(28, 'Porsche 911 GT3 Cup (Type 992)'),
|
||||
(29, 'Lamborghini Huracán Super Trofeo EVO2'),
|
||||
(30, 'BMW M4 GT3'),
|
||||
(31, 'Audi R8 LMS GT3 evo II'),
|
||||
(32, 'Ferrari 296 GT3'),
|
||||
(33, 'Lamborghini Huracan Evo2'),
|
||||
(34, 'Porsche 992 GT3 R'),
|
||||
|
||||
(50, 'Alpine A110 GT4'),
|
||||
(51, 'Aston Martin Vantage GT4'),
|
||||
(52, 'Audi R8 LMS GT4'),
|
||||
(53, 'BMW M4 GT4'),
|
||||
(55, 'Chevrolet Camaro GT4'),
|
||||
(56, 'Ginetta G55 GT4'),
|
||||
(57, 'KTM X-Bow GT4'),
|
||||
(58, 'Maserati MC GT4'),
|
||||
(59, 'McLaren 570S GT4'),
|
||||
(60, 'Mercedes AMG GT4'),
|
||||
(61, 'Porsche 718 Cayman GT4'),
|
||||
)
|
||||
|
||||
CAR_GROUPS = (
|
||||
("FreeForAll", "FreeForAll"),
|
||||
("GT3", "GT3"),
|
||||
("GT4", "GT4"),
|
||||
("GTC", "GTC"),
|
||||
("TCX", "TCX"),
|
||||
)
|
||||
|
||||
SESSION_TYPES = (
|
||||
("P",'Practice'),
|
||||
("Q",'Qualify'),
|
||||
("R",'Race'),
|
||||
)
|
||||
|
||||
EVENT_TYPES = (
|
||||
("E_3h",'Endurance - 3h'),
|
||||
("E_6h",'Endurance - 6h'),
|
||||
)
|
||||
|
||||
DRIVER_CATEGORY = {
|
||||
(3, "Platinum"),
|
||||
(2, "Gold"),
|
||||
(1, "Silver"),
|
||||
(0, "Bronze")
|
||||
}
|
||||
|
||||
CUP_CATEGORY = {
|
||||
(0, "Overall"),
|
||||
(1, "ProAm"),
|
||||
(2, "Am"),
|
||||
(3, "Silver"),
|
||||
(4, "National")
|
||||
}
|
||||
|
||||
MESSAGES = json.load(open(os.path.join(BASE_DIR, 'accservermanager/messages.json'), 'r'))
|
40
ACC/accservermanager/urls.py
Normal file
40
ACC/accservermanager/urls.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""accservermanager URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/2.1/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
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.contrib import admin
|
||||
from django.urls import path, include
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
urlpatterns = [
|
||||
path('', TemplateView.as_view(template_name='main.html'), name='login'),
|
||||
path('cfgs/', include('cfgs.urls')),
|
||||
path('instances/', include('instances.urls')),
|
||||
path('instances/<instance>/results/', include('results.urls')),
|
||||
path('admin/', admin.site.urls),
|
||||
path('accounts/', include('django.contrib.auth.urls')),
|
||||
]
|
||||
|
||||
|
||||
def on_startup():
|
||||
import os, shutil
|
||||
from accservermanager import settings
|
||||
if not os.path.exists(settings.CONFIGS): os.makedirs(settings.CONFIGS)
|
||||
if not os.path.exists(settings.INSTANCES): os.makedirs(settings.INSTANCES)
|
||||
# make sure that there is always a cfg in the cfg folder
|
||||
if len(os.listdir(settings.CONFIGS) ) == 0:
|
||||
shutil.copy(os.path.join(settings.ACCSERVER,'cfg','event.json'),
|
||||
os.path.join(settings.CONFIGS,'event.json'))
|
||||
|
||||
on_startup()
|
16
ACC/accservermanager/wsgi.py
Normal file
16
ACC/accservermanager/wsgi.py
Normal file
@ -0,0 +1,16 @@
|
||||
"""
|
||||
WSGI config for accservermanager project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accservermanager.settings')
|
||||
|
||||
application = get_wsgi_application()
|
0
ACC/cfgs/__init__.py
Normal file
0
ACC/cfgs/__init__.py
Normal file
5
ACC/cfgs/apps.py
Normal file
5
ACC/cfgs/apps.py
Normal file
@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class CfgsConfig(AppConfig):
|
||||
name = 'cfgs'
|
71
ACC/cfgs/confEdit.py
Normal file
71
ACC/cfgs/confEdit.py
Normal file
@ -0,0 +1,71 @@
|
||||
from django import forms
|
||||
from django.utils.safestring import mark_safe
|
||||
|
||||
import re
|
||||
|
||||
from accservermanager import settings
|
||||
from accservermanager.settings import TRACKS, SESSION_TYPES, EVENT_TYPES
|
||||
|
||||
|
||||
def fieldForKey(key, value):
|
||||
# list of fields that get special treatment, other fields are derived from value type
|
||||
if key == 'track':
|
||||
return forms.ChoiceField(
|
||||
widget=forms.Select,
|
||||
choices=sorted(TRACKS),
|
||||
)
|
||||
if key == 'sessionType':
|
||||
return forms.ChoiceField(
|
||||
widget=forms.Select,
|
||||
choices=SESSION_TYPES,
|
||||
)
|
||||
if key == 'eventType':
|
||||
return forms.ChoiceField(
|
||||
widget=forms.Select,
|
||||
choices=EVENT_TYPES,
|
||||
)
|
||||
|
||||
if isinstance(value, list): return forms.CharField()
|
||||
if isinstance(value, int): return forms.IntegerField()
|
||||
if isinstance(value, float): return forms.FloatField()
|
||||
if isinstance(value, str): return forms.CharField()
|
||||
return None
|
||||
|
||||
|
||||
def createLabel(key):
|
||||
""" create label from json key, ie thisIsAKey -> This Is A Key """
|
||||
key = key[0].upper()+key[1:]
|
||||
return ' '.join(re.findall('[A-Z][^A-Z]*', key))
|
||||
|
||||
|
||||
def createForm(obj, path):
|
||||
""" create a form form the objs keys, pre-filled with its values """
|
||||
|
||||
# if the object is a list, create a form for each item
|
||||
if isinstance(obj, list):
|
||||
return [createForm(obj[i], path + [str(i)]) for i in range(len(obj))]
|
||||
|
||||
# if the object is a integer, create a temporary object and proceed
|
||||
if isinstance(obj, int) or isinstance(obj, float) or isinstance(obj, str):
|
||||
obj = {'value': obj}
|
||||
|
||||
# iterate over the objects elements and add fields to the form
|
||||
form = forms.Form()
|
||||
for key, value in sorted(obj.items(), key=lambda x:x[0]):
|
||||
# if the element is a object itself, let the form display a link to further drilldown into this object
|
||||
if isinstance(value, dict) or \
|
||||
(isinstance(value, list) and len(value)>0 and isinstance(value[0], dict)):
|
||||
form.fields[key] = forms.CharField(
|
||||
disabled=True,
|
||||
widget=forms.TextInput(
|
||||
attrs={'placeholder': '', 'disabled': True, 'hidden': True}),
|
||||
label=mark_safe('<a href="/%s">%s</a>'%('/'.join(path+[key]),key)))
|
||||
else:
|
||||
form.fields[key] = fieldForKey(key, value)
|
||||
form.fields[key].label = createLabel(key)
|
||||
form.fields[key].initial = value
|
||||
form.fields[key].required = True
|
||||
if key in settings.MESSAGES:
|
||||
form.fields[key].help_text = settings.MESSAGES[key]
|
||||
|
||||
return form
|
35
ACC/cfgs/confSelect.py
Normal file
35
ACC/cfgs/confSelect.py
Normal file
@ -0,0 +1,35 @@
|
||||
from django import forms
|
||||
|
||||
import os, glob, ntpath
|
||||
|
||||
from accservermanager import settings
|
||||
|
||||
|
||||
def getCfgs():
|
||||
""" Check the cfg/custom folder for available configs, return list of file names w/o suffix """
|
||||
return list(map(lambda x: os.path.splitext(ntpath.basename(x))[0],
|
||||
glob.glob('%s/*.json'%(settings.CONFIGS))))
|
||||
|
||||
|
||||
def getCfgsField(selected=None, **kwargs):
|
||||
""" A select component showing the available configs """
|
||||
return forms.TypedChoiceField(
|
||||
empty_value=None,
|
||||
choices=[(i,i) for i in getCfgs()],
|
||||
initial=None if selected is None else selected,
|
||||
**kwargs
|
||||
)
|
||||
|
||||
|
||||
class CfgsForm(forms.Form):
|
||||
""" A form with a select component showing the available configs """
|
||||
def __init__(self, selected=None):
|
||||
super().__init__()
|
||||
self.fields['cfgs'] = getCfgsField(selected)
|
||||
|
||||
|
||||
class CfgCreate(forms.Form):
|
||||
""" A form creating a new config, only holds a name field """
|
||||
name = forms.CharField(max_length=100,
|
||||
required=True,
|
||||
widget=forms.TextInput(attrs={"onkeyup":"nospaces(this)"}))
|
0
ACC/cfgs/migrations/__init__.py
Normal file
0
ACC/cfgs/migrations/__init__.py
Normal file
148
ACC/cfgs/templates/cfgs/confEdit.html
Normal file
148
ACC/cfgs/templates/cfgs/confEdit.html
Normal file
@ -0,0 +1,148 @@
|
||||
{% extends "main.html" %}
|
||||
{% block content %}
|
||||
|
||||
<style>
|
||||
#cfg-wrapper {
|
||||
height:100%;
|
||||
position:relative;
|
||||
}
|
||||
|
||||
#cfg-inner-wrapper {
|
||||
height:100%;
|
||||
padding-top: 100px;
|
||||
}
|
||||
|
||||
#cfgs {
|
||||
height:100px;
|
||||
margin-top:-100px;
|
||||
}
|
||||
|
||||
#cfg {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
<!--margin-left: 200px;-->
|
||||
padding-left: 30px;
|
||||
<!--border-left: 1px solid #9e9e9e;-->
|
||||
}
|
||||
|
||||
sidenav {
|
||||
position: fixed!important;
|
||||
width:200px;
|
||||
padding-left:10px;
|
||||
}
|
||||
|
||||
input[type=submit] {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.container {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
{% load django_bootstrap_breadcrumbs %}
|
||||
{% block breadcrumbs %}
|
||||
{% clear_breadcrumbs %}
|
||||
{% for b, u in path %}
|
||||
{% breadcrumb_raw_safe b u %}
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
{% bootstrap_css %}
|
||||
{% bootstrap_javascript %}
|
||||
|
||||
<div id="cfg-wrapper" class="container">
|
||||
<div class="card" style="height:100%; border:none">
|
||||
<div id="cfg-inner-wrapper">
|
||||
|
||||
<header id="cfgs">
|
||||
{% render_breadcrumbs %}
|
||||
</header>
|
||||
|
||||
{% if form is not None %}
|
||||
<div id="cfg">
|
||||
<!--<div>-->
|
||||
<!--<h6 style="font-weight:bold">{{request.path}}</h6>-->
|
||||
<form action="" method="post" style="padding-right:20px">
|
||||
|
||||
{% csrf_token %}
|
||||
{% bootstrap_form form %}
|
||||
</form>
|
||||
<!--</div>-->
|
||||
</div>
|
||||
{% endif%}
|
||||
|
||||
{% if forms is not None %}
|
||||
<div id="cfg">
|
||||
{% for frm in forms %}
|
||||
<div id="form{{forloop.counter0}}" class="card" style="display:none">
|
||||
<!--<h6 style="font-weight:bold">{{request.path}}/{{forloop.counter0}}</h6>-->
|
||||
<form action="" method="post" style="padding-right:20px">
|
||||
|
||||
{% csrf_token %}
|
||||
<!--{{ frm }}-->
|
||||
{% bootstrap_form frm %}
|
||||
<input type="hidden" name="_id" value="{{forloop.counter0}}">
|
||||
</form>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<input id="prevbutton" type="button" value="Previous" class="btn btn-primary" disabled/>
|
||||
<input id="nextbutton" type="button" value="Next" class="btn btn-primary" disabled/>
|
||||
<input id="removebutton" type="button" class="btn btn-danger" value="Remove" disabled/>
|
||||
<input id="addbutton" type="button" value="Add" class="btn btn-success" disabled/>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
var form_id = 0
|
||||
|
||||
function handleButtons(new_form_id) {
|
||||
form_id = new_form_id
|
||||
$("div[id^='form']").hide();
|
||||
$("#form"+new_form_id).show();
|
||||
|
||||
if (new_form_id>0) $("#prevbutton").prop('disabled', false);
|
||||
else $("#prevbutton").prop('disabled', true);
|
||||
|
||||
if ($('#form1').length) $("#removebutton").prop('disabled', false);
|
||||
else $("#removebutton").prop('disabled', true);
|
||||
|
||||
if ($('#form'+(new_form_id+1)).length) {
|
||||
$("#nextbutton").prop('disabled', false);
|
||||
$("#addbutton").prop('disabled', true);
|
||||
} else {
|
||||
$("#nextbutton").prop('disabled', true);
|
||||
$("#addbutton").prop('disabled', false);
|
||||
}
|
||||
}
|
||||
|
||||
$("#prevbutton").click(function (){handleButtons(form_id-1)})
|
||||
$("#nextbutton").click(function (){handleButtons(form_id+1)})
|
||||
$("#addbutton").click(function() {
|
||||
window.location = '{{request.path}}'+'/add';
|
||||
})
|
||||
$("#removebutton").click(function() {
|
||||
window.location = '{{request.path}}'+'/remove/'+form_id;
|
||||
})
|
||||
|
||||
handleButtons(form_id)
|
||||
</script>
|
||||
|
||||
{% endif %}
|
||||
|
||||
|
||||
<script>
|
||||
$(function() { $(":input").change(function() {
|
||||
$.post( '', $(this.form).serialize(), function(data) {
|
||||
alert('server response'+data);
|
||||
}, 'json' );
|
||||
})
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
88
ACC/cfgs/templates/cfgs/confSelect.html
Normal file
88
ACC/cfgs/templates/cfgs/confSelect.html
Normal file
@ -0,0 +1,88 @@
|
||||
{% extends "main.html" %}
|
||||
{% block content %}
|
||||
|
||||
<style>
|
||||
tr:hover {
|
||||
background-color: #d3d3d3;
|
||||
}
|
||||
.container {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
{% bootstrap_css %}
|
||||
{% bootstrap_javascript %}
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h6 style="font-weight:bold">Create new config</h6>
|
||||
<form action="/cfgs/create" method="post">
|
||||
{% csrf_token %}
|
||||
{% bootstrap_form form %}
|
||||
<input type="submit" value="Create" class="btn btn-success">
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h6 style="font-weight:bold">Existing configs</h6>
|
||||
<table>
|
||||
<tr><td style="font-weight:bold">Name</td><td style="font-weight:bold">Actions</td><td></td><td></td></tr>
|
||||
{% for cfg in cfgs %}
|
||||
<tr>
|
||||
<td style="width: 200px">
|
||||
<form id="cfgform{{forloop.counter0}}" style="margin: 0" action="/cfgs/rename" method="post">{% csrf_token %}
|
||||
<input hidden name="cfg" value="{{cfg}}">
|
||||
<i id="rename{{forloop.counter0}}" type="button"
|
||||
style="vertical-align: middle; color: blue"
|
||||
title="Rename" class="material-icons">edit</i>
|
||||
<input id="cfgname{{forloop.counter0}}" name="cfgname"
|
||||
oldvalue={{cfg}} value={{cfg}} style="width: 150px" readonly>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form style="margin: 0" action="/cfgs/clone" method="post">{% csrf_token %}
|
||||
<input hidden name="cfg" value="{{cfg}}">
|
||||
<a href="/cfgs/{{cfg}}" class="btn btn-primary">Edit</a>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form style="margin: 0" action="/cfgs/clone" method="post">{% csrf_token %}
|
||||
<input hidden name="cfg" value="{{cfg}}">
|
||||
<input type="submit" value="Clone" class="btn btn-success">
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form style="margin: 0" action="/cfgs/delete" method="post">{% csrf_token %}
|
||||
<input hidden name="cfg" value="{{cfg}}">
|
||||
<input type="submit" value="Delete" class="btn btn-danger">
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<script>
|
||||
$("#rename{{forloop.counter0}}").click(function (){
|
||||
var cfg = $("#cfgname{{forloop.counter0}}");
|
||||
var ro = cfg.prop('readonly');
|
||||
cfg.prop('readonly', !ro);
|
||||
if (ro) {
|
||||
$(this).css('color','red');
|
||||
cfg.prop('oldvalue', cfg.val());
|
||||
cfg.prop('type', 'text');
|
||||
cfg.focus()
|
||||
} else {
|
||||
$(this).css('color','blue');
|
||||
if (cfg.prop('oldvalue') != cfg.val()) {
|
||||
$("#cfgform{{forloop.counter0}}").submit();
|
||||
}
|
||||
}
|
||||
})
|
||||
</script>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
12
ACC/cfgs/urls.py
Normal file
12
ACC/cfgs/urls.py
Normal file
@ -0,0 +1,12 @@
|
||||
from django.urls import path, re_path
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path(r'', views.confSelect, name='confSelect'),
|
||||
path(r'delete', views.confDelete, name='confDelete'),
|
||||
path(r'create', views.confCreate, name='confCreate'),
|
||||
path(r'rename', views.confRename, name='confRename'),
|
||||
path(r'clone', views.confClone, name='confClone'),
|
||||
re_path(r'^([^/]+)/?(.*)', views.formForKey, name='formForKey'),
|
||||
]
|
161
ACC/cfgs/views.py
Normal file
161
ACC/cfgs/views.py
Normal file
@ -0,0 +1,161 @@
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.shortcuts import render
|
||||
|
||||
import os, json, shutil, glob
|
||||
from pathlib import Path
|
||||
|
||||
from accservermanager import settings
|
||||
from accservermanager.settings import SESSION_TEMPLATE
|
||||
from cfgs.confEdit import createLabel, createForm
|
||||
from cfgs.confSelect import CfgsForm, getCfgs, CfgCreate
|
||||
|
||||
|
||||
@login_required
|
||||
def confCreate(request):
|
||||
""" Create a new config based on the backuped origin custom.json """
|
||||
_base = os.path.join(settings.ACCSERVER,'cfg','event.json')
|
||||
_f = os.path.join(settings.CONFIGS, request.POST['name']+'.json')
|
||||
if not os.path.exists(_f): shutil.copy(_base, _f)
|
||||
return HttpResponseRedirect('/cfgs')
|
||||
|
||||
|
||||
@login_required
|
||||
def confClone(request):
|
||||
""" Clone a config file """
|
||||
_f = os.path.join(settings.CONFIGS, request.POST['cfg']+'.json')
|
||||
_n = os.path.join(settings.CONFIGS, request.POST['cfg']+'_clone.json')
|
||||
if not os.path.exists(_n): shutil.copy(_f, _n)
|
||||
return HttpResponseRedirect('/cfgs')
|
||||
|
||||
|
||||
@login_required
|
||||
def confRename(request):
|
||||
""" Rename a config file """
|
||||
_o = request.POST['cfg']
|
||||
_n = request.POST['cfgname']
|
||||
_old = os.path.join(settings.CONFIGS, _o+'.json')
|
||||
_new = os.path.join(settings.CONFIGS, _n+'.json')
|
||||
if _o != _n and os.path.exists(_old) and not os.path.exists(_new):
|
||||
# create a copy of the config with the new name
|
||||
shutil.copy(_old, _new)
|
||||
# change the link of instances using the old config
|
||||
from instances.views import executors
|
||||
for inst_dir in glob.glob(os.path.join(settings.INSTANCES, '*')):
|
||||
inst_name = os.path.split(inst_dir)[-1]
|
||||
if inst_name in executors:
|
||||
executors[inst_name].config = _n+'.json'
|
||||
|
||||
cfg = os.path.join(inst_dir, 'cfg', 'event.json')
|
||||
if Path(cfg).resolve().name == _o+'.json':
|
||||
os.remove(cfg)
|
||||
os.symlink(_new, cfg)
|
||||
|
||||
# finally, remove the original config
|
||||
os.remove(_old)
|
||||
|
||||
return HttpResponseRedirect('/cfgs')
|
||||
|
||||
|
||||
@login_required
|
||||
def confDelete(request):
|
||||
""" Delete a config file """
|
||||
_f = os.path.join(settings.CONFIGS, request.POST['cfg']+'.json')
|
||||
if os.path.exists(_f):
|
||||
# check that no executor references the cfg
|
||||
# TODO: give some feedback to the UI!
|
||||
for inst_dir in glob.glob(os.path.join(settings.INSTANCES, '*')):
|
||||
cfg = os.path.join(inst_dir, 'cfg', 'event.json')
|
||||
if Path(cfg).resolve().name == request.POST['cfg']+'.json':
|
||||
return HttpResponseRedirect('/cfgs')
|
||||
os.remove(_f)
|
||||
return HttpResponseRedirect('/cfgs')
|
||||
|
||||
|
||||
@login_required
|
||||
def confSelect(request):
|
||||
""" Show available configs and form to create a new config """
|
||||
context = {
|
||||
'form' : CfgCreate(),
|
||||
'cfgs' : getCfgs(),
|
||||
}
|
||||
return render(request, 'cfgs/confSelect.html', context)
|
||||
|
||||
|
||||
def formForKey(request, config, *args):
|
||||
""" Read the select config file and display the selected portion of the json object """
|
||||
cfg_path = os.path.join(settings.CONFIGS, config+'.json')
|
||||
cfg = json.load(open(cfg_path, 'r', encoding='utf-16'))
|
||||
if len(cfg['sessions']) == 0:
|
||||
cfg['sessions'] = [SESSION_TEMPLATE]
|
||||
args = args[0]
|
||||
|
||||
# drill down into the json object to the selected part
|
||||
obj = cfg
|
||||
path = ['cfgs',config]
|
||||
if len(args)>0:
|
||||
for arg in args.split('/'):
|
||||
if isinstance(obj, list):
|
||||
# handle add/remove requests for list objects
|
||||
if arg in ['add','remove']:
|
||||
# copy the last object and add to the list
|
||||
if arg=='add': obj.append(obj[-1])
|
||||
# remove selected element
|
||||
elif arg=='remove':
|
||||
obj.remove(obj[int(args.split('/')[-1])])
|
||||
|
||||
json.dump(cfg, open(cfg_path, 'w', encoding='utf-16'))
|
||||
return HttpResponseRedirect('/'+'/'.join(path))
|
||||
|
||||
# select specific element of the list object
|
||||
arg = int(arg)
|
||||
# if the element is not in the list, redirect to the current path
|
||||
# (happens eg when jumping to another config which doesn't have the same
|
||||
# number of events)
|
||||
if arg>=len(obj): return HttpResponseRedirect('/'+'/'.join(path))
|
||||
|
||||
obj = obj[arg]
|
||||
path.append(str(arg))
|
||||
|
||||
if request.method == 'POST':
|
||||
# another config was selected
|
||||
if 'cfgs' in request.POST.keys():
|
||||
return HttpResponseRedirect('/cfgs/%s/%s'%(request.POST['cfgs'],args))
|
||||
|
||||
# the form was submitted, update the values in the json obj and dump it to file
|
||||
if isinstance(obj, list): obj = obj[int(request.POST['_id'])]
|
||||
for key, value in request.POST.items():
|
||||
if key in ['csrfmiddlewaretoken', '_id']: continue
|
||||
|
||||
if isinstance(obj[key], list): continue
|
||||
if isinstance(obj[key], int): value = int(value)
|
||||
elif isinstance(obj[key], float): value = float(value)
|
||||
elif not isinstance(obj[key], str):
|
||||
print('Unknown type',type(obj[key]), type(value))
|
||||
obj[key] = value
|
||||
|
||||
json.dump(cfg, open(cfg_path, 'w', encoding='utf-16'))
|
||||
return HttpResponseRedirect(request.path)
|
||||
|
||||
_form, _forms = None, None
|
||||
_form = createForm(obj, path)
|
||||
|
||||
# ugly switch to handle list-values (like events)
|
||||
if isinstance(_form, list):
|
||||
_forms = _form
|
||||
_form = None
|
||||
|
||||
# extract first level keys of the json object, they are displayed in the navigation sidebar
|
||||
# only if they are not emptylists
|
||||
emptyList = lambda x: not (isinstance(cfg[x], list) and len(cfg[x])==0)
|
||||
keys = sorted(filter(emptyList, cfg.keys()))
|
||||
|
||||
context = {
|
||||
# 'keys': [(k, createLabel(k)) for k in keys],
|
||||
'cfgs': CfgsForm(config),
|
||||
'cfg': config,
|
||||
'path': [(j, '/'+'/'.join(path[:i+1])) for i,j in enumerate(path)],
|
||||
'forms': _forms,
|
||||
'form': _form
|
||||
}
|
||||
return render(request, 'cfgs/confEdit.html', context)
|
14
ACC/docker-compose.yml
Normal file
14
ACC/docker-compose.yml
Normal file
@ -0,0 +1,14 @@
|
||||
version: '2'
|
||||
services:
|
||||
acc:
|
||||
image: git.tgj.services/thatguyjack/ACC:latest
|
||||
volumes:
|
||||
# - ./accservermanager/server:/server
|
||||
- ./accservermanager/data:/data
|
||||
environment:
|
||||
# - ALLOWED_HOSTS=["*"]
|
||||
- SECRET_KEY=
|
||||
ports:
|
||||
- 9232:9232/tcp
|
||||
- 9231:9231/udp
|
||||
- 8000:8000
|
69
ACC/instances/Executor.py
Normal file
69
ACC/instances/Executor.py
Normal file
@ -0,0 +1,69 @@
|
||||
import os, subprocess, time, datetime, json
|
||||
from multiprocessing import Value
|
||||
from threading import Thread
|
||||
from pathlib import Path
|
||||
|
||||
from accservermanager import settings
|
||||
|
||||
try: import resource
|
||||
except: resource = None
|
||||
|
||||
|
||||
class Executor(Thread):
|
||||
"""
|
||||
Thread for running the server process
|
||||
"""
|
||||
def __init__(self, instanceDir):
|
||||
super().__init__()
|
||||
|
||||
# add all configuration values to the object
|
||||
for key, val in json.load(open(os.path.join(instanceDir, 'cfg', 'configuration.json'), 'r', encoding='utf-16')).items():
|
||||
setattr(self, key, val)
|
||||
for key, val in json.load(open(os.path.join(instanceDir, 'cfg', 'settings.json'), 'r', encoding='utf-16')).items():
|
||||
setattr(self, key, val)
|
||||
|
||||
# find the name of the config file, just needed to display it in the instances list
|
||||
self.config = Path(os.path.join(instanceDir, 'cfg', 'event.json')).resolve().name
|
||||
|
||||
self.p = None
|
||||
self.stdout = None
|
||||
self.stderr = None
|
||||
self.serverlog = None
|
||||
self.retval = None
|
||||
self.instanceDir = instanceDir
|
||||
|
||||
self.stop = Value('i', 0)
|
||||
|
||||
def run(self):
|
||||
preexec_fn = None
|
||||
exec = settings.ACCEXEC
|
||||
if resource:
|
||||
# in linux, limit ram to 1GB soft, 2GB hard
|
||||
preexec_fn = lambda: resource.setrlimit(resource.RLIMIT_DATA, (2**30, 2**31))
|
||||
else:
|
||||
# if 'resource' is not available, assume windows which needs to full path to the exec
|
||||
exec = os.path.join(self.instanceDir, *settings.ACCEXEC)
|
||||
|
||||
# fire up the server, store stderr to the log/ dir
|
||||
_tm = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
|
||||
self.stdout = os.path.join(self.instanceDir, 'log', 'stdout-%s.log'%(_tm))
|
||||
self.stderr = os.path.join(self.instanceDir, 'log', 'stderr-%s.log'%(_tm))
|
||||
self.serverlog = os.path.join(self.instanceDir, 'log', 'server.log')
|
||||
self.p = subprocess.Popen(exec,
|
||||
# set working dir
|
||||
cwd=self.instanceDir,
|
||||
# limit ram to 1GB soft, 2GB hard
|
||||
preexec_fn=preexec_fn,
|
||||
# shell=True,
|
||||
universal_newlines=True,
|
||||
stdout=open(self.stdout,'w'),
|
||||
stderr=open(self.stderr,'w'))
|
||||
|
||||
# wait for the stop signal or for the server to die on its own
|
||||
self.retval = None
|
||||
while self.retval is None:
|
||||
if self.stop.value == 1: self.p.kill()
|
||||
time.sleep(1)
|
||||
self.retval = self.p.poll()
|
||||
|
||||
print("Retval:",self.retval)
|
119
ACC/instances/InstanceForm.py
Normal file
119
ACC/instances/InstanceForm.py
Normal file
@ -0,0 +1,119 @@
|
||||
from django import forms
|
||||
|
||||
from accservermanager.settings import CAR_GROUPS
|
||||
from cfgs.confEdit import createLabel
|
||||
from cfgs.confSelect import getCfgsField
|
||||
|
||||
from accservermanager import settings
|
||||
|
||||
|
||||
class BaseForm(forms.Form):
|
||||
def __init__(self, data):
|
||||
super().__init__(data)
|
||||
|
||||
for key in self.fields:
|
||||
if key == 'cfg': continue
|
||||
# generate better label
|
||||
self.fields[key].label = createLabel(key)
|
||||
|
||||
# add help text if available
|
||||
if key in settings.MESSAGES:
|
||||
self.fields[key].help_text = settings.MESSAGES[key]
|
||||
|
||||
# use default values from the 'data' object
|
||||
if key in data:
|
||||
self.fields[key].initial = data[key]
|
||||
|
||||
|
||||
class SettingsForm(BaseForm):
|
||||
"""
|
||||
Form around settings.json
|
||||
"""
|
||||
serverName = forms.CharField(max_length=100)
|
||||
|
||||
password = forms.CharField(max_length=100, required=False)
|
||||
spectatorPassword = forms.CharField(max_length=100, required=False)
|
||||
adminPassword = forms.CharField(max_length=100, required=False)
|
||||
|
||||
carGroup = forms.ChoiceField(widget=forms.Select, choices=CAR_GROUPS)
|
||||
trackMedalsRequirement = forms.IntegerField(max_value=3, min_value=0, required=False)
|
||||
safetyRatingRequirement = forms.IntegerField(max_value=99, min_value=-1, required=False)
|
||||
racecraftRatingRequirement = forms.IntegerField(max_value=99, min_value=-1, required=False)
|
||||
|
||||
maxCarSlots = forms.IntegerField(max_value=1000, min_value=0, required=False)
|
||||
|
||||
isRaceLocked = forms.BooleanField(required=False)
|
||||
allowAutoDQ = forms.BooleanField(required=False)
|
||||
shortFormationLap = forms.BooleanField(required=False)
|
||||
dumpEntryList = forms.BooleanField(required=False)
|
||||
dumpLeaderboards = forms.BooleanField(required=False)
|
||||
randomizeTrackWhenEmpty = forms.BooleanField(required=False)
|
||||
ignorePrematureDisconnects = forms.BooleanField(required=False)
|
||||
|
||||
|
||||
class ConfigurationForm(BaseForm):
|
||||
"""
|
||||
Form around configuration.json
|
||||
"""
|
||||
udpPort = forms.IntegerField(max_value=None, min_value=1000)
|
||||
tcpPort = forms.IntegerField(max_value=None, min_value=1000)
|
||||
maxConnections = forms.IntegerField(max_value=1000, min_value=0, required=False)
|
||||
registerToLobby = forms.BooleanField(required=False)
|
||||
lanDiscovery = forms.BooleanField(required=False)
|
||||
|
||||
|
||||
class AssistRulesForm(BaseForm):
|
||||
"""
|
||||
Form around assistRules.json
|
||||
"""
|
||||
stabilityControlLevelMax = forms.IntegerField(max_value=100, min_value=0, required=False)
|
||||
disableIdealLine = forms.BooleanField(required=False)
|
||||
disableAutosteer = forms.BooleanField(required=False)
|
||||
disableAutoPitLimiter = forms.BooleanField(required=False)
|
||||
disableAutoGear = forms.BooleanField(required=False)
|
||||
disableAutoClutch = forms.BooleanField(required=False)
|
||||
disableAutoEngineStart = forms.BooleanField(required=False)
|
||||
disableAutoWiper = forms.BooleanField(required=False)
|
||||
disableAutoLights = forms.BooleanField(required=False)
|
||||
|
||||
|
||||
class EventRulesForm(BaseForm):
|
||||
"""
|
||||
Form around eventRules.json
|
||||
"""
|
||||
qualifyStandingType = forms.IntegerField(min_value=0, required=False)
|
||||
pitWindowLengthSec = forms.IntegerField(required=False)
|
||||
driverStintTimeSec = forms.IntegerField(required=False)
|
||||
mandatoryPitstopCount = forms.IntegerField(min_value=0, required=False)
|
||||
maxTotalDrivingTime = forms.IntegerField(required=False)
|
||||
maxDriversCount = forms.IntegerField(min_value=0, required=False)
|
||||
isRefuellingAllowedInRace = forms.BooleanField(required=False)
|
||||
isRefuellingTimeFixed = forms.BooleanField(required=False)
|
||||
isMandatoryPitstopRefuellingRequired = forms.BooleanField(required=False)
|
||||
isMandatoryPitstopTyreChangeRequired = forms.BooleanField(required=False)
|
||||
isMandatoryPitstopSwapDriverRequired = forms.BooleanField(required=False)
|
||||
tyreSetCount = forms.IntegerField(min_value=0, required=False)
|
||||
|
||||
|
||||
class InstanceForm(forms.Form):
|
||||
"""
|
||||
Form used to fire up a new server instance
|
||||
"""
|
||||
instanceName = forms.CharField(
|
||||
max_length=100,
|
||||
widget=forms.TextInput(attrs={"onkeyup": "nospaces(this)"}))
|
||||
|
||||
def __init__(self, data):
|
||||
super().__init__(data)
|
||||
self.settings = SettingsForm(data)
|
||||
self.configuration = ConfigurationForm(data)
|
||||
self.assistRules = AssistRulesForm(data)
|
||||
self.eventRules = EventRulesForm(data)
|
||||
|
||||
# There is an issue with the 'required' error, so set this field
|
||||
# to not-required. This is ok, since it is always pre-filled.
|
||||
# This field has to be instantiated here in order to pick-up new configs.
|
||||
self.fields['event'] = getCfgsField(label='Event', required=False)
|
||||
|
||||
def is_valid(self):
|
||||
return self.settings.is_valid() and self.configuration.is_valid() and self.assistRules.is_valid() and self.eventRules.is_valid()
|
0
ACC/instances/__init__.py
Normal file
0
ACC/instances/__init__.py
Normal file
5
ACC/instances/apps.py
Normal file
5
ACC/instances/apps.py
Normal file
@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class InstancesConfig(AppConfig):
|
||||
name = 'instances'
|
0
ACC/instances/migrations/__init__.py
Normal file
0
ACC/instances/migrations/__init__.py
Normal file
50
ACC/instances/templates/instances/instance.html
Normal file
50
ACC/instances/templates/instances/instance.html
Normal file
@ -0,0 +1,50 @@
|
||||
{% extends "main.html" %}
|
||||
{% block content %}
|
||||
|
||||
<style>
|
||||
.container {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
{% load django_bootstrap_breadcrumbs %}
|
||||
{% block breadcrumbs %}
|
||||
{% clear_breadcrumbs %}
|
||||
{% for b, u in path %}
|
||||
{% breadcrumb_raw_safe b u %}
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
{% bootstrap_css %}
|
||||
{% bootstrap_javascript %}
|
||||
|
||||
<div class="container">
|
||||
<div class="card" style="padding: 10px 16px 20px 16px;">
|
||||
{% render_breadcrumbs %}
|
||||
|
||||
{% for r in resources %}
|
||||
<h6 style="font-weight:bold">{{r.label}} | <a href="{{request.path}}{{r.path}}">{{r.text}}</a> </h6>
|
||||
<textarea id="{{r.path}}" style="height: 200px;" disabled></textarea>
|
||||
<script>
|
||||
(function {{r.path}}() {
|
||||
$.post(
|
||||
'{{request.path}}{{r.path}}',
|
||||
{% if r.update %} { lines: 10 } {% else %} { } {% endif %}
|
||||
).done(function(data) {
|
||||
if (typeof data !== "string") data = JSON.stringify(data, null, 4);
|
||||
$('textarea#{{r.path}}').val(data);
|
||||
{% if r.update %} setTimeout({{r.path}}, 2000); {% endif %}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
<div style="padding: 10px 16px 20px 16px;">
|
||||
<a href="results"><input type="button" value="Results" class="btn btn-success"/></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{% endblock %}
|
166
ACC/instances/templates/instances/instances.html
Normal file
166
ACC/instances/templates/instances/instances.html
Normal file
@ -0,0 +1,166 @@
|
||||
{% extends "main.html" %}
|
||||
{% block content %}
|
||||
|
||||
<style>
|
||||
.container {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
{% bootstrap_css %}
|
||||
{% bootstrap_javascript %}
|
||||
|
||||
<div class="container">
|
||||
{% if messages %}
|
||||
{% for message in messages %}
|
||||
<div {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}
|
||||
class="card red"
|
||||
{% else %} class="card green"
|
||||
{% endif %}>
|
||||
<div id="message" {% if message.tags %} class="{{ message.tags }}" {% endif %} style="padding: 10px 5px;">
|
||||
<strong>{{ message|escape }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<div class="card">
|
||||
<h5 style="font-weight:bold">Instance config</h5>
|
||||
<form name="instance_form" action="start" method="POST"
|
||||
onsubmit="return (document.forms['instance_form']['cfg'].value.length>0)">{% csrf_token %}
|
||||
{% bootstrap_form form %}
|
||||
<div class="accordion" id="instance-config">
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header" id="settings-header">
|
||||
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#settings" aria-expanded="true" aria-controls="settings">
|
||||
Settings
|
||||
</button>
|
||||
</h2>
|
||||
<div id="settings" class="accordion-collapse collapse show" aria-labelledby="settings-header" data-bs-parent="#instance-config">
|
||||
<div class="accordion-body">
|
||||
{% bootstrap_form form.settings %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header" id="config-header">
|
||||
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#config" aria-expanded="false" aria-controls="config">
|
||||
Configuration
|
||||
</button>
|
||||
</h2>
|
||||
<div id="config" class="accordion-collapse collapse" aria-labelledby="config-header" data-bs-parent="#instance-config">
|
||||
<div class="accordion-body">
|
||||
{% bootstrap_form form.configuration %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header" id="assist-rules-header">
|
||||
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#assist-rules" aria-expanded="false" aria-controls="assist-rules">
|
||||
AssistRules
|
||||
</button>
|
||||
</h2>
|
||||
<div id="assist-rules" class="accordion-collapse collapse" aria-labelledby="assist-rules-header" data-bs-parent="#instance-config">
|
||||
<div class="accordion-body">
|
||||
{% bootstrap_form form.assistRules %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="accordion-item">
|
||||
<h2 class="accordion-header" id="event-rules-header">
|
||||
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#event-rules" aria-expanded="false" aria-controls="event-rules">
|
||||
EventRules
|
||||
</button>
|
||||
</h2>
|
||||
<div id="event-rules" class="accordion-collapse collapse" aria-labelledby="event-rules-header" data-bs-parent="#instance-config">
|
||||
<div class="accordion-body">
|
||||
{% bootstrap_form form.eventRules %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-success" type="submit">Start</button>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h5 style="font-weight:bold">Server instances</h5><br>
|
||||
<table>
|
||||
<tr><td>Instance Name</td><td>Server Name</td><td>Config</td><td>UDP</td><td>TCP</td><td>PID</td><td></td></tr>
|
||||
{% for name,executor in executors.items %}
|
||||
<tr id="row{{forloop.counter0}}">
|
||||
<td><a href="/instances/{{name}}" class="btn btn-primary">{{name}}</a></td>
|
||||
<td style="">{{executor.serverName}}</td>
|
||||
<td style="">{{executor.config}}</td>
|
||||
<td style="">{{executor.udpPort}}</td>
|
||||
<td style="">{{executor.tcpPort}}</td>
|
||||
|
||||
<td id="pid{{forloop.counter0}}" style="">
|
||||
{% if executor.is_alive %}
|
||||
{{executor.p.pid}}
|
||||
{% else %}
|
||||
exited with {{executor.retval}}
|
||||
{% endif %}
|
||||
</td>
|
||||
{% if executor.is_alive %}
|
||||
<td>
|
||||
<button id="stop{{forloop.counter0}}" class="btn btn-danger" onclick="stop(this, '{{name}}')">Stop</button>
|
||||
</td><td></td>
|
||||
{% else %}
|
||||
<td>
|
||||
<button id="restart{{forloop.counter0}}" class="btn btn-success" onclick="start(this, '{{name}}')">Start</button>
|
||||
</td><td>
|
||||
<button id="delete{{forloop.counter0}}" class="btn btn-danger" onclick="del(this, '{{name}}')">Delete</button>
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
$('#message').on('click', function(){
|
||||
$(this).parent().remove();
|
||||
});
|
||||
|
||||
function start(el, name) {
|
||||
el.innerHTML = 'Starting'
|
||||
el.disabled = true;
|
||||
var delel = $('#delete'+el.id.replace('restart',''))[0];
|
||||
delel.disabled = true;
|
||||
$.post("/instances/"+name+"/start", function(json) {
|
||||
$('td#pid'+el.id.replace('restart','')).html(json['pid']);
|
||||
delel.id = el.id.replace('restart','stop');
|
||||
delel.innerHTML = 'Stop';
|
||||
delel.onclick = function() {stop(el, name)};
|
||||
delel.disabled = false;
|
||||
el.remove();
|
||||
});
|
||||
}
|
||||
function stop(el, name) {
|
||||
el.innerHTML = 'Stopping'
|
||||
el.disabled = true;
|
||||
$.post("/instances/"+name+"/stop", function(json) {
|
||||
$('td#pid'+el.id.replace('stop','')).html('exited with '+json['retval']);
|
||||
el.id = el.id.replace('stop','delete')
|
||||
el.innerHTML = 'Delete';
|
||||
el.onclick = function() {del(el, name)};
|
||||
el.disabled = false;
|
||||
});
|
||||
}
|
||||
function del(el, name) {
|
||||
el.disabled = true;
|
||||
$.post("/instances/"+name+"/delete", function(json) {
|
||||
$('tr#row'+el.id.replace('delete','')).remove();
|
||||
});
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
20
ACC/instances/urls.py
Normal file
20
ACC/instances/urls.py
Normal file
@ -0,0 +1,20 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.index, name='instances'),
|
||||
path('start', views.create, name='start'),
|
||||
path('<name>/', views.instance, name='instance'),
|
||||
path('<name>/start', views.start, name='start'),
|
||||
path('<name>/stop', views.stop, name='stop'),
|
||||
path('<name>/delete', views.delete, name='delete'),
|
||||
path('<name>/stderr', views.stderr, name='stderr'),
|
||||
path('<name>/stdout', views.stdout, name='stdout'),
|
||||
path('<name>/serverlog', views.serverlog, name='serverlog'),
|
||||
path('<name>/configuration', views.download_configuration_file, name='configuration'),
|
||||
path('<name>/assistRules', views.download_assistRules_file, name='assistRules'),
|
||||
path('<name>/eventRules', views.download_eventRules_file, name='eventRules'),
|
||||
path('<name>/event', views.download_event_file, name='event'),
|
||||
path('<name>/settings', views.download_settings_file, name='settings'),
|
||||
]
|
330
ACC/instances/views.py
Normal file
330
ACC/instances/views.py
Normal file
@ -0,0 +1,330 @@
|
||||
import os, shutil, json, time, string, glob, platform
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.http import HttpResponse, HttpResponseRedirect, Http404
|
||||
from django.template import loader
|
||||
from django.contrib import messages
|
||||
|
||||
from random_word import RandomWords
|
||||
|
||||
from instances.Executor import Executor
|
||||
from instances.InstanceForm import InstanceForm
|
||||
|
||||
try: r = RandomWords()
|
||||
except: r = None
|
||||
|
||||
from accservermanager import settings
|
||||
|
||||
|
||||
# the server process execution threads
|
||||
executors = {}
|
||||
|
||||
|
||||
# resources a running instance uses and can be viewed/downloaded
|
||||
# format is (path,label,text), see instance.html
|
||||
resources = [
|
||||
('stdout', "Latest stdout", "Download full"),
|
||||
('stderr', "Latest stderr", "Download full"),
|
||||
('serverlog', "Server log", "Download full"),
|
||||
('configuration', "configuration.json", "Download"),
|
||||
('event', "event.json", "Download"),
|
||||
('settings', "settings.json", "Download"),
|
||||
('assistRules', "assistRules.json", "Download"),
|
||||
('eventRules', "eventRules.json", "Download"),
|
||||
]
|
||||
|
||||
@login_required
|
||||
def instance(request, name):
|
||||
if name not in executors: return HttpResponseRedirect('/instances')
|
||||
template = loader.get_template('instances/instance.html')
|
||||
|
||||
path = request.path
|
||||
if path[0] == '/': path = path[1:]
|
||||
if path[-1] == '/':path = path[:-1]
|
||||
path = path.split('/')
|
||||
|
||||
return HttpResponse(template.render(
|
||||
{'path' : [(j, '/'+'/'.join(path[:i+1])) for i,j in enumerate(path)],
|
||||
'resources': [dict(path=r[0], label=r[1], text=r[2], update=r[0] in ['stdout','stderr','serverlog']) for r in resources]},
|
||||
request))
|
||||
|
||||
|
||||
@login_required
|
||||
def stdout(request, name):
|
||||
if 'lines' not in request.POST:
|
||||
return download(executors[name].stdout)
|
||||
return log(executors[name].stdout, int(request.POST['lines']))
|
||||
|
||||
|
||||
@login_required
|
||||
def stderr(request, name):
|
||||
if 'lines' not in request.POST:
|
||||
return download(executors[name].stderr)
|
||||
return log(executors[name].stderr, int(request.POST['lines']))
|
||||
|
||||
|
||||
@login_required
|
||||
def serverlog(request, name):
|
||||
if 'lines' not in request.POST:
|
||||
return download(executors[name].serverlog)
|
||||
return log(executors[name].serverlog, int(request.POST['lines']))
|
||||
|
||||
|
||||
@login_required
|
||||
def download_configuration_file(request, name):
|
||||
f = os.path.join(settings.INSTANCES, name, 'cfg', 'configuration.json')
|
||||
return download(f, content_type='text/json')
|
||||
|
||||
|
||||
@login_required
|
||||
def download_event_file(request, name):
|
||||
f = os.path.join(settings.INSTANCES, name, 'cfg', 'event.json')
|
||||
return download(f, content_type='text/json')
|
||||
|
||||
|
||||
@login_required
|
||||
def download_settings_file(request, name):
|
||||
f = os.path.join(settings.INSTANCES, name, 'cfg', 'settings.json')
|
||||
return download(f, content_type='text/json')
|
||||
|
||||
|
||||
@login_required
|
||||
def download_assistRules_file(request, name):
|
||||
f = os.path.join(settings.INSTANCES, name, 'cfg', 'assistRules.json')
|
||||
return download(f, content_type='text/json')
|
||||
|
||||
|
||||
@login_required
|
||||
def download_eventRules_file(request, name):
|
||||
f = os.path.join(settings.INSTANCES, name, 'cfg', 'eventRules.json')
|
||||
return download(f, content_type='text/json')
|
||||
|
||||
|
||||
|
||||
# https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail
|
||||
def tail(f, n=10):
|
||||
assert n >= 0
|
||||
pos, lines = n+1, []
|
||||
while len(lines) <= n:
|
||||
try:
|
||||
f.seek(-pos, 2)
|
||||
except IOError:
|
||||
f.seek(0)
|
||||
break
|
||||
finally:
|
||||
lines = list(f)
|
||||
pos *= 2
|
||||
return lines[-n:]
|
||||
|
||||
|
||||
def log(_f, n):
|
||||
if _f is not None and os.path.isfile(_f):
|
||||
with open(_f, 'r', encoding='latin-1') as fh:
|
||||
return HttpResponse(tail(fh, n))
|
||||
raise Http404
|
||||
|
||||
|
||||
def download(_f, content_type="text/plain"):
|
||||
if _f is not None and os.path.isfile(_f):
|
||||
with open(_f, 'r', encoding='utf-16' if content_type=='text/json' else None) as fh:
|
||||
response = HttpResponse(fh.read(), content_type=content_type)
|
||||
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(_f)
|
||||
return response
|
||||
raise Http404
|
||||
|
||||
|
||||
@login_required
|
||||
def delete(request, name):
|
||||
if name in executors:
|
||||
if not executors[name].is_alive():
|
||||
shutil.rmtree(executors[name].instanceDir)
|
||||
executors.pop(name)
|
||||
|
||||
return HttpResponse(json.dumps({'success': True}),
|
||||
content_type='application/json')
|
||||
|
||||
|
||||
@login_required
|
||||
def stop(request, name):
|
||||
""" handle stop request from client """
|
||||
global executors
|
||||
if name in executors and executors[name].stop.value != 1:
|
||||
executors[name].stop.value = 1
|
||||
|
||||
i = 0
|
||||
# wait max 2 seconds for the instance to stop
|
||||
while executors[name].is_alive() and i<10:
|
||||
time.sleep(.2)
|
||||
i+=1
|
||||
|
||||
# return HttpResponseRedirect('/instances')
|
||||
return HttpResponse(json.dumps({'success': True, 'retval':executors[name].retval}),
|
||||
content_type='application/json')
|
||||
|
||||
|
||||
@login_required
|
||||
def start(request, name):
|
||||
""" handle (re)start request from client """
|
||||
global executors
|
||||
|
||||
# create the Executor for the instance
|
||||
# - if it does not exist yet
|
||||
# - if the executor thread was alive and exited
|
||||
if name not in executors or \
|
||||
(not executors[name].is_alive() and executors[name].retval is not None):
|
||||
inst_dir = os.path.join(settings.INSTANCES, name)
|
||||
executors[name] = Executor(inst_dir)
|
||||
|
||||
# don't try to start running instances
|
||||
if not executors[name].is_alive():
|
||||
executors[name].start()
|
||||
i = 0
|
||||
# wait max 2 seconds for the instance to start
|
||||
while (not executors[name].is_alive() or executors[name].p is None) and i<10:
|
||||
time.sleep(.2)
|
||||
i+=1
|
||||
|
||||
return HttpResponse(json.dumps({'success': True, 'pid':executors[name].p.pid}),
|
||||
content_type='application/json')
|
||||
|
||||
|
||||
def render_from(request, form):
|
||||
template = loader.get_template('instances/instances.html')
|
||||
context = {
|
||||
'form': form,
|
||||
'executors': executors,
|
||||
}
|
||||
return HttpResponse(template.render(context, request))
|
||||
|
||||
|
||||
def write_config(name, inst_dir, form):
|
||||
### use the values of the default *.json as basis
|
||||
cfg = {}
|
||||
if os.path.isfile(os.path.join(settings.ACCSERVER, 'cfg', name)):
|
||||
cfg = json.load(open(os.path.join(settings.ACCSERVER, 'cfg', name), 'r', encoding='utf-16'))
|
||||
|
||||
for key in form.cleaned_data.keys():
|
||||
if key == 'csrfmiddlewaretoken': continue
|
||||
value = form.cleaned_data[key]
|
||||
# eventRules needs to be true/false not 0/1
|
||||
if name != 'eventRules.json':
|
||||
if isinstance(value, bool): value = int(value)
|
||||
|
||||
if value is not None: cfg[key] = value
|
||||
|
||||
# write the file into the instances' directory
|
||||
json.dump(cfg, open(os.path.join(inst_dir, 'cfg', name), 'w', encoding='utf-16'))
|
||||
|
||||
|
||||
@login_required
|
||||
def create(request):
|
||||
""" handle create/start request from client """
|
||||
|
||||
# this function should only be entered via POST request
|
||||
if request.method != 'POST':
|
||||
return HttpResponseRedirect('/instances')
|
||||
|
||||
form = InstanceForm(request.POST)
|
||||
name = request.POST['instanceName']
|
||||
|
||||
# form is invalid...
|
||||
if not form.is_valid():
|
||||
messages.error(request, "Form is not valid")
|
||||
return render_from(request, form)
|
||||
|
||||
# instance with similar name already exists
|
||||
if name in executors:
|
||||
messages.error(request, "Instance with similar name already exists")
|
||||
return render_from(request, form)
|
||||
|
||||
if not settings.ALLOW_SAME_PORTS and form.configuration['udpPort'].value() == form.configuration['tcpPort'].value():
|
||||
messages.error(request, 'UDP and TCP port have to be different')
|
||||
return render_from(request, form)
|
||||
|
||||
# check if a running instance already uses the same ports
|
||||
if len(list(filter(lambda x: x.is_alive() and
|
||||
(form.configuration['udpPort'].value() in [x.udpPort, x.tcpPort] or
|
||||
form.configuration['tcpPort'].value() in [x.udpPort, x.tcpPort]),
|
||||
executors.values()))) > 0:
|
||||
messages.error(request, "The ports are already in use")
|
||||
return render_from(request, form)
|
||||
|
||||
# create instance environment
|
||||
inst_dir = os.path.join(settings.INSTANCES, name)
|
||||
if os.path.isdir(inst_dir):
|
||||
messages.error(request, "The instance directory exists already")
|
||||
return render_from(request, form)
|
||||
|
||||
# create the directory for the instance
|
||||
os.makedirs(os.path.join(inst_dir, 'cfg'))
|
||||
os.makedirs(os.path.join(inst_dir, 'log'))
|
||||
# link the server exe into the instance environment
|
||||
os.symlink(os.path.join(settings.ACCSERVER, settings.SERVER_FILES[0]),
|
||||
os.path.join(inst_dir, settings.SERVER_FILES[0]))
|
||||
# the target configuration json
|
||||
cfg = os.path.join(settings.CONFIGS, form['event'].value() + '.json')
|
||||
# link the requested config into the instance environment
|
||||
os.symlink(cfg, os.path.join(inst_dir, 'cfg', 'event.json'))
|
||||
# link (possible) cars directory into the instance environment
|
||||
if os.path.isdir(os.path.join(settings.ACCSERVER, 'cfg', 'cars')):
|
||||
os.symlink(os.path.join(settings.ACCSERVER, 'cfg', 'cars'),
|
||||
os.path.join(inst_dir, 'cfg', 'cars'))
|
||||
|
||||
# write the json files
|
||||
write_config('configuration.json', inst_dir, form.configuration)
|
||||
write_config('settings.json', inst_dir, form.settings)
|
||||
write_config('assistRules.json', inst_dir, form.assistRules)
|
||||
write_config('eventRules.json', inst_dir, form.eventRules)
|
||||
|
||||
# start the instance
|
||||
start(request, name)
|
||||
|
||||
messages.info(request, "Successfully started the instance")
|
||||
return HttpResponseRedirect('/instances')
|
||||
|
||||
|
||||
def random_word():
|
||||
s = 'somename'
|
||||
try:
|
||||
while s is None or any(c for c in s if c not in string.ascii_letters):
|
||||
s = r.get_random_word(hasDictionaryDef="true",
|
||||
minLength=5,
|
||||
maxLength=10)
|
||||
except: pass
|
||||
return s
|
||||
|
||||
|
||||
def index(request):
|
||||
# read defaults from files
|
||||
cfg = json.load(open(os.path.join(
|
||||
settings.ACCSERVER, 'cfg', 'configuration.json'), 'r', encoding='utf-16'))
|
||||
cfg.update(json.load(open(os.path.join(
|
||||
settings.ACCSERVER, 'cfg', 'settings.json'), 'r', encoding='utf-16')))
|
||||
cfg.update(json.load(open(os.path.join(
|
||||
settings.ACCSERVER, 'cfg', 'assistRules.json'), 'r', encoding='utf-16')))
|
||||
if os.path.isfile(os.path.join(settings.ACCSERVER, 'cfg', 'eventRules.json')):
|
||||
cfg.update(json.load(open(os.path.join(
|
||||
settings.ACCSERVER, 'cfg', 'eventRules.json'), 'r', encoding='utf-16')))
|
||||
else:
|
||||
cfg.update(settings.EVENT_RULES_TEMPLATE)
|
||||
|
||||
# some static defaults
|
||||
cfg['instanceName'] = random_word()
|
||||
cfg['serverName'] = 'ACC server'
|
||||
cfg['dumpLeaderboards'] = 1
|
||||
cfg['registerToLobby'] = 1
|
||||
cfg['dumpLeaderboards'] = 1
|
||||
# this setting seems to work only in windows
|
||||
cfg['ignorePrematureDisconnects'] = platform.system() == "Windows"
|
||||
|
||||
# overwrite nonsense trackMedalsRequirement default value
|
||||
if cfg['trackMedalsRequirement'] == -1:
|
||||
cfg['trackMedalsRequirement'] = 0
|
||||
|
||||
for inst_dir in glob.glob(os.path.join(settings.INSTANCES, '*')):
|
||||
inst_name = os.path.split(inst_dir)[-1]
|
||||
if inst_name not in executors:
|
||||
executors[inst_name] = Executor(inst_dir)
|
||||
|
||||
return render_from(request, InstanceForm(cfg))
|
||||
|
15
ACC/manage.py
Executable file
15
ACC/manage.py
Executable file
@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == '__main__':
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'accservermanager.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
15
ACC/requirements.txt
Normal file
15
ACC/requirements.txt
Normal file
@ -0,0 +1,15 @@
|
||||
certifi==2023.7.22
|
||||
chardet==5.0.0
|
||||
Django==4.1.10
|
||||
django4-bootstrap-breadcrumbs==0.10.0
|
||||
django-bootstrap5==22.2
|
||||
django-tables2==2.5.1
|
||||
idna==3.3
|
||||
nose==1.3.7
|
||||
pytz==2022.1
|
||||
PyYAML==6.0
|
||||
Random-Word==1.0.7
|
||||
requests==2.28.1
|
||||
six==1.16.0
|
||||
sqlparse==0.4.4
|
||||
urllib3==1.26.11
|
0
ACC/results/__init__.py
Normal file
0
ACC/results/__init__.py
Normal file
5
ACC/results/apps.py
Normal file
5
ACC/results/apps.py
Normal file
@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class ResultsConfig(AppConfig):
|
||||
name = 'results'
|
30
ACC/results/templates/results/results.html
Normal file
30
ACC/results/templates/results/results.html
Normal file
@ -0,0 +1,30 @@
|
||||
{% extends "main.html" %}
|
||||
{% block content %}
|
||||
|
||||
<style>
|
||||
.container {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
{% load django_bootstrap_breadcrumbs %}
|
||||
{% block breadcrumbs %}
|
||||
{% clear_breadcrumbs %}
|
||||
{% for b, u in path %}
|
||||
{% breadcrumb_raw_safe b u %}
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
{% bootstrap_css %}
|
||||
{% bootstrap_javascript %}
|
||||
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
{% render_breadcrumbs %}
|
||||
{% load django_tables2 %}
|
||||
{% render_table table %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
@ -0,0 +1 @@
|
||||
<a class="btn btn-success" href="{{record.name}}.json">Download</a>
|
@ -0,0 +1 @@
|
||||
<a class="btn btn-dark" target="_blank" href="https://simresults.net/remote?result={{ request.build_absolute_uri }}{{record.name}}.json">Simresults</a>
|
@ -0,0 +1 @@
|
||||
<a class="btn btn-primary" href="{{record.name}}">View</a>
|
9
ACC/results/urls.py
Normal file
9
ACC/results/urls.py
Normal file
@ -0,0 +1,9 @@
|
||||
from django.urls import re_path, path
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.resultSelect, name='instances'),
|
||||
re_path(r'^([^/]+)/?(.*).json', views.download, name='download'),
|
||||
re_path(r'^([^/]+)/?(.*)', views.results, name='results'),
|
||||
]
|
137
ACC/results/views.py
Normal file
137
ACC/results/views.py
Normal file
@ -0,0 +1,137 @@
|
||||
import glob
|
||||
import itertools
|
||||
import ntpath
|
||||
|
||||
from django.http import HttpResponse, Http404
|
||||
from django.shortcuts import render
|
||||
|
||||
import os, json
|
||||
|
||||
from django.utils.html import format_html
|
||||
from django_tables2 import tables, Column, TemplateColumn, RequestConfig
|
||||
|
||||
from accservermanager.settings import CAR_MODEL_TYPES, DATA_DIR
|
||||
|
||||
|
||||
class LeaderBoard(tables.Table):
|
||||
position = Column(empty_values=())
|
||||
raceNumber = Column(accessor='car.raceNumber')
|
||||
carModel = Column(accessor='car.carModel')
|
||||
teamName = Column(accessor='car.teamName')
|
||||
drivers = Column(accessor='car.drivers')
|
||||
bestLap = Column(accessor='timing')
|
||||
laps = Column(accessor='timing.lapCount')
|
||||
totaltime = Column(accessor='timing.totalTime')
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(LeaderBoard, self).__init__(*args, **kwargs)
|
||||
self.counter = itertools.count(start=1)
|
||||
|
||||
def render_position(self):
|
||||
return '%d' % next(self.counter)
|
||||
|
||||
def render_carModel(self, value):
|
||||
for model in CAR_MODEL_TYPES:
|
||||
if model[0]==value: return model[1]
|
||||
return 'Unknown model %i'%value
|
||||
|
||||
def render_drivers(self, value):
|
||||
short = ' / '.join([d['shortName'] for d in value])
|
||||
long = ' / '.join(['%s %s'%(d['firstName'],d['lastName']) for d in value])
|
||||
return format_html('<p title="{}">{}</p>', long, short)
|
||||
|
||||
def render_time(self, value):
|
||||
if(value == 2147483647):
|
||||
return '---'
|
||||
s = value//1000
|
||||
m = s//60
|
||||
s %=60
|
||||
if m==0: return '%02i.%03i'%(s, value%1000)
|
||||
return '%i:%02i.%03i'%(m, s, value%1000)
|
||||
|
||||
def render_bestLap(self, value):
|
||||
return format_html('<p title="{}">{}</p>',
|
||||
' | '.join(list(map(self.render_time, value['bestSplits']))),
|
||||
self.render_time(value['bestLap']))
|
||||
|
||||
def render_totaltime(self, value):
|
||||
return self.render_time(value)
|
||||
|
||||
|
||||
class Results(tables.Table):
|
||||
name = Column()
|
||||
type = Column()
|
||||
track = Column()
|
||||
entries = Column()
|
||||
wetSession = Column()
|
||||
view = TemplateColumn(template_name='results/table/results_view_column.html')
|
||||
download = TemplateColumn(template_name='results/table/results_download_column.html')
|
||||
simresults = TemplateColumn(template_name='results/table/results_simresults_column.html')
|
||||
# delete = TemplateColumn(template_name='results/table/results_delete_column.html')
|
||||
|
||||
|
||||
def parse_url(args, kwargs):
|
||||
""" Read the select results file and display the selected portion of the json object """
|
||||
instance = kwargs['instance']
|
||||
result = args[0]
|
||||
results_path = os.path.join(DATA_DIR, 'instances', instance, 'results')
|
||||
return os.path.join(results_path, result+'.json')
|
||||
|
||||
|
||||
def results(request, *args, **kwargs):
|
||||
""" Read the select results file and display the selected portion of the json object """
|
||||
results = json.load(open(parse_url(args, kwargs), 'rb'))
|
||||
path = request.path
|
||||
if path[0] == '/': path = path[1:]
|
||||
if path[-1] == '/': path = path[:-1]
|
||||
path = path.split('/')
|
||||
|
||||
context = {
|
||||
'path': [(j, '/'+'/'.join(path[:i+1])) for i,j in enumerate(path)],
|
||||
'table': LeaderBoard(results['sessionResult']['leaderBoardLines'])
|
||||
}
|
||||
return render(request, 'results/results.html', context)
|
||||
|
||||
|
||||
def download(request, *args, **kwargs):
|
||||
_f = parse_url(args, kwargs)
|
||||
print(_f, os.path.basename(_f))
|
||||
if _f is not None and os.path.isfile(_f):
|
||||
with open(_f, 'r') as fh:
|
||||
response = HttpResponse(fh.read(), content_type="text/plain")
|
||||
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(_f)
|
||||
return response
|
||||
raise Http404
|
||||
|
||||
|
||||
def resultSelect(request, instance):
|
||||
""" Show available results """
|
||||
results_path = os.path.join(DATA_DIR, 'instances', instance, 'results')
|
||||
files = sorted(glob.glob('%s/*.json'%(results_path)), reverse=True)
|
||||
files = filter(lambda x: not x.endswith('entrylist.json') , files)
|
||||
|
||||
results = []
|
||||
for f in files:
|
||||
r = json.load(open(f, 'rb'))
|
||||
|
||||
results.append(dict(
|
||||
name=os.path.splitext(ntpath.basename(f))[0],
|
||||
type=r['sessionType'], # TODO: decode session type, seems to be borked atm
|
||||
entries=len(r['sessionResult']['leaderBoardLines']),
|
||||
wetSession=r['sessionResult']['isWetSession'],
|
||||
track=r['trackName'],
|
||||
))
|
||||
|
||||
path = request.path
|
||||
if path[0] == '/': path = path[1:]
|
||||
if path[-1] == '/':path = path[:-1]
|
||||
path = path.split('/')
|
||||
|
||||
table = Results(results)
|
||||
RequestConfig(request).configure(table)
|
||||
|
||||
context = {
|
||||
'path' : [(j, '/'+'/'.join(path[:i+1])) for i,j in enumerate(path)],
|
||||
'table' : table,
|
||||
}
|
||||
return render(request, 'results/results.html', context)
|
84
ACC/templates/base.html
Normal file
84
ACC/templates/base.html
Normal file
@ -0,0 +1,84 @@
|
||||
<html>
|
||||
|
||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
|
||||
rel="stylesheet">
|
||||
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
function nospaces(t){
|
||||
if(t.value.match(/\s/g)){
|
||||
alert('Spaces are not allowed');
|
||||
t.value=t.value.replace(/\s/g,'');
|
||||
}}
|
||||
|
||||
$.ajaxSetup({
|
||||
headers: { "X-CSRFToken": '{{csrf_token}}' }
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
<style>
|
||||
html, body {
|
||||
width:100%;
|
||||
height:100%;
|
||||
margin:0;
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
|
||||
#wrapper {
|
||||
width:100%;
|
||||
height:100%;
|
||||
position:fixed;
|
||||
overflow:auto;
|
||||
}
|
||||
|
||||
header nav {
|
||||
width:100%;
|
||||
height:60px;
|
||||
background: #c21807;
|
||||
}
|
||||
|
||||
#content {
|
||||
position:absolute;
|
||||
top:60px;
|
||||
bottom:30px;
|
||||
left:0;
|
||||
width:100%;
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2px 16px;
|
||||
}
|
||||
|
||||
.breadcrumb {
|
||||
color: black;
|
||||
list-style-type: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.breadcrumb > li {
|
||||
float:left;
|
||||
}
|
||||
.breadcrumb:last-child {
|
||||
color: black;
|
||||
}
|
||||
.divider {
|
||||
color: black;
|
||||
padding-right: .2em;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
<body>
|
||||
|
||||
<div id="wrapper">
|
||||
{% block base %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
|
||||
<footer style="float: right; text-align: right; position: absolute; bottom: 0px; right: 10px;">
|
||||
© 2023 Matthias Gorzellik | v0.4 | <a href="https://github.com/gotzl/accservermanager">GitHub</a>
|
||||
</footer>
|
||||
</body>
|
||||
<html>
|
32
ACC/templates/main.html
Normal file
32
ACC/templates/main.html
Normal file
@ -0,0 +1,32 @@
|
||||
{% extends "base.html" %}
|
||||
{% block base %}
|
||||
|
||||
{% if user.is_authenticated %}
|
||||
<header>
|
||||
<nav class="navbar navbar-expand-lg navbar-dark">
|
||||
<div class="container-fluid">
|
||||
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
|
||||
<div class="navbar-nav">
|
||||
<a class="nav-link" style="font-size:20px; font-weight: bold;" href="/cfgs">Configs</a>
|
||||
<a class="nav-link" style="font-size:20px; font-weight: bold;" href="/instances">Instances</a>
|
||||
<a class="nav-link" style="font-size:20px; font-weight: bold;" href="{% url 'logout' %}">Logout</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div id="content">
|
||||
{% block content %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
|
||||
{% else %}
|
||||
<p>You are not logged in</p>
|
||||
<a href="{% url 'login' %}">login</a>
|
||||
{% endif %}
|
||||
|
||||
{% endblock %}
|
16
ACC/templates/main_app.html
Normal file
16
ACC/templates/main_app.html
Normal file
@ -0,0 +1,16 @@
|
||||
{% extends "base.html" %}
|
||||
{% block base %}
|
||||
|
||||
<header>
|
||||
<nav style="background: #c21807;">
|
||||
<a href="/cfgs">Configs</a>
|
||||
<a href="/instances">Instances</a>
|
||||
<a href="/results">Results</a>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div id="content">
|
||||
{% block content %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
{% endblock %}
|
31
ACC/templates/registration/login.html
Normal file
31
ACC/templates/registration/login.html
Normal file
@ -0,0 +1,31 @@
|
||||
{% extends "base.html" %}
|
||||
{% block base %}
|
||||
|
||||
<style>
|
||||
/* Add some padding inside the card container */
|
||||
.container {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
{% bootstrap_css %}
|
||||
{% bootstrap_javascript %}
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %}
|
||||
{% if 'username' in form.fields %}
|
||||
{% bootstrap_form form %}
|
||||
{% else %}
|
||||
{% bootstrap_form form %}
|
||||
{% endif %}
|
||||
<div class="action right-align">
|
||||
<button type="submit" class="btn btn-primary">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
|
31
ACC/tools/extractMessages.py
Normal file
31
ACC/tools/extractMessages.py
Normal file
@ -0,0 +1,31 @@
|
||||
#!/usr/bin/python
|
||||
"""
|
||||
Small script to extract helptexts from the ACC ServerAdminHandbook.
|
||||
Usage: First, use pdftohtml with the pdf, then
|
||||
python extractMessages.py ../path/to/ServerAdminHandbooks.html
|
||||
"""
|
||||
|
||||
import re, sys, json
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print('Usage: python extractMessages.py ../path/to/ServerAdminHandbooks.html')
|
||||
exit(1)
|
||||
|
||||
outer = """Property.*\nRemarks.*\n((?:.|\n)*?)<br\/>\n(?:<b>)? (?:<\/b>)?<br\/>"""
|
||||
pattern = """(.*)<b>(?:.*)<br\/>\n((?:.|\n)+?(?=.*<b>|\Z))"""
|
||||
|
||||
messages = {}
|
||||
for b in re.findall(outer, open(sys.argv[1]).read()):
|
||||
for (key, value) in re.findall(pattern, b):
|
||||
for c in [('<br/>',''), ('\n',''), (' ',' '), ('“','"'), ('”','"')]:
|
||||
key = key.replace(*c).strip()
|
||||
value = value.replace(*c).strip()
|
||||
value = re.sub('<hr/><a.*</a>', '', value)
|
||||
value = re.sub('((?:S|s)ee\s+".*")', r'\1 (ServerAdminHandbook)', value)
|
||||
value = re.sub('(?:S|s)ee.*next table', 'see table in ServerAdminHandbook', value)
|
||||
messages[key] = value
|
||||
|
||||
print(messages.keys())
|
||||
json.dump(messages, open('messages.json', 'w'), sort_keys=True, indent=4)
|
Loading…
x
Reference in New Issue
Block a user