Initial Commit
This commit is contained in:
commit
883a85ec7f
29
.gitignore
vendored
Normal file
29
.gitignore
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
# User preferance files
|
||||
/rsc/
|
||||
/md5/
|
||||
/src/cfg*.py
|
||||
|
||||
# Virtual environment
|
||||
/venv/
|
||||
/src/__pycache__/
|
||||
|
||||
# PyCharm IDE folder
|
||||
/.idea/
|
||||
|
||||
# Editor files
|
||||
/*~
|
||||
/*#
|
||||
|
||||
# Automation scripts + odds and ends
|
||||
/notes.txt
|
||||
/compile.sh
|
||||
/upload.sh
|
||||
/balance_2.csv
|
||||
/DEFAULT.csv
|
||||
/generate_random.sh
|
||||
/src/make_master_template.py
|
||||
/src/make_master_list.py
|
||||
/src/hash_path_exists.py
|
||||
/utils/
|
||||
/cfg_availible/
|
||||
/profile/
|
674
LICENSE.txt
Normal file
674
LICENSE.txt
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
216
README.md
Normal file
216
README.md
Normal file
@ -0,0 +1,216 @@
|
||||
# Readme
|
||||
Yandere Lewd Bot is a customizable, no frills image-posting bot for Pleroma.
|
||||
|
||||
A live example can be viewed at [Neckbeard.xyz](https://neckbeard.xyz/YandereLewdBot).
|
||||
|
||||
Currently the bot will only run on Linux. I believe it should run on most distros but I have only tested it on Arch and Raspbian.
|
||||
|
||||
## Usage
|
||||
```text
|
||||
usage: main.py [--dry-run] [--debug] [-w WAIT] [-t TIME] [-d DATE] [-c CONFIG]
|
||||
[-o] [-h]
|
||||
|
||||
A bot for posting on Mastodon
|
||||
|
||||
optional arguments:
|
||||
--dry-run Will not login or post to Plemora
|
||||
--debug Same as --dry-run
|
||||
-w WAIT, --wait WAIT Wait before posting first image (seconds)
|
||||
-t TIME, --time TIME Wait for time before posting first image
|
||||
-d DATE, --date DATE Wait for date before posting first image
|
||||
-c CONFIG, --config CONFIG
|
||||
Set custom config file (Default: cfg)
|
||||
-o, --output-hashes Output list of hashes
|
||||
-h, --help Show this help message and exit
|
||||
|
||||
TIME %I:%M%p 03:58PM
|
||||
DATE %m/%d/%Y 11/26/2021
|
||||
```
|
||||
|
||||
## About
|
||||
Yandere Lewd Bot is designed to be simple to understand (from a technical perspective) and easy to modify/extend. Yandere Lewd Bot relies on GNU formatted hash files to configure and organize posts (from the GNU coreutils package):
|
||||
(ex. `26d00a6ee5ae8fa3d58ee44b32b8992f *./rsc/nsfw/image.jpg`)
|
||||
|
||||
The bot is still in development and can easily be crashed by writing a poorly configured `cfg.py` file, or messing with the hash files it uses to configure posts.
|
||||
|
||||
## Installing
|
||||
To setup the python3 environment (for Arch Linux) run the following commands:
|
||||
```
|
||||
sudo pacman -Syu
|
||||
sudo pacman -S --needed python git
|
||||
git clone 'https://github.com/YandereLewdBot/YandereLewdBot.git'
|
||||
cd yandereLewdBot/
|
||||
python -m venv venv
|
||||
source ./venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -r requierements.txt
|
||||
deactivate
|
||||
cp ./bin/cfg_default.py ./bin/cfg.py
|
||||
<chmod.txt xargs -i chmod +x '{}'
|
||||
./run.sh -h
|
||||
```
|
||||
If everything worked correctly you should see usage information on Yandere Lewd Bot.
|
||||
|
||||
The ./run.sh file will automatically activate and deactive the python virtual environment. You may want add a symlink to `/usr/local/bin` for convienence.
|
||||
|
||||
```
|
||||
sudo ln -s "$(pwd)/run.sh" "/usr/local/bin/yandereLewdBot"
|
||||
yandereLewdBot -h
|
||||
```
|
||||
|
||||
For Debian or Ubuntu based distros I believe you need to change python with python3 for the package and command name `¯\_(ツ)_/¯`
|
||||
## Generating your OAuth Tokens
|
||||
Before you can begin posting from the bot, you must first create an account on the instance of your choice, and then generate your OAuth tokens.
|
||||
|
||||
To generate your tokens, run the following commands and follow the interactive prompts.
|
||||
```
|
||||
source ./venv/bin/activate
|
||||
./bin/create_app.py
|
||||
# Follow the interactive prompts.
|
||||
deactivate
|
||||
```
|
||||
|
||||
**NOTE:** Yandere Lewd Bot only requieres write permissions. When prompted you should accept the default permission unless extending the bot's default functionality.
|
||||
|
||||
If you did everything correctly you should see `Success! :)` at the end of the terminal, as well as your credentials in the format below:
|
||||
```text
|
||||
settings_server = OrderedDict([
|
||||
"app_name": "app",
|
||||
"api_base_url": "https://neckbeard.xyz",
|
||||
"client_id": "Long String of Text",
|
||||
"client_secret": "Long String of Text",
|
||||
"access_token": "Long String of Text"
|
||||
])
|
||||
|
||||
settings_reminder = "09/20/2020 02:58PM"
|
||||
|
||||
settings_encrypt = {
|
||||
"encrypt": False,
|
||||
"salt": "",
|
||||
}
|
||||
```
|
||||
If you used encryption, everything in the `settings_server` dictionary will be encrypted and you will have to enter your password every time you start the bot. Your `settings_encrypt` will look like this:
|
||||
```text
|
||||
settings_encrypt = {
|
||||
"encrypt": True,
|
||||
"salt": "A Short String of Text",
|
||||
}
|
||||
```
|
||||
|
||||
Copy and paste these values from the terminal into your `bin/cfg.py` file. **Make sure you paste over or delete the placeholder values with the same names.**
|
||||
## Posting
|
||||
To begin posting:
|
||||
|
||||
- Make sure you already have a Pleroma account set up .
|
||||
- Generate your OAuth tokens following the guide above.
|
||||
- Put some images in the rsc/ folder (organize by safe and nsfw posts).
|
||||
- 'safe' posts will be marked with `#yandere`
|
||||
- 'nsfw' posts will be spoilered and marked as `#yandere #nsfw`
|
||||
- cd into the root directory (the directory with `run.sh`)
|
||||
- Start the bot with `./run.sh`
|
||||
- Enter your password if you encrypted your OAuth tokens.
|
||||
- If you symlinked the file in the [Installing](##installing) section you can simply run `yandereLewdBot` instead of changing directories and starting the bot with `./run.sh`
|
||||
- If everything worked correctly, you should see your first image posted to your account.
|
||||
- Hit Ctrl+C to stop the bot.
|
||||
- When you start the bot again, it will begin posting from where it last left off.
|
||||
- It accomplishes this by writing to a `md5/blacklist.txt` file. If you see this file, it worked correctly.
|
||||
- Keep in mind that the bot's default visibility setting is set to unlisted for testing. You may want to update it to public.
|
||||
- Read [docs/configuration.md](configuration.md) to customize the bot for your purposes.
|
||||
|
||||
# Useful Tips and Commands
|
||||
## Quickly Sum the Entire rsc/ Folder
|
||||
To quickly sum everything in the `rsc/` folder, run the following commands:
|
||||
```
|
||||
cd yandereLewdBot/
|
||||
find "./rsc" -type f -exec md5sum -b {} \; > "./md5/master_file.txt"
|
||||
```
|
||||
## Installing Screen
|
||||
Most likely, you will want this bot to run over a long period of time. It is probobly best to install the `screen` package for Linux so you don't have to have a terminal window constantly open (especially if you are running it from a remote machine such as a Raspberry Pi or server).
|
||||
```
|
||||
sudo pacman -Syu
|
||||
sudo pacman -S --needed screen
|
||||
|
||||
# Screen cheatsheet
|
||||
# To create a new screen session named 'yandereLewdBot'
|
||||
screen -S yandereLewdBot
|
||||
# To detach from the screen session
|
||||
Ctrl+a d
|
||||
# To reconnect to the screen session
|
||||
screen -r yandereLewdBot
|
||||
# List screen sessions
|
||||
screen -ls
|
||||
# Kill the screen session
|
||||
Ctrl+a k y
|
||||
# Scroll back
|
||||
Ctrl+a ESC Page Up
|
||||
# End scroll back
|
||||
ESC
|
||||
```
|
||||
## A More Useful rsc/ Folder Structure
|
||||
A more advanced (and useful) way of organizing images in the `rsc/` folder is by date added, group (such as a character name like Yuno Gasai), and safe/nsfw profiles. To do this, the following folder structure would be used: `rsc/year.month.day/character/safe_or_nsfw/image.png`
|
||||
|
||||
To configure this in the `settings_post` section, use the following for safe/nsfw repectivly:
|
||||
```
|
||||
setup_safe_profile("Yuno.safe", "./rsc/*/Yuno/safe/*", "#Yuno_Gasai #yandere")
|
||||
setup_nsfw_profile("Yuno.nsfw", "./rsc/*/Yuno/nsfw/*", "#Yuno_Gasai #nsfw #yandere")
|
||||
```
|
||||
Notice the wildcard character `'*'` is used in place of year.month.day. This will match any folder in the resource folder, and all of our folders will be in order of when we added them.
|
||||
## A Master Blacklist
|
||||
The default configuration file has the following settings below (these files will not exist by default. The bot will simply ignore blacklist hash files that it can't open). The _r stands for read and the _w stands for write. This will ensure that the master_blacklist.txt is always read, but is never written to. This is intended for the user to manually add GNU formatted hashes to master_blacklist.txt in case they want to make especially sure that hashes and paths that are matched in the list are never uploaded accidentally.
|
||||
```
|
||||
"master_blacklist_r": ("./md5/blacklist.txt", "./md5/master_blacklist.txt"),
|
||||
"master_blacklist_w": ("./md5/blacklist.txt",),
|
||||
```
|
||||
## Quickly Create Configuration Files
|
||||
Configuration files for Yandere Lewd Bot are just python files. Because of this we can easily create multiple configurations by importing the main configuration file, and overriding the values we need. This is useful for creating holiday and debug configurations without needing to create a new configuration file from scratch.
|
||||
```
|
||||
# Name: alt.py
|
||||
# Post to an alt account using the exact same settings as the main configuration file
|
||||
# Run with the following command: ./run.sh -c alt
|
||||
|
||||
# cfg.py is the default configuration. You should set this to whatever you are overriding.
|
||||
from cfg import *
|
||||
|
||||
settings_server = OrderedDict([
|
||||
("app_name", "generate from ./bin/create_app.py"),
|
||||
("api_base_url", "generate from ./bin/create_app.py"),
|
||||
("client_id", "generate from ./bin/create_app.py"),
|
||||
("client_secret", "generate from ./bin/create_app.py"),
|
||||
("access_token", "generate from ./bin/create_app.py")
|
||||
])
|
||||
|
||||
settings_reminder = "generate from ./bin/create_app.py"
|
||||
|
||||
settings_encrypt = {
|
||||
"encrypt": False,
|
||||
"salt": "generate from ./bin/create_app.py"
|
||||
}
|
||||
|
||||
settings_behavior["master_blacklist_r"] = ("./md5/blacklist_alt.txt", "./md5/master_blacklist.txt")
|
||||
settings_behavior["master_blacklist_w"] = ("./md5/blacklist_alt.txt",)
|
||||
|
||||
# Uncommenting the below might be useful if your alt is used for debugging and testing
|
||||
# settings_behavior["master_list"] = ("master_file_alt.txt",)
|
||||
# settings_behavior["visibility"] = "private"
|
||||
# settings_behavior["debug"] = True
|
||||
# settings_behavior["master_blacklist_w"] = tuple()
|
||||
```
|
||||
|
||||
```
|
||||
# Name: xmas.py
|
||||
# An xmas themed config file!
|
||||
# Run with the following command: ./run.sh -c xmas
|
||||
|
||||
# cfg.py is the default configuration. You should set this to whatever you are overriding.
|
||||
from cfg import *
|
||||
|
||||
settings_behavior["master_list"] = ("./md5/event_xmas.txt",)
|
||||
settings_behavior["master_blacklist_r"] = ("./md5/blacklist_xmas.txt", "master_blacklist.txt")
|
||||
settings_behavior["master_blacklist_w"] = ("./md5/blacklist_xmas.txt",)
|
||||
|
||||
# Prepend '#Merry #Christmas' to the beginning of the first line in each post
|
||||
for setting in settings_post:
|
||||
if len(setting["message"]) and issubclass(type(setting["message"][0]), str):
|
||||
new_msg = "#Merry #Christmas {}".format(setting["message"][0])
|
||||
setting["message"] = (new_msg,) + setting["message"][1:]
|
||||
```
|
139
docs/configuration.md
Normal file
139
docs/configuration.md
Normal file
@ -0,0 +1,139 @@
|
||||
# Configuration
|
||||
Yandere Lewd Bot uses regular python files to configure posts. The default configuration is `cfg.py`
|
||||
|
||||
Included in the file are three [helper functions](#setting-up-profiles-in-a-single-line) to quickly configure posts. These are located at the top of the configuration file.
|
||||
|
||||
Below is a detailed description of each parameter in the configuration file.
|
||||
|
||||
## setting_server
|
||||
Paste the generated credentials from `create_app.py` in the fields below.
|
||||
|
||||
**`app_name:`** The name of the application.
|
||||
|
||||
**`api_base_url:`** The URL of the instance.
|
||||
|
||||
**`client_id:`** The client ID generated by `create_app.py`
|
||||
|
||||
**`client_secret:`** The client secret generated by `create_app.py`
|
||||
|
||||
**`access_token:`** The client token generated by `create_app.py`
|
||||
|
||||
**NOTE:** If you enabled encryption when generating your tokens, the above should be long strings of seemingly incoherent text.
|
||||
|
||||
## settings_reminder
|
||||
A setting to remind the user to regenerate their OAuth tokens
|
||||
|
||||
**`settings_reminder:`** A date and time, formatted as `settings_time["long_date_format"]`. Used to remind the user to regenerate their OAuth tokens.
|
||||
|
||||
## settings_encrypt
|
||||
Paste the generated credentials from `create_app.py` in the fields below.
|
||||
|
||||
**`encrypt:`** If encryption is enabled this should be set to `True`
|
||||
|
||||
**`salt:`** The salt value generated by `create_app.py`
|
||||
|
||||
## settings_behavior
|
||||
This is the main configuration setting for the bot.
|
||||
|
||||
**`master_list:`** The master list(s) for the bot to post from. This should be a GNU formatted hash file. If multiple lists are specified they will be concatenated in order.
|
||||
|
||||
**`master_blacklist_r:`** The master blacklist(s) to be *read* when the bot starts. This should be a GNU formatted hash file. All hashes and paths specified in this setting will be blacklisted when the bot initializes and will not be posted.
|
||||
|
||||
**`master_blacklist_w:`** The master file(s) to *write* to when the bot makes a successful post. This will be a GNU formatted hash file.
|
||||
|
||||
**`max_size:`** The max upload size (in bytes). Files that are over will be excluded from posting. Set this to `None` if there is no limit (not recommended). If you find that the bot is continuously attempting to repost a post that is failing, and the connection is timing out, it usually signifies that you are attempting to upload a large file over a slow connection and getting dropped from the server. Reducing this value should fix the issue.
|
||||
|
||||
**`visibility:`** The visibility of the post ('public', 'unlisted', 'private', or 'direct').
|
||||
|
||||
**`feature_set:`** The feature set of the instance you are connecting to ('mainline', 'fedibird', or 'pleroma'). **This bot has only been tested with 'pleroma'.**
|
||||
|
||||
**`sleep_seconds:`** The time between posts (in seconds)
|
||||
|
||||
**`uploads_per_post:`** The number of times the bot should post after `sleep_seconds`
|
||||
|
||||
**`retry_seconds:`** The time the bot should wait before attempting to re-upload a post that failed (in seconds). This value is ignored if the bot experiences a FileNotFoundError (the file was deleted after the bot was started) or encounters a 413 error (file upload size is too large). In either of the two cases the bot will continue posting the next image in the list.
|
||||
|
||||
**`multi_media_ext:`** Files ending with this extension will be treated as a multi-upload list. All GNU formatted hashes contained within will be uploaded in a single post when picked by the bot. Setting this value to `None` or `False` will disable this behavior.
|
||||
|
||||
**`content_type:`** The content type of the post ('text/plain' (default), 'text/markdown', 'text/html', 'text/bbcode'). **This bot has only been tested with `'text/plain'` and `'text/markdown'`**.
|
||||
|
||||
**`content_newline:`** The newline character or string. This will be inserted between each line in the message. If `content_type` is `'text/plain'`, this value should be `'\n'`. If `content_type` is `'text/markdown'` you may need to experiment. On some instances the defualt `'\n'` works, on others you may need to change this to `'<br/>'`.
|
||||
|
||||
**`post_image_link:`** If set to `True` this will insert a direct media link at the end of the message for each media file uploaded. If `content_type` is `'text\markdown'` it will make the link actionable, otherwise it will simply be a plain text html link. Some instances add this link automatically, in which case this should be set to `False`. See `content_newline` and `content_type` to correctly configure actionable links.
|
||||
|
||||
**`post_random:`** Shuffle all items in `master_list` so that they post in random order.
|
||||
|
||||
**`atomic_saving:`** If set to `True`, when the bot blacklists a file it will create a temporary copy of the file(s) that it is writing to. It will write to the temp file, then write over the old file. This is basically a paranoid saving option in case your server loses power unexpectedly while the bot is writing data. Generally speaking setting this option to `True` is probably unnecessary and will result in excessive writes to the disk.
|
||||
|
||||
**`sync_save:`** If set to`True` the bot will synchronize data to the disk immediately when it writes to a blacklist file. Generally speaking this should be set to `True` in case the server looses power unexpectedly. It should be set to `False` you are posting a lot of images at once. You should also be aware that if `atomic_saving` is enabled, it will syncronize all writes to and from the temp file which is probobly excessive.
|
||||
|
||||
**`tmp_dir:`** The temporary directory to use if `atomic_saving` is set to `True`. The default location is `/var/tmp`.
|
||||
|
||||
**`debug:`** Set this to true for testing. This will prevent Yandere Lewd Bot from logging into the mastodon instance and asking for your encryption password (meaning that nothing will actually get posted to your account, but it will still do everything else).
|
||||
|
||||
**NOTE:** `master_list`, `master_blacklist_r`, and `master_blacklist_w` all take a tuple() of str(). Please see below for formatting help.
|
||||
> To specify multiple files: `master_blacklist_r: ("./md5/blacklist.txt", "./md5/master_blacklist.txt"),`
|
||||
> To specify a single file: `master_blacklist_r: ("./md5/blacklist.txt",),`
|
||||
> To specify no file: `master_blacklist_r: tuple(),`
|
||||
|
||||
## settings_time
|
||||
Time localization settings.
|
||||
|
||||
**`time_format:`** This is used to schedule posts using the `-t` switch. Referenced in `set_pretimer_hour()`
|
||||
|
||||
**`time_format_seconds:`** Unused. Should be the same as `time_format` but with a resolution in seconds.
|
||||
|
||||
**`date_format:`** This is used to schedule posts using the `-d` switch. Referenced in `set_pretimer_day()`
|
||||
|
||||
**`long_date_format:`** Time and date format. `settings_encrypt["reminder"]` Should be in this format. Referenced in `print_header_stats()` and `_sanity_warnings()`
|
||||
|
||||
**`long_date_seconds_format:`** Unused. Should be the same as `long_date_format` but with a resolution in seconds.
|
||||
|
||||
**`long_date_week:`** The same as `long_date_format` but with the day of the week specified. Referenced in `print_header_stats()`
|
||||
|
||||
## settings_post
|
||||
Configure Yandere Lewd Bot profiles. In the default configuration, images are sorted by safe and nsfw profiles. This means that all 'safe' images should be located in `./rsc/safe/*` and all 'nsfw' images should be located in `./rsc/nsfw/*`. The bot will apply profiles based on it's file path using [Unix filename pattern matching](https://docs.python.org/3/library/fnmatch.html).
|
||||
|
||||
**`settings_post:`** A tuple() containing all of the profile dictionaries that the bot can post. See `setup_profile()`, `setup_nsfw_profile()`, and `setup_safe_profile()` for help configuring custom profiles.
|
||||
|
||||
**`settings_post_default:`** The default post profile. If no profile can be matched for an item in the `master_list` it will default to the profile specified by this value. If the value is `None`, the bot will error out and output the offending line(s) from the hash file (recommended). If you want to apply a default post behavior for unmatched profiles, create a default setting with `setup_profile()` helper function. The Unix `path` keyword will be completely ignored.
|
||||
|
||||
# Setting Up Profiles
|
||||
Each profile in `settings_post` contains a dictionary with the following keywords: `name`, `path`, `message`, and `spoiler`
|
||||
|
||||
Below is an explanation of each keyword:
|
||||
|
||||
* **`name:`** String value. The name of the profile. This is mainly used to help you identify what profile is being applied to posts. This information is printed by the bot, but is otherwise unused.
|
||||
|
||||
* **`path:`** String value. This should be a Unix path with wildcards. The bot will configure posts accordingly by using [Unix filename pattern matching](https://docs.python.org/3/library/fnmatch.html) implemented in the `fnmatch` python library.
|
||||
|
||||
* **`message:`** A tuple of strings. The message. Each string in the tuple will be placed on a new line.
|
||||
|
||||
* **`spoiler:`** Boolean value. Mark the media as sensitive. Use for nsfw or spoilers.
|
||||
|
||||
## Setting Up Profiles in a Single Line
|
||||
At the top of the default configuration file are the following three helper functions to make setting up posts more intuative.
|
||||
>**`setup_profile(name, path, spoiler, *message)`**
|
||||
**`setup_nsfw_profiles(name, path, *message)`**
|
||||
**`setup_safe_profiles(name, path, *message)`**
|
||||
|
||||
---
|
||||
**`setup_profile(name, path, spoiler, *message)`**
|
||||
Returns a post setting dictionary that contains all of the information about a single profile. Each parameter corresponds to the keywords listed above.
|
||||
|
||||
* **`name:`** The name of the profile.
|
||||
|
||||
* **`path:`** A Unix path with wildcards.
|
||||
|
||||
* **`spoiler:`** Mark the media as sensitive. Use for nsfw or spoilers.
|
||||
|
||||
* **`*message:`** The message. This is a variable length parameter (meaning that multiple parameters may be passed to it). Each line in your message should be passed as a separate string to the `*message` variable.
|
||||
>**DO NOT** use the newline character `\n` to configure multiline messages. Instead pass each line as a separate string parameter: ex. `setup_profile("profile.safe", "./rsc/safe/*", False, "First line in my message", "Second line in my message")`
|
||||
|
||||
> Each line in the example above will be placed on a new line.
|
||||
|
||||
**`setup_nsfw_profiles(name, path, *message)`**
|
||||
Returns a post_setting dictionary that contains all of the information about a single **nsfw** profile.
|
||||
|
||||
**`setup_safe_profiles(name, path, *message)`**
|
||||
Returns a post_setting dictionary that contains all of the information about a single **safe** profile.
|
2
requirements.txt
Normal file
2
requirements.txt
Normal file
@ -0,0 +1,2 @@
|
||||
Mastodon.py
|
||||
cryptography
|
19
run.sh
Executable file
19
run.sh
Executable file
@ -0,0 +1,19 @@
|
||||
#! /usr/bin/env bash
|
||||
|
||||
# Get the runtime path of the bot
|
||||
ABS_PATH="$(readlink -f "$0")"
|
||||
RUN_DIR="$(dirname "$ABS_PATH")"
|
||||
|
||||
# Relative paths to the virtual environment and main.py
|
||||
VENV='./venv/bin/activate'
|
||||
ENTRY='./src/main.py'
|
||||
|
||||
# cd into the bot's root path, set up the virtual environment, and run
|
||||
cd "$RUN_DIR"
|
||||
[ ! -f "$VENV" ] && echo "Virtual environment not found: ${VENV}" && cd - > /dev/null && exit 1
|
||||
source "$VENV"
|
||||
"$ENTRY" "$@"
|
||||
|
||||
# Cleanup
|
||||
deactivate
|
||||
cd - > /dev/null
|
143
src/create_app.py
Executable file
143
src/create_app.py
Executable file
@ -0,0 +1,143 @@
|
||||
#! /usr/bin/env python
|
||||
|
||||
# Program Name: Name
|
||||
# Purpose: Purpose
|
||||
|
||||
import getpass
|
||||
import re
|
||||
import sys
|
||||
import datetime
|
||||
import importlib
|
||||
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonAPIError, MastodonIOError
|
||||
from collections import OrderedDict
|
||||
import yanlib
|
||||
|
||||
|
||||
class CreateAppError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def get_client_id_and_secret(app, permissions, domain):
|
||||
try:
|
||||
return Mastodon.create_app(app, scopes=permissions, api_base_url=domain)
|
||||
except MastodonIOError:
|
||||
raise CreateAppError("An error occurred. Make sure the domain name is correct.")
|
||||
|
||||
|
||||
def get_api(client_id, client_secret, domain):
|
||||
api = Mastodon(client_id, client_secret, api_base_url=domain)
|
||||
return api
|
||||
|
||||
|
||||
def get_token(api, email, password, permissions):
|
||||
try:
|
||||
token = api.log_in(email, password, scopes=permissions)
|
||||
return token
|
||||
except MastodonIllegalArgumentError:
|
||||
raise CreateAppError("Username or Password is incorrect.")
|
||||
except MastodonAPIError:
|
||||
raise CreateAppError("Could not grant scopes:", ", ".join(permissions))
|
||||
|
||||
|
||||
def get_cfg(cfg_name):
|
||||
try:
|
||||
cfg = importlib.import_module(cfg_name)
|
||||
return cfg
|
||||
except ImportError:
|
||||
raise CreateAppError("Cannot import module:", cfg_name, "Make sure you omitted the .py extension and try again")
|
||||
|
||||
|
||||
def package_settings(app, domain, client_id, client_secret, token):
|
||||
settings_server = OrderedDict([
|
||||
("app_name", app),
|
||||
("api_base_url", domain),
|
||||
("client_id", client_id),
|
||||
("client_secret", client_secret),
|
||||
("access_token", token)
|
||||
])
|
||||
return settings_server
|
||||
|
||||
|
||||
def get_setting_reminder(fmt):
|
||||
dt_now = datetime.datetime.now()
|
||||
dt_now = dt_now.replace(year=dt_now.year + 1)
|
||||
settings_reminder = dt_now.strftime(fmt)
|
||||
return settings_reminder
|
||||
|
||||
|
||||
def main():
|
||||
# Create App
|
||||
print("Generate and register Mastodon App")
|
||||
print("You can just hit enter to accept the default for prompts that have them")
|
||||
print("Ctrl+C to Quit\n")
|
||||
|
||||
try:
|
||||
# Get instance information
|
||||
app = input("Enter your app name (Default: app): ") or "app"
|
||||
domain = input("URL of Instance (Default: https://yandere.cc): ") or "https://yandere.cc"
|
||||
email = input("Enter your email: ")
|
||||
password = getpass.getpass("Enter password: ")
|
||||
print("Scopes: read, write, follow, push")
|
||||
print("Separate each scope with a comma (example above).")
|
||||
print("!!! Accept the default unless you intend to modify Yandere Lewd Bot !!!")
|
||||
ans = input("Scopes (Default: write): ") or "write"
|
||||
ans = re.sub(r"\s+", "", ans, flags=re.UNICODE)
|
||||
permissions = ans.split(",")
|
||||
print("Granting:", permissions)
|
||||
|
||||
# Begin logging in
|
||||
client_id, client_secret = get_client_id_and_secret(app, permissions, domain)
|
||||
api = get_api(client_id, client_secret, domain)
|
||||
token = get_token(api, email, password, permissions)
|
||||
|
||||
# Get user setting for settings_time["long_date_format"]
|
||||
# Needed for setting_reminder
|
||||
print("What is the name of your main configuration file? Exclude the '.py' extension.")
|
||||
ans = input("(Default: cfg): ") or "cfg"
|
||||
cfg = get_cfg(ans)
|
||||
|
||||
# Credentials (unencrypted)
|
||||
encrypt, salt = False, ""
|
||||
settings_server = package_settings(app, domain, client_id, client_secret, token)
|
||||
reminder = get_setting_reminder(cfg.settings_time["long_date_format"])
|
||||
|
||||
# Encrypt
|
||||
ans = input("Do you want to encrypt your credentials (y/N)? ")
|
||||
if ans.upper() in ("Y", "YES"):
|
||||
import encryption
|
||||
encrypt = True
|
||||
salt, settings_server = encryption.settings_server_encrypt_cfg(settings_server)
|
||||
|
||||
settings_encrypt = OrderedDict([
|
||||
("encrypt", encrypt),
|
||||
("salt", salt),
|
||||
])
|
||||
|
||||
# Output the user's new credentials
|
||||
print("Copy to your config file!!!")
|
||||
yanlib.pp_ordered_dict("settings_server", settings_server)
|
||||
print('\nsettings_reminder = "{}"\n'.format(reminder))
|
||||
yanlib.pp_dict("settings_encrypt", settings_encrypt)
|
||||
|
||||
return 0
|
||||
except (KeyboardInterrupt, EOFError):
|
||||
print("Quitting...")
|
||||
return 1
|
||||
except CreateAppError as e:
|
||||
print(e)
|
||||
return 2
|
||||
except Exception as e:
|
||||
print("Unhandled Exception!!", e)
|
||||
return 3
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
status_code = main()
|
||||
status_msg = {
|
||||
0: "Success :)",
|
||||
1: "User Quit :|",
|
||||
2: "Error :(",
|
||||
3: "Unhandled Exception ¯\\_(ツ)_/¯"
|
||||
}
|
||||
print(status_msg[status_code])
|
||||
sys.exit(status_code)
|
231
src/encryption.py
Executable file
231
src/encryption.py
Executable file
@ -0,0 +1,231 @@
|
||||
#! /usr/bin/env python
|
||||
|
||||
# Program Name: Encryption
|
||||
# Purpose: Encrypt and store key
|
||||
|
||||
import sys
|
||||
import base64
|
||||
import os
|
||||
import getpass
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
|
||||
class PasswordMismatch(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# Salts
|
||||
def generate_salt():
|
||||
return os.urandom(16)
|
||||
|
||||
|
||||
# Return string from bytes
|
||||
def salt_encode(b):
|
||||
return base64.urlsafe_b64encode(b).decode()
|
||||
|
||||
|
||||
# Return bytes from string
|
||||
def salt_decode(s):
|
||||
return base64.urlsafe_b64decode(s.encode())
|
||||
|
||||
|
||||
# Ordered Dictionaries
|
||||
def change_encoding_dict(settings_server, encoding_type):
|
||||
return OrderedDict([(k, encoding_type(v)) for k, v in settings_server.items()])
|
||||
|
||||
|
||||
# Return bytes from string
|
||||
def encode_dict(settings_server):
|
||||
return change_encoding_dict(settings_server, str.encode)
|
||||
|
||||
|
||||
# Return string from bytes
|
||||
def decode_dict(settings_server):
|
||||
return change_encoding_dict(settings_server, bytes.decode)
|
||||
|
||||
|
||||
# password: Bytes
|
||||
# salt: Bytes
|
||||
def derive_key(password, salt):
|
||||
kdf = PBKDF2HMAC(
|
||||
algorithm=hashes.SHA256(),
|
||||
length=32,
|
||||
salt=salt,
|
||||
iterations=100000,
|
||||
backend=default_backend()
|
||||
)
|
||||
r_key = base64.urlsafe_b64encode(kdf.derive(password))
|
||||
return r_key
|
||||
|
||||
|
||||
# Encryption functions
|
||||
# message: Bytes
|
||||
# key: Bytes
|
||||
def encrypt(message, key):
|
||||
f = Fernet(key)
|
||||
token = f.encrypt(message)
|
||||
return token
|
||||
|
||||
|
||||
# token: Bytes
|
||||
# key: Bytes
|
||||
def decrypt(token, key):
|
||||
f = Fernet(key)
|
||||
message = f.decrypt(token)
|
||||
return message
|
||||
|
||||
|
||||
# password: bytes()
|
||||
# salt: bytes()
|
||||
# settings_server: dict() -> Byte values
|
||||
# encryption_function: encrypt(message, key) : decrypt(token, key):
|
||||
# Returns settings_server_decrypted dictionary with Byte() values. Will need to use
|
||||
# ChangeEncodingDict to make them strings (recommended cfg file friendly)
|
||||
def __settings_server(password, salt, settings_server, encryption_function):
|
||||
key = derive_key(password, salt)
|
||||
settings_server_decrypted = OrderedDict()
|
||||
for setting in settings_server:
|
||||
settings_server_decrypted[setting] = encryption_function(settings_server[setting], key)
|
||||
return settings_server_decrypted
|
||||
|
||||
|
||||
# Returns (salt, settings_server)
|
||||
def _settings_server_encrypt(settings_server):
|
||||
salt = generate_salt()
|
||||
password = getpass.getpass("Enter password: ")
|
||||
password2 = getpass.getpass("Retype Password: ")
|
||||
|
||||
if password != password2:
|
||||
raise PasswordMismatch
|
||||
|
||||
settings_server_encrypted = __settings_server(password.encode(), salt, encode_dict(settings_server), encrypt)
|
||||
|
||||
return salt, settings_server_encrypted
|
||||
|
||||
|
||||
# Returns (settings_server)
|
||||
def _settings_server_decrypt(settings_server, settings_encrypt):
|
||||
settings_server_encoded = encode_dict(settings_server)
|
||||
if settings_encrypt["encrypt"]:
|
||||
salt = salt_decode(settings_encrypt["salt"])
|
||||
password = getpass.getpass("Enter password: ")
|
||||
return __settings_server(password.encode(), salt, settings_server_encoded, decrypt)
|
||||
else:
|
||||
return settings_server_encoded
|
||||
|
||||
|
||||
# Wrapper function that will catch exceptions and exit
|
||||
def settings_server_new(function, **kwargs):
|
||||
try:
|
||||
return function(**kwargs)
|
||||
|
||||
# If the user cancels the login
|
||||
except KeyboardInterrupt:
|
||||
print("\nQuitting...")
|
||||
|
||||
# If the user passwords do not match (encrypt)
|
||||
except PasswordMismatch:
|
||||
print("Passwords do not match...")
|
||||
|
||||
# Incorrect password entered (decrypt)
|
||||
except InvalidToken:
|
||||
print("Password or Token Incorrect...")
|
||||
|
||||
# Probably the salt value got modified
|
||||
except base64.binascii.Error:
|
||||
print("Salt is invalid...")
|
||||
|
||||
# Some other kind of fuck up
|
||||
except Exception as e:
|
||||
print("Unknown exception occurred...")
|
||||
print(e)
|
||||
|
||||
# Exit if an exception was thrown
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# Glue functions that package **kwargs automatically
|
||||
def settings_server_encrypt(settings_server):
|
||||
kwargs = {"settings_server": settings_server}
|
||||
return settings_server_new(_settings_server_encrypt, **kwargs)
|
||||
|
||||
|
||||
def settings_server_decrypt(settings_server, settings_encrypt):
|
||||
kwargs = {
|
||||
"settings_server": settings_server,
|
||||
"settings_encrypt": settings_encrypt
|
||||
}
|
||||
return settings_server_new(_settings_server_decrypt, **kwargs)
|
||||
|
||||
|
||||
# The _cfg functions should return a regular string
|
||||
# These are the functions that should interface with the bot a return a plain string
|
||||
# settings_server ordered dictionary
|
||||
def settings_server_encrypt_cfg(settings_server):
|
||||
salt, settings_server = settings_server_encrypt(settings_server)
|
||||
return salt_encode(salt), decode_dict(settings_server)
|
||||
|
||||
|
||||
def settings_server_decrypt_cfg(settings_server, settings_encrypt):
|
||||
settings_server = settings_server_decrypt(settings_server, settings_encrypt)
|
||||
return decode_dict(settings_server)
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
import yanlib
|
||||
|
||||
default_cfg = "cfg"
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="A class to encrypt server credentials",
|
||||
epilog="There are no additional parameters.",
|
||||
add_help=True )
|
||||
parser.add_argument("--encrypt", help="Generate encrypted authentication.", action="store_true")
|
||||
parser.add_argument("--decrypt", help="Decrypt encrypted authentication", action="store_true")
|
||||
parser.add_argument("--recrypt", help="Recrypt encrypted authentication", action="store_true")
|
||||
parser.add_argument("-c", "--cfg", help="Specify config file.", default=default_cfg)
|
||||
|
||||
arguments = parser.parse_args()
|
||||
|
||||
if arguments.recrypt:
|
||||
arguments.encrypt = True
|
||||
arguments.decrypt = True
|
||||
|
||||
if arguments.encrypt or arguments.decrypt:
|
||||
import importlib
|
||||
cfg = importlib.import_module(arguments.cfg)
|
||||
settings_server = cfg.settings_server
|
||||
settings_encrypt = None
|
||||
|
||||
if arguments.decrypt and arguments.encrypt:
|
||||
print("Re-encrypting")
|
||||
|
||||
if arguments.decrypt: # arguments.decrypt
|
||||
print("Decrypt...")
|
||||
settings_server = settings_server_decrypt_cfg(cfg.settings_server, cfg.settings_encrypt)
|
||||
settings_encrypt = OrderedDict([
|
||||
("encrypt", False),
|
||||
("salt", cfg.settings_encrypt["encrypt"])
|
||||
])
|
||||
|
||||
if arguments.encrypt:
|
||||
print("Encrypt...")
|
||||
salt, settings_server = settings_server_encrypt_cfg(settings_server)
|
||||
settings_encrypt = OrderedDict([
|
||||
("encrypt", True),
|
||||
("salt", salt)
|
||||
])
|
||||
|
||||
yanlib.pp_ordered_dict("settings_server", settings_server)
|
||||
yanlib.pp_dict("settings_encrypt", settings_encrypt)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
256
src/main.py
Executable file
256
src/main.py
Executable file
@ -0,0 +1,256 @@
|
||||
#! /usr/bin/env python
|
||||
import sys
|
||||
import argparse
|
||||
import signal
|
||||
import yanlib
|
||||
import yandereBot
|
||||
import datetime
|
||||
import contextlib
|
||||
|
||||
|
||||
# A class that inherits from either YandereBot from yandereBot module
|
||||
# This class is used to handle command line arguments gracefully, and extend functionality quickly
|
||||
# Bot specific changes should be made here (if they are minor enough).
|
||||
# This will be instantiated from the main() function
|
||||
class YandereBot(yandereBot.YandereBot):
|
||||
# The below settings are required from the configuration module
|
||||
settings_time = None
|
||||
settings_reminder = None
|
||||
|
||||
# Wait before running
|
||||
delay_start = 0
|
||||
|
||||
def __init__(self, cfg, debug_mode, prime_bot, delay_d=None, delay_h=None, delay_s=None):
|
||||
super(YandereBot, self).__init__(cfg, debug_mode, prime_bot=False)
|
||||
self.load_settings(self.cfg, ("settings_time", "settings_reminder"))
|
||||
self.set_pretimer(delay_d, delay_h, delay_s)
|
||||
|
||||
if self.debug_mode:
|
||||
print("[DEBUG MODE ON - DRY RUN BEGIN]")
|
||||
|
||||
# Do not perform sanity test if stdout is None.
|
||||
# input() will fail if stdout is None, which could happen with the following command
|
||||
# ./run --dry-run -h -d 'a date in the past'
|
||||
if sys.stdout is not None and not self.pass_sanity_test():
|
||||
raise FailedSanityTest
|
||||
|
||||
if prime_bot:
|
||||
self.prime_bot()
|
||||
|
||||
def print_date_time_example(self):
|
||||
print_fmt = " {0:6} {1:10} {2}"
|
||||
time_fmt = self.settings_time["time_format"]
|
||||
date_fmt = self.settings_time["date_format"]
|
||||
current_time = self.dateSelection
|
||||
|
||||
print(print_fmt.format(
|
||||
"TIME", time_fmt, current_time.strftime(time_fmt)
|
||||
))
|
||||
print(print_fmt.format(
|
||||
"DATE", date_fmt, current_time.strftime(date_fmt)
|
||||
))
|
||||
|
||||
def dump_pictures(self):
|
||||
for ele in self.listPictures:
|
||||
print(ele.get_full_string())
|
||||
|
||||
def set_delay_d(self, d):
|
||||
try:
|
||||
t = datetime.datetime.strptime(d, self.settings_time["date_format"])
|
||||
self.dateNextSelection = self.dateNextSelection.replace(
|
||||
year=t.year, month=t.month, day=t.day
|
||||
)
|
||||
except Exception:
|
||||
print("Invalid date format: {}\n\nCorrect date/time format examples:".format(d))
|
||||
self.print_date_time_example()
|
||||
raise DateWrongFormat
|
||||
|
||||
def set_delay_h(self, h, add_24):
|
||||
try:
|
||||
t = datetime.datetime.strptime(h, self.settings_time["time_format"])
|
||||
self.dateNextSelection = self.dateNextSelection.replace(
|
||||
hour=t.hour, minute=t.minute, second=t.second, microsecond=t.microsecond
|
||||
)
|
||||
if self.dateNextSelection < self.dateSelection and add_24:
|
||||
self.dateNextSelection = yanlib.time_add_seconds(self.dateNextSelection, 60 * 60 * 24)
|
||||
except Exception:
|
||||
print("Invalid time format: {}\n\nCorrect date/time format examples:".format(h))
|
||||
self.print_date_time_example()
|
||||
raise TimeWrongFormat
|
||||
|
||||
def set_pretimer(self, d=None, h=None, s=0):
|
||||
if d:
|
||||
self.set_delay_d(d)
|
||||
if h:
|
||||
self.set_delay_h(h, d is None)
|
||||
if s:
|
||||
self.delay_start = max(0, s)
|
||||
|
||||
# Check for potential misconfigurations by the user
|
||||
def pass_sanity_test(self):
|
||||
# Calculate pre-timer value
|
||||
seconds_until_next_pos = yanlib.time_diff_seconds(self.dateNextSelection, self.dateSelection)
|
||||
|
||||
# Possible misconfigurations that will prompt the user to continue
|
||||
pretimer_less_than_zero = seconds_until_next_pos < 0
|
||||
pretimer_greater_than_sleep = seconds_until_next_pos > self.settings_behavior["sleep_seconds"]
|
||||
|
||||
# Prompt the user
|
||||
prompt_user = pretimer_less_than_zero or pretimer_greater_than_sleep
|
||||
|
||||
# Remind the user to generate new OAuth tokens
|
||||
dt = datetime.datetime.strptime(self.settings_reminder, self.settings_time["long_date_format"])
|
||||
if dt < datetime.datetime.now():
|
||||
print("REMINDER: Generate new tokens!!")
|
||||
|
||||
# Check if the bot is back-posting in time and make sure this is what the user wanted to avoid spamming
|
||||
if pretimer_less_than_zero:
|
||||
sleep = round(abs(seconds_until_next_pos), 2)
|
||||
images = round(sleep / (self.settings_behavior["sleep_seconds"] * self.settings_behavior["uploads_per_post"]), 2) + 1
|
||||
print("WARNING: Pre-timer is less than the current time by: {} seconds. {} images will post immediately".format(
|
||||
sleep, images
|
||||
))
|
||||
# Check if the bot will wait for longer than the default amount of sleep time configured in the cfg.py
|
||||
elif pretimer_greater_than_sleep:
|
||||
print("WARNING: Pre-timer will sleep for {} seconds. This is more than the configured amount ({} seconds)".format(
|
||||
round(seconds_until_next_pos, 2), self.settings_behavior["sleep_seconds"]
|
||||
))
|
||||
|
||||
# Prompt the user if something doesn't seem right
|
||||
# This must be done before we set up our keyboard interrupts. Otherwise the below exceptions will not work.
|
||||
try:
|
||||
if prompt_user:
|
||||
# Default to 'y' if the user just presses enter
|
||||
ans = input("Do you want to continue [Y/n]? ") or "y"
|
||||
return ans.lower() in ("y", "yes")
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
print()
|
||||
return False
|
||||
|
||||
# Sanity test passed
|
||||
return True
|
||||
|
||||
def start(self, delay=None):
|
||||
_delay = delay or self.delay_start
|
||||
return super(YandereBot, self).start(max(0, _delay))
|
||||
|
||||
|
||||
# Custom exceptions
|
||||
class TimeWrongFormat(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class DateWrongFormat(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FailedSanityTest(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FailedToLoadCfg(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# Entry point if run from the command line
|
||||
def main():
|
||||
# Default config file
|
||||
default_cfg = "cfg"
|
||||
|
||||
# Parser
|
||||
parser = argparse.ArgumentParser(
|
||||
description="A bot for posting on Mastodon",
|
||||
# epilog="All switches can be combined for greater control",
|
||||
add_help=False)
|
||||
parser.add_argument("--dry-run", help="Will not login or post to Plemora", action="store_true")
|
||||
parser.add_argument("--debug", help="Same as --dry-run", action="store_true")
|
||||
parser.add_argument("-w", "--wait", type=int, help="Wait before posting first image (seconds)", default=0)
|
||||
parser.add_argument("-t", "--time", help="Wait for time before posting first image", default=None)
|
||||
parser.add_argument("-d", "--date", help="Wait for date before posting first image", default=None)
|
||||
parser.add_argument("-c", "--config", help="Set custom config file (Default: {})".format(default_cfg), default=default_cfg)
|
||||
parser.add_argument("-o", "--output-hashes", help="Output list of hashes", action="store_true")
|
||||
parser.add_argument("-h", "--help", help="Show this help message and exit", action="store_true")
|
||||
parser.add_argument("remainder", help=argparse.SUPPRESS, nargs=argparse.REMAINDER)
|
||||
arguments = parser.parse_args()
|
||||
|
||||
# Redirect stdout when the bot first initializes if the bot is not going to run normally
|
||||
redirect_stdout = None if arguments.output_hashes or arguments.help else sys.stdout
|
||||
|
||||
# Yandere Lewd Bot
|
||||
yandere = None
|
||||
yandere_config = None
|
||||
|
||||
# Configuration file for Yandere Lewd Bot
|
||||
try:
|
||||
import importlib
|
||||
yandere_config = importlib.import_module(arguments.config)
|
||||
except ImportError:
|
||||
print("Failed to Load Configuration:", arguments.config)
|
||||
raise FailedToLoadCfg
|
||||
|
||||
# Flag if the bot is running in debug mode
|
||||
debug_mode = (arguments.dry_run or arguments.debug or arguments.output_hashes or arguments.help)
|
||||
|
||||
with contextlib.redirect_stdout(redirect_stdout):
|
||||
prime_bot = not arguments.help
|
||||
|
||||
yandere = YandereBot(
|
||||
yandere_config,
|
||||
debug_mode,
|
||||
prime_bot,
|
||||
arguments.date,
|
||||
arguments.time,
|
||||
arguments.wait
|
||||
)
|
||||
|
||||
# Print Usage Information with Time and Date Formats with Examples
|
||||
if arguments.help:
|
||||
parser.print_help()
|
||||
print()
|
||||
yandere.print_date_time_example()
|
||||
print()
|
||||
return 0
|
||||
|
||||
# Output all of the images in the bot's picture list
|
||||
if arguments.output_hashes:
|
||||
yandere.dump_pictures()
|
||||
return 0
|
||||
|
||||
# Setup exit calls
|
||||
# Must be done after we declare our bot(s), otherwise this will be called if quitting on decrypting settings )
|
||||
def yandere_quit(signo, _frame):
|
||||
print("\nInterrupted by {}, shutting down...".format(signo))
|
||||
yandere.exit()
|
||||
|
||||
# Setup our exit calls
|
||||
for sig in ("TERM", "HUP", "INT"):
|
||||
signal.signal(getattr(signal, "SIG" + sig), yandere_quit)
|
||||
|
||||
return yandere.start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# A return value of 0 or 1 is a normal exit
|
||||
try:
|
||||
sys.exit(main())
|
||||
# Exceptions raised from the main function
|
||||
except FailedToLoadCfg:
|
||||
sys.exit(10)
|
||||
except FailedSanityTest:
|
||||
sys.exit(9)
|
||||
except DateWrongFormat:
|
||||
sys.exit(8)
|
||||
except TimeWrongFormat:
|
||||
sys.exit(7)
|
||||
|
||||
# Exceptions raised from the bot
|
||||
except yandereBot.Debug:
|
||||
sys.exit(6)
|
||||
except yandereBot.MissingMasterList:
|
||||
sys.exit(5)
|
||||
except yandereBot.BadCfgFile:
|
||||
sys.exit(4)
|
||||
except yandereBot.BadPostSettings:
|
||||
sys.exit(3)
|
||||
except yandereBot.FailedLogin:
|
||||
sys.exit(2)
|
471
src/yandereBot.py
Executable file
471
src/yandereBot.py
Executable file
@ -0,0 +1,471 @@
|
||||
#! /usr/bin/env python
|
||||
|
||||
# Program Name: Name
|
||||
# Purpose: Purpose
|
||||
import yanlib
|
||||
|
||||
import os
|
||||
import datetime
|
||||
import contextlib
|
||||
import fnmatch
|
||||
import math
|
||||
from threading import Event
|
||||
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonAPIError, MastodonVersionError
|
||||
|
||||
|
||||
class YanBotHash(yanlib.HashObject):
|
||||
_postSettings = None
|
||||
|
||||
def __init__(self, hash_obj, profile):
|
||||
super(YanBotHash, self).__init__()
|
||||
if hash_obj is None:
|
||||
return
|
||||
self._sHash = hash_obj.get_hash_string()
|
||||
self._sBinaryChar = hash_obj.get_binary_char()
|
||||
self._sPath = hash_obj.get_hash_path()
|
||||
self._postSettings = profile
|
||||
|
||||
def get_post_setting(self):
|
||||
return self._postSettings
|
||||
|
||||
|
||||
class YandereBot:
|
||||
# From the threading library. Is responsible for putting the bot to sleep, and exiting when the user quits (Ctrl+C)
|
||||
eventSleep = Event()
|
||||
|
||||
# The configuration module
|
||||
cfg = None
|
||||
|
||||
# The below settings are required from the configuration module
|
||||
settings_server = None
|
||||
settings_behavior = None
|
||||
settings_time = None
|
||||
settings_post = None
|
||||
settings_post_default = None
|
||||
settings_encrypt = None
|
||||
|
||||
# Class variables
|
||||
mastodon_api = None
|
||||
listPictures = []
|
||||
lenBlacklist = 0
|
||||
failed_uploads = 0
|
||||
currentSessionCount = 0
|
||||
debug_mode = False
|
||||
primed = False
|
||||
decrypted = False
|
||||
|
||||
# Time variables
|
||||
dateSelection = None
|
||||
dateNextSelection = None
|
||||
|
||||
# YandereBot.__init__()
|
||||
# @param cfg A dynamically loaded python module. See yanlib.module_load() for an example
|
||||
# @param debug_mode Should the bot run in debug mode (do not sign in or post to Pleroma)
|
||||
# prime_bot Should the bot immediately prime itself (configure picture list and login, but don't post)
|
||||
def __init__(self, cfg, debug_mode=False, prime_bot=True):
|
||||
self.dateSelection = datetime.datetime.now()
|
||||
self.dateNextSelection = self.dateSelection
|
||||
self.cfg = cfg
|
||||
self.load_settings(self.cfg)
|
||||
self.debug_mode = debug_mode or self.settings_behavior["debug"]
|
||||
if prime_bot:
|
||||
self.prime_bot()
|
||||
|
||||
# Setup Exit Calls
|
||||
def exit(self):
|
||||
self.eventSleep.set()
|
||||
|
||||
# Make sure there are no profiles in listPictures set to none. Print the bad post and exit if there is.
|
||||
def validate_post_settings(self):
|
||||
bad_post_count = 0
|
||||
for i in self.listPictures:
|
||||
if i.get_post_setting() is None:
|
||||
print("Bad post setting [{}]: {}".format(bad_post_count, i.get_full_string()))
|
||||
bad_post_count += 1
|
||||
if bad_post_count:
|
||||
raise BadPostSettings
|
||||
|
||||
# Decryption settings
|
||||
# Used to set class attributes with the same name to the value specified in the config file.
|
||||
def load_settings(self, cfg, settings=None):
|
||||
try:
|
||||
default_settings = (
|
||||
"settings_server",
|
||||
"settings_behavior",
|
||||
"settings_time",
|
||||
"settings_post",
|
||||
"settings_post_default",
|
||||
"settings_encrypt"
|
||||
)
|
||||
_settings = settings or default_settings
|
||||
for ele in _settings:
|
||||
setattr(self, ele, getattr(cfg, ele))
|
||||
|
||||
except AttributeError as e:
|
||||
print(e)
|
||||
raise BadCfgFile
|
||||
|
||||
def decrypt_settings(self):
|
||||
if self.settings_encrypt["encrypt"] and not self.decrypted and not self.debug_mode:
|
||||
import encryption
|
||||
self.settings_server = encryption.settings_server_decrypt_cfg(self.settings_server, self.settings_encrypt)
|
||||
self.decrypted = True
|
||||
|
||||
# Login to Pleroma
|
||||
def login(self):
|
||||
skip_login = self.debug_mode or self.mastodon_api is not None
|
||||
if skip_login:
|
||||
return
|
||||
if not self.decrypted:
|
||||
self.decrypt_settings()
|
||||
try:
|
||||
self.mastodon_api = Mastodon(
|
||||
client_id=self.settings_server["client_id"],
|
||||
client_secret=self.settings_server["client_secret"],
|
||||
access_token=self.settings_server["access_token"],
|
||||
api_base_url=self.settings_server["api_base_url"],
|
||||
feature_set=self.settings_behavior["feature_set"] # <--- Necessary for Mastodon Version 1.5.1
|
||||
)
|
||||
except (MastodonIllegalArgumentError, MastodonVersionError) as e:
|
||||
print(e)
|
||||
raise FailedLogin
|
||||
|
||||
# Set up lists
|
||||
def read_blacklist_files(self):
|
||||
list_blacklist = []
|
||||
for i in self.settings_behavior["master_blacklist_r"]:
|
||||
# It doesn't matter if the picture file doesn't exist
|
||||
with contextlib.suppress(IOError):
|
||||
list_blacklist.extend(yanlib.get_hash_list(i))
|
||||
return list_blacklist
|
||||
|
||||
def blacklist(self, picked):
|
||||
self.lenBlacklist += 1
|
||||
for f in self.settings_behavior["master_blacklist_w"]:
|
||||
yanlib.append_file(
|
||||
f, picked.get_full_string(),
|
||||
self.settings_behavior["atomic_saving"],
|
||||
self.settings_behavior["sync_save"],
|
||||
self.settings_behavior["tmp_dir"]
|
||||
)
|
||||
|
||||
# load_pictures will return a list of YanHashObj() with a blacklist(s) applied
|
||||
# @param list_blacklist A list of HashObjects() that are blacklist hashes
|
||||
def load_pictures(self, list_blacklist):
|
||||
list_pictures = []
|
||||
if not self.settings_behavior["master_list"]:
|
||||
raise MissingMasterList
|
||||
|
||||
# Return a list of hashes with profiles
|
||||
try:
|
||||
for f in self.settings_behavior["master_list"]:
|
||||
add_list = get_list_of_hashes_with_profiles(f, self.settings_post, self.settings_post_default, get_profile)
|
||||
list_pictures.extend(add_list)
|
||||
except IOError as e:
|
||||
print(e)
|
||||
raise MissingMasterList
|
||||
return yanlib.get_hash_list_blacklist(list_pictures, list_blacklist, self.settings_behavior["max_size"])
|
||||
|
||||
def load_picture_list(self):
|
||||
list_blacklist = self.read_blacklist_files()
|
||||
self.listPictures = self.load_pictures(list_blacklist)
|
||||
self.lenBlacklist = len(list_blacklist)
|
||||
|
||||
def shuffle_list(self):
|
||||
if self.settings_behavior["post_random"]:
|
||||
import random
|
||||
random.seed(os.urandom(16))
|
||||
random.shuffle(self.listPictures)
|
||||
|
||||
# Maybe I should remove this from the backend?
|
||||
def print_header_stats(self, picked, date_selection, date_next_selection):
|
||||
_picked = picked.get_full_string() if picked else None
|
||||
picked_profile = picked.get_post_setting()["name"] if picked else None
|
||||
picked_next = self.listPictures[0].get_full_string() if self.listPictures else None
|
||||
picked_next_profile = self.listPictures[0].get_post_setting()["name"] if self.listPictures else None
|
||||
next_selection_seconds = max(0, int(yanlib.time_diff_seconds(date_next_selection, date_selection)))
|
||||
|
||||
n_posts_remain = math.ceil(len(self.listPictures) / self.settings_behavior["uploads_per_post"])
|
||||
if date_selection != date_next_selection:
|
||||
n_posts_remain -= 1
|
||||
|
||||
remaining_seconds = n_posts_remain * self.settings_behavior["sleep_seconds"]
|
||||
date_end_selection = yanlib.time_add_seconds(date_selection, remaining_seconds + next_selection_seconds)
|
||||
date_end_selection_seconds = max(0, yanlib.time_diff_seconds(date_end_selection, date_selection))
|
||||
if date_selection != date_next_selection and picked is None:
|
||||
date_end_selection_seconds += next_selection_seconds
|
||||
d, h, m, s = yanlib.humanize_time_delta(date_end_selection_seconds)
|
||||
|
||||
print("[Profile]", picked_profile)
|
||||
print("[Profile Next]", picked_next_profile)
|
||||
print(_picked)
|
||||
print("Next:", picked_next) # There should always be something in picture_next list
|
||||
print("Selection time: {}".format(
|
||||
date_selection.strftime(self.settings_time["long_date_format"])) )
|
||||
print("Next selection time: {} ({} seconds)".format(
|
||||
date_next_selection.strftime(self.settings_time["long_date_format"]), next_selection_seconds) )
|
||||
print("End selection time: {}".format(date_end_selection.strftime(
|
||||
self.settings_time["long_date_week"])) )
|
||||
print("Time Remaining: {} Days | {} Hours | {} Minutes | {} Seconds".format(d, h, m, s) )
|
||||
print("[ {} Pictures | {} Blacklisted | {} Selected during session | {} Failed ]\n".format(
|
||||
len(self.listPictures), self.lenBlacklist, self.currentSessionCount, self.failed_uploads) )
|
||||
|
||||
# Returns a list of media paths (without the hashes)
|
||||
def get_media_list(self, picked):
|
||||
ext = self.settings_behavior["multi_media_ext"]
|
||||
if ext and os.path.splitext(picked.get_hash_path())[1].lower() == ext.lower():
|
||||
return [i.get_hash_path() for i in yanlib.get_hash_list(picked.get_hash_path())]
|
||||
else:
|
||||
return [picked.get_hash_path()]
|
||||
|
||||
# Returns a list of tuples that contain the media list path and media mastodon dictionary
|
||||
def upload_media_list(self, path_list):
|
||||
media_list = []
|
||||
for ele in path_list:
|
||||
if not self.debug_mode:
|
||||
media = self.mastodon_api.media_post(ele, description=os.path.basename(ele))
|
||||
media_list.append((ele, media))
|
||||
return media_list
|
||||
|
||||
def get_post_text(self, picked, media_list):
|
||||
content_type = self.settings_behavior["content_type"]
|
||||
content_newline = self.settings_behavior["content_newline"]
|
||||
static_message = content_newline.join(picked.get_post_setting()["message"])
|
||||
string_post = ""
|
||||
string_imglinks = []
|
||||
|
||||
if media_list and self.settings_behavior["post_image_link"]:
|
||||
for ele in media_list:
|
||||
path, media = ele
|
||||
if path is None or media is None:
|
||||
continue
|
||||
elif content_type == "text/markdown" and not self.debug_mode:
|
||||
string_imglinks.append(
|
||||
"[{}]({})".format(os.path.basename(path), media["url"])
|
||||
)
|
||||
else:
|
||||
string_imglinks.append(media["url"])
|
||||
|
||||
# Join non empty strings with a newline character
|
||||
string_imglinks_joined = content_newline.join(filter(None, string_imglinks))
|
||||
string_post = content_newline.join(filter(None, (static_message, string_imglinks_joined)))
|
||||
|
||||
return content_type, string_post
|
||||
|
||||
def _post(self, picked):
|
||||
images = self.get_media_list(picked)
|
||||
if not images:
|
||||
raise ValueError("Media list is empty")
|
||||
media_list = self.upload_media_list(images)
|
||||
content_type, message = self.get_post_text(picked, media_list)
|
||||
if self.debug_mode:
|
||||
return picked
|
||||
self.mastodon_api.status_post(
|
||||
message,
|
||||
media_ids=[i[1] for i in media_list if len(i) == 2],
|
||||
visibility=self.settings_behavior["visibility"],
|
||||
sensitive=picked.get_post_setting()["spoiler"],
|
||||
content_type=content_type
|
||||
)
|
||||
return picked
|
||||
|
||||
# The main post function
|
||||
# This function is responsible for incrementing self.currentSessionCount, as well as posting and blacklisting the
|
||||
# picked item.
|
||||
#
|
||||
# It is also responsible for removing the picked item from self.listPictures, which can be accomplished by simply
|
||||
# popping it at index 0. This should handle any error that might occur while posting.
|
||||
#
|
||||
# This function should return 'None' if a post failed, and the picked item from self.listPictures if it succeeded.
|
||||
def post(self):
|
||||
picked = None
|
||||
|
||||
# Flags that are set if an upload fails
|
||||
reinsert_image = False
|
||||
timeout = False
|
||||
|
||||
# Attempt post
|
||||
try:
|
||||
# Post
|
||||
picked = self.listPictures.pop(0)
|
||||
self._post(picked)
|
||||
|
||||
# After a successful post
|
||||
self.currentSessionCount += 1
|
||||
self.blacklist(picked)
|
||||
|
||||
# The post was successful
|
||||
return picked
|
||||
|
||||
# Attempted to post a file that doesn't exist (immediately repost ignoring retry_seconds)
|
||||
except FileNotFoundError:
|
||||
print("File not found:", picked.get_hash_path())
|
||||
# Exception flags
|
||||
reinsert_image, timeout = False, False
|
||||
|
||||
# Media list is empty
|
||||
except ValueError as e:
|
||||
print("Media list cannot be empty:", picked.get_hash_path())
|
||||
# Exception flags
|
||||
reinsert_image, timeout = False, False
|
||||
|
||||
# Check if the file limit has been reached
|
||||
except MastodonAPIError as e:
|
||||
# Check if the file limit has been reached (413 error)
|
||||
file_limit_reached = False
|
||||
with contextlib.suppress(IndexError):
|
||||
file_limit_reached = (e.args[1] == 413)
|
||||
|
||||
print("API Error:", e)
|
||||
# Exception flags
|
||||
reinsert_image, timeout = not file_limit_reached, True
|
||||
|
||||
# Server Errors
|
||||
# Assume all exceptions are on the server side
|
||||
# If the connection is timing out it could be for two reasons:
|
||||
# 1. The error was caused by the user attempting to upload a large file over a slow connection:
|
||||
# a. FIX: Reduce settings_behavior["max_size"]
|
||||
# 2. The server is down. Check to verify in a web browser (this is the default assumption since the
|
||||
# mastodon.py API will not specify why the connection timed out).
|
||||
# The default assumption is #2
|
||||
except Exception as e:
|
||||
print("Unhandled Exception:", e)
|
||||
# Exception flags
|
||||
reinsert_image, timeout = True, True
|
||||
|
||||
# An exception occurred
|
||||
self.failed_uploads += 1
|
||||
print("[Errors: {}] {}{}".format(self.failed_uploads, picked.get_full_string(), os.linesep))
|
||||
if reinsert_image:
|
||||
self.listPictures.insert(0, picked)
|
||||
if timeout:
|
||||
self.eventSleep.wait(self.settings_behavior["retry_seconds"])
|
||||
|
||||
# The post failed
|
||||
return None
|
||||
|
||||
def schedule_next_post(self):
|
||||
self.dateSelection = self.dateNextSelection
|
||||
self.dateNextSelection = yanlib.time_add_seconds(self.dateSelection, self.settings_behavior["sleep_seconds"])
|
||||
|
||||
# Will wait between the current time and the time of next selection
|
||||
def wait_future_time(self):
|
||||
seconds = yanlib.time_diff_seconds(self.dateNextSelection, datetime.datetime.now())
|
||||
self.eventSleep.wait(max(0, seconds))
|
||||
|
||||
# [BEGIN THE PROGRAM]
|
||||
def prime_bot(self):
|
||||
self.load_picture_list()
|
||||
self.validate_post_settings()
|
||||
self.shuffle_list()
|
||||
if not self.debug_mode:
|
||||
self.decrypt_settings()
|
||||
if self.can_post():
|
||||
self.login()
|
||||
self.primed = True
|
||||
|
||||
def start(self, delay=0):
|
||||
# Prime bot if not already primed.
|
||||
if not self.primed:
|
||||
self.prime_bot()
|
||||
|
||||
# Early out if the bot is incapable of posting
|
||||
if not self.can_post():
|
||||
print("Bot is incapable of posting!!")
|
||||
return 1
|
||||
|
||||
start_time = self.dateSelection
|
||||
delay_seconds = max(yanlib.time_diff_seconds(self.dateNextSelection, start_time) + delay, delay)
|
||||
delay_time = yanlib.time_add_seconds(start_time, delay_seconds)
|
||||
|
||||
# Print the first image in the list if a delay or pretimer is set
|
||||
if delay_seconds:
|
||||
self.print_header_stats(None, start_time, delay_time)
|
||||
|
||||
# The delay parameter is different from the dateSelection and dateSelectionNext
|
||||
# It will literally time out the bot for a given number of seconds regardless of the pre-timer setting
|
||||
# This is useful if you want to set a delay of 30 seconds, before back-posting several images
|
||||
self.eventSleep.wait(max(0, delay))
|
||||
|
||||
# Check if the pre-timer is set
|
||||
# dateNextSelection should be greater than dateSelection if it is
|
||||
# dateSelection and dateNextSelection are both set to the current time when the bot is initialized
|
||||
if delay_seconds:
|
||||
self.wait_future_time()
|
||||
|
||||
# Begin posting
|
||||
self.main_loop()
|
||||
|
||||
# Return 1 if there are still pictures in the picture list
|
||||
return len(self.listPictures) > 0
|
||||
|
||||
# End Conditions:
|
||||
# 1. User presses Ctrl+C
|
||||
# 2. There is nothing left in the picture list to select from
|
||||
# 3. settings_behavior["uploads_per_post"] is less than one for some reason
|
||||
def can_post(self):
|
||||
return not self.eventSleep.is_set() and bool(len(self.listPictures)) and self.settings_behavior["uploads_per_post"] > 0
|
||||
|
||||
def main_loop(self):
|
||||
target_posts = self.settings_behavior["uploads_per_post"]
|
||||
while self.can_post():
|
||||
successful_posts = 0
|
||||
while (successful_posts < target_posts) and self.can_post():
|
||||
last_picked = self.post()
|
||||
successful_posts += int(last_picked is not None)
|
||||
if successful_posts >= target_posts:
|
||||
self.schedule_next_post()
|
||||
self.print_header_stats(last_picked, self.dateSelection, self.dateNextSelection)
|
||||
else:
|
||||
self.print_header_stats(last_picked, self.dateNextSelection, self.dateNextSelection)
|
||||
|
||||
if self.can_post():
|
||||
self.wait_future_time()
|
||||
|
||||
|
||||
# A callback function for get_list_of_hashes_with_profiles() that returns a single profile from @param hash_obj
|
||||
# @param hash_obj A HashObject() (or subclass)
|
||||
# @param profiles A list of available profiles to match
|
||||
# @param profiles_default The default profile to return if no profile is matched
|
||||
def get_profile(hash_obj, profiles, profiles_default):
|
||||
profile_gen = (x for x in profiles if fnmatch.fnmatch(hash_obj.get_hash_path(), x["path"]))
|
||||
return next(profile_gen, profiles_default)
|
||||
|
||||
|
||||
# Takes a file path and transforms it into a list of YanBotHash() with the appropriate profile
|
||||
# @param f_name Path of hash file
|
||||
# @param profiles List of profiles -> self.settings_post
|
||||
# @param profiles_default The default profile to apply
|
||||
# @param callback_get_profile Callback function -> should return a single profile. Default: get_profile()
|
||||
def get_list_of_hashes_with_profiles(f_name, profiles, profiles_default, callback_get_profile):
|
||||
r = []
|
||||
with open(f_name, "r") as f:
|
||||
for _line in f:
|
||||
line = _line.strip()
|
||||
if not yanlib.is_valid_hash(line):
|
||||
continue
|
||||
hash_obj = yanlib.HashObject(line)
|
||||
post_setting = callback_get_profile(hash_obj, profiles, profiles_default)
|
||||
r.append(YanBotHash(hash_obj, post_setting))
|
||||
return r
|
||||
|
||||
|
||||
# Custom Exceptions for YandereBot
|
||||
class Debug(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BadPostSettings(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FailedLogin(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BadCfgFile(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class MissingMasterList(Exception):
|
||||
pass
|
249
src/yanlib.py
Executable file
249
src/yanlib.py
Executable file
@ -0,0 +1,249 @@
|
||||
#! /usr/bin/env python
|
||||
|
||||
# Program Name: yandereBot
|
||||
# Purpose: A Simple Mastadon Bot to Post Images
|
||||
|
||||
# yanlib.py is required by yandereBot.py
|
||||
# This file contains functions and utilities that may be useful to external tools and programs that interface with
|
||||
# yandereBot, or manipulate hash files in some way. Typically instantiating a yandereBot object is unnecessary for this.
|
||||
|
||||
import os
|
||||
import datetime
|
||||
import shutil
|
||||
import contextlib
|
||||
|
||||
|
||||
# Requires properly formatted MD5 checksum lines.
|
||||
# The length of the string shouldn't matter.
|
||||
# But it should be formatted like so: '8d20714ec6d3ee6d444931d01dd68626 *./rsc/file.png'
|
||||
# The initializer does NOT check for the validity of the hash string. This should be done manually with is_valid_hash()
|
||||
# ex. hashes = [HashObject(i) for i in hash_list if is_valid_hash(i)]
|
||||
# See: get_hash_list() and get_hash_list_str() for functions to make the above example even more simple
|
||||
class HashObject:
|
||||
_sHash = ""
|
||||
_sBinaryChar = ""
|
||||
_sPath = ""
|
||||
_sDeliminator = ' ' # This should never change
|
||||
|
||||
def __init__(self, s_hash=None):
|
||||
if s_hash is not None:
|
||||
self.set_hash(s_hash)
|
||||
|
||||
def set_hash(self, s):
|
||||
line = s.strip()
|
||||
split_hash = line.split(self._sDeliminator, 1)
|
||||
self._sHash = split_hash[0] # The hash value
|
||||
self._sBinaryChar = split_hash[1][:1] # The binary character
|
||||
self._sPath = split_hash[1][1:] # The path to the file
|
||||
|
||||
def get_hash_string(self):
|
||||
return self._sHash
|
||||
|
||||
def get_hash_path(self):
|
||||
return self._sPath
|
||||
|
||||
def get_binary_char(self):
|
||||
return self._sBinaryChar
|
||||
|
||||
def get_deliminator(self):
|
||||
return self._sDeliminator
|
||||
|
||||
def get_full_string(self):
|
||||
return (
|
||||
self._sHash +
|
||||
self._sDeliminator +
|
||||
self._sBinaryChar +
|
||||
self._sPath)
|
||||
|
||||
|
||||
# -------------------------------- HASH FUNCTIONS --------------------------------------------
|
||||
# For MD5 hashes
|
||||
|
||||
# Checking for the binary character when comparing hash string is usually overkill since the CoreUtils package reads
|
||||
# files in binary mode regardless of whether the -b switch is passed.
|
||||
# It is included here since it may be useful for some other applications besides the bot.
|
||||
def is_matching_atter_binary(v_list, v_hash, v_atter):
|
||||
atter_bin = "get_binary_char"
|
||||
return next(
|
||||
(x for x in v_list if
|
||||
getattr(v_hash, v_atter)() == getattr(x, v_atter)() and
|
||||
getattr(v_hash, atter_bin)() == getattr(x, atter_bin)()
|
||||
), None)
|
||||
|
||||
|
||||
def is_matching_atter(v_list, v_hash, v_atter):
|
||||
return next((x for x in v_list if getattr(v_hash, v_atter)() == getattr(x, v_atter)()), None)
|
||||
|
||||
|
||||
def get_matching(v_list, v_hash, atter, match_bin=False):
|
||||
return is_matching_atter(v_list, v_hash, atter) if not match_bin else is_matching_atter_binary(v_list, v_hash, atter)
|
||||
|
||||
|
||||
def get_matching_hash_in_list(v_list, v_hash, match_bin=False):
|
||||
return get_matching(v_list, v_hash, "get_hash_string", match_bin)
|
||||
|
||||
|
||||
def get_matching_path_in_list(v_list, v_hash, match_bin=False):
|
||||
return get_matching(v_list, v_hash, "get_hash_path", match_bin)
|
||||
|
||||
|
||||
def get_matching_full_string_in_list(v_list, v_hash, match_bin=False):
|
||||
return get_matching(v_list, v_hash, "get_full_string", match_bin)
|
||||
|
||||
|
||||
# ---------------------------- HASH LIST FUNCTIONS --------------------------------------------
|
||||
# This is a very lazy check. We only care if the bot will crash when initializing a HashObject()
|
||||
# A 'hash' of '1 *b' or '1 b' will pass in this function.
|
||||
def is_valid_hash(s):
|
||||
line = s.strip()
|
||||
split_hash = line.find(' ')
|
||||
|
||||
# Check
|
||||
return not (
|
||||
line.startswith('#') or
|
||||
len(line) < 4 or
|
||||
split_hash in (-1, len(line) - 2) or
|
||||
line[split_hash + 1] not in (' ', '*')
|
||||
)
|
||||
|
||||
|
||||
def get_hash_list_str(lst_str):
|
||||
return [HashObject(i) for i in lst_str if is_valid_hash(i)]
|
||||
|
||||
|
||||
def get_hash_list(f_name):
|
||||
with open(f_name, "r") as f:
|
||||
return get_hash_list_str(f.readlines())
|
||||
|
||||
|
||||
def is_hash_blacklisted(line_hash, v_pictures, v_blacklist, max_size=None):
|
||||
# Print out the entire line
|
||||
line = line_hash.get_full_string()
|
||||
full_path = line_hash.get_hash_path()
|
||||
|
||||
# Used for comparing file size
|
||||
cmp_size = max_size is not None
|
||||
|
||||
# Only add it to the pictures list if the following conditions are met:
|
||||
# NOTICE: This is going to be CPU intensive.
|
||||
if get_matching_hash_in_list(v_pictures, line_hash): # No hash duplicates
|
||||
print("Ignoring Duplicate Hash:", line)
|
||||
elif get_matching_path_in_list(v_pictures, line_hash): # No path duplicates
|
||||
print("Ignoring Duplicate Path:", line)
|
||||
elif get_matching_hash_in_list(v_blacklist, line_hash): # File hash is not blacklisted
|
||||
print("Ignoring Blacklisted Hash:", line)
|
||||
elif get_matching_path_in_list(v_blacklist, line_hash): # File path is not blacklisted
|
||||
print("Ignoring Blacklisted Path:", line)
|
||||
elif not os.path.isfile(full_path): # File exists
|
||||
print("File not found:", line)
|
||||
elif cmp_size and os.path.getsize(full_path) > max_size: # Does not exceed max file limit (if max_size is set)
|
||||
print("Exceeds Max File Size:", line)
|
||||
else:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def get_hash_list_blacklist(v_pictures, v_blacklist, max_size=None):
|
||||
ret = []
|
||||
for lineHash in v_pictures:
|
||||
if not is_hash_blacklisted(lineHash, ret, v_blacklist, max_size):
|
||||
ret.append(lineHash)
|
||||
return ret
|
||||
|
||||
|
||||
# ------------------------------- TIME FUNCTIONS ---------------------------------------------
|
||||
def time_add_seconds(dt, seconds):
|
||||
return dt + datetime.timedelta(0, seconds)
|
||||
|
||||
|
||||
def time_diff_seconds(d1, d2):
|
||||
return (d1-d2).total_seconds()
|
||||
|
||||
|
||||
def input_time_format(s):
|
||||
return s.replace("-", "")
|
||||
|
||||
|
||||
def humanize_time_delta(total_seconds):
|
||||
m, s = divmod(int(total_seconds), 60)
|
||||
h, m = divmod(m, 60)
|
||||
d, h = divmod(h, 24)
|
||||
return d, h, m, s
|
||||
|
||||
|
||||
# -------------------------------- Pretty Print Functions ------------------------------------
|
||||
# If value is a subclass of string, return it in parentheses (used for generating a python configuration file)
|
||||
def _pp_str(v):
|
||||
if issubclass(str, type(v)):
|
||||
return '"{}"'.format(v)
|
||||
else:
|
||||
return "{}".format(v)
|
||||
|
||||
|
||||
# Prints out a dictionary in pretty print form as valid python code.
|
||||
# setting_dict should consist of string formats with key value pairs defined in setting_dict ex. '{key} {value}'.
|
||||
def _pp_dict(head, setting_dict, fmt, tail):
|
||||
if head:
|
||||
print(head)
|
||||
last_index = len(setting_dict) - 1
|
||||
# i, k -> index and key value of setting_dict
|
||||
for i, k in enumerate(setting_dict):
|
||||
_fmt = fmt
|
||||
_k = _pp_str(k)
|
||||
_v = _pp_str(setting_dict[k])
|
||||
# Add comma separator on all but the last value setting
|
||||
if i < last_index:
|
||||
_fmt += ","
|
||||
print(_fmt.format(_k, _v))
|
||||
if tail:
|
||||
print(tail)
|
||||
|
||||
|
||||
def pp_ordered_dict(setting, setting_dict):
|
||||
_pp_dict(
|
||||
"{} = OrderedDict([".format(setting),
|
||||
setting_dict,
|
||||
'\t({},\t{})',
|
||||
"])")
|
||||
|
||||
|
||||
def pp_dict(setting, setting_dict):
|
||||
_pp_dict(
|
||||
"{} = {{".format(setting),
|
||||
setting_dict,
|
||||
'\t{}:\t{}',
|
||||
"}")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------
|
||||
def sync_to_disk(file_handle):
|
||||
file_handle.flush()
|
||||
os.fsync(file_handle.fileno())
|
||||
|
||||
|
||||
def append_file(f_name, s, atomic_saving=False, sync_save=False, tmp_dir="/var/tmp"):
|
||||
file_handle = None
|
||||
if atomic_saving:
|
||||
import tempfile
|
||||
file_handle = tempfile.NamedTemporaryFile(dir=tmp_dir)
|
||||
with contextlib.suppress(IOError):
|
||||
with open(f_name, "rb") as src:
|
||||
shutil.copyfileobj(src, file_handle)
|
||||
if sync_save:
|
||||
sync_to_disk(file_handle)
|
||||
else:
|
||||
file_handle = open(f_name, "ab")
|
||||
|
||||
file_handle.write(str.encode(s + os.linesep))
|
||||
|
||||
if sync_save:
|
||||
sync_to_disk(file_handle)
|
||||
|
||||
if atomic_saving:
|
||||
file_handle.seek(0)
|
||||
with open(f_name, "wb") as dst_file:
|
||||
shutil.copyfileobj(file_handle, dst_file)
|
||||
if sync_save:
|
||||
sync_to_disk(dst_file)
|
||||
|
||||
file_handle.close()
|
Reference in New Issue
Block a user