Compare commits
No commits in common. "master" and "docker-fixes" have entirely different histories.
master
...
docker-fix
|
@ -3,3 +3,4 @@
|
|||
config.ini
|
||||
README.md
|
||||
TODO
|
||||
requirements.txt
|
||||
|
|
|
@ -1,16 +0,0 @@
|
|||
on: [push]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.x
|
||||
- name: Install dependencies
|
||||
run: pip install .[test]
|
||||
- name: Test with pytest
|
||||
run: pytest -vv --color=yes
|
|
@ -1,4 +1,3 @@
|
|||
dist/
|
||||
__pycache__
|
||||
*.py[cow]
|
||||
config-*.ini
|
||||
|
|
674
LICENSE
674
LICENSE
|
@ -1,674 +0,0 @@
|
|||
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>.
|
100
README.md
100
README.md
|
@ -1,29 +1,14 @@
|
|||
# mastoposter - easy-to-use mastodon-to-[everything] reposter
|
||||
# mastoposter - easy-to-use mastodon-to-[everything] reposter!
|
||||
|
||||
Mastoposter is a simple zero-headache* service that forwards your toots from any
|
||||
Mastodon-compatible Fediverse software (Pleroma also works\*\*!) to any of your
|
||||
Mastodon-compatible Fediverse software (Pleroma also works!) to any of your
|
||||
other services! For now it supports only Discord webhooks and Telegram, but it
|
||||
can be easily extended to support pretty much anything!
|
||||
|
||||
## Installation
|
||||
|
||||
### Via pip
|
||||
|
||||
Since recently we have package published to pip (thanks to
|
||||
[@cybertailor@deadinsi.de](https://deadinsi.de/@cybertailor) for adding
|
||||
pyproject file), so now you can just do the following:
|
||||
|
||||
```sh
|
||||
pip install mastoposter
|
||||
```
|
||||
|
||||
Note that you would still have to clone repository to build a Docker image.
|
||||
|
||||
### Old way
|
||||
|
||||
You can run it either on your host machine, or inside a Docker container.
|
||||
In any case, you have to clone that repo first in order to do anything:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/hatkidchan/mastoposter && cd mastoposter
|
||||
```
|
||||
|
@ -31,14 +16,11 @@ git clone https://github.com/hatkidchan/mastoposter && cd mastoposter
|
|||
After that, you can either run it in Docker, set up a standalone systemd
|
||||
service, or just run it as it is!
|
||||
|
||||
### Docker
|
||||
### Docker:
|
||||
|
||||
```sh
|
||||
docker build -t mastoposter .
|
||||
docker run -d \
|
||||
--restart=unless-stopped \
|
||||
-v /path/to/config.ini:/config.ini:ro \
|
||||
--name mastoposter mastoposter
|
||||
docker run --restart=always -dv /path/to/config.ini:/config.ini:ro --name mastoposter mastoposter
|
||||
```
|
||||
|
||||
And you should be good to go
|
||||
|
@ -64,38 +46,27 @@ Restart=on-failure
|
|||
WantedBy=network.target
|
||||
```
|
||||
|
||||
Before running it though, don't forget to install dependencies from the
|
||||
Before running it though, don't forget to install dependencies from the
|
||||
./requirements.txt, but it's a good idea to use a virtual environment for that.
|
||||
Though, that's outside of the scope of that, so I won't cover it here.
|
||||
|
||||
### Running manually
|
||||
|
||||
Just be in the folder with it, have dependencies installed and run:
|
||||
|
||||
```sh
|
||||
python3 -m mastoposter config.ini
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configuration file is just a regular INI file with a couple sections.
|
||||
|
||||
Configuration wizard is still in progress, but we have a couple examples for
|
||||
common use-cases. If you have troubles configuring it yourself, you could
|
||||
either use discussions feature, or ask me on Fedi directly (links on profile).
|
||||
|
||||
### [main]
|
||||
|
||||
Section `main` contains settings of your account (ie, your instance, list ID,
|
||||
user ID, access token), as well as list of modules to load.
|
||||
|
||||
#### instance
|
||||
|
||||
This is your instance. It should be written without the `https://` part, so,
|
||||
for example, `mastodon.social`.
|
||||
|
||||
#### token
|
||||
|
||||
This is your access token.
|
||||
|
||||
On Mastodon, you can acquire it by creating an application with the minimum of
|
||||
|
@ -107,7 +78,6 @@ tab of the devtools and look for `chats` request. Inside the request headers,
|
|||
there should be `Authorization: Bearer XXXXXXXXXXX` header. That's your token.
|
||||
|
||||
#### user
|
||||
|
||||
It's still not properly tested, but you could just leave it as `auto` for now.
|
||||
|
||||
In case it fails, on Mastodon you can get your user ID by looking at your
|
||||
|
@ -118,7 +88,6 @@ On Pleroma you're out of luck again, I don't remember how I got mine. Just hope
|
|||
that "auto" will work, lol.
|
||||
|
||||
#### list
|
||||
|
||||
That's the main problem of this crossposter: it requires a list to be created
|
||||
to function properly. Both Pleroma and Mastodon support them, so it shouldn't be
|
||||
a big deal. Just create a list, add yourself into it and copy its ID (it should
|
||||
|
@ -128,22 +97,14 @@ List is required to filter incoming events. You can't just listen for home
|
|||
timeline 'cause some events are not guaranteed to be there (boosts at least).
|
||||
|
||||
#### auto-reconnect
|
||||
|
||||
You can set it to either `yes` or `no`. When set to `yes`, it will reconnect
|
||||
on any websocket error, but not on any error related to modules (even if it's a
|
||||
connection error!!!)
|
||||
|
||||
#### modules
|
||||
|
||||
More about them later
|
||||
|
||||
#### loglevel
|
||||
|
||||
Self-explanatory, logging level. Can be either `DEBUG`, `INFO`, `WARNING` or
|
||||
`ERROR`. Defaults to `INFO`
|
||||
|
||||
### Modules
|
||||
|
||||
There's two types of modules supported at this point: `telegram` and `discord`.
|
||||
Both of them are self-explanatory, but we'll go over them real quick.
|
||||
|
||||
|
@ -156,7 +117,6 @@ not have the `module/` prefix since it's always there. You can use multiple
|
|||
modules and separate them using spaces.
|
||||
|
||||
#### `type = telegram`
|
||||
|
||||
Module with that type will work in Telegram mode.
|
||||
It requires your Bot token to be set in the `token` field, as well as `chat`
|
||||
to be set with your chat ID. You can use `@username` if the chat is public.
|
||||
|
@ -171,14 +131,13 @@ such as `reblog_or_status` which points to either reblog, or status itself. Or
|
|||
`name_emojiless` which contains the name without emojis. Or `name` which
|
||||
contains either `display_name` or `username`, if first one is empty.
|
||||
|
||||
#### `type = discord`
|
||||
|
||||
#### `type = discord`
|
||||
Module for Discord webhooks. The only required parameter (besides the `type`) is
|
||||
`webhook`. It **should** have `wait=true` set. You can also use `thread_id` as a
|
||||
GET parameter to that. You also can use filters, nothing special about that.
|
||||
|
||||
### Filters
|
||||
|
||||
Filters are the most powerful feature of this crossposter. They allow you to...
|
||||
|
||||
Filter out where posts should and shouldn't go! It's that easy!
|
||||
|
@ -192,7 +151,6 @@ AND operator. You can also prefix filter name with either `~` or `!` to invert
|
|||
its behavior.
|
||||
|
||||
#### `type = boost`
|
||||
|
||||
Simple filter that passes through posts that are boosted from someone.
|
||||
|
||||
It also has an optional `list` property where you can specify the list of
|
||||
|
@ -204,53 +162,36 @@ trigger that filter. If list is not empty, it will allow only users from that
|
|||
list.
|
||||
|
||||
#### `type = mention`
|
||||
|
||||
This filter is kinda similar to the `boost` one, but works with mentions.
|
||||
Also has `list` property, yada yada you got the idea, same deal with fnmatch.
|
||||
|
||||
#### `type = spoiler`
|
||||
|
||||
Matches posts with spoilers/content-warnings.
|
||||
|
||||
Has an optional `regexp` parameter that will allow you to specify regular
|
||||
expression to match your spoiler text.
|
||||
|
||||
#### `type = content`
|
||||
|
||||
Filter to match post content against either a regular expression, or a list of
|
||||
tags. Matching is done on the plaintext version of the post.
|
||||
|
||||
You can have one of two properties (but not both because fuck you): `tags` or
|
||||
`regexp`. It's obvious what does what: if you have `regexp` set, plaintext
|
||||
version of status is checked against that regular expression, and if you have
|
||||
`tags` set, then only statuses that have those tags will be allowed.
|
||||
`mode` property determines the type of operation. Can be either `regexp`,
|
||||
`tag` or `hashtag` (two last ones are the same).
|
||||
|
||||
Please note that in case of tags, you should NOT use `#` symbol in front of
|
||||
them.
|
||||
In `mode = regexp` you have to specify the `regexp` option with a regular
|
||||
expression to match against.
|
||||
|
||||
In `mode = tag` or `mode = hashtag`, `tags` option should contain a
|
||||
space-separated list of tags. If any of the tags are present in that list,
|
||||
filter will be triggered.
|
||||
|
||||
#### `type = visibility`
|
||||
|
||||
Simple filter that just checks for post visibility.
|
||||
Has a single property `options` that is a space-separated list of allowed
|
||||
visibility levels. Note that `direct` visibility is always ignored so cannot
|
||||
be used here.
|
||||
|
||||
#### `type = media`
|
||||
|
||||
Filter that allows only some media types to be posted.
|
||||
|
||||
`valid_media` is a space-separated list of media types from Mastodon API
|
||||
(`image`, `gifv`, `video`, `audio` or `unknown`). If your Fedi software has
|
||||
support for other types, they also should work.
|
||||
|
||||
`mode` option defines the mode of operation: it can be either `include`,
|
||||
`exclude` or `only`. In case of `include`, filter will trigger when post
|
||||
has media with that type, but others are allowed as well. `exclude` is the
|
||||
opposite: if status has media with that type, filter won't trigger. `only`
|
||||
allows statuses with either no media, or listed types only.
|
||||
|
||||
#### `type = combined`
|
||||
|
||||
The most powerful filter 'cause it allows you to combine multiple filters using
|
||||
different operations.
|
||||
|
||||
|
@ -265,8 +206,7 @@ some sort.
|
|||
|
||||
## Sample configurations
|
||||
|
||||
### For Telegram
|
||||
|
||||
### For Telegram:
|
||||
```ini
|
||||
[main]
|
||||
modules = tg
|
||||
|
@ -281,8 +221,7 @@ token = 12345:blahblahblah
|
|||
chat = 12345
|
||||
```
|
||||
|
||||
### For Telegram with a separate shitpost channel
|
||||
|
||||
### For Telegram with a separate shitpost channel:
|
||||
```ini
|
||||
[main]
|
||||
modules = tg tg-shitpost
|
||||
|
@ -299,7 +238,7 @@ filters = !shitpost
|
|||
|
||||
[module/tg-shitpost]
|
||||
type = telegram
|
||||
token = ${module/tg:token}
|
||||
token = 12345:blahblahblah
|
||||
chat = @shitposting
|
||||
filters = shitpost
|
||||
|
||||
|
@ -308,8 +247,3 @@ type = content
|
|||
mode = tag
|
||||
tags = shitpost
|
||||
```
|
||||
|
||||
## Asterisks
|
||||
|
||||
1. Well, most of the time that is.
|
||||
2. Works only when it has lists support.
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
[integrations,core] Add database support so remote messages are stored and can be used to reply to them
|
||||
[core] Somehow find a way to get your user ID by token
|
||||
[core] Maybe get rid of `main.list` field and create one automatically on a startup?
|
||||
[integrations] Add support for shellscript integration
|
||||
[integrations] Add formatting option
|
||||
[integrations] Add filters
|
||||
[integrations,vk] Add VK integration
|
22
config.ini
22
config.ini
|
@ -6,13 +6,8 @@ modules = telegram
|
|||
# Mastodon instance to grab posts from
|
||||
instance = mastodon.example.org
|
||||
|
||||
# Uncomment and change this if your instance makes invalid redirects
|
||||
# on the streaming path (like mastodon.social does). Check the following issue
|
||||
# for more details: https://github.com/hatkidchan/mastoposter/issues/45
|
||||
#streaming-url = wss://streaming.mastodon.example.org/api/v1/streaming
|
||||
|
||||
# Mastodon user token.
|
||||
# Required permissions: read:accounts read:statuses read:lists
|
||||
# Required permissions: read:statuses read:lists
|
||||
# You can get your token by creating application in
|
||||
# ${instance}/settings/applications
|
||||
token = blahblah
|
||||
|
@ -32,23 +27,10 @@ user = auto
|
|||
# address bar while you have that list open)
|
||||
list = 1
|
||||
|
||||
# Allow replies to be boosted as well
|
||||
# By default replies will be ignores unless it's a reply to your post
|
||||
# replies_to_other_accounts_should_not_be_skipped = yes
|
||||
|
||||
# Should we automatically reconnect to the streaming socket?
|
||||
# That option exists because it's not really a big deal when crossposter runs
|
||||
# as a service and restarts automatically by the service manager.
|
||||
auto-reconnect = yes
|
||||
reconnect-delay = 1.0
|
||||
|
||||
# Change websocket connection opening timeout.
|
||||
# It may be useful when initial server connection may take a long time.
|
||||
connect-timeout = 60.0
|
||||
|
||||
# Number of retries in case request fails. Applies globally
|
||||
# Can be changed on per-module basis
|
||||
http-retries = 5
|
||||
|
||||
# Example Telegram integration. You can use it as a template
|
||||
[module/telegram]
|
||||
|
@ -121,7 +103,7 @@ webhook = url
|
|||
;type = content
|
||||
;# Mode of the filter.
|
||||
;# "regexp" requires "regexp" property and should contain... A RegExp
|
||||
;# "tag" should contain space-separated list of tags
|
||||
;# "hashtag" should contain space-separated list of tags
|
||||
;mode = regexp
|
||||
;# Regular expression pattern to be matched
|
||||
;regexp = ^x-no-repost
|
||||
|
|
|
@ -1,26 +0,0 @@
|
|||
#!/sbin/openrc-run
|
||||
# mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
# Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
#
|
||||
# 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.
|
||||
|
||||
# shellcheck shell=sh
|
||||
|
||||
command="/usr/bin/mastoposter"
|
||||
command_args="${MASTOPOSTER_CONFIG_FILE:=/etc/mastoposter/config.ini}"
|
||||
command_background=1
|
||||
pidfile="/run/${RC_SVCNAME}.pid"
|
||||
output_log="/var/log/${RC_SVCNAME}.log"
|
||||
error_log="${output_log}"
|
||||
|
||||
depend() {
|
||||
need net
|
||||
}
|
|
@ -1,28 +0,0 @@
|
|||
# mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
# Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
#
|
||||
# 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.
|
||||
|
||||
[Unit]
|
||||
Description=Configurable reposter from Mastodon-compatible Fediverse servers
|
||||
After=network.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/mastoposter /etc/mastoposter/config.ini
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
StandardOutput=journal
|
||||
StandardError=inherit
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
|
@ -1,21 +1,5 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from asyncio import gather
|
||||
from configparser import ConfigParser
|
||||
from logging import getLogger
|
||||
from typing import Dict, List, Optional
|
||||
from mastoposter.filters import run_filters
|
||||
from mastoposter.filters.base import BaseFilter, FilterInstance
|
||||
|
@ -27,54 +11,33 @@ from mastoposter.integrations import (
|
|||
)
|
||||
from mastoposter.types import Status
|
||||
|
||||
__version__ = "0.2"
|
||||
__description__ = (
|
||||
"Configurable reposter from Mastodon-compatible Fediverse servers"
|
||||
)
|
||||
|
||||
logger = getLogger()
|
||||
|
||||
|
||||
def load_integrations_from(config: ConfigParser) -> List[FilteredIntegration]:
|
||||
modules: List[FilteredIntegration] = []
|
||||
for module_name in config.get("main", "modules").split():
|
||||
mod = config[f"module/{module_name}"]
|
||||
logger.info(
|
||||
"Configuring %s integration (type=%s)", module_name, mod["type"]
|
||||
)
|
||||
|
||||
filters: Dict[str, FilterInstance] = {}
|
||||
for filter_name in mod.get("filters", "").split():
|
||||
filter_basename = filter_name.lstrip("~!")
|
||||
|
||||
logger.info(
|
||||
"Loading filter %s for integration %s",
|
||||
filter_basename,
|
||||
module_name,
|
||||
)
|
||||
|
||||
filters[filter_basename] = BaseFilter.new_instance(
|
||||
filter_name, config[f"filter/{filter_basename}"]
|
||||
)
|
||||
|
||||
for finst in list(filters.values()):
|
||||
logger.info("Running post-initialization hook for %r", finst)
|
||||
finst.filter.post_init(filters, config)
|
||||
|
||||
# TODO: make a registry of integrations
|
||||
# INFO: mastoposter/integrations/base.py@__init__
|
||||
if mod["type"] == "telegram":
|
||||
modules.append(
|
||||
FilteredIntegration(
|
||||
TelegramIntegration.from_section(mod),
|
||||
list(filters.values()),
|
||||
TelegramIntegration(mod), list(filters.values())
|
||||
)
|
||||
)
|
||||
elif mod["type"] == "discord":
|
||||
modules.append(
|
||||
FilteredIntegration(
|
||||
DiscordIntegration.from_section(mod),
|
||||
list(filters.values()),
|
||||
DiscordIntegration(mod), list(filters.values())
|
||||
)
|
||||
)
|
||||
else:
|
||||
|
@ -85,7 +48,6 @@ def load_integrations_from(config: ConfigParser) -> List[FilteredIntegration]:
|
|||
async def execute_integrations(
|
||||
status: Status, sinks: List[FilteredIntegration]
|
||||
) -> List[Optional[str]]:
|
||||
logger.info("Executing integrations...")
|
||||
return await gather(
|
||||
*[sink[0](status) for sink in sinks if run_filters(sink[1], status)],
|
||||
return_exceptions=True,
|
||||
|
|
|
@ -1,161 +1,78 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
from argparse import ArgumentParser
|
||||
from asyncio import run
|
||||
from configparser import ConfigParser, ExtendedInterpolation
|
||||
from logging import (
|
||||
INFO,
|
||||
Formatter,
|
||||
Logger,
|
||||
StreamHandler,
|
||||
getLevelName,
|
||||
getLogger,
|
||||
)
|
||||
from os import getenv
|
||||
from sys import stdout
|
||||
from typing import AsyncGenerator, Callable, List
|
||||
|
||||
from httpx import Client, HTTPTransport
|
||||
|
||||
from mastoposter import (
|
||||
execute_integrations,
|
||||
load_integrations_from,
|
||||
__version__,
|
||||
__description__,
|
||||
)
|
||||
from mastoposter import execute_integrations, load_integrations_from
|
||||
from mastoposter.integrations import FilteredIntegration
|
||||
from mastoposter.sources import websocket_source
|
||||
from typing import AsyncGenerator, Callable, List
|
||||
from mastoposter.types import Account, Status
|
||||
from mastoposter.utils import normalize_config
|
||||
from httpx import Client
|
||||
|
||||
|
||||
WSOCK_TEMPLATE = "wss://{instance}/api/v1/streaming"
|
||||
VERIFY_CREDS_TEMPLATE = "https://{instance}/api/v1/accounts/verify_credentials"
|
||||
|
||||
logger = getLogger()
|
||||
|
||||
|
||||
def init_logger(loglevel: int = INFO):
|
||||
stdout_handler = StreamHandler(stdout)
|
||||
stdout_handler.setLevel(loglevel)
|
||||
formatter = Formatter("[%(asctime)s][%(levelname)5s:%(name)s] %(message)s")
|
||||
stdout_handler.setFormatter(formatter)
|
||||
logger.addHandler(stdout_handler)
|
||||
logger.setLevel(loglevel)
|
||||
for log in logger.manager.loggerDict.values():
|
||||
if isinstance(log, Logger):
|
||||
log.setLevel(loglevel)
|
||||
|
||||
|
||||
async def listen(
|
||||
source: Callable[..., AsyncGenerator[Status, None]],
|
||||
drains: List[FilteredIntegration],
|
||||
user: str,
|
||||
replies_to_other_accounts_should_not_be_skipped: bool = False,
|
||||
/,
|
||||
**kwargs,
|
||||
):
|
||||
logger.info("Starting listening...")
|
||||
async for status in source(**kwargs):
|
||||
logger.info("New status: %s", status.uri)
|
||||
logger.debug("Got status: %r", status)
|
||||
if status.account.id != user and user != "all":
|
||||
logger.info(
|
||||
"Skipping status %s (account.id=%r != %r)",
|
||||
status.uri,
|
||||
status.account.id,
|
||||
user,
|
||||
)
|
||||
if status.account.id != user:
|
||||
continue
|
||||
|
||||
# TODO: add option/filter to handle that
|
||||
if status.visibility in ("direct",):
|
||||
logger.info(
|
||||
"Skipping post %s (status.visibility=%r)",
|
||||
status.uri,
|
||||
status.visibility,
|
||||
)
|
||||
continue
|
||||
|
||||
# TODO: find a better way to handle threads
|
||||
if (
|
||||
status.in_reply_to_account_id is not None
|
||||
and status.in_reply_to_account_id != user
|
||||
) and not replies_to_other_accounts_should_not_be_skipped:
|
||||
logger.info(
|
||||
"Skipping post %s because it's a reply to another person",
|
||||
status.uri,
|
||||
)
|
||||
):
|
||||
continue
|
||||
|
||||
logger.info(await execute_integrations(status, drains))
|
||||
await execute_integrations(status, drains)
|
||||
|
||||
|
||||
def main():
|
||||
parser = ArgumentParser(prog="mastoposter", description=__description__)
|
||||
parser.add_argument(
|
||||
"config", nargs="?", default=getenv("MASTOPOSTER_CONFIG_FILE")
|
||||
)
|
||||
parser.add_argument("-v", action="version", version=__version__)
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.config:
|
||||
raise RuntimeError("No config file. Aborting")
|
||||
|
||||
def main(config_path: str):
|
||||
conf = ConfigParser(interpolation=ExtendedInterpolation())
|
||||
conf.read(args.config)
|
||||
init_logger(getLevelName(conf["main"].get("loglevel", "INFO")))
|
||||
normalize_config(conf)
|
||||
conf.read(config_path)
|
||||
|
||||
for section in conf.sections():
|
||||
_remove = set()
|
||||
for k, v in conf[section].items():
|
||||
normalized_key = k.replace(" ", "_").replace("-", "_")
|
||||
if k == normalized_key:
|
||||
continue
|
||||
conf[section][normalized_key] = v
|
||||
_remove.add(k)
|
||||
for k in _remove:
|
||||
del conf[section][k]
|
||||
|
||||
modules: List[FilteredIntegration] = load_integrations_from(conf)
|
||||
retries: int = conf["main"].getint("http-retries", 5)
|
||||
|
||||
logger.info("Loaded %d integrations", len(modules))
|
||||
|
||||
user_id: str = conf["main"]["user"]
|
||||
if user_id == "auto":
|
||||
logger.info("config.main.user is set to auto, getting user ID")
|
||||
with Client(transport=HTTPTransport(retries=retries)) as c:
|
||||
with Client() as c:
|
||||
rq = c.get(
|
||||
VERIFY_CREDS_TEMPLATE.format(**conf["main"]),
|
||||
params={"access_token": conf["main"]["token"]},
|
||||
)
|
||||
user_id = Account.from_dict(rq.json()).id
|
||||
|
||||
logger.info("account.id=%s", user_id)
|
||||
|
||||
url = conf["main"].get(
|
||||
"streaming_url",
|
||||
"wss://{}/api/v1/streaming".format(conf["main"]["instance"]),
|
||||
)
|
||||
account = Account.from_dict(rq.json())
|
||||
user_id = account.id
|
||||
|
||||
url = "wss://{}/api/v1/streaming".format(conf["main"]["instance"])
|
||||
run(
|
||||
listen(
|
||||
websocket_source,
|
||||
modules,
|
||||
user_id,
|
||||
url=url,
|
||||
replies_to_other_accounts_should_not_be_skipped=conf[
|
||||
"main"
|
||||
].getboolean(
|
||||
"replies_to_other_accounts_should_not_be_skipped", False
|
||||
),
|
||||
reconnect=conf["main"].getboolean("auto_reconnect", False),
|
||||
reconnect_delay=conf["main"].getfloat("reconnect_delay", 1.0),
|
||||
connect_timeout=conf["main"].getfloat("connect_timeout", 60.0),
|
||||
list=conf["main"]["list"],
|
||||
access_token=conf["main"]["token"],
|
||||
)
|
||||
|
@ -163,4 +80,6 @@ def main():
|
|||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
from sys import argv
|
||||
|
||||
main(argv[1])
|
||||
|
|
|
@ -1,19 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from logging import getLogger
|
||||
from typing import List
|
||||
|
||||
from mastoposter.types import Status
|
||||
|
@ -26,26 +10,8 @@ from mastoposter.filters.text import TextFilter # NOQA
|
|||
from mastoposter.filters.spoiler import SpoilerFilter # NOQA
|
||||
from mastoposter.filters.visibility import VisibilityFilter # NOQA
|
||||
|
||||
logger = getLogger("filters")
|
||||
|
||||
|
||||
def run_filters(filters: List[FilterInstance], status: Status) -> bool:
|
||||
logger.debug("Running filters on %r", status.id)
|
||||
|
||||
if not filters:
|
||||
logger.debug("No filters, returning True")
|
||||
return True
|
||||
|
||||
results: List[bool] = []
|
||||
for fil in filters:
|
||||
result = fil.filter(status)
|
||||
logger.debug(
|
||||
"%r -> %r ^ %r -> %r",
|
||||
fil.filter,
|
||||
result,
|
||||
fil.inverse,
|
||||
result ^ fil.inverse,
|
||||
)
|
||||
results.append(result ^ fil.inverse)
|
||||
logger.debug("Result: %r", all(results))
|
||||
return all(results)
|
||||
return all((fil.filter(status) ^ fil.inverse for fil in filters))
|
||||
|
|
|
@ -1,18 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from configparser import ConfigParser, SectionProxy
|
||||
from typing import ClassVar, Dict, NamedTuple, Type
|
||||
|
@ -38,8 +23,8 @@ class BaseFilter(ABC):
|
|||
|
||||
filter_name: ClassVar[str] = "_base"
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
def __init__(self, section: SectionProxy):
|
||||
UNUSED(section)
|
||||
|
||||
def __init_subclass__(cls, filter_name: str, **kwargs):
|
||||
super().__init_subclass__(**kwargs)
|
||||
|
@ -66,11 +51,7 @@ class BaseFilter(ABC):
|
|||
def load_filter(cls, name: str, section: SectionProxy) -> "BaseFilter":
|
||||
if name not in cls.FILTER_REGISTRY:
|
||||
raise KeyError(f"no filter with name {name!r} was found")
|
||||
return cls.FILTER_REGISTRY[name].from_section(section)
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "BaseFilter":
|
||||
raise NotImplementedError
|
||||
return cls.FILTER_REGISTRY[name](section)
|
||||
|
||||
@classmethod
|
||||
def new_instance(cls, name: str, section: SectionProxy) -> FilterInstance:
|
||||
|
|
|
@ -1,33 +1,13 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from fnmatch import fnmatch
|
||||
from typing import List
|
||||
from mastoposter.filters.base import BaseFilter
|
||||
from mastoposter.types import Status
|
||||
|
||||
|
||||
class BoostFilter(BaseFilter, filter_name="boost"):
|
||||
def __init__(self, accounts: List[str]):
|
||||
super().__init__()
|
||||
self.list = accounts
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "BoostFilter":
|
||||
return cls(section["list"].split())
|
||||
def __init__(self, section: SectionProxy):
|
||||
super().__init__(section)
|
||||
self.list = section.get("list", "").split()
|
||||
|
||||
@classmethod
|
||||
def check_account(cls, acct: str, mask: str) -> bool:
|
||||
|
|
|
@ -1,18 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import ConfigParser, SectionProxy
|
||||
from typing import Callable, ClassVar, Dict, List, Sequence
|
||||
from mastoposter.filters.base import BaseFilter, FilterInstance
|
||||
|
@ -26,26 +11,19 @@ class CombinedFilter(BaseFilter, filter_name="combined"):
|
|||
"single": lambda d: sum(d) == 1,
|
||||
}
|
||||
|
||||
def __init__(self, filter_names: List[str], operator: str):
|
||||
self._filter_names = filter_names
|
||||
self._operator_name = operator
|
||||
self.operator = self.OPERATORS[self._operator_name]
|
||||
def __init__(self, section: SectionProxy):
|
||||
self.filter_names = section.get("filters", "").split()
|
||||
self.operator = self.OPERATORS[section.get("operator", "all")]
|
||||
self._operator_name = section.get("operator", "all")
|
||||
self.filters: List[FilterInstance] = []
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "CombinedFilter":
|
||||
return cls(
|
||||
filter_names=section["filters"].split(),
|
||||
operator=section.get("operator", "all"),
|
||||
)
|
||||
|
||||
def post_init(
|
||||
self, filters: Dict[str, FilterInstance], config: ConfigParser
|
||||
):
|
||||
super().post_init(filters, config)
|
||||
self.filters = [
|
||||
self.new_instance(name, config["filter/" + name.lstrip("~!")])
|
||||
for name in self._filter_names
|
||||
for name in self.filter_names
|
||||
]
|
||||
|
||||
def __call__(self, post: Status) -> bool:
|
||||
|
@ -54,12 +32,7 @@ class CombinedFilter(BaseFilter, filter_name="combined"):
|
|||
return self.operator([f[1](post) ^ f[0] for f in self.filters])
|
||||
|
||||
def __repr__(self):
|
||||
if self.filters:
|
||||
return (
|
||||
f"Filter:combined(op={self._operator_name}, "
|
||||
f"filters={self.filters!r})"
|
||||
)
|
||||
return (
|
||||
f"Filter:combined(op={self._operator_name}, "
|
||||
f"filters={self._filter_names!r}, loaded=False)"
|
||||
f"filters={self.filters!r})"
|
||||
)
|
||||
|
|
|
@ -1,41 +1,16 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from typing import Literal, Set
|
||||
from typing import Set
|
||||
from mastoposter.filters.base import BaseFilter
|
||||
from mastoposter.types import Status
|
||||
|
||||
|
||||
class MediaFilter(BaseFilter, filter_name="media"):
|
||||
def __init__(
|
||||
self,
|
||||
valid_media: Set[str],
|
||||
mode: Literal["include", "exclude", "only"],
|
||||
):
|
||||
super().__init__()
|
||||
self.valid_media: Set[str] = valid_media
|
||||
self.mode = mode
|
||||
assert self.mode in ("include", "exclude", "only")
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "MediaFilter":
|
||||
return cls(
|
||||
valid_media=set(section["valid_media"].split()),
|
||||
mode=section.get("mode", "include"), # type: ignore
|
||||
)
|
||||
def __init__(self, section: SectionProxy):
|
||||
super().__init__(section)
|
||||
self.valid_media: Set[str] = set(section.get("valid_media").split())
|
||||
self.mode = section.get("mode", "include")
|
||||
if self.mode not in ("include", "exclude", "only"):
|
||||
raise ValueError(f"{self.mode=} is not valid")
|
||||
|
||||
def __call__(self, status: Status) -> bool:
|
||||
if not status.media_attachments:
|
||||
|
|
|
@ -1,21 +1,6 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from re import Pattern, compile as regexp
|
||||
from typing import ClassVar, Set
|
||||
from typing import ClassVar
|
||||
from fnmatch import fnmatch
|
||||
from mastoposter.filters.base import BaseFilter
|
||||
from mastoposter.types import Status
|
||||
|
@ -24,27 +9,22 @@ from mastoposter.types import Status
|
|||
class MentionFilter(BaseFilter, filter_name="mention"):
|
||||
MENTION_REGEX: ClassVar[Pattern] = regexp(r"@([^@]+)(@([^@]+))?")
|
||||
|
||||
def __init__(self, accounts: Set[str]):
|
||||
super().__init__()
|
||||
self.accounts = accounts
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "MentionFilter":
|
||||
return cls(set(section.get("list", "").split()))
|
||||
def __init__(self, section: SectionProxy):
|
||||
super().__init__(section)
|
||||
self.list = section.get("list", "").split()
|
||||
|
||||
@classmethod
|
||||
def check_account(cls, acct: str, mask: str) -> bool:
|
||||
return fnmatch("@" + acct, mask)
|
||||
|
||||
def __call__(self, status: Status) -> bool:
|
||||
if not self.accounts and status.mentions:
|
||||
if not self.list and status.mentions:
|
||||
return True
|
||||
# XXX: make it better somehow. and faster. and stronger.
|
||||
return any(
|
||||
(
|
||||
any(
|
||||
self.check_account(mention.acct, mask)
|
||||
for mask in self.accounts
|
||||
for mask in self.list
|
||||
)
|
||||
for mention in status.mentions
|
||||
)
|
||||
|
@ -52,7 +32,5 @@ class MentionFilter(BaseFilter, filter_name="mention"):
|
|||
|
||||
def __repr__(self):
|
||||
return str.format(
|
||||
"Filter:{name}({list!r})",
|
||||
name=self.filter_name,
|
||||
list=self.accounts,
|
||||
"Filter:{name}({list!r})", name=self.filter_name, list=self.list
|
||||
)
|
||||
|
|
|
@ -1,18 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from re import Pattern, compile as regexp
|
||||
from mastoposter.filters.base import BaseFilter
|
||||
|
@ -20,13 +5,9 @@ from mastoposter.types import Status
|
|||
|
||||
|
||||
class SpoilerFilter(BaseFilter, filter_name="spoiler"):
|
||||
def __init__(self, regex: str = "^.*$"):
|
||||
super().__init__()
|
||||
self.regexp: Pattern = regexp(regex)
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "SpoilerFilter":
|
||||
return cls(section.get("regexp", section.get("regex", "^.*$")))
|
||||
def __init__(self, section: SectionProxy):
|
||||
super().__init__(section)
|
||||
self.regexp: Pattern = regexp(section.get("regexp", "^.*$"))
|
||||
|
||||
def __call__(self, status: Status) -> bool:
|
||||
return self.regexp.match(status.spoiler_text) is not None
|
||||
|
|
|
@ -1,50 +1,50 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from re import Pattern, compile as regexp
|
||||
from typing import Optional, Set
|
||||
|
||||
from bs4 import BeautifulSoup, PageElement, Tag
|
||||
from mastoposter.filters.base import BaseFilter
|
||||
from mastoposter.types import Status
|
||||
|
||||
|
||||
class TextFilter(BaseFilter, filter_name="content"):
|
||||
def __init__(
|
||||
self, regex: Optional[str] = None, tags: Optional[Set[str]] = None
|
||||
):
|
||||
super().__init__()
|
||||
assert regex is not None or tags
|
||||
def __init__(self, section: SectionProxy):
|
||||
super().__init__(section)
|
||||
self.mode = section["mode"]
|
||||
self.tags: Set[str] = set()
|
||||
self.regexp: Optional[Pattern] = None
|
||||
|
||||
self.tags: Optional[Set[str]] = tags
|
||||
self.regexp: Optional[Pattern] = regexp(regex) if regex else None
|
||||
if self.mode == "regexp":
|
||||
self.regexp = regexp(section["regexp"])
|
||||
elif self.mode in ("hashtag", "tag"):
|
||||
self.tags = set(map(str.lower, section["tags"].split()))
|
||||
else:
|
||||
raise ValueError(f"Invalid filter mode {self.mode}")
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "TextFilter":
|
||||
if "regexp" in section and "tags" in section:
|
||||
raise AssertionError("you can't use both tags and regexp")
|
||||
elif "regexp" in section:
|
||||
return cls(regex=section["regexp"])
|
||||
elif "tags" in section:
|
||||
return cls(tags=set(section["tags"].split()))
|
||||
raise AssertionError("neither regexp or tags were set")
|
||||
def node_to_text(cls, el: PageElement) -> str:
|
||||
if isinstance(el, Tag):
|
||||
if el.name == "br":
|
||||
return "\n"
|
||||
elif el.name == "p":
|
||||
return (
|
||||
str.join("", map(cls.node_to_text, el.children)) + "\n\n"
|
||||
)
|
||||
return str.join("", map(cls.node_to_text, el.children))
|
||||
return str(el)
|
||||
|
||||
@classmethod
|
||||
def html_to_plain(cls, html: str) -> str:
|
||||
soup = BeautifulSoup(html, "lxml")
|
||||
return cls.node_to_text(soup).rstrip()
|
||||
|
||||
def __call__(self, status: Status) -> bool:
|
||||
source = status.reblog or status
|
||||
if self.regexp is not None:
|
||||
return self.regexp.search(source.content_plaintext) is not None
|
||||
return (
|
||||
self.regexp.match(self.html_to_plain(source.content))
|
||||
is not None
|
||||
)
|
||||
elif self.tags:
|
||||
return len(self.tags & {t.name.lower() for t in source.tags}) > 0
|
||||
else:
|
||||
|
@ -63,4 +63,3 @@ class TextFilter(BaseFilter, filter_name="content"):
|
|||
name=self.filter_name,
|
||||
tags=self.tags,
|
||||
)
|
||||
return "Filter:{name}(invalid)".format(name=self.filter_name)
|
||||
|
|
|
@ -1,32 +1,12 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from typing import Set
|
||||
from mastoposter.filters.base import BaseFilter
|
||||
from mastoposter.types import Status
|
||||
|
||||
|
||||
class VisibilityFilter(BaseFilter, filter_name="visibility"):
|
||||
def __init__(self, options: Set[str]):
|
||||
super().__init__()
|
||||
self.options = options
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "BaseFilter":
|
||||
return cls(set(section["options"].split()))
|
||||
def __init__(self, section: SectionProxy):
|
||||
super().__init__(section)
|
||||
self.options = set(section["options"].split())
|
||||
|
||||
def __call__(self, status: Status) -> bool:
|
||||
return status.visibility in self.options
|
||||
|
|
|
@ -1,18 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from typing import List, NamedTuple
|
||||
from mastoposter.filters.base import FilterInstance
|
||||
|
||||
|
|
|
@ -1,18 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from configparser import SectionProxy
|
||||
from typing import Optional
|
||||
|
@ -21,14 +6,9 @@ from mastoposter.types import Status
|
|||
|
||||
|
||||
class BaseIntegration(ABC):
|
||||
# TODO: make a registry of integrations
|
||||
def __init__(self):
|
||||
def __init__(self, section: SectionProxy):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "BaseIntegration":
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def __call__(self, status: Status) -> Optional[str]:
|
||||
raise NotImplementedError
|
||||
|
|
|
@ -1,22 +1,6 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from logging import getLogger
|
||||
from typing import List, Optional
|
||||
from httpx import AsyncClient, AsyncHTTPTransport
|
||||
from httpx import AsyncClient
|
||||
from zlib import crc32
|
||||
from mastoposter.integrations.base import BaseIntegration
|
||||
from mastoposter.integrations.discord.types import (
|
||||
|
@ -26,17 +10,10 @@ from mastoposter.integrations.discord.types import (
|
|||
)
|
||||
from mastoposter.types import Status
|
||||
|
||||
logger = getLogger("integrations.discord")
|
||||
|
||||
|
||||
class DiscordIntegration(BaseIntegration):
|
||||
def __init__(self, webhook: str, retries: int = 5):
|
||||
self.webhook = webhook
|
||||
self.retries = retries
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "DiscordIntegration":
|
||||
return cls(section["webhook"], section.getint("retries", 5))
|
||||
def __init__(self, section: SectionProxy):
|
||||
self.webhook = section.get("webhook", "")
|
||||
|
||||
async def execute_webhook(
|
||||
self,
|
||||
|
@ -44,30 +21,22 @@ class DiscordIntegration(BaseIntegration):
|
|||
username: Optional[str] = None,
|
||||
avatar_url: Optional[str] = None,
|
||||
embeds: Optional[List[DiscordEmbed]] = None,
|
||||
) -> None:
|
||||
async with AsyncClient(
|
||||
transport=AsyncHTTPTransport(retries=self.retries)
|
||||
) as c:
|
||||
) -> dict:
|
||||
async with AsyncClient() as c:
|
||||
json = {
|
||||
"content": content,
|
||||
"username": username,
|
||||
"avatar_url": avatar_url,
|
||||
"embeds": (
|
||||
[embed.asdict() for embed in embeds]
|
||||
if embeds is not None
|
||||
else []
|
||||
),
|
||||
"embeds": [embed.asdict() for embed in embeds]
|
||||
if embeds is not None
|
||||
else [],
|
||||
}
|
||||
|
||||
logger.debug("Executing webhook with %r", json)
|
||||
|
||||
result = (
|
||||
return (
|
||||
await c.post(
|
||||
self.webhook,
|
||||
json=json,
|
||||
)
|
||||
).json()
|
||||
logger.debug("Result: %r", result)
|
||||
|
||||
async def __call__(self, status: Status) -> Optional[str]:
|
||||
source = status.reblog or status
|
||||
|
@ -109,11 +78,6 @@ class DiscordIntegration(BaseIntegration):
|
|||
),
|
||||
)
|
||||
)
|
||||
else:
|
||||
logger.warn(
|
||||
"Unsupported attachment %r for Discord Embed",
|
||||
attachment.type,
|
||||
)
|
||||
|
||||
await self.execute_webhook(
|
||||
username=status.account.acct,
|
||||
|
|
|
@ -1,18 +1,3 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
|
|
@ -1,32 +1,13 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import SectionProxy
|
||||
from dataclasses import dataclass
|
||||
from logging import getLogger
|
||||
from typing import Any, List, Mapping, Optional, Tuple
|
||||
from httpx import AsyncClient, AsyncHTTPTransport
|
||||
from typing import Any, List, Mapping, Optional
|
||||
from httpx import AsyncClient
|
||||
from jinja2 import Template
|
||||
from mastoposter.integrations.base import BaseIntegration
|
||||
from mastoposter.types import Attachment, Poll, Status
|
||||
from emoji import emojize
|
||||
|
||||
|
||||
logger = getLogger("integrations.telegram")
|
||||
|
||||
|
||||
@dataclass
|
||||
class TGResponse:
|
||||
ok: bool
|
||||
|
@ -59,13 +40,6 @@ MEDIA_MAPPING: Mapping[str, str] = {
|
|||
"audio": "audio",
|
||||
"unknown": "document",
|
||||
}
|
||||
MEDIA_SPOILER_SUPPORT: Mapping[str, bool] = {
|
||||
"image": True,
|
||||
"video": True,
|
||||
"gifv": True,
|
||||
"audio": False,
|
||||
"unknown": False,
|
||||
}
|
||||
DEFAULT_TEMPLATE: str = """\
|
||||
{% if status.reblog %}\
|
||||
Boost from <a href="{{status.reblog.account.url}}">\
|
||||
|
@ -80,57 +54,23 @@ Boost from <a href="{{status.reblog.account.url}}">\
|
|||
|
||||
|
||||
class TelegramIntegration(BaseIntegration):
|
||||
def __init__(
|
||||
self,
|
||||
token: str,
|
||||
chat_id: str,
|
||||
template: Optional[Template] = None,
|
||||
silent: bool = True,
|
||||
retries: int = 5,
|
||||
):
|
||||
self.token = token
|
||||
self.chat_id = chat_id
|
||||
self.silent = silent
|
||||
self.retries = retries
|
||||
|
||||
if template is None:
|
||||
self.template = Template(emojize(DEFAULT_TEMPLATE))
|
||||
else:
|
||||
self.template = template
|
||||
|
||||
@classmethod
|
||||
def from_section(cls, section: SectionProxy) -> "TelegramIntegration":
|
||||
return cls(
|
||||
token=section["token"],
|
||||
chat_id=section["chat"],
|
||||
template=Template(
|
||||
emojize(section.get("template", DEFAULT_TEMPLATE))
|
||||
),
|
||||
silent=section.getboolean("silent", True),
|
||||
retries=section.getint("http_retries", 5),
|
||||
def __init__(self, sect: SectionProxy):
|
||||
self.token = sect.get("token", "")
|
||||
self.chat_id = sect.get("chat", "")
|
||||
self.silent = sect.getboolean("silent", True)
|
||||
self.template: Template = Template(
|
||||
emojize(sect.get("template", DEFAULT_TEMPLATE))
|
||||
)
|
||||
|
||||
async def _tg_request(
|
||||
self, client: AsyncClient, method: str, **kwargs
|
||||
) -> TGResponse:
|
||||
async def _tg_request(self, method: str, **kwargs) -> TGResponse:
|
||||
url = API_URL.format(self.token, method)
|
||||
logger.debug("TG request: %s(%r)", method, kwargs)
|
||||
response = TGResponse.from_dict(
|
||||
(await client.post(url, json=kwargs)).json(), kwargs
|
||||
)
|
||||
if not response.ok:
|
||||
logger.error("TG error: %r", response.error)
|
||||
logger.error("parameters: %r", kwargs)
|
||||
else:
|
||||
logger.debug("Result: %r", response.result)
|
||||
return response
|
||||
async with AsyncClient() as client:
|
||||
return TGResponse.from_dict(
|
||||
(await client.post(url, json=kwargs)).json(), kwargs
|
||||
)
|
||||
|
||||
async def _post_plaintext(
|
||||
self, client: AsyncClient, text: str
|
||||
) -> TGResponse:
|
||||
logger.debug("Sending HTML message: %r", text)
|
||||
async def _post_plaintext(self, text: str) -> TGResponse:
|
||||
return await self._tg_request(
|
||||
client,
|
||||
"sendMessage",
|
||||
parse_mode="HTML",
|
||||
disable_notification=self.silent,
|
||||
|
@ -139,22 +79,12 @@ class TelegramIntegration(BaseIntegration):
|
|||
text=text,
|
||||
)
|
||||
|
||||
async def _post_media(
|
||||
self,
|
||||
client: AsyncClient,
|
||||
text: str,
|
||||
media: Attachment,
|
||||
spoiler: bool = False,
|
||||
) -> TGResponse:
|
||||
async def _post_media(self, text: str, media: Attachment) -> TGResponse:
|
||||
# Just to be safe
|
||||
if media.type not in MEDIA_MAPPING:
|
||||
logger.warning(
|
||||
"Media %r has unknown type, falling back to plaintext", media
|
||||
)
|
||||
return await self._post_plaintext(client, text)
|
||||
return await self._post_plaintext(text)
|
||||
|
||||
return await self._tg_request(
|
||||
client,
|
||||
"send%s" % MEDIA_MAPPING[media.type].title(),
|
||||
parse_mode="HTML",
|
||||
disable_notification=self.silent,
|
||||
|
@ -162,51 +92,25 @@ class TelegramIntegration(BaseIntegration):
|
|||
chat_id=self.chat_id,
|
||||
caption=text,
|
||||
**{MEDIA_MAPPING[media.type]: media.url},
|
||||
**(
|
||||
{"has_spoiler": spoiler}
|
||||
if MEDIA_SPOILER_SUPPORT.get(media.type, False)
|
||||
else {}
|
||||
),
|
||||
)
|
||||
|
||||
async def _post_mediagroup(
|
||||
self,
|
||||
client: AsyncClient,
|
||||
text: str,
|
||||
media: List[Attachment],
|
||||
spoiler: bool = False,
|
||||
) -> Tuple[TGResponse, List[Attachment]]:
|
||||
logger.debug("Sendind media group: %r (text=%r)", media, text)
|
||||
self, text: str, media: List[Attachment]
|
||||
) -> TGResponse:
|
||||
media_list: List[dict] = []
|
||||
allowed_medias = {"image", "gifv", "video", "audio", "unknown"}
|
||||
unused: List[Attachment] = []
|
||||
for attachment in media:
|
||||
if attachment.type not in allowed_medias:
|
||||
continue
|
||||
if attachment.type not in MEDIA_COMPATIBILITY:
|
||||
logger.warning(
|
||||
"attachment %r is not in %r",
|
||||
attachment.type,
|
||||
MEDIA_COMPATIBILITY,
|
||||
)
|
||||
continue
|
||||
|
||||
if attachment.type not in allowed_medias or len(media_list) >= 10:
|
||||
unused.append(attachment)
|
||||
continue
|
||||
|
||||
allowed_medias &= MEDIA_COMPATIBILITY[attachment.type]
|
||||
|
||||
media_list.append(
|
||||
{
|
||||
"type": MEDIA_MAPPING[attachment.type],
|
||||
"media": attachment.url,
|
||||
**(
|
||||
{"has_spoiler": spoiler}
|
||||
if MEDIA_SPOILER_SUPPORT.get(attachment.type, False)
|
||||
else {}
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
if len(media_list) == 1:
|
||||
media_list[0].update(
|
||||
{
|
||||
|
@ -215,24 +119,18 @@ class TelegramIntegration(BaseIntegration):
|
|||
}
|
||||
)
|
||||
|
||||
return (
|
||||
await self._tg_request(
|
||||
client,
|
||||
"sendMediaGroup",
|
||||
disable_notification=self.silent,
|
||||
disable_web_page_preview=True,
|
||||
chat_id=self.chat_id,
|
||||
media=media_list,
|
||||
),
|
||||
unused,
|
||||
return await self._tg_request(
|
||||
"sendMediaGroup",
|
||||
disable_notification=self.silent,
|
||||
disable_web_page_preview=True,
|
||||
chat_id=self.chat_id,
|
||||
media=media_list,
|
||||
)
|
||||
|
||||
async def _post_poll(
|
||||
self, client: AsyncClient, poll: Poll, reply_to: Optional[str] = None
|
||||
self, poll: Poll, reply_to: Optional[str] = None
|
||||
) -> TGResponse:
|
||||
logger.debug("Sending poll: %r", poll)
|
||||
return await self._tg_request(
|
||||
client,
|
||||
"sendPoll",
|
||||
disable_notification=self.silent,
|
||||
disable_web_page_preview=True,
|
||||
|
@ -246,59 +144,44 @@ class TelegramIntegration(BaseIntegration):
|
|||
async def __call__(self, status: Status) -> Optional[str]:
|
||||
source = status.reblog or status
|
||||
|
||||
has_spoiler = source.sensitive
|
||||
text = self.template.render({"status": status})
|
||||
|
||||
ids = []
|
||||
|
||||
async with AsyncClient(
|
||||
transport=AsyncHTTPTransport(retries=self.retries)
|
||||
) as client:
|
||||
if not source.media_attachments:
|
||||
if (res := await self._post_plaintext(client, text)).ok:
|
||||
if res.result:
|
||||
ids.append(res.result["message_id"])
|
||||
|
||||
elif len(source.media_attachments) == 1:
|
||||
if (
|
||||
res := await self._post_media(
|
||||
client, text, source.media_attachments[0], has_spoiler
|
||||
)
|
||||
).ok and res.result is not None:
|
||||
if not source.media_attachments:
|
||||
if (res := await self._post_plaintext(text)).ok:
|
||||
if res.result:
|
||||
ids.append(res.result["message_id"])
|
||||
else:
|
||||
pending, i = source.media_attachments, 0
|
||||
while len(pending) > 0 and i < 5:
|
||||
res, left = await self._post_mediagroup(
|
||||
client, text if i == 0 else "", pending, has_spoiler
|
||||
)
|
||||
if res.ok and res.result is not None:
|
||||
ids.extend([msg["message_id"] for msg in res.result])
|
||||
pending = left
|
||||
i += 1
|
||||
|
||||
if source.poll:
|
||||
if (
|
||||
res := await self._post_poll(
|
||||
client, source.poll, reply_to=ids[0] if ids else None
|
||||
)
|
||||
).ok and res.result:
|
||||
ids.append(res.result["message_id"])
|
||||
elif len(source.media_attachments) == 1:
|
||||
if (
|
||||
res := await self._post_media(
|
||||
text, source.media_attachments[0]
|
||||
)
|
||||
).ok and res.result is not None:
|
||||
ids.append(res.result["message_id"])
|
||||
else:
|
||||
if (
|
||||
res := await self._post_mediagroup(
|
||||
text, source.media_attachments
|
||||
)
|
||||
).ok and res.result is not None:
|
||||
ids.append(res.result["message_id"])
|
||||
|
||||
if source.poll:
|
||||
if (
|
||||
res := await self._post_poll(
|
||||
source.poll, reply_to=ids[0] if ids else None
|
||||
)
|
||||
).ok and res.result:
|
||||
ids.append(res.result["message_id"])
|
||||
|
||||
return str.join(",", map(str, ids))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
bot_uid, key = self.token.split(":")
|
||||
return (
|
||||
"<TelegramIntegration "
|
||||
"chat_id={chat!r} "
|
||||
"template={template!r} "
|
||||
"token={bot_uid}:{key} "
|
||||
"silent={silent!r}>"
|
||||
).format(
|
||||
chat=self.chat_id,
|
||||
silent=self.silent,
|
||||
template=self.template,
|
||||
bot_uid=bot_uid,
|
||||
key=str.join("", ("X" for _ in key)),
|
||||
)
|
||||
).format(chat=self.chat_id, silent=self.silent, template=self.template)
|
||||
|
|
|
@ -1,68 +1,27 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from asyncio import exceptions, sleep
|
||||
from asyncio import exceptions
|
||||
from json import loads
|
||||
from logging import getLogger
|
||||
from typing import AsyncGenerator
|
||||
from urllib.parse import urlencode
|
||||
from mastoposter.types import Status
|
||||
|
||||
logger = getLogger("sources")
|
||||
from mastoposter.types import Status
|
||||
|
||||
|
||||
async def websocket_source(
|
||||
url: str, reconnect: bool = False, reconnect_delay: float = 1.0,
|
||||
connect_timeout: float = 60.0, **params
|
||||
url: str, reconnect: bool = False, **params
|
||||
) -> AsyncGenerator[Status, None]:
|
||||
from websockets.client import connect
|
||||
from websockets.exceptions import WebSocketException
|
||||
|
||||
param_dict = {"stream": "list", **params}
|
||||
public_param_dict = param_dict.copy()
|
||||
public_param_dict["access_token"] = 'SCRUBBED'
|
||||
public_url = f"{url}?" + urlencode(public_param_dict)
|
||||
url = f"{url}?" + urlencode(param_dict)
|
||||
url = f"{url}?" + urlencode({"stream": "list", **params})
|
||||
while True:
|
||||
try:
|
||||
logger.info("attempting to connect to %s", public_url)
|
||||
async with connect(url, open_timeout=connect_timeout) as ws:
|
||||
logger.info("Connected to WebSocket")
|
||||
async with connect(url) as ws:
|
||||
while (msg := await ws.recv()) is not None:
|
||||
event = loads(msg)
|
||||
logger.debug("data: %r", event)
|
||||
if "error" in event:
|
||||
raise Exception(event["error"])
|
||||
if event["event"] == "update":
|
||||
yield Status.from_dict(loads(event["payload"]))
|
||||
else:
|
||||
logger.warn("unknown event type %r", event["event"])
|
||||
except (
|
||||
WebSocketException,
|
||||
TimeoutError,
|
||||
exceptions.TimeoutError,
|
||||
ConnectionError,
|
||||
) as e:
|
||||
except (WebSocketException, TimeoutError, exceptions.TimeoutError):
|
||||
if not reconnect:
|
||||
raise
|
||||
else:
|
||||
logger.warn("%r caught, reconnecting", e)
|
||||
await sleep(reconnect_delay)
|
||||
else:
|
||||
logger.info(
|
||||
"WebSocket closed connection without any errors, "
|
||||
"but we're not done yet"
|
||||
)
|
||||
await sleep(reconnect_delay)
|
||||
|
|
|
@ -1,106 +0,0 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from typing import Callable, Iterable, Literal, Optional
|
||||
from bs4.element import Tag, PageElement
|
||||
|
||||
VALID_OUTPUT_TYPES = Literal["plain", "html", "markdown"]
|
||||
BULLET = "\u2022"
|
||||
STRIPE = "\u258d"
|
||||
|
||||
|
||||
def md_escape(text: str) -> str:
|
||||
return (
|
||||
text.replace("\\", "\\\\")
|
||||
.replace("*", "\\*")
|
||||
.replace("[", "\\[")
|
||||
.replace("]", "\\]")
|
||||
.replace("_", "\\_")
|
||||
.replace("~", "\\~")
|
||||
.replace("|", "\\|")
|
||||
.replace("`", "\\`")
|
||||
)
|
||||
|
||||
|
||||
node_processors: dict[
|
||||
tuple[VALID_OUTPUT_TYPES, str],
|
||||
list[
|
||||
Callable[
|
||||
[
|
||||
PageElement,
|
||||
],
|
||||
Optional[str],
|
||||
]
|
||||
],
|
||||
] = {}
|
||||
|
||||
|
||||
def register_converter(tag: str, output_type: VALID_OUTPUT_TYPES = "plain"):
|
||||
def decorate(function):
|
||||
node_processors.setdefault((output_type, tag), [])
|
||||
node_processors[output_type, tag].append(function)
|
||||
return function
|
||||
|
||||
return decorate
|
||||
|
||||
|
||||
def register_text_node_converter(output_type: VALID_OUTPUT_TYPES = "plain"):
|
||||
def decorate(function):
|
||||
node_processors[output_type, ":text:"] = [function]
|
||||
return function
|
||||
|
||||
return decorate
|
||||
|
||||
|
||||
def register_fmt_converter(
|
||||
format: str,
|
||||
tag: str,
|
||||
output_type: VALID_OUTPUT_TYPES = "plain",
|
||||
separator: str = "",
|
||||
):
|
||||
def fmt_tag(el: Tag) -> str:
|
||||
if "%s" in format:
|
||||
return format % nodes_process(el.children, output_type, separator)
|
||||
return format
|
||||
|
||||
register_converter(tag, output_type)(fmt_tag)
|
||||
|
||||
|
||||
def node_process(el: PageElement, type_: VALID_OUTPUT_TYPES) -> str:
|
||||
if isinstance(el, Tag):
|
||||
if (type_, el.name) in node_processors:
|
||||
for func in node_processors[type_, el.name]:
|
||||
result = func(el)
|
||||
if result:
|
||||
return result
|
||||
return nodes_process(el.children, type_)
|
||||
if (type_, ":text:") in node_processors:
|
||||
return node_processors[type_, ":text:"][0](el) or str(el)
|
||||
return str(el)
|
||||
|
||||
|
||||
def nodes_process(
|
||||
els: Iterable[PageElement],
|
||||
type_: VALID_OUTPUT_TYPES = "plain",
|
||||
separator: str = "",
|
||||
) -> str:
|
||||
return str.join(separator, (node_process(el, type_) for el in els))
|
||||
|
||||
|
||||
__all__ = ["node_process", "nodes_process", "md_escape", "BULLET", "STRIPE"]
|
||||
|
||||
import mastoposter.text.html # noqa F401
|
||||
import mastoposter.text.markdown # noqa F401
|
||||
import mastoposter.text.plain # noqa F401
|
|
@ -1,36 +0,0 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from mastoposter.text import node_process, VALID_OUTPUT_TYPES
|
||||
from argparse import ArgumentParser, FileType
|
||||
from typing import get_args as T_get_args
|
||||
from bs4 import BeautifulSoup
|
||||
import sys
|
||||
|
||||
parser = ArgumentParser("mastoposter.text", description="HTML-to-* converter")
|
||||
|
||||
parser.add_argument(
|
||||
"--type",
|
||||
"-t",
|
||||
choices=T_get_args(VALID_OUTPUT_TYPES),
|
||||
default=T_get_args(VALID_OUTPUT_TYPES)[0],
|
||||
dest="output_type",
|
||||
)
|
||||
parser.add_argument("file", default=sys.stdin, type=FileType("r"))
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
soup = BeautifulSoup(args.file.read(), "lxml")
|
||||
print(node_process(soup, args.output_type))
|
|
@ -1,101 +0,0 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from bs4 import NavigableString
|
||||
from mastoposter.text import (
|
||||
nodes_process,
|
||||
register_converter,
|
||||
register_fmt_converter,
|
||||
register_text_node_converter,
|
||||
node_process,
|
||||
STRIPE,
|
||||
BULLET,
|
||||
)
|
||||
|
||||
from typing import Optional
|
||||
from bs4.element import Tag
|
||||
from html import escape
|
||||
|
||||
|
||||
@register_text_node_converter("html")
|
||||
def proc_text_node_to_html(txt: NavigableString) -> str:
|
||||
return escape(txt)
|
||||
|
||||
|
||||
@register_converter("a", "html")
|
||||
def proc_tag_a_to_html(tag: Tag):
|
||||
return '<a href="%s">%s</a>' % (
|
||||
escape(tag.attrs.get("href", "#")),
|
||||
nodes_process(tag.children, "html"),
|
||||
)
|
||||
|
||||
|
||||
register_fmt_converter("%s\n\n", "p", "html")
|
||||
register_fmt_converter("<i>%s</i>", "i", "html")
|
||||
register_fmt_converter("<i>%s</i>", "em", "html")
|
||||
register_fmt_converter("<b>%s</b>", "b", "html")
|
||||
register_fmt_converter("<b>%s</b>", "strong", "html")
|
||||
register_fmt_converter("<s>%s</s>", "s", "html")
|
||||
register_fmt_converter("<s>%s</s>", "del", "html")
|
||||
register_fmt_converter("<u>%s</u>", "u", "html")
|
||||
register_fmt_converter("<u>%s</u>", "ins", "html")
|
||||
register_fmt_converter("\n", "br", "html")
|
||||
register_fmt_converter("\n<pre>%s</pre>\n", "pre", "html")
|
||||
register_fmt_converter("<code>%s</code>", "code", "html")
|
||||
|
||||
|
||||
@register_converter("span", "html")
|
||||
def proc_tag_span_to_html(tag: Tag) -> Optional[str]:
|
||||
if "_mfm_blur_" in tag.attrs.get("class", ""):
|
||||
return '<span class="tg-spoiler">%s</span>' % nodes_process(
|
||||
tag.children, "html"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@register_converter("blockquote", "html")
|
||||
def proc_tag_blockquote_to_html(tag: Tag) -> str:
|
||||
return str.join(
|
||||
"\n",
|
||||
(
|
||||
STRIPE + " " + line
|
||||
for line in nodes_process(tag.children, "html").strip().split("\n")
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@register_converter("ul", "html")
|
||||
def proc_tag_ul_to_html(tag: Tag) -> str:
|
||||
return "\n" + str.join(
|
||||
"\n",
|
||||
(
|
||||
BULLET
|
||||
+ " "
|
||||
+ node_process(el, "html").replace("\n", "\n ").rstrip()
|
||||
for el in tag.children
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@register_converter("ol", "html")
|
||||
def proc_tag_li_to_html(tag: Tag) -> str:
|
||||
return "\n" + str.join(
|
||||
"\n",
|
||||
(
|
||||
"%d. %s"
|
||||
% (i, node_process(el, "html").replace("\n", "\n ").rstrip())
|
||||
for i, el in enumerate(tag.children, 1)
|
||||
),
|
||||
)
|
|
@ -1,75 +0,0 @@
|
|||
from mastoposter.text import (
|
||||
nodes_process,
|
||||
register_converter,
|
||||
register_fmt_converter,
|
||||
node_process,
|
||||
)
|
||||
|
||||
from typing import Optional
|
||||
from bs4.element import Tag
|
||||
from html import escape
|
||||
|
||||
|
||||
@register_converter("a", "markdown")
|
||||
def proc_tag_a_to_markdown(tag: Tag):
|
||||
return "[%s](%s)" % (
|
||||
nodes_process(tag.children, "markdown"),
|
||||
escape(tag.attrs.get("href", "#")),
|
||||
)
|
||||
|
||||
|
||||
register_fmt_converter("%s\n\n", "p", "markdown")
|
||||
register_fmt_converter("*%s*", "i", "markdown")
|
||||
register_fmt_converter("*%s*", "em", "markdown")
|
||||
register_fmt_converter("**%s**", "b", "markdown")
|
||||
register_fmt_converter("**%s**", "strong", "markdown")
|
||||
register_fmt_converter("~~%s~~", "s", "markdown")
|
||||
register_fmt_converter("~~%s~~", "del", "markdown")
|
||||
register_fmt_converter("__%s__", "u", "markdown")
|
||||
register_fmt_converter("__%s__", "ins", "markdown")
|
||||
register_fmt_converter("\n", "br", "markdown")
|
||||
register_fmt_converter("\n```%s```\n", "pre", "markdown")
|
||||
register_fmt_converter("`%s`", "code", "markdown")
|
||||
|
||||
|
||||
@register_converter("span", "markdown")
|
||||
def proc_tag_span_to_markdown(tag: Tag) -> Optional[str]:
|
||||
if "_mfm_blur_" in tag.attrs.get("class", ""):
|
||||
return "||%s||" % nodes_process(tag.children, "markdown")
|
||||
return None
|
||||
|
||||
|
||||
@register_converter("blockquote", "markdown")
|
||||
def proc_tag_blockquote_to_markdown(tag: Tag) -> str:
|
||||
return str.join(
|
||||
"\n",
|
||||
(
|
||||
"> " + line
|
||||
for line in nodes_process(tag.children, "markdown")
|
||||
.strip()
|
||||
.split("\n")
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@register_converter("ul", "markdown")
|
||||
def proc_tag_ul_to_markdown(tag: Tag) -> str:
|
||||
return "\n" + str.join(
|
||||
"\n",
|
||||
(
|
||||
"* " + node_process(el, "markdown").replace("\n", "\n ").rstrip()
|
||||
for el in tag.children
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@register_converter("ol", "markdown")
|
||||
def proc_tag_li_to_markdown(tag: Tag) -> str:
|
||||
return "\n" + str.join(
|
||||
"\n",
|
||||
(
|
||||
"%d. %s"
|
||||
% (i, node_process(el, "markdown").replace("\n", "\n ").rstrip())
|
||||
for i, el in enumerate(tag.children, 1)
|
||||
),
|
||||
)
|
|
@ -1,75 +0,0 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from mastoposter.text import (
|
||||
nodes_process,
|
||||
register_converter,
|
||||
register_fmt_converter,
|
||||
node_process,
|
||||
STRIPE,
|
||||
BULLET,
|
||||
)
|
||||
|
||||
from bs4.element import Tag
|
||||
|
||||
|
||||
@register_converter("a", "plain")
|
||||
def proc_tag_a_to_plain(tag: Tag):
|
||||
return "%s (%s)" % (
|
||||
nodes_process(tag.children, "plain"),
|
||||
tag.attrs.get("href", "#"),
|
||||
)
|
||||
|
||||
|
||||
register_fmt_converter("%s\n\n", "p", "plain")
|
||||
register_fmt_converter("\n", "br", "plain")
|
||||
|
||||
|
||||
@register_converter("blockquote", "plain")
|
||||
def proc_tag_blockquote_to_plain(tag: Tag) -> str:
|
||||
return str.join(
|
||||
"\n",
|
||||
(
|
||||
STRIPE + " " + line
|
||||
for line in nodes_process(tag.children, "plain")
|
||||
.strip()
|
||||
.split("\n")
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@register_converter("ul", "plain")
|
||||
def proc_tag_ul_to_plain(tag: Tag) -> str:
|
||||
return "\n" + str.join(
|
||||
"\n",
|
||||
(
|
||||
BULLET
|
||||
+ " "
|
||||
+ node_process(el, "plain").replace("\n", "\n ").rstrip()
|
||||
for el in tag.children
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@register_converter("ol", "plain")
|
||||
def proc_tag_li_to_plain(tag: Tag) -> str:
|
||||
return "\n" + str.join(
|
||||
"\n",
|
||||
(
|
||||
"%d. %s"
|
||||
% (i, node_process(el, "plain").replace("\n", "\n ").rstrip())
|
||||
for i, el in enumerate(tag.children, 1)
|
||||
),
|
||||
)
|
|
@ -1,25 +1,10 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field, fields
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable, Optional, List, Literal, TypeVar
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from mastoposter.text import node_process
|
||||
from mastoposter.utils import node_to_html, node_to_markdown, node_to_plaintext
|
||||
|
||||
|
||||
def _date(val: str) -> datetime:
|
||||
|
@ -87,7 +72,7 @@ class Account:
|
|||
emojis: List[Emoji]
|
||||
discoverable: bool
|
||||
created_at: datetime
|
||||
last_status_at: Optional[datetime]
|
||||
last_status_at: datetime
|
||||
statuses_count: int
|
||||
followers_count: int
|
||||
following_count: int
|
||||
|
@ -112,7 +97,7 @@ class Account:
|
|||
emojis=list(map(Emoji.from_dict, data["emojis"])),
|
||||
discoverable=data.get("discoverable", False),
|
||||
created_at=_date(data["created_at"]),
|
||||
last_status_at=_date_or_none(data.get("last_status_at")),
|
||||
last_status_at=_date(data["last_status_at"]),
|
||||
statuses_count=data["statuses_count"],
|
||||
followers_count=data["followers_count"],
|
||||
following_count=data["following_count"],
|
||||
|
@ -159,7 +144,7 @@ class AttachmentMetaImage:
|
|||
**{f.name: data[f.name] for f in fields(cls) if f.name in data},
|
||||
original=cls.AttachmentMetaImageDimensions(**data["original"]),
|
||||
small=cls.AttachmentMetaImageDimensions(**data["small"]),
|
||||
focus=cls.Vec2F(**data["focus"]),
|
||||
focus=cls.Vec2F(**data["focus"])
|
||||
)
|
||||
|
||||
|
||||
|
@ -198,7 +183,7 @@ class AttachmentMetaVideo:
|
|||
return cls(
|
||||
**data,
|
||||
original=cls.AttachmentMetaVideoOriginal(**data["original"]),
|
||||
small=cls.AttachmentMetaVideoSmall(**data["small"]),
|
||||
small=cls.AttachmentMetaVideoSmall(**data["small"])
|
||||
)
|
||||
|
||||
|
||||
|
@ -356,18 +341,18 @@ class Status:
|
|||
|
||||
@property
|
||||
def content_flathtml(self) -> str:
|
||||
return node_process(
|
||||
BeautifulSoup(self.content, features="lxml"), "html"
|
||||
return node_to_html(
|
||||
BeautifulSoup(self.content, features="lxml")
|
||||
).rstrip()
|
||||
|
||||
@property
|
||||
def content_markdown(self) -> str:
|
||||
return node_process(
|
||||
BeautifulSoup(self.content, features="lxml"), "markdown"
|
||||
return node_to_markdown(
|
||||
BeautifulSoup(self.content, features="lxml")
|
||||
).rstrip()
|
||||
|
||||
@property
|
||||
def content_plaintext(self) -> str:
|
||||
return node_process(
|
||||
BeautifulSoup(self.content, features="lxml"), "plain"
|
||||
return node_to_plaintext(
|
||||
BeautifulSoup(self.content, features="lxml")
|
||||
).rstrip()
|
||||
|
|
|
@ -1,36 +1,60 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from configparser import ConfigParser
|
||||
from logging import getLogger
|
||||
|
||||
logger = getLogger("utils")
|
||||
from html import escape
|
||||
from bs4.element import Tag, PageElement
|
||||
|
||||
|
||||
def normalize_config(conf: ConfigParser):
|
||||
for section in conf.sections():
|
||||
_remove = set()
|
||||
for k, v in conf[section].items():
|
||||
normalized_key = k.replace(" ", "_").replace("-", "_")
|
||||
if k == normalized_key:
|
||||
continue
|
||||
logger.info(
|
||||
"moving %r.%r -> %r.%r", section, k, section, normalized_key
|
||||
def md_escape(text: str) -> str:
|
||||
return (
|
||||
text.replace("\\", "\\\\")
|
||||
.replace("*", "\\*")
|
||||
.replace("[", "\\[")
|
||||
.replace("]", "\\]")
|
||||
.replace("_", "\\_")
|
||||
.replace("~", "\\~")
|
||||
.replace("|", "\\|")
|
||||
.replace("`", "\\`")
|
||||
)
|
||||
|
||||
|
||||
def node_to_html(el: PageElement) -> str:
|
||||
if isinstance(el, Tag):
|
||||
if el.name == "a":
|
||||
return '<a href="{}">{}</a>'.format(
|
||||
escape(el.attrs["href"]),
|
||||
str.join("", map(node_to_html, el.children)),
|
||||
)
|
||||
conf[section][normalized_key] = v
|
||||
_remove.add(k)
|
||||
for k in _remove:
|
||||
logger.info("removing key %r.%r", section, k)
|
||||
del conf[section][k]
|
||||
elif el.name == "p":
|
||||
return str.join("", map(node_to_html, el.children)) + "\n\n"
|
||||
elif el.name == "br":
|
||||
return "\n"
|
||||
return str.join("", map(node_to_html, el.children))
|
||||
return escape(str(el))
|
||||
|
||||
|
||||
def node_to_markdown(el: PageElement) -> str:
|
||||
if isinstance(el, Tag):
|
||||
if el.name == "a":
|
||||
return "[%s](%s)" % (
|
||||
md_escape(str.join("", map(node_to_markdown, el.children))),
|
||||
el.attrs["href"],
|
||||
)
|
||||
elif el.name == "p":
|
||||
return str.join("", map(node_to_markdown, el.children)) + "\n\n"
|
||||
elif el.name == "br":
|
||||
return "\n"
|
||||
return str.join("", map(node_to_markdown, el.children))
|
||||
return md_escape(str(el))
|
||||
|
||||
|
||||
def node_to_plaintext(el: PageElement) -> str:
|
||||
if isinstance(el, Tag):
|
||||
if el.name == "a":
|
||||
return "%s (%s)" % (
|
||||
str.join("", map(node_to_plaintext, el.children)),
|
||||
el.attrs["href"],
|
||||
)
|
||||
elif el.name == "p":
|
||||
return str.join("", map(node_to_plaintext, el.children)) + "\n\n"
|
||||
elif el.name == "br":
|
||||
return "\n"
|
||||
return str.join("", map(node_to_plaintext, el.children))
|
||||
return str(el)
|
||||
|
|
|
@ -1,52 +0,0 @@
|
|||
[build-system]
|
||||
requires = ["flit_core >=3.2,<4"]
|
||||
build-backend = "flit_core.buildapi"
|
||||
|
||||
[project]
|
||||
name = "mastoposter"
|
||||
description = "Configurable reposter from Mastodon-compatible Fediverse servers"
|
||||
authors = [
|
||||
{name = "hatkidchan", email = "hatkidchan@gmail.com"}
|
||||
]
|
||||
readme = "README.md"
|
||||
license = {file = "LICENSE"}
|
||||
classifiers = [
|
||||
"Environment :: No Input/Output (Daemon)",
|
||||
"Intended Audience :: End Users/Desktop",
|
||||
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
|
||||
"Topic :: Communications",
|
||||
"Topic :: Internet :: WWW/HTTP"
|
||||
]
|
||||
keywords = ["mastodon", "discord", "telegram"]
|
||||
requires-python = ">=3.8"
|
||||
dependencies = [
|
||||
"Jinja2",
|
||||
"beautifulsoup4[lxml]",
|
||||
"emoji",
|
||||
"httpx",
|
||||
"websockets"
|
||||
]
|
||||
dynamic = ["version"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = [
|
||||
"pytest"
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Source = "https://github.com/hatkidchan/mastoposter"
|
||||
|
||||
[project.scripts]
|
||||
mastoposter = "mastoposter.__main__:main"
|
||||
|
||||
[tool.flit.sdist]
|
||||
include = ["config.ini", "contrib/*"]
|
||||
|
||||
[tool.black]
|
||||
line-length = 79
|
||||
target-version = ['py37', 'py38']
|
||||
|
||||
[tool.mypy]
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
check_untyped_defs = true
|
|
@ -1,191 +0,0 @@
|
|||
"""
|
||||
mastoposter - configurable reposter from Mastodon-compatible Fediverse servers
|
||||
Copyright (C) 2022-2023 hatkidchan <hatkidchan@gmail.com>
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from pytest import mark
|
||||
|
||||
from mastoposter.text import md_escape, node_process
|
||||
|
||||
|
||||
def test_md_escape():
|
||||
assert md_escape(r"text") == r"text"
|
||||
assert md_escape(r"*meow*") == r"\*meow\*"
|
||||
assert md_escape(r"\~test") == r"\\\~test"
|
||||
|
||||
|
||||
def test_node_to_plaintext_strip_tag():
|
||||
soup = BeautifulSoup('<b>test</b>', features="lxml")
|
||||
assert node_process(soup, "plain") == "test"
|
||||
|
||||
|
||||
def test_node_to_plaintext_tag_a():
|
||||
soup = BeautifulSoup('<a href="https://example.com">test</a>',
|
||||
features="lxml")
|
||||
assert node_process(soup, "plain") == "test (https://example.com)"
|
||||
|
||||
|
||||
def test_node_to_plaintext_tag_p():
|
||||
soup = BeautifulSoup('<p>Lorem ipsum</p>', features="lxml")
|
||||
assert node_process(soup, "plain") == "Lorem ipsum\n\n"
|
||||
|
||||
|
||||
def test_node_to_plaintext_tag_br():
|
||||
soup = BeautifulSoup('<p>test1<br>test2</p>', features="lxml")
|
||||
assert node_process(soup, "plain").rstrip() == "test1\ntest2"
|
||||
|
||||
|
||||
def test_node_to_plaintext_tag_blockquote():
|
||||
soup = BeautifulSoup('<blockquote>Lorem ipsum</blockquote>',
|
||||
features="lxml")
|
||||
assert node_process(soup, "plain").rstrip() == "\u258d Lorem ipsum"
|
||||
|
||||
|
||||
def test_node_to_plaintext_tag_ul():
|
||||
soup = BeautifulSoup('<ul><li>test1<li>test2</ul>', features="lxml")
|
||||
assert node_process(soup, "plain") == "\n\u2022 test1\n\u2022 test2"
|
||||
|
||||
|
||||
def test_node_to_plaintext_tag_ol():
|
||||
soup = BeautifulSoup('<ol><li>test1<li>test2</ol>', features="lxml")
|
||||
assert node_process(soup, "plain") == "\n1. test1\n2. test2"
|
||||
|
||||
|
||||
@mark.parametrize("tag", ["video", "span"])
|
||||
def test_node_to_markdown_strip_tag(tag):
|
||||
soup = BeautifulSoup('<{0}>test</{0}>'.format(tag), features="lxml")
|
||||
assert node_process(soup, "markdown") == "test"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_a():
|
||||
soup = BeautifulSoup('<a href="https://example.com">test</a>',
|
||||
features="lxml")
|
||||
assert node_process(soup, "markdown") == "[test](https://example.com)"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_p():
|
||||
soup = BeautifulSoup('<p>Lorem ipsum</p>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "Lorem ipsum\n\n"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_i():
|
||||
soup = BeautifulSoup('<i>test</i>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "*test*"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_b():
|
||||
soup = BeautifulSoup('<b>test</b>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "**test**"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_s():
|
||||
soup = BeautifulSoup('<s>test</s>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "~~test~~"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_u():
|
||||
soup = BeautifulSoup('<u>test</u>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "__test__"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_pre():
|
||||
soup = BeautifulSoup('<pre>Lorem ipsum</pre>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "\n```Lorem ipsum```\n"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_code():
|
||||
soup = BeautifulSoup('<code>test</code>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "`test`"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_blockquote():
|
||||
soup = BeautifulSoup('<blockquote>Lorem ipsum</blockquote>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "> Lorem ipsum"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_br():
|
||||
soup = BeautifulSoup('<p>test1<br>test2</p>', features="lxml")
|
||||
assert node_process(soup, "markdown").rstrip() == "test1\ntest2"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_ul():
|
||||
soup = BeautifulSoup('<ul><li>test1<li>test2</ul>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "\n* test1\n* test2"
|
||||
|
||||
|
||||
def test_node_to_markdown_tag_ol():
|
||||
soup = BeautifulSoup('<ol><li>test1<li>test2</ol>', features="lxml")
|
||||
assert node_process(soup, "markdown") == "\n1. test1\n2. test2"
|
||||
|
||||
|
||||
@mark.parametrize("tag", ["video", "span"])
|
||||
def test_node_to_html_strip_tag(tag):
|
||||
soup = BeautifulSoup('<{0}>test</{0}>'.format(tag), features="lxml")
|
||||
assert node_process(soup, "html") == "test"
|
||||
|
||||
|
||||
@mark.parametrize("tag", ["i", "b", "s", "u", "code"])
|
||||
def test_node_to_html_keep_tag(tag):
|
||||
html = '<{0}>test</{0}>'.format(tag)
|
||||
soup = BeautifulSoup(html, features="lxml")
|
||||
assert node_process(soup, "html") == html
|
||||
|
||||
|
||||
@mark.parametrize("old_tag,new_tag",
|
||||
[("strong", "b"), ("em", "i"), ("del", "s"), ("ins", "u")])
|
||||
def test_node_to_html_subst_tag(old_tag, new_tag):
|
||||
soup = BeautifulSoup('<{0}>test</{0}>'.format(old_tag), features="lxml")
|
||||
assert node_process(soup, "html") == '<{0}>test</{0}>'.format(new_tag)
|
||||
|
||||
|
||||
def test_node_to_html_tag_a():
|
||||
html = '<a href="https://example.com">test</a>'
|
||||
soup = BeautifulSoup(html, features="lxml")
|
||||
assert node_process(soup, "html") == html
|
||||
|
||||
|
||||
def test_node_to_html_tag_p():
|
||||
soup = BeautifulSoup('<p>Lorem ipsum</p>', features="lxml")
|
||||
assert node_process(soup, "html") == "Lorem ipsum\n\n"
|
||||
|
||||
|
||||
def test_node_to_html_tag_pre():
|
||||
soup = BeautifulSoup('<pre>Lorem ipsum</pre>', features="lxml")
|
||||
assert node_process(soup, "html") == "\n<pre>Lorem ipsum</pre>\n"
|
||||
|
||||
|
||||
def test_node_to_html_tag_blockquote():
|
||||
soup = BeautifulSoup('<blockquote>Lorem ipsum</blockquote>',
|
||||
features="lxml")
|
||||
assert node_process(soup, "html").rstrip() == "▍ Lorem ipsum"
|
||||
|
||||
|
||||
def test_node_to_html_tag_br():
|
||||
soup = BeautifulSoup('<p>test1<br>test2</p>', features="lxml")
|
||||
assert node_process(soup, "html").rstrip() == "test1\ntest2"
|
||||
|
||||
|
||||
def test_node_to_html_tag_ul():
|
||||
soup = BeautifulSoup('<ul><li>test1<li>test2</ul>', features="lxml")
|
||||
assert node_process(soup, "html") == "\n\u2022 test1\n\u2022 test2"
|
||||
|
||||
|
||||
def test_node_to_html_tag_ol():
|
||||
soup = BeautifulSoup('<ol><li>test1<li>test2</ol>', features="lxml")
|
||||
assert node_process(soup, "html") == "\n1. test1\n2. test2"
|
||||
|
||||
|
||||
def test_node_to_html_spoiler():
|
||||
soup = BeautifulSoup('<span class="_mfm_blur_">test</span>', features="lxml")
|
||||
assert node_process(soup, "html") == '<span class="tg-spoiler">test</span>'
|
Loading…
Reference in New Issue