1
0
Fork 0

Compare commits

..

96 Commits

Author SHA1 Message Date
Casey e7e2a13c7d
Merge branch 'vftdan-log-websocket-connection' 2024-06-12 23:30:28 +03:00
Casey b824d088ae
Merge branch 'log-websocket-connection' of https://git.salushnes.solutions/vftdan/mastoposter into vftdan-log-websocket-connection 2024-06-12 23:30:01 +03:00
Vftdan 37c1052b39
Add connect-timeout config option 2024-06-11 20:01:43 +02:00
Vftdan fac1e46859 Merge remote-tracking branch 'origin/master' into log-websocket-connection 2024-06-11 19:42:10 +02:00
Vftdan 3e82b5c979
Set websocket open timeout to 1 minute and log attempts 2024-06-08 17:03:38 +02:00
Casey 624998817b
Added option to post replies anyways
Also reformatting because I forgot
2024-06-08 16:32:04 +03:00
Casey 2ddb2639bf
Print every received event in debug mode 2023-07-03 17:03:20 +03:00
Casey 8d91d619dd
Workaround for wrong redirects on some instances 2023-07-02 20:51:48 +03:00
Casey 686cfced29
Allowed "all" to be used as user selector 2023-07-02 20:45:19 +03:00
Casey 09cc8deb37
Version bump 2023-06-17 00:54:45 +03:00
Casey da16cee1e0
Merge branch 'CyberTailor-tests' 2023-05-21 12:03:16 +03:00
Anna “CyberTailor” 8871479c85
Added tests GitHub Actions 2023-05-20 13:42:54 +05:00
Anna “CyberTailor” 88c1fadd5a
Added tests for utils 2023-05-20 13:42:54 +05:00
Casey cea0af44ba
Apparently that squishes some things together 2023-05-15 10:00:35 +03:00
Casey 291a8b8643
More logs? 2023-05-13 21:50:11 +03:00
Casey 18b47f6866
Added media limit 2023-05-13 21:47:40 +03:00
Casey 9889ca251a
Merge branch 'html2everything' 2023-05-13 09:58:55 +03:00
Casey db100c0f7e
Text node processor, typo fixes, text2* cli program 2023-05-13 09:33:21 +03:00
Casey 32d7784276
Reworked node_to_* functions 2023-05-13 08:45:46 +03:00
Casey 9cfbcf635a
Merge branch 'CyberTailor-master' 2023-05-13 08:09:18 +03:00
Anna “CyberTailor” ca944715f6
Fixed Markdown formatting
* Triple backticks for <pre>
* Double asterisks for <b>
* Double tildes for <s>
* Native syntax for lists and blockquotes

See: https://support.discord.com/hc/en-us/articles/210298617
2023-05-13 07:41:29 +05:00
Casey 1b3a0bbe0b
Added blockquote element to node_to_plaintext 2023-05-10 12:33:33 +03:00
Casey 277c32b09d
Merge branch 'CyberTailor-ol_numeration' 2023-05-10 12:30:38 +03:00
Anna “CyberTailor” a8129d2a88
Fix numeration in node_to_plaintext 2023-05-10 14:27:12 +05:00
Casey a2e5f15c21
Merge branch 'CyberTailor-metadata' 2023-05-10 12:20:11 +03:00
Anna “CyberTailor” 81a8f6b039
Fix pyproject metadata
* Fix description
* Fix bs4 dep (lxml support is needed)
* Set minimum Python version to 3.8 (for := operator)
2023-05-10 14:15:56 +05:00
Casey 76b2241a82
Updated pyproject.toml, black+mypy 2023-05-10 09:19:22 +03:00
Casey 8d5a8fd424
Merge branch 'CyberTailor-argparse' 2023-05-10 09:14:41 +03:00
Anna “CyberTailor” 43963144c4
Include 'contrib' in sdist 2023-05-10 09:14:27 +03:00
Anna “CyberTailor” 19cdde7ef4
Added SystemD service 2023-05-10 09:14:27 +03:00
Anna “CyberTailor” f6dbac76e4
Added OpenRC service 2023-05-10 09:14:27 +03:00
Anna “CyberTailor” cc817f9924
Fixed misplaces ul/ol in node_to_plaintext 2023-05-10 09:14:27 +03:00
Anna “CyberTailor” 9d8c8252a4
Updated boilerplate config
There were some mistakes.
2023-05-10 09:14:27 +03:00
Casey a94c842340
Merge branch 'CyberTailor-master' 2023-05-10 09:12:05 +03:00
Casey 2fac32e770
Merge branch 'CyberTailor-ul_ol' 2023-05-10 09:02:44 +03:00
Anna “CyberTailor” a08630e23b
Updated boilerplate config
There were some mistakes.
2023-05-10 09:01:23 +03:00
Casey 038177b1c2
Merge branch 'CyberTailor-config' 2023-05-10 08:55:47 +03:00
Anna “CyberTailor” c60f19d7c6
Fixed misplaces ul/ol in node_to_plaintext 2023-05-10 08:50:52 +05:00
Anna “CyberTailor” 65d0cc5b4d
Added argument parser
Just for config file path. Defaults to environment variable
"MASTOPOSTER_CONFIG_FILE".
2023-05-10 07:33:28 +05:00
Anna “CyberTailor” df01956b72
Updated boilerplate config
There were some mistakes.
2023-05-10 07:30:06 +05:00
Anna “CyberTailor” 8c8d304066
Include 'contrib' in sdist 2023-05-10 06:50:14 +05:00
Anna “CyberTailor” d168db772c
Added SystemD service 2023-05-10 06:49:39 +05:00
Anna “CyberTailor” f045145f00
Added OpenRC service 2023-05-10 06:48:56 +05:00
Casey d740ddb0b1
Version bump 2023-05-09 18:46:16 +03:00
Casey 0f3cac3cbf
Fixed a little issue with classes not being here 2023-05-09 18:42:47 +03:00
Casey 7955120a7c
Added _mfm_blur_ class check 2023-05-08 18:28:43 +03:00
Casey 3bd0b78122
Improved README, added section about Pip package 2023-05-08 17:57:43 +03:00
Casey fb7d5b8e44
Removed unused TODO file 2023-05-08 17:35:16 +03:00
Casey 6e24781d76
Merge branch 'CyberTailor-master' 2023-05-08 17:26:31 +03:00
Anna “CyberTailor” 9ed31cc5c8
Added packaging (via Flit) 2023-05-08 19:23:20 +05:00
Casey d761cf5951
Added license (closes #29)
Reasnoing behind using GNU GPLv3:
 * Permits modification
 * Permits free distribution
 * Permits private modifications
 * Gives no warranty that this software works or works in an expected
   way
 * No liability for damage (if any is possible)
 * Commonly used in FOSS software
2023-05-08 13:18:44 +03:00
Casey 7f2e87523c
Python moment 2023-03-19 20:09:43 +03:00
Casey b789cc6015
Uh, now it should post every media
In separate messages, if they're incompatible with each other
idk i barely tested it, but it seems to be working
2023-03-07 11:17:46 +03:00
Casey 854bb859ec
Try, try again 2023-03-07 10:26:45 +03:00
Casey 6d3e00ba4a
Fixed regex mode of text filter just NOT WORKING
Apparently, `re.match` checks for the first line ONLY. We have to use
`.search` instead.

Also nuked away that plaintext conversion, we have it in status already
as a property
2023-02-08 19:38:31 +03:00
Casey 8b03ccf44a
Apparently, this exists
And I have no fucking clue how I missed it.
2023-01-28 22:27:08 +03:00
Casey 1632cddcb4
Pythom lomgimng yummy cool... 2023-01-26 13:44:30 +03:00
Casey f3f7bff945
Iiiii fucked up. Again. 2023-01-20 13:22:23 +03:00
Casey 80e845300f
Merge pull request #27 from hatkidchan/26-media-spoilers-in-telegram
Added spoilers (closes #26)
2023-01-20 13:03:28 +03:00
Casey f8d903b478
Added spoilers (closes #26) 2023-01-20 12:59:42 +03:00
Casey 89658132a0
We all need some space and we hate to <code> 2023-01-13 11:47:40 +03:00
Casey 3753c6a342
Forgot about plaintext 2023-01-13 10:47:23 +03:00
Casey bbc5053cf6
We just need some space 2023-01-13 10:43:48 +03:00
Casey 3fc8a3bcd8
Added ordered list 2023-01-13 10:40:40 +03:00
Casey f3ddb4a1d9
Added unordered lists 2023-01-13 10:36:58 +03:00
Casey f8e1ea1661
Merge pull request #23 from hatkidchan/22-crash-when-using-user=auto-on-pleroma-account-with-no-posts
Changed type of `last_status_at` to be nullable
2022-11-12 00:01:51 +03:00
Casey a44df7030d
Changed type of `last_status_at` to be nullable 2022-11-12 00:00:14 +03:00
Casey 5b7a4dec1a
Merge pull request #19 from hatkidchan/logging
Added logging functionality
2022-11-02 20:30:19 +03:00
Casey 5bc4ae932e
Added docs for the forgotten filter 2022-11-02 20:23:01 +03:00
Casey 3904e475a4
MORE. LOGS. 2022-11-02 20:18:31 +03:00
Casey 94f477bc45
Added configurable logging level 2022-11-02 20:11:38 +03:00
Casey bfa0534f6d
uh, more logging? 2022-11-01 14:33:47 +03:00
Casey fd05f39f4a
Changed default level to ERROR, added TG API logs 2022-11-01 13:52:40 +03:00
Casey 95c9a523e0
More logging? 2022-11-01 13:37:47 +03:00
Casey 1ec78d5f53
Forgot to initialize logger 2022-11-01 13:04:31 +03:00
Casey d861b2fe45
Uhh I think I added logging and some other stuff
Yeah so basically now initialization of integrations and filters is
moved to from_section instead of __init__ because muh better imo
2022-11-01 12:55:23 +03:00
Casey e4cd94b7c3
Fixed .dockerignore
> COPY failed: file not found in build context or excluded by
> .dockerignore: stat requirements.txt: file does not exist
2022-10-11 09:17:47 +03:00
Casey dd60de5067
Added more HTML tags 2022-10-11 09:00:37 +03:00
Casey 6bff6fd73e
Merge branch 'vapronva-docker-fixes' into unsafe 2022-09-30 15:42:59 +03:00
Vladimir (vapronva) 43abba6f46
add: `dockerignore`; change: df layers handling 2022-09-30 05:44:17 +03:00
Casey 6b3c48e067
Added proper README 2022-09-23 19:28:08 +03:00
Casey 3644ebad82
[WIP] Added documentation 2022-09-23 18:44:45 +03:00
Casey cb4b32fa8b
Added property that removes emojis from the name 2022-09-23 18:31:16 +03:00
Casey cfe26cfd8f
DUROV I FUCKING HATE YOU 2022-09-23 18:21:31 +03:00
Casey 248f06be2a
I should sleep more 2022-09-22 19:16:52 +03:00
Casey 8950c10ce2
[WIP] Experimental Docker build (gone wrong) 2022-09-22 19:10:18 +03:00
Casey 3e707ab004
Oh my fucking god that's so embarassing 2022-09-18 16:59:19 +03:00
Casey a722833d7b
Added note that Pleroma is not properly supported 2022-09-18 16:55:13 +03:00
Casey 9fa28d518c
Oopsie 2022-09-14 20:37:51 +03:00
Casey 03cfa75bc7
Merge branch 'master' into unsafe 2022-09-14 20:35:35 +03:00
Casey 84eb94447f
[WIP] Added automatic user_id retrieving and more
* Added safe-er way to unpack data from instances
   -> like, now we're passing only the fields that
      we really need, not just everything that was
      sent by out our instance. that fixes pleroma
      being weird and adding pleroma field to some
      of objects, which was causing KeyError to be
      raised. this should be fixed now but I'm not
      completely sure so that's why it's in unsafe
      branch of the project. oh wow also this comm
      message is looking funky. hahahahah. ok bai.
2022-09-14 20:29:23 +03:00
Casey b7b3d12652
Now "private" posts could be reposted.
If you don't want to, add a separate filter, idk.
2022-09-01 00:57:36 +03:00
Casey 1c85e96502
Template example was in the wrong place.
iwannadie
2022-08-31 19:48:12 +03:00
Casey fd661b6a99
Merge pull request #16 from hatkidchan/formatting
Implemented custom formatting
2022-08-31 18:43:05 +03:00
Casey 87a74898eb
Why there's so many exceptions to catch?
And why there's TimeoutError and asyncio.exceptions.TimeoutError?
2022-08-31 12:34:25 +03:00
Casey 0e59717c91
Whoopsie
forgot that TimeoutError is not the same as WebSocketException
2022-08-31 00:27:34 +03:00
37 changed files with 2557 additions and 269 deletions

5
.dockerignore Normal file
View File

@ -0,0 +1,5 @@
.git
.gitignore
config.ini
README.md
TODO

16
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,16 @@
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
.gitignore vendored
View File

@ -1,3 +1,4 @@
dist/
__pycache__
*.py[cow]
config-*.ini

11
Dockerfile Normal file
View File

@ -0,0 +1,11 @@
FROM python:3.10-alpine
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r /app/requirements.txt && rm /app/requirements.txt
COPY . /app
CMD ["python3", "-m", "mastoposter", "/config.ini"]

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

10
README
View File

@ -1,10 +0,0 @@
mastoreposter - easy-to-use mastodon-to-[everything] reposter!
# TODO: readme
Configuration: check `config.ini`
Run:
python3 -m virtualenv venv
source venv/bin/activate
pip install -r ./requirements.txt
python3 -m mastoreposter config.ini

315
README.md Normal file
View File

@ -0,0 +1,315 @@
# 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
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
```
After that, you can either run it in Docker, set up a standalone systemd
service, or just run it as it is!
### Docker
```sh
docker build -t mastoposter .
docker run -d \
--restart=unless-stopped \
-v /path/to/config.ini:/config.ini:ro \
--name mastoposter mastoposter
```
And you should be good to go
### Systemd
Let's say that you've cloned that repo to the `$MASTOPOSTER_ROOT`, then
configuration should look something like that:
```systemd
[Unit]
Description=Crossposter from Mastodon
After=network.target
[Service]
Type=simple
User=$MASTOPOSTER_USER
ExecStart=/usr/bin/python3 -m mastoposter config.ini
WorkingDirectory=$MASTOPOSTER_ROOT
Restart=on-failure
[Install]
WantedBy=network.target
```
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
`read:statuses` and `read:lists` permissions.
On Pleroma you're out of luck and have to manually lure your token out of the
frontend you're using. For example, in Pleroma FE you can look in the "Network"
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
profile picture URL. The part between "/avatars/" and "original/" without all of
the slashes is your user ID.
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
be in the address bar).
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.
Each module should contain at least `type` property and its name should start
with the `module/`. `filters` field is also can be specified. Check the
corresponding section to learn more about them.
To use module, add it to the `modules` field in the `main` section. It should
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.
Also there's a `silent` field, when it's set to `true`, it'll set
`disable_notification` flag on every post sent.
`template` field contains your template for the message. It's pretty much
Jinja2 template. Since we use `parse_mode=html`, your `template` should be
formatted appropriately. Template itself has only `status` variable exposed,
which contains the status/post/toot itself. There's also some handy properties
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`
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!
There's a couple of filters with different types and options, but all of them
should be contained in sections with names starting with `filter/`, as well
as have a `type` field with filter type.
Also, you can specify multiple filters and they'll be chained together using
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
accounts to check from. You can use globbing, but be aware, that it uses
`fnmatch` function to glob stuff, so `@*` doesn't mean "any local user", but
rather it means "any user". NOTE that his behavior is not intended and may be
changed to more appropriate one later. If `list` is empty, any boost will
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.
Please note that in case of tags, you should NOT use `#` symbol in front of
them.
#### `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.
`filters` option should contain space-separated list of filters. You also can
negate them using `!` or `~` prefixes.
`operator` is a type of operation to be used. Can be either `all`, `any` or
`single`. `all` means that all of the filters should be used. `any` means
that if any filter is triggered, this one will also trigger. `single` means
that only one filter should be triggered. Think of it as an XOR operation of
some sort.
## Sample configurations
### For Telegram
```ini
[main]
modules = tg
instance = expired.mentality.rip
token = haha-no
list = 42
user = auto
[module/tg]
type = telegram
token = 12345:blahblahblah
chat = 12345
```
### For Telegram with a separate shitpost channel
```ini
[main]
modules = tg tg-shitpost
instance = expired.mentality.rip
token = haha-no
list = 42
user = auto
[module/tg]
type = telegram
token = 12345:blahblahblah
chat = 12345
filters = !shitpost
[module/tg-shitpost]
type = telegram
token = ${module/tg:token}
chat = @shitposting
filters = shitpost
[filters/shitpost]
type = content
mode = tag
tags = shitpost
```
## Asterisks
1. Well, most of the time that is.
2. Works only when it has lists support.

7
TODO
View File

@ -1,7 +0,0 @@
[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

View File

@ -6,20 +6,24 @@ 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:statuses read:lists
# Required permissions: read:accounts read:statuses read:lists
# You can get your token by creating application in
# ${instance}/settings/applications
token = blahblah
# Mastodon user ID. Used to filter out posts. Unfortunately, I can't find a way
# to get it using token itself. GARGROOOOOOON!!!!!
# Anyways, you could navigate to your profile ${instance}/@${username} and
# look for your profile picture link. For example, for me it's
# https://mastodon.astrr.ru/system/accounts/avatars/107/914/495/779/447/227/original/9651ac2f47cb2993.jpg
# that part between "avarars" and "original" is the user ID. Grab it, remove
# all of the slashes and you should be left with, for example, this:
user = 107914495779447227
# Your user ID.
# Doesn't necessarily yours, it can be any user's ID, but that user should be
# on the list for crossposter to find it.
# Setting it to "auto" will just grab yours instead. Don't worry about it
# EXCEPT if you're using Pleroma. Check #11 issue for more details:
# https://github.com/hatkidchan/mastoposter/issues/11
user = auto
# Mastodon user list ID. AGAIN, UNFORTUNATELY, there is no way to reliably use
# streaming API to get all of your posts. Using home timeline is unreliable and
@ -28,10 +32,23 @@ user = 107914495779447227
# 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]
@ -50,13 +67,6 @@ chat = @username
# https://core.telegram.org/bots/api#sendmessage `disable_notification`
silent = true
# Discord integration
[module/discord]
type = discord
# Webhook URL with the `?wait=true`
webhook = url
# Jinja2 template string for the post. Works only in Telegram.
# This is the default template, not specifying that property at all will result
# in this string (probably)
@ -67,6 +77,13 @@ template = {% if status.reblog %}Boost from <a href="{{status.reblog.account.url
<a href="{{status.link}}">Link to post</a>
# Discord integration
[module/discord]
type = discord
# Webhook URL with the `?wait=true`
webhook = url
;# Boost filter. Only boosts will be matched by that one
;[filter/boost]
;type = boost
@ -104,7 +121,7 @@ template = {% if status.reblog %}Boost from <a href="{{status.reblog.account.url
;type = content
;# Mode of the filter.
;# "regexp" requires "regexp" property and should contain... A RegExp
;# "hashtag" should contain space-separated list of tags
;# "tag" should contain space-separated list of tags
;mode = regexp
;# Regular expression pattern to be matched
;regexp = ^x-no-repost

26
contrib/mastoposter.initd Normal file
View File

@ -0,0 +1,26 @@
#!/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
}

View File

@ -0,0 +1,28 @@
# 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

View File

@ -1,5 +1,21 @@
"""
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
@ -11,33 +27,54 @@ 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(mod), list(filters.values())
TelegramIntegration.from_section(mod),
list(filters.values()),
)
)
elif mod["type"] == "discord":
modules.append(
FilteredIntegration(
DiscordIntegration(mod), list(filters.values())
DiscordIntegration.from_section(mod),
list(filters.values()),
)
)
else:
@ -48,6 +85,7 @@ 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,

View File

@ -1,63 +1,161 @@
#!/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 mastoposter import execute_integrations, load_integrations_from
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.integrations import FilteredIntegration
from mastoposter.sources import websocket_source
from typing import AsyncGenerator, Callable, List
from mastoposter.types import Status
from mastoposter.types import Account, Status
from mastoposter.utils import normalize_config
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):
if status.account.id != user:
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,
)
continue
# TODO: add option/filter to handle that
if status.visibility in ("direct", "private"):
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
await execute_integrations(status, drains)
logger.info(await execute_integrations(status, drains))
def main(config_path: str):
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")
conf = ConfigParser(interpolation=ExtendedInterpolation())
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]
conf.read(args.config)
init_logger(getLevelName(conf["main"].get("loglevel", "INFO")))
normalize_config(conf)
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:
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"]),
)
url = "wss://{}/api/v1/streaming".format(conf["main"]["instance"])
run(
listen(
websocket_source,
modules,
conf["main"]["user"],
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"],
)
@ -65,6 +163,4 @@ def main(config_path: str):
if __name__ == "__main__":
from sys import argv
main(argv[1])
main()

View File

@ -1,3 +1,19 @@
"""
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
@ -10,8 +26,26 @@ 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
return all((fil.filter(status) ^ fil.inverse for fil in filters))
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)

View File

@ -1,3 +1,18 @@
"""
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
@ -23,8 +38,8 @@ class BaseFilter(ABC):
filter_name: ClassVar[str] = "_base"
def __init__(self, section: SectionProxy):
UNUSED(section)
def __init__(self):
pass
def __init_subclass__(cls, filter_name: str, **kwargs):
super().__init_subclass__(**kwargs)
@ -51,7 +66,11 @@ 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](section)
return cls.FILTER_REGISTRY[name].from_section(section)
@classmethod
def from_section(cls, section: SectionProxy) -> "BaseFilter":
raise NotImplementedError
@classmethod
def new_instance(cls, name: str, section: SectionProxy) -> FilterInstance:

View File

@ -1,13 +1,33 @@
"""
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, section: SectionProxy):
super().__init__(section)
self.list = section.get("list", "").split()
def __init__(self, accounts: List[str]):
super().__init__()
self.list = accounts
@classmethod
def from_section(cls, section: SectionProxy) -> "BoostFilter":
return cls(section["list"].split())
@classmethod
def check_account(cls, acct: str, mask: str) -> bool:

View File

@ -1,3 +1,18 @@
"""
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
@ -11,19 +26,26 @@ class CombinedFilter(BaseFilter, filter_name="combined"):
"single": lambda d: sum(d) == 1,
}
def __init__(self, section: SectionProxy):
self.filter_names = section.get("filters", "").split()
self.operator = self.OPERATORS[section.get("operator", "and")]
self._operator_name = section.get("operator", "and")
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]
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:
@ -32,7 +54,12 @@ 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.filters!r})"
f"filters={self._filter_names!r}, loaded=False)"
)

View File

@ -1,16 +1,41 @@
"""
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 typing import Literal, Set
from mastoposter.filters.base import BaseFilter
from mastoposter.types import Status
class MediaFilter(BaseFilter, filter_name="media"):
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 __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 __call__(self, status: Status) -> bool:
if not status.media_attachments:

View File

@ -1,6 +1,21 @@
"""
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
from typing import ClassVar, Set
from fnmatch import fnmatch
from mastoposter.filters.base import BaseFilter
from mastoposter.types import Status
@ -9,22 +24,27 @@ from mastoposter.types import Status
class MentionFilter(BaseFilter, filter_name="mention"):
MENTION_REGEX: ClassVar[Pattern] = regexp(r"@([^@]+)(@([^@]+))?")
def __init__(self, section: SectionProxy):
super().__init__(section)
self.list = section.get("list", "").split()
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()))
@classmethod
def check_account(cls, acct: str, mask: str) -> bool:
return fnmatch("@" + acct, mask)
def __call__(self, status: Status) -> bool:
if not self.list and status.mentions:
if not self.accounts 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.list
for mask in self.accounts
)
for mention in status.mentions
)
@ -32,5 +52,7 @@ class MentionFilter(BaseFilter, filter_name="mention"):
def __repr__(self):
return str.format(
"Filter:{name}({list!r})", name=self.filter_name, list=self.list
"Filter:{name}({list!r})",
name=self.filter_name,
list=self.accounts,
)

View File

@ -1,3 +1,18 @@
"""
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
@ -5,9 +20,13 @@ from mastoposter.types import Status
class SpoilerFilter(BaseFilter, filter_name="spoiler"):
def __init__(self, section: SectionProxy):
super().__init__(section)
self.regexp: Pattern = regexp(section.get("regexp", "^.*$"))
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 __call__(self, status: Status) -> bool:
return self.regexp.match(status.spoiler_text) is not None

View File

@ -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, section: SectionProxy):
super().__init__(section)
self.mode = section["mode"]
self.tags: Set[str] = set()
self.regexp: Optional[Pattern] = None
def __init__(
self, regex: Optional[str] = None, tags: Optional[Set[str]] = None
):
super().__init__()
assert regex is not None or tags
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}")
self.tags: Optional[Set[str]] = tags
self.regexp: Optional[Pattern] = regexp(regex) if regex else None
@classmethod
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 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 __call__(self, status: Status) -> bool:
source = status.reblog or status
if self.regexp is not None:
return (
self.regexp.match(self.html_to_plain(source.content))
is not None
)
return self.regexp.search(source.content_plaintext) is not None
elif self.tags:
return len(self.tags & {t.name.lower() for t in source.tags}) > 0
else:
@ -63,3 +63,4 @@ class TextFilter(BaseFilter, filter_name="content"):
name=self.filter_name,
tags=self.tags,
)
return "Filter:{name}(invalid)".format(name=self.filter_name)

View File

@ -1,12 +1,32 @@
"""
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, section: SectionProxy):
super().__init__(section)
self.options = set(section["options"].split())
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 __call__(self, status: Status) -> bool:
return status.visibility in self.options

View File

@ -1,3 +1,18 @@
"""
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

View File

@ -1,3 +1,18 @@
"""
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
@ -6,9 +21,14 @@ from mastoposter.types import Status
class BaseIntegration(ABC):
def __init__(self, section: SectionProxy):
# TODO: make a registry of integrations
def __init__(self):
pass
@classmethod
def from_section(cls, section: SectionProxy) -> "BaseIntegration":
raise NotImplementedError
@abstractmethod
async def __call__(self, status: Status) -> Optional[str]:
raise NotImplementedError

View File

@ -1,6 +1,22 @@
"""
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
from httpx import AsyncClient, AsyncHTTPTransport
from zlib import crc32
from mastoposter.integrations.base import BaseIntegration
from mastoposter.integrations.discord.types import (
@ -10,10 +26,17 @@ from mastoposter.integrations.discord.types import (
)
from mastoposter.types import Status
logger = getLogger("integrations.discord")
class DiscordIntegration(BaseIntegration):
def __init__(self, section: SectionProxy):
self.webhook = section.get("webhook", "")
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))
async def execute_webhook(
self,
@ -21,22 +44,30 @@ class DiscordIntegration(BaseIntegration):
username: Optional[str] = None,
avatar_url: Optional[str] = None,
embeds: Optional[List[DiscordEmbed]] = None,
) -> dict:
async with AsyncClient() as c:
) -> None:
async with AsyncClient(
transport=AsyncHTTPTransport(retries=self.retries)
) 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 []
),
}
return (
logger.debug("Executing webhook with %r", json)
result = (
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
@ -78,6 +109,11 @@ class DiscordIntegration(BaseIntegration):
),
)
)
else:
logger.warn(
"Unsupported attachment %r for Discord Embed",
attachment.type,
)
await self.execute_webhook(
username=status.account.acct,

View File

@ -1,3 +1,18 @@
"""
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

View File

@ -1,13 +1,32 @@
"""
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 typing import Any, List, Mapping, Optional
from httpx import AsyncClient
from logging import getLogger
from typing import Any, List, Mapping, Optional, Tuple
from httpx import AsyncClient, AsyncHTTPTransport
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
@ -40,6 +59,13 @@ 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}}">\
@ -54,23 +80,57 @@ Boost from <a href="{{status.reblog.account.url}}">\
class TelegramIntegration(BaseIntegration):
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))
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),
)
async def _tg_request(self, method: str, **kwargs) -> TGResponse:
async def _tg_request(
self, client: AsyncClient, method: str, **kwargs
) -> TGResponse:
url = API_URL.format(self.token, method)
async with AsyncClient() as client:
return TGResponse.from_dict(
(await client.post(url, json=kwargs)).json(), kwargs
)
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 def _post_plaintext(self, text: str) -> TGResponse:
async def _post_plaintext(
self, client: AsyncClient, text: str
) -> TGResponse:
logger.debug("Sending HTML message: %r", text)
return await self._tg_request(
client,
"sendMessage",
parse_mode="HTML",
disable_notification=self.silent,
@ -79,12 +139,22 @@ class TelegramIntegration(BaseIntegration):
text=text,
)
async def _post_media(self, text: str, media: Attachment) -> TGResponse:
async def _post_media(
self,
client: AsyncClient,
text: str,
media: Attachment,
spoiler: bool = False,
) -> TGResponse:
# Just to be safe
if media.type not in MEDIA_MAPPING:
return await self._post_plaintext(text)
logger.warning(
"Media %r has unknown type, falling back to plaintext", media
)
return await self._post_plaintext(client, text)
return await self._tg_request(
client,
"send%s" % MEDIA_MAPPING[media.type].title(),
parse_mode="HTML",
disable_notification=self.silent,
@ -92,25 +162,51 @@ 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, text: str, media: List[Attachment]
) -> TGResponse:
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)
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(
{
@ -119,69 +215,90 @@ class TelegramIntegration(BaseIntegration):
}
)
return await self._tg_request(
"sendMediaGroup",
disable_notification=self.silent,
disable_web_page_preview=True,
chat_id=self.chat_id,
media=media_list,
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,
)
async def _post_poll(
self, poll: Poll, reply_to: Optional[str] = None
self, client: AsyncClient, 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,
chat_id=self.chat_id,
question=f"Poll:{poll.id}",
reply_to_message_id=reply_to,
allow_multiple_answers=poll.multiple,
allows_multiple_answers=poll.multiple,
options=[opt.title for opt in poll.options],
)
async def __call__(self, status: Status) -> Optional[str]:
source = status.reblog or status
has_spoiler = source.sensitive
text = self.template.render({"status": status})
ids = []
if not source.media_attachments:
if (res := await self._post_plaintext(text)).ok:
if res.result:
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:
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
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"])
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"])
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)
).format(
chat=self.chat_id,
silent=self.silent,
template=self.template,
bot_uid=bot_uid,
key=str.join("", ("X" for _ in key)),
)

View File

@ -1,26 +1,68 @@
"""
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 json import loads
from logging import getLogger
from typing import AsyncGenerator
from urllib.parse import urlencode
from mastoposter.types import Status
logger = getLogger("sources")
async def websocket_source(
url: str, reconnect: bool = False, **params
url: str, reconnect: bool = False, reconnect_delay: float = 1.0,
connect_timeout: float = 60.0, **params
) -> AsyncGenerator[Status, None]:
from websockets.client import connect
from websockets.exceptions import WebSocketException
url = f"{url}?" + urlencode({"stream": "list", **params})
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)
while True:
try:
async with connect(url) as ws:
logger.info("attempting to connect to %s", public_url)
async with connect(url, open_timeout=connect_timeout) as ws:
logger.info("Connected to WebSocket")
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"]))
except WebSocketException:
else:
logger.warn("unknown event type %r", event["event"])
except (
WebSocketException,
TimeoutError,
exceptions.TimeoutError,
ConnectionError,
) as e:
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)

View File

@ -0,0 +1,106 @@
"""
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

View File

@ -0,0 +1,36 @@
"""
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))

101
mastoposter/text/html.py Normal file
View File

@ -0,0 +1,101 @@
"""
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)
),
)

View File

@ -0,0 +1,75 @@
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)
),
)

75
mastoposter/text/plain.py Normal file
View File

@ -0,0 +1,75 @@
"""
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)
),
)

View File

@ -1,10 +1,25 @@
from dataclasses import dataclass, field
"""
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.utils import node_to_html, node_to_markdown, node_to_plaintext
from mastoposter.text import node_process
def _date(val: str) -> datetime:
@ -51,7 +66,9 @@ class Emoji:
@classmethod
def from_dict(cls, data: dict) -> "Emoji":
return cls(**data)
return cls(
**{f.name: data[f.name] for f in fields(cls) if f.name in data}
)
@dataclass
@ -70,7 +87,7 @@ class Account:
emojis: List[Emoji]
discoverable: bool
created_at: datetime
last_status_at: datetime
last_status_at: Optional[datetime]
statuses_count: int
followers_count: int
following_count: int
@ -95,7 +112,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(data["last_status_at"]),
last_status_at=_date_or_none(data.get("last_status_at")),
statuses_count=data["statuses_count"],
followers_count=data["followers_count"],
following_count=data["following_count"],
@ -108,6 +125,15 @@ class Account:
def name(self) -> str:
return self.display_name or self.username
@property
def name_emojiless(self) -> str:
if not self.display_name:
return self.username
name = self.display_name
for emoji in self.emojis:
name = name.replace(":%s:" % emoji.shortcode, "")
return name.strip() or self.username
@dataclass
class AttachmentMetaImage:
@ -130,10 +156,10 @@ class AttachmentMetaImage:
@classmethod
def from_dict(cls, data: dict) -> "AttachmentMetaImage":
return cls(
**data,
**{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"]),
)
@ -172,7 +198,7 @@ class AttachmentMetaVideo:
return cls(
**data,
original=cls.AttachmentMetaVideoOriginal(**data["original"]),
small=cls.AttachmentMetaVideoSmall(**data["small"])
small=cls.AttachmentMetaVideoSmall(**data["small"]),
)
@ -191,7 +217,9 @@ class Attachment:
@classmethod
def from_dict(cls, data: dict) -> "Attachment":
return cls(**data)
return cls(
**{f.name: data[f.name] for f in fields(cls) if f.name in data}
)
@dataclass
@ -202,7 +230,9 @@ class Application:
@classmethod
def from_dict(cls, data: dict) -> "Application":
return cls(**data)
return cls(
**{f.name: data[f.name] for f in fields(cls) if f.name in data}
)
@dataclass
@ -214,7 +244,9 @@ class Mention:
@classmethod
def from_dict(cls, data: dict) -> "Mention":
return cls(**data)
return cls(
**{f.name: data[f.name] for f in fields(cls) if f.name in data}
)
@dataclass
@ -224,7 +256,9 @@ class Tag:
@classmethod
def from_dict(cls, data: dict) -> "Tag":
return cls(**data)
return cls(
**{f.name: data[f.name] for f in fields(cls) if f.name in data}
)
@dataclass
@ -322,18 +356,18 @@ class Status:
@property
def content_flathtml(self) -> str:
return node_to_html(
BeautifulSoup(self.content, features="lxml")
return node_process(
BeautifulSoup(self.content, features="lxml"), "html"
).rstrip()
@property
def content_markdown(self) -> str:
return node_to_markdown(
BeautifulSoup(self.content, features="lxml")
return node_process(
BeautifulSoup(self.content, features="lxml"), "markdown"
).rstrip()
@property
def content_plaintext(self) -> str:
return node_to_plaintext(
BeautifulSoup(self.content, features="lxml")
return node_process(
BeautifulSoup(self.content, features="lxml"), "plain"
).rstrip()

View File

@ -1,60 +1,36 @@
from html import escape
from bs4.element import Tag, PageElement
"""
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")
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)),
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
)
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)
conf[section][normalized_key] = v
_remove.add(k)
for k in _remove:
logger.info("removing key %r.%r", section, k)
del conf[section][k]

52
pyproject.toml Normal file
View File

@ -0,0 +1,52 @@
[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

191
tests/test_text_utils.py Normal file
View File

@ -0,0 +1,191 @@
"""
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>'