Skip to content
Snippets Groups Projects

Compare revisions

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

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • to/majak
  • b1242/majak
2 results
Select Git revision
Show changes
Commits on Source (2038)
Showing
with 1948 additions and 19 deletions
.git .git
.venv .venv
.envrc .envrc
static_files/
media_files/
...@@ -142,3 +142,14 @@ cython_debug/ ...@@ -142,3 +142,14 @@ cython_debug/
# direnv # direnv
.envrc .envrc
media_files/
static_files/
.python-version
.idea/
update_election_statics.sh
download_static.sh
matice.csv
.vscode/
stages:
- build
image: docker:20.10.8
variables:
DOCKER_TLS_CERTDIR: "/certs"
IMAGE_TAG_APP: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
IMAGE_TAG_NGINX: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-nginx
services:
- docker:20.10.8-dind
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
build_app:
stage: build
script:
- docker pull $CI_REGISTRY_IMAGE:test || true
- docker build --cache-from $CI_REGISTRY_IMAGE:test -t $IMAGE_TAG_APP .
- docker push $IMAGE_TAG_APP
build_nginx:
stage: build
when: manual
script:
- docker pull $CI_REGISTRY_IMAGE:test-nginx || true
- docker build --cache-from $CI_REGISTRY_IMAGE:test-nginx -t $IMAGE_TAG_NGINX . -f Dockerfile.nginx
- docker push $IMAGE_TAG_NGINX
...@@ -2,6 +2,5 @@ ...@@ -2,6 +2,5 @@
# config compatible with Black # config compatible with Black
line_length = 88 line_length = 88
multi_line_output = 3 multi_line_output = 3
default_sectiont = "THIRDPARTY"
include_trailing_comma = true include_trailing_comma = true
known_third_party = django,environ,wagtail known_third_party = PyPDF2,arrow,bleach,bs4,captcha,celery,clamd,dateutil,django,django_ratelimit,environ,faker,fastjsonschema,gql,httplib2,icalendar,instaloader,markdown,modelcluster,nh3,pirates,pytest,pytz,requests,sentry_sdk,taggit,wagtail,wagtailmetadata,weasyprint,willow,yaml
default_language_version: default_language_version:
python: python3.7 python: python3.12
exclude: snapshots/
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.5.0 rev: v4.4.0
hooks: hooks:
- id: trailing-whitespace - id: trailing-whitespace
exclude: ^.*\.md$ exclude: ^.*\.md$
...@@ -15,16 +16,27 @@ repos: ...@@ -15,16 +16,27 @@ repos:
- id: check-merge-conflict - id: check-merge-conflict
- repo: https://github.com/asottile/seed-isort-config - repo: https://github.com/asottile/seed-isort-config
rev: v2.1.0 rev: v2.2.0
hooks: hooks:
- id: seed-isort-config - id: seed-isort-config
- repo: https://github.com/timothycrosley/isort - repo: https://github.com/timothycrosley/isort
rev: 4.3.21 rev: 5.12.0
hooks: hooks:
- id: isort - id: isort
- repo: https://github.com/PyCQA/autoflake
rev: v2.2.1
hooks:
- id: autoflake
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 19.10b0 rev: 23.1.0
hooks: hooks:
- id: black - id: black
args: ["-t", "py310"]
- repo: https://github.com/PyCQA/autoflake
rev: v2.3.1
hooks:
- id: autoflake
args: [--remove-all-unused-imports, --in-place]
[MASTER]
# jobs=0 means 'use all CPUs'
jobs=0
[MESSAGES CONTROL]
disable =
missing-docstring,
line-too-long,
invalid-name,
no-value-for-parameter,
no-member,
unused-argument,
broad-except,
relative-import,
wrong-import-position,
bare-except,
locally-disabled,
protected-access,
abstract-method,
no-self-use,
fixme,
too-few-public-methods,
ungrouped-imports,
bad-continuation,
redefined-outer-name,
too-many-ancestors,
attribute-defined-outside-init,
too-many-arguments,
[REPORTS]
output-format=colorized
[FORMAT]
logging-modules=
logging,
structlog,
FROM python:3.8-slim FROM python:3.11
RUN apt-get update && apt-get install -y \
# requirements for OpenCV
libgl1-mesa-dev \
# requirements for WeasyPrint
python3-cffi \
# requirements for Wand (GIF image resizing)
libmagickwand-dev \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir /app RUN mkdir /app
WORKDIR /app WORKDIR /app
...@@ -8,12 +17,22 @@ RUN pip install -r requirements/base.txt -r requirements/production.txt ...@@ -8,12 +17,22 @@ RUN pip install -r requirements/base.txt -r requirements/production.txt
COPY . . COPY . .
RUN useradd app RUN bash -c 'adduser --disabled-login --quiet --gecos app app && \
RUN chown -R app /app chmod -R o+r /app/ && \
mkdir /app/media_files && \
mkdir /app/static_files && \
chown -R app:app /app/media_files && \
chown -R app:app /app/static_files && \
chmod o+x /app/run.sh'
USER app USER app
ENV DJANGO_SETTINGS_MODULE "majak.settings.production" ENV DJANGO_SETTINGS_MODULE "majak.settings.production"
# fake values for required env variables used to run collectstatic during build
RUN DJANGO_SECRET_KEY=x DATABASE_URL=postgres://x/x DJANGO_ALLOWED_HOSTS=x \
OIDC_RP_CLIENT_ID=x OIDC_RP_CLIENT_SECRET=x OIDC_RP_REALM_URL=x \
python manage.py collectstatic
EXPOSE 8000 EXPOSE 8000
CMD ["bash", "run.sh"] CMD ["bash", "run.sh"]
FROM nginx:latest
EXPOSE 8080
ADD nginx.conf /etc/nginx/conf.d/majak.conf
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.
...@@ -10,22 +10,28 @@ help: ...@@ -10,22 +10,28 @@ help:
@echo " install Install dependencies to venv" @echo " install Install dependencies to venv"
@echo " install-hooks Install pre-commit hooks" @echo " install-hooks Install pre-commit hooks"
@echo " hooks Run pre-commit hooks manually" @echo " hooks Run pre-commit hooks manually"
@echo " upgrade Upgrade requirements"
@echo "" @echo ""
@echo "Application:" @echo "Application:"
@echo " run Run the application on port ${PORT}" @echo " run Run the application on port ${PORT}"
@echo " shell Run Django shell" @echo " shell Run Django shell"
@echo " worker Run Celery worker"
@echo "" @echo ""
@echo "Database:" @echo "Database:"
@echo " migrations Generate migrations" @echo " migrations Generate migrations"
@echo " migrate Run migrations" @echo " migrate Run migrations"
@echo "" @echo ""
@echo "Testing:"
@echo " test Run tests"
@echo " coverage Coverage report"
@echo ""
venv: .venv/bin/python venv: .venv/bin/python
.venv/bin/python: .venv/bin/python:
${PYTHON} -m venv ${VENV} ${PYTHON} -m venv ${VENV}
install: venv install: venv
${VENV}/bin/pip install -r requirements/base.txt ${VENV}/bin/pip install -r requirements/base.txt -r requirements/dev.txt
install-hooks: install-hooks:
pre-commit install --install-hooks pre-commit install --install-hooks
...@@ -39,13 +45,28 @@ run: venv ...@@ -39,13 +45,28 @@ run: venv
shell: venv shell: venv
${VENV}/bin/python manage.py shell_plus ${VENV}/bin/python manage.py shell_plus
worker: venv
${VENV}/bin/celery -A majak worker --pool solo -E -l INFO
migrations: venv migrations: venv
${VENV}/bin/python manage.py makemigrations ${VENV}/bin/python manage.py makemigrations
migrate: venv migrate: venv
${VENV}/bin/python manage.py migrate ${VENV}/bin/python manage.py migrate
.PHONY: help venv install install-hooks hooks run shell test:
.PHONY: migrations migrate ${VENV}/bin/pytest
coverage:
${VENV}/bin/pytest --cov --cov-report term-missing
upgrade:
(cd requirements && pip-compile -U base.in)
(cd requirements && pip-compile -U dev.in)
(cd requirements && pip-compile -U production.in)
.PHONY: help venv install install-hooks hooks run shell upgrade
.PHONY: migrations migrate test coverage
# EOF # EOF
...@@ -5,14 +5,216 @@ Maják je CMS pro Pirátské weby. Postavený je na [Wagtail](https://wagtail.io ...@@ -5,14 +5,216 @@ Maják je CMS pro Pirátské weby. Postavený je na [Wagtail](https://wagtail.io
[![code style: Black](https://img.shields.io/badge/code%20style-Black-000000)](https://github.com/psf/black) [![code style: Black](https://img.shields.io/badge/code%20style-Black-000000)](https://github.com/psf/black)
[![powered by: Wagtail](https://img.shields.io/badge/powered%20by-Wagtail-43b1b0)](https://wagtail.io) [![powered by: Wagtail](https://img.shields.io/badge/powered%20by-Wagtail-43b1b0)](https://wagtail.io)
[![powered by: Django](https://img.shields.io/badge/powered%20by-Django-0C4B33)](https://www.djangoproject.com) [![powered by: Django](https://img.shields.io/badge/powered%20by-Django-0C4B33)](https://www.djangoproject.com)
[![licence AGPLv3](https://img.shields.io/badge/licence-AGPLv3-brightgreen)](LICENSE)
## Konfigurace ## Pod pokličkou
[Wagtail](https://wagtail.io) a [Django](https://www.djangoproject.com) jsou poměrně
vyspělé frameworky. Vždy mysli na to, že problém co řešíš, už pravděpodobně řešil
někdo před tebou. A obvykle existuje elegantní řešení.
Pár užitečných odkazů:
* [docs Wagtail](https://docs.wagtail.io/)
* [docs Django](https://docs.djangoproject.com/)
A za zmínku stojí [Awesome Wagtail](https://github.com/springload/awesome-wagtail)
jako přehled pluginů a rozšíření pro Wagtail.
Rozšíření která používáme:
* [wagtail-metadata](https://github.com/neon-jungle/wagtail-metadata)
- upravený template `shared/templates/wagtailmetadata/parts/tags.html`
### Struktura projektu
.
├── donate = app na web dary.pirati.cz
├── elections2021 = app na količní web k volbám 2021
├── senate = app na web senat.pirati.cz
├── senat_campaign = app na weby kandidátů na senátory
├── districts = app na web kraje.pirati.cz
├── district = app na weby oblastních sdružení
├── uniweb = app na univerzalni webove stranky
...
├── majak = Django projekt s konfigurací Majáku
├── shared = app se sdílenými static soubory a templaty pro weby
├── calendar_utils = app s modelem a utilitami na iCal kalendáře
├── tuning = app na tuning administračního rozhraní Majáku
└── users = app s custom user modelem a SSO, apod.
Poznámky k uspořádání:
* nesdílíme a nemícháme modely zděděné z `Page` mezi jednotlivými appkami a weby,
abychom předešli rozbití cizího webu
* části definice tříd stránek sdílíme jako mixin pattern (`shared.models.ArticleMixin`,
`share.models.SubpageMixin`, apod.)
* sdílet se mohou obyčejné Django modely z `models.Model`, ale umístěné v nějaké
appce/knihovně určené pro sdílení (`shared`, `calendar_utils`, apod.), nikoliv
mezi weby (mezi appkami na weby by nikdy neměly vzniknout závislosti)
### Konfigurace webu
Konfigurace konkrétního webu (odkazy do patičky, Matomo ID, apod.) se definuje v
kořenové `xxxHomePage` webu. Je to pro uživatele snažší na správu než
[Site Settings](https://docs.wagtail.io/en/stable/reference/contrib/settings.html)
Wagtailu pro konfigurace webů. A pro vývojáře je to skoro jedno.
Z různých podstránek webu se k té konfiguraci dostaneme přes property `root_page`
kterou přidává `shared.models.SubpageMixin`. V `xxxHomePage` webu je třeba
definovat `root_page` tak, aby vedla na `self`.
### Styleguide
Některé weby využívají [Pirátskou UI styleguide](https://gitlab.pirati.cz/to/weby/ui-styleguide)
pro vzhled. Idea je, že se budou sdílet nejen statické assety (CSS, JS, ...),
ale i univerzální kusy template, které se dají includovat v různých webech
(patička webu, karta článku do přehledu, atp.).
Sdílené části využívané na více webech se umísťují do:
shared/static/styleguideXX/ = statické assety (CSS, JS, obrázky, ...)
shared/templates/styleguideXX/ = snippety pro include v templatech
`XX` v názvu adresáře je číslo major a minor verze šablony. Např. `styleguide18`
obsahuje věci ze šablony verze `1.8.x`. Důvodem je snažší migrace na novější
verze šablony, které mohou obsahovat nekompatibilní změny. Každý web tak může
(a nemusí) migrovat nezávisle dle potřeby.
Různé verze šablony jsou k vidění na [styleguide.pirati.cz](https://styleguide.pirati.cz/)
### Kalendáře
Pro práci s kalendáři v iCal formátu je připravena appka `calendar_utils`.
Poskytuje `CalendarMixin` do modelu, který přidá fieldy `calendar_url` pro
editaci a `calendar` pro vazbu na model `Calendar` (který se plní a automaticky
spravuje na pozadí). Typicky se použije ve Wagtail settings pro web, kde stačí
`calendar_url` zpřístupnit pro editaci.
Kalendář se stáhne při uložení modelu obsahujícího `CalendarMixin`.
Appka přidává management command `update_callendars`, který stahuje a updatuje
kalendáře. Je třeba ho pravidelně volat na pozadí (přes CRON).
### Celery (Import z Jekyllu)
Import z Jekyll GitHub repozitářů pirátských webů je řešen asynchroně přes Celery.
Celery využívá Redis, který může běžet např. lokálně, typicky 6379:
V envu pak je pak potřeba mít nastavený Celery broker:
```
CELERY_BROKER_URL=redis://localhost:6379/6
CELERY_RESULT_BACKEND=redis://localhost:6379/6
```
Aby se celery tasky vykonávaly, je potřeba pustit celery v terminálu:
```
celery -A majak worker
```
Pokud není zadán `CELERY_BROKER_URL`, tak se automaticky nastaví
`CELERY_TASK_ALWAYS_EAGER = True`, čímž se tasky vykonají synchronně přímo v
procesu webserveru.
### Stránka 404
Pokud je třeba vlastní 404 pro web, stačí do kořenové `xxxHomePage` webu
definovat metodu `get_404_response` vracející Django HTTP Reponse objekt.
def get_404_response(self, request):
return HttpResponse("Stránka nenalezena", status=404)
## Deployment
### Konfigurace
Je třeba nastavit environment proměnné: Je třeba nastavit environment proměnné:
| proměnná | default | popis | | proměnná | default | popis |
| --- | --- | --- | | --- | --- | --- |
| `DATABASE_URL` | | DSN k databázi (např. `postgres://user:pass@localhost:5342/majak`) | | `DATABASE_URL` | | DSN k databázi (např. `postgres://user:pass@localhost:5432/majak`) |
| `OIDC_RP_REALM_URL` | | OpenID server realm URL (např. `http://localhost:8080/auth/realms/master/`) |
| `OIDC_RP_CLIENT_ID` | | OpenID Client ID |
| `OIDC_RP_CLIENT_SECRET` | | OpenID Client Secret |
| `BASE_URL` | https://majak.pirati.cz | základní URL pro notifikační emaily apod. |
V produkci musí být navíc nastaveno:
| proměnná | default | popis |
| --- | --- | --- |
| `DJANGO_SECRET_KEY` | | tajný šifrovací klíč |
| `DJANGO_ALLOWED_HOSTS` | | allowed hosts (více hodnot odděleno čárkami) |
| `CELERY_BROKER_URL` | | URL pro Celery Broker |
| `CELERY_RESULT_BACKEND` | | URL pro Celery Result Backend |
| `EMAIL_HOST` | SMTP pro odesílání přihlášek do kariér |
| `EMAIL_HOST_USER` | --||-- Username |
| `EMAIL_HOST_PASSWORD` | --||-- Heslo |
| `EMAIL_PORT` | --||-- Port |
| `CLAMD_TCP_ADDR` | ClamAV host (pro skenování virů v nahraných souborech) |
| `CLAMD_TCP_SOCKET` | ClamAV socket |
Různé:
| proměnná | default | popis |
| --- | --- | --- |
| `MAJAK_ENV` | prod | `prod`/`test`/`dev` prostředí kde Maják běží |
| `SENTRY_DSN` | | pokud je zadáno, pády se reportují do Sentry |
| `SEARCH_CONFIG` | english | nastavení jazyka fulltextového vyhledávání, viz níže |
| `DEBUG_TOOLBAR` | False | zobrazit Django Debug Toolbar (pro vývoj) |
| `MAILTRAIN_API_URL` | | URL k API Mailtrain |
| `MAILTRAIN_API_TOKEN` | | token k API Mailtrain |
Settings pro appky na weby:
| proměnná | default | popis |
| --- | --- | --- |
| `DONATE_PORTAL_REDIRECT_URL` | "" | URL pro přesměrování z darovacího formuláře |
| `DONATE_PORTAL_REDIRECT_SOURCE` | dary.pirati.cz | identifikátor zdroje pro přesměrování na darovací portál |
| `DONATE_PORTAL_API_URL` | "" | URL s API darovacího portálu |
### Management commands
Přes CRON je třeba na pozadí spouštět Django `manage.py` commandy:
* `clearsessions` - maže expirované sessions (denně až týdně)
* `publish_scheduled_pages` - publikuje naplánované stránky (každou hodinu)
* `update_callendars` - stáhne a aktualizuje kalendáře (několikrát denně)
* `update_main_timeline_articles` - aktualizuje články na `pirati.cz` z `https://piratipracuji.cz/api/`
* `update_redmine_issues` - aktualizuje programované body MS a KS stránek napojených na Redmine (několikrát denně)
### Fulltextové vyhledávání v češtině
Pro fulltextové vyhledávání je třeba do PostgreSQL přidat
[slovníky](https://github.com/f00b4r/postgresql-czech) do adresáře
`/usr/local/share/postgresql/tsearch_data/`.
V databázi Majáku je třeba nakonfigurovat český fulltext:
```sql
CREATE TEXT SEARCH DICTIONARY cspell (template=ispell, dictfile=czech, afffile=czech, stopwords=czech);
CREATE TEXT SEARCH CONFIGURATION czech (copy=english);
ALTER TEXT SEARCH CONFIGURATION czech ALTER MAPPING FOR word, asciiword WITH cspell, simple;
CREATE extension IF NOT EXISTS unaccent;
```
Otestovat funkčnost lze dotazem:
```sql
SELECT * FROM ts_debug('czech', 'Příliš žluťoučký kůň se napil žluté vody');
```
Dále nastavit environment proměnnou `SEARCH_CONFIG=czech`. A nakonec jednorázově
spustit naplnění indexu pro vyhledávání `python manage.py update_index`.
Aktualizace indexu poté probíhají automaticky při uložení stránek.
### Přidání nového webu
Doména či subdoména se musí nakonfigurovat v:
* environment proměnné `DJANGO_ALLOWED_HOSTS`
* proxy před Majákem
## Vývoj ## Vývoj
...@@ -65,9 +267,34 @@ To nainstaluje Pythonní závislosti pro vývoj projektu na lokále. ...@@ -65,9 +267,34 @@ To nainstaluje Pythonní závislosti pro vývoj projektu na lokále.
#### Nastavení environment proměnných #### Nastavení environment proměnných
Nastav environment proměnné (viz konfigurace výše). Pro jednoduchost doporučujeme Environment proměnné (viz konfigurace výše) se načítají ze souboru `.env`, který
použít [direnv](https://direnv.net/), který nastaví environment proměnné pro vývoj může vypadat takto:
při změně adresáře na adresář s projektem.
DATABASE_URL=postgres://db:db@localhost:5432/majak
OIDC_RP_REALM_URL=http://localhost:8080/auth/realms/master/
OIDC_RP_CLIENT_ID=majak
OIDC_RP_CLIENT_SECRET=abcd
Pro lokální vývoj obsahují settings tyto výchozí hodnoty:
DEBUG = True
ALLOWED_HOSTS = ["*"]
MAJAK_ENV = "dev"
#### Autentifikace a autorizace
Jako OIDC server můžete použít lokálně spuštěný Keycloak z [Dev Tools](https://gitlab.pirati.cz/to/dev-tools).
Prvním přihlášením přes OIDC se vytvoří uživatel, ale bez oprávnění. Je třeba
mu přes Django shell (viz níže) nastavit oprávnění pro přístup do administrace:
```python
from users.models import User
u = User.objects.get()
u.is_superuser = True
u.is_staff = True
u.save()
```
### Management projektu ### Management projektu
...@@ -89,12 +316,47 @@ Django development server na portu `8006` se spustí příkazem: ...@@ -89,12 +316,47 @@ Django development server na portu `8006` se spustí příkazem:
Poté můžete otevřít web na adrese [http://localhost:8006](http://localhost:8006) Poté můžete otevřít web na adrese [http://localhost:8006](http://localhost:8006)
##### Debug Toolbar
Pro spuštění development serveru s Django Debug Toolbar nastavte environment
proměnnou `DEBUG_TOOLBAR`. Např.:
$ DEBUG_TOOLBAR=1 make run
#### Django shell #### Django shell
Django shell používající `shell_plus` z Django extensions spustíte: Django shell používající `shell_plus` z Django extensions spustíte:
$ make shell $ make shell
### Lokální weby
Pro vývoj různých webů si nastavte v `/etc/hosts` (na Linux, Mac OS, apod.)
pojmenované aliasy k lokální IP 127.0.0.1 jako např.:
127.0.0.1 majak.loc dalsiweb.loc
K Majáku spuštěnému v development serveru na portu `8006` se pak dostanete na
adrese [http://majak.loc:8006/admin/](http://majak.loc:8006/admin/).
A pokud nějakému webu v nastavení v Majáku dáte adresu třeba `dalsiweb.loc` a
port `8006`, dostanete se pak na něj přes adresu
[http://dalsiweb.loc:8006](http://dalsiweb.loc:8006).
### Testy
Používá se testovací framework [pytest](https://pytest.org). Spuštění testů:
$ pytest
Případně přes `make`, ale bez možnosti parametrizovat spuštění testů:
$ make test
Coverage report:
$ make coverage
### Code quality ### Code quality
K formátování kódu se používá [black](https://github.com/psf/black). Doporučujeme K formátování kódu se používá [black](https://github.com/psf/black). Doporučujeme
...@@ -129,5 +391,6 @@ K upgrade se používají [pip-tools](https://github.com/jazzband/pip-tools) (`p ...@@ -129,5 +391,6 @@ K upgrade se používají [pip-tools](https://github.com/jazzband/pip-tools) (`p
$ cd requirements/ $ cd requirements/
$ pip-compile -U base.in $ pip-compile -U base.in
$ pip-compile -U production.in $ pip-compile -U production.in
$ pip-compile -U dev.in
Tím se vygenerují `base.txt` a `production.txt`. Tím se vygenerují `base.txt`, `production.txt` a `dev.txt`.
File moved
from django.apps import AppConfig
class ArticleImportUtilsConfig(AppConfig):
name = "article_import_utils"
File moved
File moved
from django.apps import AppConfig
class CalendarUtilsConfig(AppConfig):
name = "calendar_utils"
"""
iCalEvents search all events occurring in a given time frame in an iCal file.
"""
__all__ = ["icaldownload", "icalparser", "icalevents"]
"""
Downloads an iCal url or reads an iCal file.
"""
import logging
from httplib2 import Http
def apple_data_fix(content):
"""
Fix Apple tzdata bug.
:param content: content to fix
:return: fixed content
"""
return content.replace("TZOFFSETFROM:+5328", "TZOFFSETFROM:+0053")
def apple_url_fix(url):
"""
Fix Apple URL.
:param url: URL to fix
:return: fixed URL
"""
if url.startswith("webcal://"):
url = url.replace("webcal://", "http://", 1)
return url
class ICalDownload:
"""
Downloads or reads and decodes iCal sources.
"""
def __init__(self, http=None, encoding="utf-8"):
# Get logger
logger = logging.getLogger()
# default http connection to use
if http is None:
try:
http = Http(".cache")
except (PermissionError, OSError) as e:
# Cache disabled if no write permission in working directory
logger.warning(
(
"Caching is disabled due to a read-only working directory: {}"
).format(e)
)
http = Http()
self.http = http
self.encoding = encoding
def data_from_url(self, url, apple_fix=False):
"""
Download iCal data from URL.
:param url: URL to download
:param apple_fix: fix Apple bugs (protocol type and tzdata in iCal)
:return: decoded (and fixed) iCal data
"""
if apple_fix:
url = apple_url_fix(url)
_, content = self.http.request(url)
if not content:
raise ConnectionError("Could not get data from %s!" % url)
return self.decode(content, apple_fix=apple_fix)
def data_from_file(self, file, apple_fix=False):
"""
Read iCal data from file.
:param file: file to read
:param apple_fix: fix wrong Apple tzdata in iCal
:return: decoded (and fixed) iCal data
"""
with open(file, mode="rb") as f:
content = f.read()
if not content:
raise IOError("File %s is not readable or is empty!" % file)
return self.decode(content, apple_fix=apple_fix)
def data_from_string(self, string_content, apple_fix=False):
if not string_content:
raise IOError("String content is not readable or is empty!")
return self.decode(string_content, apple_fix=apple_fix)
def decode(self, content, apple_fix=False):
"""
Decode content using the set charset.
:param content: content do decode
:param apple_fix: fix Apple txdata bug
:return: decoded (and fixed) content
"""
content = content.decode(self.encoding)
content = content.replace("\r", "")
if apple_fix:
content = apple_data_fix(content)
return content
from threading import Lock, Thread
from .icaldownload import ICalDownload
from .icalparser import Event, parse_events
# Lock for event data
event_lock = Lock()
# Event data
event_store = {}
# Threads
threads = {}
def events(
url=None,
file=None,
string_content=None,
start=None,
end=None,
fix_apple=False,
http=None,
tzinfo=None,
sort=None,
strict=False,
) -> list[Event]:
"""
Get all events form the given iCal URL occurring in the given time range.
:param url: iCal URL
:param file: iCal file path
:param string_content: iCal content as string
:param start: start date (see dateutils.date)
:param end: end date (see dateutils.date)
:param fix_apple: fix known Apple iCal issues
:param tzinfo: return values in specified tz
:param sort: sort return values
:param strict: return dates, datetimes and datetime with timezones as specified in ical
:sort sorts events by start time
:return events
"""
found_events = []
content = None
ical_download = ICalDownload(http=http)
if url:
content = ical_download.data_from_url(url, apple_fix=fix_apple)
if not content and file:
content = ical_download.data_from_file(file, apple_fix=fix_apple)
if not content and string_content:
content = ical_download.data_from_string(string_content, apple_fix=fix_apple)
found_events += parse_events(
content, start=start, end=end, tzinfo=tzinfo, sort=sort, strict=strict
)
if found_events is not None and sort is True:
found_events.sort()
return found_events
def request_data(key, url, file, string_content, start, end, fix_apple):
"""
Request data, update local data cache and remove this Thread from queue.
:param key: key for data source to get result later
:param url: iCal URL
:param file: iCal file path
:param string_content: iCal content as string
:param start: start date
:param end: end date
:param fix_apple: fix known Apple iCal issues
"""
data = []
try:
data += events(
url=url,
file=file,
string_content=string_content,
start=start,
end=end,
fix_apple=fix_apple,
)
finally:
update_events(key, data)
request_finished(key)
def events_async(
key, url=None, file=None, start=None, string_content=None, end=None, fix_apple=False
):
"""
Trigger an asynchronous data request.
:param key: key for data source to get result later
:param url: iCal URL
:param file: iCal file path
:param string_content: iCal content as string
:param start: start date
:param end: end date
:param fix_apple: fix known Apple iCal issues
"""
t = Thread(
target=request_data,
args=(key, url, file, string_content, start, end, fix_apple),
)
with event_lock:
if key not in threads:
threads[key] = []
threads[key].append(t)
if not threads[key][0].is_alive():
threads[key][0].start()
def request_finished(key):
"""
Remove finished Thread from queue.
:param key: data source key
"""
with event_lock:
threads[key] = threads[key][1:]
if threads[key]:
threads[key][0].run()
def update_events(key, data):
"""
Set the latest events for a key.
:param key: key to set
:param data: events for key
"""
with event_lock:
event_store[key] = data
def latest_events(key):
"""
Get the latest downloaded events for the given key.
:return: events for key
"""
with event_lock:
# copy data
res = event_store[key][:]
return res
def all_done(key):
"""
Check if requests for the given key are active.
:param key: key for requests
:return: True if requests are pending or active
"""
with event_lock:
if threads[key]:
return False
return True
"""
Parse iCal data to Events.
"""
from datetime import date, datetime, timedelta
# for UID generation
from random import randint
from typing import Optional
from uuid import uuid4
from dateutil.rrule import rrulestr
from dateutil.tz import UTC, gettz
from icalendar import Calendar
from icalendar.prop import vDDDLists, vText
from icalendar.timezone.windows_to_olson import WINDOWS_TO_OLSON
from pytz import timezone
def now():
"""
Get current time.
:return: now as datetime with timezone
"""
return datetime.now(UTC)
class Attendee(str):
def __init__(self, address):
self.address = address
def __repr__(self):
return self.address.encode("utf-8").decode("ascii")
@property
def params(self):
return self.address.params
class Event:
"""
Represents one event (occurrence in case of reoccurring events).
"""
def __init__(self):
"""
Create a new event occurrence.
"""
self.uid = -1
self.summary = None
self.description = None
self.start = None
self.end = None
self.all_day = True
self.transparent = False
self.recurring = False
self.location = None
self.private = False
self.created = None
self.last_modified = None
self.sequence = None
self.recurrence_id = None
self.attendee = None
self.organizer = None
self.categories = None
self.floating = None
self.status = None
self.url = None
def time_left(self, time=None):
"""
timedelta form now to event.
:return: timedelta from now
"""
time = time or now()
return self.start - time
def __lt__(self, other):
"""
Events are sorted by start time by default.
:param other: other event
:return: True if start of this event is smaller than other
"""
if not other or not isinstance(other, Event):
raise ValueError(
"Only events can be compared with each other! Other is %s" % type(other)
)
else:
# start and end can be dates, datetimes and datetimes with timezoneinfo
if type(self.start) is date and type(other.start) is date:
return self.start < other.start
elif type(self.start) is datetime and type(other.start) is datetime:
if self.start.tzinfo == other.start.tzinfo:
return self.start < other.start
else:
return self.start.astimezone(UTC) < other.start.astimezone(UTC)
elif type(self.start) is date and type(other.start) is datetime:
return self.start < other.start.date()
elif type(self.start) is datetime and type(other.start) is date:
return self.start.date() < other.start
def __str__(self):
return "%s: %s (%s)" % (self.start, self.summary, self.end - self.start)
def astimezone(self, tzinfo):
if type(self.start) is datetime:
self.start = self.start.astimezone(tzinfo)
if type(self.end) is datetime:
self.end = self.end.astimezone(tzinfo)
return self
def copy_to(self, new_start=None, uid=None):
"""
Create a new event equal to this with new start date.
:param new_start: new start date
:param uid: UID of new event
:return: new event
"""
if not new_start:
new_start = self.start
if not uid:
uid = "%s_%d" % (self.uid, randint(0, 1000000))
ne = Event()
ne.summary = self.summary
ne.description = self.description
ne.start = new_start
if self.end:
duration = self.end - self.start
ne.end = new_start + duration
ne.all_day = self.all_day
ne.recurring = self.recurring
ne.location = self.location
ne.attendee = self.attendee
ne.organizer = self.organizer
ne.private = self.private
ne.transparent = self.transparent
ne.uid = uid
ne.created = self.created
ne.last_modified = self.last_modified
ne.categories = self.categories
ne.floating = self.floating
ne.status = self.status
ne.url = self.url
return ne
def encode(value: Optional[vText]) -> Optional[str]:
if value is None:
return None
try:
return str(value)
except UnicodeEncodeError:
return str(value.encode("utf-8"))
def create_event(component, utc_default):
"""
Create an event from its iCal representation.
:param component: iCal component
:return: event
"""
event = Event()
event.start = component.get("dtstart").dt
# The RFC specifies that the TZID parameter must be specified for datetime or time
# Otherwise we set a default timezone (if only one is set with VTIMEZONE) or utc
event.floating = type(component.get("dtstart").dt) == date and utc_default
if component.get("dtend"):
event.end = component.get("dtend").dt
elif component.get("duration"): # compute implicit end as start + duration
event.end = event.start + component.get("duration").dt
else: # compute implicit end as start + 0
event.end = event.start
event.summary = encode(component.get("summary"))
event.description = encode(component.get("description"))
event.all_day = type(component.get("dtstart").dt) is date
if component.get("rrule"):
event.recurring = True
event.location = encode(component.get("location"))
if component.get("attendee"):
event.attendee = component.get("attendee")
if type(event.attendee) is list:
event.attendee = [Attendee(attendee) for attendee in event.attendee]
else:
event.attendee = Attendee(event.attendee)
else:
event.attendee = str(None)
if component.get("uid"):
event.uid = component.get("uid").encode("utf-8").decode("ascii")
else:
event.uid = str(uuid4()) # Be nice - treat every event as unique
if component.get("organizer"):
event.organizer = component.get("organizer").encode("utf-8").decode("ascii")
else:
event.organizer = str(None)
if component.get("class"):
event_class = component.get("class")
event.private = event_class == "PRIVATE" or event_class == "CONFIDENTIAL"
if component.get("transp"):
event.transparent = component.get("transp") == "TRANSPARENT"
if component.get("created"):
event.created = component.get("created").dt
if component.get("RECURRENCE-ID"):
rid = component.get("RECURRENCE-ID").dt
# Spec defines that if DTSTART is a date RECURRENCE-ID also is to be interpreted as a date
if type(component.get("dtstart").dt) is date:
event.recurrence_id = date(year=rid.year, month=rid.month, day=rid.day)
else:
event.recurrence_id = rid
if component.get("last-modified"):
event.last_modified = component.get("last-modified").dt
elif event.created:
event.last_modified = event.created
# sequence can be 0 - test for None instead
if not component.get("sequence") is None:
event.sequence = component.get("sequence")
if component.get("categories"):
categoriesval = component.get("categories")
categories = (
component.get("categories").cats
if hasattr(categoriesval, "cats")
else categoriesval
)
encoded_categories = list()
for category in categories:
encoded_categories.append(encode(category))
event.categories = encoded_categories
if component.get("status"):
event.status = encode(component.get("status"))
if component.get("url"):
event.url = encode(component.get("url"))
return event
def parse_events(
content,
start=None,
end=None,
default_span=timedelta(days=7),
tzinfo=None,
sort=False,
strict=False,
):
"""
Query the events occurring in a given time range.
:param content: iCal URL/file content as String
:param start: start date for search, default today (in UTC format)
:param end: end date for search (in UTC format)
:param default_span: default query length (one week)
:return: events as list
"""
if not start:
start = now()
if not end:
end = start + default_span
if not content:
raise ValueError("Content is invalid!")
calendar = Calendar.from_ical(content)
# > Will be deprecated ========================
# Calendar.from_ical already parses timezones as specified in the ical.
# We can specify a 'default' tz but this is not according to spec.
# Kept this here to verify tests and backward compatibility
# Keep track of the timezones defined in the calendar
timezones = {}
# Parse non standard timezone name
if "X-WR-TIMEZONE" in calendar:
x_wr_timezone = str(calendar["X-WR-TIMEZONE"])
timezones[x_wr_timezone] = get_timezone(x_wr_timezone)
for c in calendar.walk("VTIMEZONE"):
name = str(c["TZID"])
try:
timezones[name] = c.to_tz()
except IndexError:
# This happens if the VTIMEZONE doesn't
# contain start/end times for daylight
# saving time. Get the system pytz
# value from the name as a fallback.
timezones[name] = timezone(name)
# If there's exactly one timezone in the file,
# assume it applies globally, otherwise UTC
utc_default = False
if len(timezones) == 1:
cal_tz = get_timezone(list(timezones)[0])
else:
utc_default = True
cal_tz = UTC
# < ==========================================
found = []
def add_if_not_exception(event):
exdate = "%04d%02d%02d" % (
event.start.year,
event.start.month,
event.start.day,
)
if exdate not in exceptions:
found.append(event)
for component in calendar.walk():
exceptions = {}
if "EXDATE" in component:
# Deal with the fact that sometimes it's a list and
# sometimes it's a singleton
exlist = []
if isinstance(component["EXDATE"], vDDDLists):
exlist = component["EXDATE"].dts
else:
exlist = component["EXDATE"]
for ex in exlist:
exdate = ex.to_ical().decode("UTF-8")
exceptions[exdate[0:8]] = exdate
if component.name == "VEVENT":
e = create_event(component, utc_default)
# make rule.between happy and provide from, to points in time that have the same format as dtstart
s = component["dtstart"].dt
if type(s) is date and not e.recurring:
f, t = date(start.year, start.month, start.day), date(
end.year, end.month, end.day
)
elif type(s) is datetime and s.tzinfo:
f, t = datetime(
start.year, start.month, start.day, tzinfo=s.tzinfo
), datetime(end.year, end.month, end.day, tzinfo=s.tzinfo)
else:
f, t = datetime(start.year, start.month, start.day), datetime(
end.year, end.month, end.day
)
if e.recurring:
rule = parse_rrule(component)
for dt in rule.between(f, t, inc=True):
# Recompute the start time in the current timezone *on* the
# date of *this* occurrence. This handles the case where the
# recurrence has crossed over the daylight savings time boundary.
if type(dt) is datetime and dt.tzinfo:
dtstart = dt.replace(tzinfo=get_timezone(str(dt.tzinfo)))
ecopy = e.copy_to(
dtstart.date() if type(s) is date else dtstart, e.uid
)
else:
ecopy = e.copy_to(dt.date() if type(s) is date else dt, e.uid)
add_if_not_exception(ecopy)
elif e.end >= f and e.start <= t:
add_if_not_exception(e)
result = found.copy()
# Remove events that are replaced in ical
for event in found:
if not event.recurrence_id and (event.uid, event.start) in [
(f.uid, f.recurrence_id) for f in found
]:
result.remove(event)
# > Will be deprecated ========================
# We will apply default cal_tz as required by some tests.
# This is just here for backward-compatibility
if not strict:
for event in result:
if type(event.start) is date:
event.start = datetime(
year=event.start.year,
month=event.start.month,
day=event.start.day,
hour=0,
minute=0,
tzinfo=cal_tz,
)
event.end = datetime(
year=event.end.year,
month=event.end.month,
day=event.end.day,
hour=0,
minute=0,
tzinfo=cal_tz,
)
elif type(event.start) is datetime:
if event.start.tzinfo:
event.start = event.start.astimezone(cal_tz)
event.end = event.end.astimezone(cal_tz)
else:
event.start = event.start.replace(tzinfo=cal_tz)
event.end = event.end.replace(tzinfo=cal_tz)
if event.created:
if type(event.created) is date:
event.created = datetime(
year=event.created.year,
month=event.created.month,
day=event.created.day,
hour=0,
minute=0,
tzinfo=cal_tz,
)
if type(event.created) is datetime:
if event.created.tzinfo:
event.created = event.created.astimezone(cal_tz)
else:
event.created = event.created.replace(tzinfo=cal_tz)
if event.last_modified:
if type(event.last_modified) is date:
event.last_modified = datetime(
year=event.last_modified.year,
month=event.last_modified.month,
day=event.last_modified.day,
hour=0,
minute=0,
tzinfo=cal_tz,
)
if type(event.last_modified) is datetime:
if event.last_modified.tzinfo:
event.last_modified = event.last_modified.astimezone(cal_tz)
else:
event.last_modified = event.last_modified.replace(tzinfo=cal_tz)
# < ==========================================
if sort:
result.sort()
if tzinfo:
result = [event.astimezone(tzinfo) for event in result]
return result
def parse_rrule(component):
"""
Extract a dateutil.rrule object from an icalendar component. Also includes
the component's dtstart and exdate properties. The rdate and exrule
properties are not yet supported.
:param component: icalendar component
:return: extracted rrule or rruleset or None
"""
dtstart = component.get("dtstart").dt
# component['rrule'] can be both a scalar and a list
rrules = component.get("rrule")
if not isinstance(rrules, list):
rrules = [rrules]
def conform_until(until, dtstart):
if type(dtstart) is datetime:
# If we have timezone defined adjust for daylight saving time
if type(until) is datetime:
return until + abs(
(
until.astimezone(dtstart.tzinfo).utcoffset()
if until.tzinfo is not None and dtstart.tzinfo is not None
else None
)
or timedelta()
)
return (
until.astimezone(UTC)
if type(until) is datetime
else datetime(
year=until.year, month=until.month, day=until.day, tzinfo=UTC
)
) + (
(dtstart.tzinfo.utcoffset(dtstart) if dtstart.tzinfo else None)
or timedelta()
)
return until.date() + timedelta(days=1) if type(until) is datetime else until
for index, rru in enumerate(rrules):
if "UNTIL" in rru:
rrules[index]["UNTIL"] = [
conform_until(until, dtstart) for until in rrules[index]["UNTIL"]
]
rule = rrulestr(
"\n".join(x.to_ical().decode() for x in rrules),
dtstart=dtstart,
forceset=True,
unfold=True,
)
if component.get("exdate"):
# Add exdates to the rruleset
for exd in extract_exdates(component):
if type(dtstart) is date:
rule.exdate(
datetime(
year=exd.year,
month=exd.month,
day=exd.day,
hour=0,
minute=0,
second=0,
)
if isinstance(exd, date)
else exd
)
else:
rule.exdate(exd)
# TODO: What about rdates and exrules?
if component.get("exrule"):
pass
if component.get("rdate"):
pass
return rule
def extract_exdates(component):
"""
Compile a list of all exception dates stored with a component.
:param component: icalendar iCal component
:return: list of exception dates
"""
dates = []
exd_prop = component.get("exdate")
if isinstance(exd_prop, list):
for exd_list in exd_prop:
dates.extend(exd.dt for exd in exd_list.dts)
else: # it must be a vDDDLists
dates.extend(exd.dt for exd in exd_prop.dts)
return dates
def get_timezone(tz_name):
if tz_name in WINDOWS_TO_OLSON:
return gettz(WINDOWS_TO_OLSON[tz_name])
else:
return gettz(tz_name)