$ git clone https://wlchat.ion.nu/wlchat.git
commit de60e95aa8fc91b551439f712e6b78341aa2ee92
Author: Alicia <...>
Date: Fri Apr 11 21:33:29 2025 +0200
Initial commit
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..dba13ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..e337947
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,5 @@
+VERSION=0.1
+
+tarball: wlchat-$(VERSION).tar.gz
+wlchat-$(VERSION).tar.gz: Makefile LICENSE README wlchat.py terminal.py irc.py gtk.py dank.png frozen.png snow.png cookies.py aes.py
+ tar --transform='s@^@wlchat-$(VERSION)/@' -czf $@ $^
diff --git a/README b/README
new file mode 100644
index 0000000..8d3f60c
--- /dev/null
+++ b/README
@@ -0,0 +1,13 @@
+Limitations:
+Currently only authentication through reddit is tested, and used as default by some interfaces
+API is not yet stable
+Currently only runs from the source directory
+
+irc.py runs as a server.
+Use IRC username and the PASS command to provide type of browser and path to browser profile to grab reddit session from.
+Join chat with the full domain as channel name, e.g.
+/join #www.somestreamer.gg
+
+terminal.py supports embedded emotes when run through Enlightenment's terminal emulator Terminology
+
+gtk.py is probably the most complete interface for most users
diff --git a/aes.py b/aes.py
new file mode 100644
index 0000000..f29b6b2
--- /dev/null
+++ b/aes.py
@@ -0,0 +1,554 @@
+# Copied from yt-dlp (revision 6a6d97b2cbc78f818de05cc96edcdcfd52caa259), Unlicense'd <http://unlicense.org/>
+# Modified to be more independent
+import base64
+from math import ceil
+
+class Cryptodome:
+ from Crypto.Cipher import AES, PKCS1_OAEP, Blowfish, PKCS1_v1_5
+
+if Cryptodome.AES:
+ def aes_cbc_decrypt_bytes(data, key, iv):
+ """ Decrypt bytes with AES-CBC using pycryptodome """
+ return Cryptodome.AES.new(key, Cryptodome.AES.MODE_CBC, iv).decrypt(data)
+
+ def aes_gcm_decrypt_and_verify_bytes(data, key, tag, nonce):
+ """ Decrypt bytes with AES-GCM using pycryptodome """
+ return Cryptodome.AES.new(key, Cryptodome.AES.MODE_GCM, nonce).decrypt_and_verify(data, tag)
+
+else:
+ def aes_cbc_decrypt_bytes(data, key, iv):
+ """ Decrypt bytes with AES-CBC using native implementation since pycryptodome is unavailable """
+ return bytes(aes_cbc_decrypt(*map(list, (data, key, iv))))
+
+ def aes_gcm_decrypt_and_verify_bytes(data, key, tag, nonce):
+ """ Decrypt bytes with AES-GCM using native implementation since pycryptodome is unavailable """
+ return bytes(aes_gcm_decrypt_and_verify(*map(list, (data, key, tag, nonce))))
+
+
+def aes_cbc_encrypt_bytes(data, key, iv, **kwargs):
+ return bytes(aes_cbc_encrypt(*map(list, (data, key, iv)), **kwargs))
+
+
+BLOCK_SIZE_BYTES = 16
+
+
+def unpad_pkcs7(data):
+ return data[:-(data[-1])]
+
+
+def pkcs7_padding(data):
+ """
+ PKCS#7 padding
+
+ @param {int[]} data cleartext
+ @returns {int[]} padding data
+ """
+
+ remaining_length = BLOCK_SIZE_BYTES - len(data) % BLOCK_SIZE_BYTES
+ return data + [remaining_length] * remaining_length
+
+
+def pad_block(block, padding_mode):
+ """
+ Pad a block with the given padding mode
+ @param {int[]} block block to pad
+ @param padding_mode padding mode
+ """
+ padding_size = BLOCK_SIZE_BYTES - len(block)
+
+ PADDING_BYTE = {
+ 'pkcs7': padding_size,
+ 'iso7816': 0x0,
+ 'whitespace': 0x20,
+ 'zero': 0x0,
+ }
+
+ if padding_size < 0:
+ raise ValueError('Block size exceeded')
+ elif padding_mode not in PADDING_BYTE:
+ raise NotImplementedError(f'Padding mode {padding_mode} is not implemented')
+
+ if padding_mode == 'iso7816' and padding_size:
+ block = [*block, 0x80] # NB: += mutates list
+ padding_size -= 1
+
+ return block + [PADDING_BYTE[padding_mode]] * padding_size
+
+
+def aes_ecb_encrypt(data, key, iv=None):
+ """
+ Encrypt with aes in ECB mode. Using PKCS#7 padding
+
+ @param {int[]} data cleartext
+ @param {int[]} key 16/24/32-Byte cipher key
+ @param {int[]} iv Unused for this mode
+ @returns {int[]} encrypted data
+ """
+ expanded_key = key_expansion(key)
+ block_count = ceil(len(data) / BLOCK_SIZE_BYTES)
+
+ encrypted_data = []
+ for i in range(block_count):
+ block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]
+ encrypted_data += aes_encrypt(pkcs7_padding(block), expanded_key)
+
+ return encrypted_data
+
+
+def aes_ecb_decrypt(data, key, iv=None):
+ """
+ Decrypt with aes in ECB mode
+
+ @param {int[]} data cleartext
+ @param {int[]} key 16/24/32-Byte cipher key
+ @param {int[]} iv Unused for this mode
+ @returns {int[]} decrypted data
+ """
+ expanded_key = key_expansion(key)
+ block_count = ceil(len(data) / BLOCK_SIZE_BYTES)
+
+ encrypted_data = []
+ for i in range(block_count):
+ block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]
+ encrypted_data += aes_decrypt(block, expanded_key)
+ return encrypted_data[:len(data)]
+
+
+def aes_ctr_decrypt(data, key, iv):
+ """
+ Decrypt with aes in counter mode
+
+ @param {int[]} data cipher
+ @param {int[]} key 16/24/32-Byte cipher key
+ @param {int[]} iv 16-Byte initialization vector
+ @returns {int[]} decrypted data
+ """
+ return aes_ctr_encrypt(data, key, iv)
+
+
+def aes_ctr_encrypt(data, key, iv):
+ """
+ Encrypt with aes in counter mode
+
+ @param {int[]} data cleartext
+ @param {int[]} key 16/24/32-Byte cipher key
+ @param {int[]} iv 16-Byte initialization vector
+ @returns {int[]} encrypted data
+ """
+ expanded_key = key_expansion(key)
+ block_count = ceil(len(data) / BLOCK_SIZE_BYTES)
+ counter = iter_vector(iv)
+
+ encrypted_data = []
+ for i in range(block_count):
+ counter_block = next(counter)
+ block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]
+ block += [0] * (BLOCK_SIZE_BYTES - len(block))
+
+ cipher_counter_block = aes_encrypt(counter_block, expanded_key)
+ encrypted_data += xor(block, cipher_counter_block)
+ return encrypted_data[:len(data)]
+
+
+def aes_cbc_decrypt(data, key, iv):
+ """
+ Decrypt with aes in CBC mode
+
+ @param {int[]} data cipher
+ @param {int[]} key 16/24/32-Byte cipher key
+ @param {int[]} iv 16-Byte IV
+ @returns {int[]} decrypted data
+ """
+ expanded_key = key_expansion(key)
+ block_count = ceil(len(data) / BLOCK_SIZE_BYTES)
+
+ decrypted_data = []
+ previous_cipher_block = iv
+ for i in range(block_count):
+ block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]
+ block += [0] * (BLOCK_SIZE_BYTES - len(block))
+
+ decrypted_block = aes_decrypt(block, expanded_key)
+ decrypted_data += xor(decrypted_block, previous_cipher_block)
+ previous_cipher_block = block
+ return decrypted_data[:len(data)]
+
+
+def aes_cbc_encrypt(data, key, iv, *, padding_mode='pkcs7'):
+ """
+ Encrypt with aes in CBC mode
+
+ @param {int[]} data cleartext
+ @param {int[]} key 16/24/32-Byte cipher key
+ @param {int[]} iv 16-Byte IV
+ @param padding_mode Padding mode to use
+ @returns {int[]} encrypted data
+ """
+ expanded_key = key_expansion(key)
+ block_count = ceil(len(data) / BLOCK_SIZE_BYTES)
+
+ encrypted_data = []
+ previous_cipher_block = iv
+ for i in range(block_count):
+ block = data[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES]
+ block = pad_block(block, padding_mode)
+
+ mixed_block = xor(block, previous_cipher_block)
+
+ encrypted_block = aes_encrypt(mixed_block, expanded_key)
+ encrypted_data += encrypted_block
+
+ previous_cipher_block = encrypted_block
+
+ return encrypted_data
+
+
+def aes_gcm_decrypt_and_verify(data, key, tag, nonce):
+ """
+ Decrypt with aes in GBM mode and checks authenticity using tag
+
+ @param {int[]} data cipher
+ @param {int[]} key 16-Byte cipher key
+ @param {int[]} tag authentication tag
+ @param {int[]} nonce IV (recommended 12-Byte)
+ @returns {int[]} decrypted data
+ """
+
+ # XXX: check aes, gcm param
+
+ hash_subkey = aes_encrypt([0] * BLOCK_SIZE_BYTES, key_expansion(key))
+
+ if len(nonce) == 12:
+ j0 = [*nonce, 0, 0, 0, 1]
+ else:
+ fill = (BLOCK_SIZE_BYTES - (len(nonce) % BLOCK_SIZE_BYTES)) % BLOCK_SIZE_BYTES + 8
+ ghash_in = nonce + [0] * fill + list((8 * len(nonce)).to_bytes(8, 'big'))
+ j0 = ghash(hash_subkey, ghash_in)
+
+ # TODO: add nonce support to aes_ctr_decrypt
+
+ # nonce_ctr = j0[:12]
+ iv_ctr = inc(j0)
+
+ decrypted_data = aes_ctr_decrypt(data, key, iv_ctr + [0] * (BLOCK_SIZE_BYTES - len(iv_ctr)))
+ pad_len = (BLOCK_SIZE_BYTES - (len(data) % BLOCK_SIZE_BYTES)) % BLOCK_SIZE_BYTES
+ s_tag = ghash(
+ hash_subkey,
+ data
+ + [0] * pad_len # pad
+ + list((0 * 8).to_bytes(8, 'big') # length of associated data
+ + ((len(data) * 8).to_bytes(8, 'big'))), # length of data
+ )
+
+ if tag != aes_ctr_encrypt(s_tag, key, j0):
+ raise ValueError('Mismatching authentication tag')
+
+ return decrypted_data
+
+
+def aes_encrypt(data, expanded_key):
+ """
+ Encrypt one block with aes
+
+ @param {int[]} data 16-Byte state
+ @param {int[]} expanded_key 176/208/240-Byte expanded key
+ @returns {int[]} 16-Byte cipher
+ """
+ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1
+
+ data = xor(data, expanded_key[:BLOCK_SIZE_BYTES])
+ for i in range(1, rounds + 1):
+ data = sub_bytes(data)
+ data = shift_rows(data)
+ if i != rounds:
+ data = list(iter_mix_columns(data, MIX_COLUMN_MATRIX))
+ data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES])
+
+ return data
+
+
+def aes_decrypt(data, expanded_key):
+ """
+ Decrypt one block with aes
+
+ @param {int[]} data 16-Byte cipher
+ @param {int[]} expanded_key 176/208/240-Byte expanded key
+ @returns {int[]} 16-Byte state
+ """
+ rounds = len(expanded_key) // BLOCK_SIZE_BYTES - 1
+
+ for i in range(rounds, 0, -1):
+ data = xor(data, expanded_key[i * BLOCK_SIZE_BYTES: (i + 1) * BLOCK_SIZE_BYTES])
+ if i != rounds:
+ data = list(iter_mix_columns(data, MIX_COLUMN_MATRIX_INV))
+ data = shift_rows_inv(data)
+ data = sub_bytes_inv(data)
+ return xor(data, expanded_key[:BLOCK_SIZE_BYTES])
+
+
+def aes_decrypt_text(data, password, key_size_bytes):
+ """
+ Decrypt text
+ - The first 8 Bytes of decoded 'data' are the 8 high Bytes of the counter
+ - The cipher key is retrieved by encrypting the first 16 Byte of 'password'
+ with the first 'key_size_bytes' Bytes from 'password' (if necessary filled with 0's)
+ - Mode of operation is 'counter'
+
+ @param {str} data Base64 encoded string
+ @param {str,unicode} password Password (will be encoded with utf-8)
+ @param {int} key_size_bytes Possible values: 16 for 128-Bit, 24 for 192-Bit or 32 for 256-Bit
+ @returns {str} Decrypted data
+ """
+ NONCE_LENGTH_BYTES = 8
+
+ data = list(base64.b64decode(data))
+ password = list(password.encode())
+
+ key = password[:key_size_bytes] + [0] * (key_size_bytes - len(password))
+ key = aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES)
+
+ nonce = data[:NONCE_LENGTH_BYTES]
+ cipher = data[NONCE_LENGTH_BYTES:]
+
+ decrypted_data = aes_ctr_decrypt(cipher, key, nonce + [0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES))
+ return bytes(decrypted_data)
+
+
+RCON = (0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36)
+SBOX = (0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
+ 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
+ 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
+ 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
+ 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
+ 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
+ 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
+ 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
+ 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
+ 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
+ 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
+ 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
+ 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
+ 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
+ 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
+ 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16)
+SBOX_INV = (0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
+ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
+ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
+ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
+ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
+ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
+ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
+ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
+ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
+ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
+ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
+ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
+ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
+ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
+ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
+ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d)
+MIX_COLUMN_MATRIX = ((0x2, 0x3, 0x1, 0x1),
+ (0x1, 0x2, 0x3, 0x1),
+ (0x1, 0x1, 0x2, 0x3),
+ (0x3, 0x1, 0x1, 0x2))
+MIX_COLUMN_MATRIX_INV = ((0xE, 0xB, 0xD, 0x9),
+ (0x9, 0xE, 0xB, 0xD),
+ (0xD, 0x9, 0xE, 0xB),
+ (0xB, 0xD, 0x9, 0xE))
+RIJNDAEL_EXP_TABLE = (0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,
+ 0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,
+ 0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,
+ 0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,
+ 0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,
+ 0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,
+ 0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,
+ 0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,
+ 0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,
+ 0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,
+ 0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,
+ 0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,
+ 0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,
+ 0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,
+ 0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,
+ 0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01)
+RIJNDAEL_LOG_TABLE = (0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1a, 0xc6, 0x4b, 0xc7, 0x1b, 0x68, 0x33, 0xee, 0xdf, 0x03,
+ 0x64, 0x04, 0xe0, 0x0e, 0x34, 0x8d, 0x81, 0xef, 0x4c, 0x71, 0x08, 0xc8, 0xf8, 0x69, 0x1c, 0xc1,
+ 0x7d, 0xc2, 0x1d, 0xb5, 0xf9, 0xb9, 0x27, 0x6a, 0x4d, 0xe4, 0xa6, 0x72, 0x9a, 0xc9, 0x09, 0x78,
+ 0x65, 0x2f, 0x8a, 0x05, 0x21, 0x0f, 0xe1, 0x24, 0x12, 0xf0, 0x82, 0x45, 0x35, 0x93, 0xda, 0x8e,
+ 0x96, 0x8f, 0xdb, 0xbd, 0x36, 0xd0, 0xce, 0x94, 0x13, 0x5c, 0xd2, 0xf1, 0x40, 0x46, 0x83, 0x38,
+ 0x66, 0xdd, 0xfd, 0x30, 0xbf, 0x06, 0x8b, 0x62, 0xb3, 0x25, 0xe2, 0x98, 0x22, 0x88, 0x91, 0x10,
+ 0x7e, 0x6e, 0x48, 0xc3, 0xa3, 0xb6, 0x1e, 0x42, 0x3a, 0x6b, 0x28, 0x54, 0xfa, 0x85, 0x3d, 0xba,
+ 0x2b, 0x79, 0x0a, 0x15, 0x9b, 0x9f, 0x5e, 0xca, 0x4e, 0xd4, 0xac, 0xe5, 0xf3, 0x73, 0xa7, 0x57,
+ 0xaf, 0x58, 0xa8, 0x50, 0xf4, 0xea, 0xd6, 0x74, 0x4f, 0xae, 0xe9, 0xd5, 0xe7, 0xe6, 0xad, 0xe8,
+ 0x2c, 0xd7, 0x75, 0x7a, 0xeb, 0x16, 0x0b, 0xf5, 0x59, 0xcb, 0x5f, 0xb0, 0x9c, 0xa9, 0x51, 0xa0,
+ 0x7f, 0x0c, 0xf6, 0x6f, 0x17, 0xc4, 0x49, 0xec, 0xd8, 0x43, 0x1f, 0x2d, 0xa4, 0x76, 0x7b, 0xb7,
+ 0xcc, 0xbb, 0x3e, 0x5a, 0xfb, 0x60, 0xb1, 0x86, 0x3b, 0x52, 0xa1, 0x6c, 0xaa, 0x55, 0x29, 0x9d,
+ 0x97, 0xb2, 0x87, 0x90, 0x61, 0xbe, 0xdc, 0xfc, 0xbc, 0x95, 0xcf, 0xcd, 0x37, 0x3f, 0x5b, 0xd1,
+ 0x53, 0x39, 0x84, 0x3c, 0x41, 0xa2, 0x6d, 0x47, 0x14, 0x2a, 0x9e, 0x5d, 0x56, 0xf2, 0xd3, 0xab,
+ 0x44, 0x11, 0x92, 0xd9, 0x23, 0x20, 0x2e, 0x89, 0xb4, 0x7c, 0xb8, 0x26, 0x77, 0x99, 0xe3, 0xa5,
+ 0x67, 0x4a, 0xed, 0xde, 0xc5, 0x31, 0xfe, 0x18, 0x0d, 0x63, 0x8c, 0x80, 0xc0, 0xf7, 0x70, 0x07)
+
+
+def key_expansion(data):
+ """
+ Generate key schedule
+
+ @param {int[]} data 16/24/32-Byte cipher key
+ @returns {int[]} 176/208/240-Byte expanded key
+ """
+ data = data[:] # copy
+ rcon_iteration = 1
+ key_size_bytes = len(data)
+ expanded_key_size_bytes = (key_size_bytes // 4 + 7) * BLOCK_SIZE_BYTES
+
+ while len(data) < expanded_key_size_bytes:
+ temp = data[-4:]
+ temp = key_schedule_core(temp, rcon_iteration)
+ rcon_iteration += 1
+ data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])
+
+ for _ in range(3):
+ temp = data[-4:]
+ data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])
+
+ if key_size_bytes == 32:
+ temp = data[-4:]
+ temp = sub_bytes(temp)
+ data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])
+
+ for _ in range(3 if key_size_bytes == 32 else 2 if key_size_bytes == 24 else 0):
+ temp = data[-4:]
+ data += xor(temp, data[-key_size_bytes: 4 - key_size_bytes])
+ return data[:expanded_key_size_bytes]
+
+
+def iter_vector(iv):
+ while True:
+ yield iv
+ iv = inc(iv)
+
+
+def sub_bytes(data):
+ return [SBOX[x] for x in data]
+
+
+def sub_bytes_inv(data):
+ return [SBOX_INV[x] for x in data]
+
+
+def rotate(data):
+ return data[1:] + [data[0]]
+
+
+def key_schedule_core(data, rcon_iteration):
+ data = rotate(data)
+ data = sub_bytes(data)
+ data[0] = data[0] ^ RCON[rcon_iteration]
+
+ return data
+
+
+def xor(data1, data2):
+ return [x ^ y for x, y in zip(data1, data2)]
+
+
+def iter_mix_columns(data, matrix):
+ for i in (0, 4, 8, 12):
+ for row in matrix:
+ mixed = 0
+ for j in range(4):
+ # xor is (+) and (-)
+ mixed ^= (0 if data[i:i + 4][j] == 0 or row[j] == 0 else
+ RIJNDAEL_EXP_TABLE[(RIJNDAEL_LOG_TABLE[data[i + j]] + RIJNDAEL_LOG_TABLE[row[j]]) % 0xFF])
+ yield mixed
+
+
+def shift_rows(data):
+ return [data[((column + row) & 0b11) * 4 + row] for column in range(4) for row in range(4)]
+
+
+def shift_rows_inv(data):
+ return [data[((column - row) & 0b11) * 4 + row] for column in range(4) for row in range(4)]
+
+
+def shift_block(data):
+ data_shifted = []
+
+ bit = 0
+ for n in data:
+ if bit:
+ n |= 0x100
+ bit = n & 1
+ n >>= 1
+ data_shifted.append(n)
+
+ return data_shifted
+
+
+def inc(data):
+ data = data[:] # copy
+ for i in range(len(data) - 1, -1, -1):
+ if data[i] == 255:
+ data[i] = 0
+ else:
+ data[i] = data[i] + 1
+ break
+ return data
+
+
+def block_product(block_x, block_y):
+ # NIST SP 800-38D, Algorithm 1
+
+ if len(block_x) != BLOCK_SIZE_BYTES or len(block_y) != BLOCK_SIZE_BYTES:
+ raise ValueError(f'Length of blocks need to be {BLOCK_SIZE_BYTES} bytes')
+
+ block_r = [0xE1] + [0] * (BLOCK_SIZE_BYTES - 1)
+ block_v = block_y[:]
+ block_z = [0] * BLOCK_SIZE_BYTES
+
+ for i in block_x:
+ for bit in range(7, -1, -1):
+ if i & (1 << bit):
+ block_z = xor(block_z, block_v)
+
+ do_xor = block_v[-1] & 1
+ block_v = shift_block(block_v)
+ if do_xor:
+ block_v = xor(block_v, block_r)
+
+ return block_z
+
+
+def ghash(subkey, data):
+ # NIST SP 800-38D, Algorithm 2
+
+ if len(data) % BLOCK_SIZE_BYTES:
+ raise ValueError(f'Length of data should be {BLOCK_SIZE_BYTES} bytes')
+
+ last_y = [0] * BLOCK_SIZE_BYTES
+ for i in range(0, len(data), BLOCK_SIZE_BYTES):
+ block = data[i: i + BLOCK_SIZE_BYTES]
+ last_y = block_product(xor(last_y, block), subkey)
+
+ return last_y
+
+
+__all__ = [
+ 'aes_cbc_decrypt',
+ 'aes_cbc_decrypt_bytes',
+ 'aes_cbc_encrypt',
+ 'aes_cbc_encrypt_bytes',
+ 'aes_ctr_decrypt',
+ 'aes_ctr_encrypt',
+ 'aes_decrypt',
+ 'aes_decrypt_text',
+ 'aes_ecb_decrypt',
+ 'aes_ecb_encrypt',
+ 'aes_encrypt',
+ 'aes_gcm_decrypt_and_verify',
+ 'aes_gcm_decrypt_and_verify_bytes',
+ 'key_expansion',
+ 'pad_block',
+ 'pkcs7_padding',
+ 'unpad_pkcs7',
+]
diff --git a/cookies.py b/cookies.py
new file mode 100644
index 0000000..1d3f50a
--- /dev/null
+++ b/cookies.py
@@ -0,0 +1,1373 @@
+# Copied from yt-dlp (revision 6a6d97b2cbc78f818de05cc96edcdcfd52caa259), Unlicense'd <http://unlicense.org/>
+# Modified to be more independent
+import base64
+import collections
+import contextlib
+import datetime as dt
+import functools
+import glob
+import hashlib
+import http.cookiejar
+import http.cookies
+import io
+import json
+import os
+import re
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+from enum import Enum, auto
+import sqlite3
+
+from aes import (
+ aes_cbc_decrypt_bytes,
+ aes_gcm_decrypt_and_verify_bytes,
+ unpad_pkcs7,
+)
+def is_path_like(f):
+ return isinstance(f, (str, bytes, os.PathLike))
+
+def expand_path(s):
+ """Expand shell variables and ~"""
+ return os.path.expandvars(os.path.expanduser(s))
+
+CHROMIUM_BASED_BROWSERS = {'brave', 'chrome', 'chromium', 'edge', 'opera', 'vivaldi', 'whale'}
+SUPPORTED_BROWSERS = CHROMIUM_BASED_BROWSERS | {'firefox', 'safari'}
+
+
+class YDLLogger():
+ def warning(self, message, only_once=False): # compat
+ return super().warning(message, once=only_once)
+
+ class ProgressBar():
+ def print(self, message):
+ True
+
+ def progress_bar(self):
+ """Return a context manager with a print method. (Optional)"""
+ # Do not print to files/pipes, loggers, or when --no-progress is used
+ if not self._ydl or self._ydl.params.get('noprogress') or self._ydl.params.get('logger'):
+ return
+ file = self._ydl._out_files.error
+ try:
+ if not file.isatty():
+ return
+ except BaseException:
+ return
+ return self.ProgressBar(file, preserve_output=False)
+
+class CookieLoadError():
+ pass
+
+class YDLLogger():
+ def __init__(x=None, y=None): True
+ def info(x, y):
+ True # print(y)
+ def debug(x, y):
+ True # print(y)
+
+def load_cookies(cookie_file, browser_specification, ydl):
+ try:
+ cookie_jars = []
+ if browser_specification is not None:
+ browser_name, profile, keyring, container = _parse_browser_specification(*browser_specification)
+ cookie_jars.append(
+ extract_cookies_from_browser(browser_name, profile, YDLLogger(ydl), keyring=keyring, container=container))
+
+ if cookie_file is not None:
+ is_filename = is_path_like(cookie_file)
+ if is_filename:
+ cookie_file = expand_path(cookie_file)
+
+ jar = YoutubeDLCookieJar(cookie_file)
+ if not is_filename or os.access(cookie_file, os.R_OK):
+ jar.load()
+ cookie_jars.append(jar)
+
+ return _merge_cookie_jars(cookie_jars)
+ except Exception:
+ raise Exception('failed to load cookies')
+
+
+def extract_cookies_from_browser(browser_name, profile=None, logger=YDLLogger(), *, keyring=None, container=None):
+ if browser_name == 'firefox':
+ return _extract_firefox_cookies(profile, container, logger)
+ elif browser_name == 'safari':
+ return _extract_safari_cookies(profile, logger)
+ elif browser_name in CHROMIUM_BASED_BROWSERS:
+ return _extract_chrome_cookies(browser_name, profile, keyring, logger)
+ else:
+ raise ValueError(f'unknown browser: {browser_name}')
+
+
+def _extract_firefox_cookies(profile, container, logger):
+ logger.info('Extracting cookies from firefox')
+ if not sqlite3:
+ logger.warning('Cannot extract cookies from firefox without sqlite3 support. '
+ 'Please use a Python interpreter compiled with sqlite3 support')
+ return YoutubeDLCookieJar()
+
+ if profile is None:
+ search_roots = list(_firefox_browser_dirs())
+ elif _is_path(profile):
+ search_roots = [profile]
+ else:
+ search_roots = [os.path.join(path, profile) for path in _firefox_browser_dirs()]
+ search_root = ', '.join(map(repr, search_roots))
+
+ cookie_database_path = _newest(_firefox_cookie_dbs(search_roots))
+ if cookie_database_path is None:
+ raise FileNotFoundError(f'could not find firefox cookies database in {search_root}')
+ logger.debug(f'Extracting cookies from: "{cookie_database_path}"')
+
+ container_id = None
+ if container not in (None, 'none'):
+ containers_path = os.path.join(os.path.dirname(cookie_database_path), 'containers.json')
+ if not os.path.isfile(containers_path) or not os.access(containers_path, os.R_OK):
+ raise FileNotFoundError(f'could not read containers.json in {search_root}')
+ with open(containers_path, encoding='utf8') as containers:
+ identities = json.load(containers).get('identities', [])
+ container_id = next((context.get('userContextId') for context in identities if container in (
+ context.get('name'),
+ try_call(lambda: re.fullmatch(r'userContext([^\.]+)\.label', context['l10nID']).group()),
+ )), None)
+ if not isinstance(container_id, int):
+ raise ValueError(f'could not find firefox container "{container}" in containers.json')
+
+ with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:
+ cursor = None
+ try:
+ cursor = _open_database_copy(cookie_database_path, tmpdir)
+ if isinstance(container_id, int):
+ logger.debug(
+ f'Only loading cookies from firefox container "{container}", ID {container_id}')
+ cursor.execute(
+ 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE originAttributes LIKE ? OR originAttributes LIKE ?',
+ (f'%userContextId={container_id}', f'%userContextId={container_id}&%'))
+ elif container == 'none':
+ logger.debug('Only loading cookies not belonging to any container')
+ cursor.execute(
+ 'SELECT host, name, value, path, expiry, isSecure FROM moz_cookies WHERE NOT INSTR(originAttributes,"userContextId=")')
+ else:
+ cursor.execute('SELECT host, name, value, path, expiry, isSecure FROM moz_cookies')
+ jar = YoutubeDLCookieJar()
+ if(True):
+ table = cursor.fetchall()
+ total_cookie_count = len(table)
+ for i, (host, name, value, path, expiry, is_secure) in enumerate(table):
+ cookie = http.cookiejar.Cookie(
+ version=0, name=name, value=value, port=None, port_specified=False,
+ domain=host, domain_specified=bool(host), domain_initial_dot=host.startswith('.'),
+ path=path, path_specified=bool(path), secure=is_secure, expires=expiry, discard=False,
+ comment=None, comment_url=None, rest={})
+ jar.set_cookie(cookie)
+ logger.info(f'Extracted {len(jar)} cookies from firefox')
+ return jar
+ finally:
+ if cursor is not None:
+ cursor.connection.close()
+
+
+def _firefox_browser_dirs():
+ if sys.platform in ('cygwin', 'win32'):
+ yield from map(os.path.expandvars, (
+ R'%APPDATA%\Mozilla\Firefox\Profiles',
+ R'%LOCALAPPDATA%\Packages\Mozilla.Firefox_n80bbvh6b1yt2\LocalCache\Roaming\Mozilla\Firefox\Profiles',
+ ))
+
+ elif sys.platform == 'darwin':
+ yield os.path.expanduser('~/Library/Application Support/Firefox/Profiles')
+
+ else:
+ yield from map(os.path.expanduser, (
+ '~/.mozilla/firefox',
+ '~/.mozilla/icecat', # Firefox based browsers too
+ '~/.mozilla/iceweasel',
+ '~/.mozilla/librewolf',
+ '~/.mozilla/waterfox',
+ '~/.mozilla/floorp',
+ '~/.mozilla/mercury',
+ '~/snap/firefox/common/.mozilla/firefox',
+ '~/.var/app/org.mozilla.firefox/.mozilla/firefox',
+ ))
+
+
+def _firefox_cookie_dbs(roots):
+ for root in map(os.path.abspath, roots):
+ for pattern in ('', '*/', 'Profiles/*/'):
+ yield from glob.iglob(os.path.join(root, pattern, 'cookies.sqlite'))
+
+
+def _get_chromium_based_browser_settings(browser_name):
+ # https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md
+ if sys.platform in ('cygwin', 'win32'):
+ appdata_local = os.path.expandvars('%LOCALAPPDATA%')
+ appdata_roaming = os.path.expandvars('%APPDATA%')
+ browser_dir = {
+ 'brave': os.path.join(appdata_local, R'BraveSoftware\Brave-Browser\User Data'),
+ 'chrome': os.path.join(appdata_local, R'Google\Chrome\User Data'),
+ 'chromium': os.path.join(appdata_local, R'Chromium\User Data'),
+ 'edge': os.path.join(appdata_local, R'Microsoft\Edge\User Data'),
+ 'opera': os.path.join(appdata_roaming, R'Opera Software\Opera Stable'),
+ 'vivaldi': os.path.join(appdata_local, R'Vivaldi\User Data'),
+ 'whale': os.path.join(appdata_local, R'Naver\Naver Whale\User Data'),
+ }[browser_name]
+
+ elif sys.platform == 'darwin':
+ appdata = os.path.expanduser('~/Library/Application Support')
+ browser_dir = {
+ 'brave': os.path.join(appdata, 'BraveSoftware/Brave-Browser'),
+ 'chrome': os.path.join(appdata, 'Google/Chrome'),
+ 'chromium': os.path.join(appdata, 'Chromium'),
+ 'edge': os.path.join(appdata, 'Microsoft Edge'),
+ 'opera': os.path.join(appdata, 'com.operasoftware.Opera'),
+ 'vivaldi': os.path.join(appdata, 'Vivaldi'),
+ 'whale': os.path.join(appdata, 'Naver/Whale'),
+ }[browser_name]
+
+ else:
+ config = _config_home()
+ browser_dir = {
+ 'brave': os.path.join(config, 'BraveSoftware/Brave-Browser'),
+ 'chrome': os.path.join(config, 'google-chrome'),
+ 'chromium': os.path.join(config, 'chromium'),
+ 'edge': os.path.join(config, 'microsoft-edge'),
+ 'opera': os.path.join(config, 'opera'),
+ 'vivaldi': os.path.join(config, 'vivaldi'),
+ 'whale': os.path.join(config, 'naver-whale'),
+ }[browser_name]
+ if(not os.path.exists(browser_dir)): # Try snap
+ browser_dir=os.path.join(os.path.expanduser('~/snap/chromium/common/'), browser_name)
+
+ # Linux keyring names can be determined by snooping on dbus while opening the browser in KDE:
+ # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
+ keyring_name = {
+ 'brave': 'Brave',
+ 'chrome': 'Chrome',
+ 'chromium': 'Chromium',
+ 'edge': 'Microsoft Edge' if sys.platform == 'darwin' else 'Chromium',
+ 'opera': 'Opera' if sys.platform == 'darwin' else 'Chromium',
+ 'vivaldi': 'Vivaldi' if sys.platform == 'darwin' else 'Chrome',
+ 'whale': 'Whale',
+ }[browser_name]
+
+ browsers_without_profiles = {'opera'}
+
+ return {
+ 'browser_dir': browser_dir,
+ 'keyring_name': keyring_name,
+ 'supports_profiles': browser_name not in browsers_without_profiles,
+ }
+
+
+def _extract_chrome_cookies(browser_name, profile, keyring, logger):
+ logger.info(f'Extracting cookies from {browser_name}')
+
+ if not sqlite3:
+ logger.warning(f'Cannot extract cookies from {browser_name} without sqlite3 support. '
+ 'Please use a Python interpreter compiled with sqlite3 support')
+ return YoutubeDLCookieJar()
+
+ config = _get_chromium_based_browser_settings(browser_name)
+
+ if profile is None:
+ search_root = config['browser_dir']
+ elif _is_path(profile):
+ search_root = profile
+ config['browser_dir'] = os.path.dirname(profile) if config['supports_profiles'] else profile
+ else:
+ if config['supports_profiles']:
+ search_root = os.path.join(config['browser_dir'], profile)
+ else:
+ logger.error(f'{browser_name} does not support profiles')
+ search_root = config['browser_dir']
+
+ cookie_database_path = _newest(_find_files(search_root, 'Cookies', logger))
+ if cookie_database_path is None:
+ raise FileNotFoundError(f'could not find {browser_name} cookies database in "{search_root}"')
+ logger.debug(f'Extracting cookies from: "{cookie_database_path}"')
+
+ with tempfile.TemporaryDirectory(prefix='yt_dlp') as tmpdir:
+ cursor = None
+ try:
+ cursor = _open_database_copy(cookie_database_path, tmpdir)
+
+ # meta_version is necessary to determine if we need to trim the hash prefix from the cookies
+ # Ref: https://chromium.googlesource.com/chromium/src/+/b02dcebd7cafab92770734dc2bc317bd07f1d891/net/extras/sqlite/sqlite_persistent_cookie_store.cc#223
+ meta_version = int(cursor.execute('SELECT value FROM meta WHERE key = "version"').fetchone()[0])
+ decryptor = get_cookie_decryptor(
+ config['browser_dir'], config['keyring_name'], logger,
+ keyring=keyring, meta_version=meta_version)
+
+ cursor.connection.text_factory = bytes
+ column_names = _get_column_names(cursor, 'cookies')
+ secure_column = 'is_secure' if 'is_secure' in column_names else 'secure'
+ cursor.execute(f'SELECT host_key, name, value, encrypted_value, path, expires_utc, {secure_column} FROM cookies')
+ jar = YoutubeDLCookieJar()
+ failed_cookies = 0
+ unencrypted_cookies = 0
+ if(True):
+ table = cursor.fetchall()
+ total_cookie_count = len(table)
+ for i, line in enumerate(table):
+ is_encrypted, cookie = _process_chrome_cookie(decryptor, *line)
+ if not cookie:
+ failed_cookies += 1
+ continue
+ elif not is_encrypted:
+ unencrypted_cookies += 1
+ jar.set_cookie(cookie)
+ if failed_cookies > 0:
+ failed_message = f' ({failed_cookies} could not be decrypted)'
+ else:
+ failed_message = ''
+ logger.info(f'Extracted {len(jar)} cookies from {browser_name}{failed_message}')
+ counts = decryptor._cookie_counts.copy()
+ counts['unencrypted'] = unencrypted_cookies
+ logger.debug(f'cookie version breakdown: {counts}')
+ return jar
+ except PermissionError as error:
+ if os.name == 'nt' and error.errno == 13:
+ message = 'Could not copy Chrome cookie database. See https://github.com/yt-dlp/yt-dlp/issues/7271 for more info'
+ logger.error(message)
+ raise DownloadError(message) # force exit
+ raise
+ finally:
+ if cursor is not None:
+ cursor.connection.close()
+
+
+def _process_chrome_cookie(decryptor, host_key, name, value, encrypted_value, path, expires_utc, is_secure):
+ host_key = host_key.decode()
+ name = name.decode()
+ value = value.decode()
+ path = path.decode()
+ is_encrypted = not value and encrypted_value
+
+ if is_encrypted:
+ value = decryptor.decrypt(encrypted_value)
+ if value is None:
+ return is_encrypted, None
+
+ # In chrome, session cookies have expires_utc set to 0
+ # In our cookie-store, cookies that do not expire should have expires set to None
+ if not expires_utc:
+ expires_utc = None
+
+ return is_encrypted, http.cookiejar.Cookie(
+ version=0, name=name, value=value, port=None, port_specified=False,
+ domain=host_key, domain_specified=bool(host_key), domain_initial_dot=host_key.startswith('.'),
+ path=path, path_specified=bool(path), secure=is_secure, expires=expires_utc, discard=False,
+ comment=None, comment_url=None, rest={})
+
+
+class ChromeCookieDecryptor:
+ """
+ Overview:
+
+ Linux:
+ - cookies are either v10 or v11
+ - v10: AES-CBC encrypted with a fixed key
+ - also attempts empty password if decryption fails
+ - v11: AES-CBC encrypted with an OS protected key (keyring)
+ - also attempts empty password if decryption fails
+ - v11 keys can be stored in various places depending on the activate desktop environment [2]
+
+ Mac:
+ - cookies are either v10 or not v10
+ - v10: AES-CBC encrypted with an OS protected key (keyring) and more key derivation iterations than linux
+ - not v10: 'old data' stored as plaintext
+
+ Windows:
+ - cookies are either v10 or not v10
+ - v10: AES-GCM encrypted with a key which is encrypted with DPAPI
+ - not v10: encrypted with DPAPI
+
+ Sources:
+ - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/
+ - [2] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_linux.cc
+ - KeyStorageLinux::CreateService
+ """
+
+ _cookie_counts = {}
+
+ def decrypt(self, encrypted_value):
+ raise NotImplementedError('Must be implemented by sub classes')
+
+
+def get_cookie_decryptor(browser_root, browser_keyring_name, logger, *, keyring=None, meta_version=None):
+ if sys.platform == 'darwin':
+ return MacChromeCookieDecryptor(browser_keyring_name, logger, meta_version=meta_version)
+ elif sys.platform in ('win32', 'cygwin'):
+ return WindowsChromeCookieDecryptor(browser_root, logger, meta_version=meta_version)
+ return LinuxChromeCookieDecryptor(browser_keyring_name, logger, keyring=keyring, meta_version=meta_version)
+
+
+class LinuxChromeCookieDecryptor(ChromeCookieDecryptor):
+ def __init__(self, browser_keyring_name, logger, *, keyring=None, meta_version=None):
+ self._logger = logger
+ self._v10_key = self.derive_key(b'peanuts')
+ self._empty_key = self.derive_key(b'')
+ self._cookie_counts = {'v10': 0, 'v11': 0, 'other': 0}
+ self._browser_keyring_name = browser_keyring_name
+ self._keyring = keyring
+ self._meta_version = meta_version or 0
+
+ @functools.cached_property
+ def _v11_key(self):
+ password = _get_linux_keyring_password(self._browser_keyring_name, self._keyring, self._logger)
+ return None if password is None else self.derive_key(password)
+
+ @staticmethod
+ def derive_key(password):
+ # values from
+ # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_linux.cc
+ return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1, key_length=16)
+
+ def decrypt(self, encrypted_value):
+ """
+
+ following the same approach as the fix in [1]: if cookies fail to decrypt then attempt to decrypt
+ with an empty password. The failure detection is not the same as what chromium uses so the
+ results won't be perfect
+
+ References:
+ - [1] https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/
+ - a bugfix to try an empty password as a fallback
+ """
+ version = encrypted_value[:3]
+ ciphertext = encrypted_value[3:]
+
+ if version == b'v10':
+ self._cookie_counts['v10'] += 1
+ return _decrypt_aes_cbc_multi(
+ ciphertext, (self._v10_key, self._empty_key), self._logger,
+ hash_prefix=self._meta_version >= 24)
+
+ elif version == b'v11':
+ self._cookie_counts['v11'] += 1
+ if self._v11_key is None:
+ self._logger.warning('cannot decrypt v11 cookies: no key found', only_once=True)
+ return None
+ return _decrypt_aes_cbc_multi(
+ ciphertext, (self._v11_key, self._empty_key), self._logger,
+ hash_prefix=self._meta_version >= 24)
+
+ else:
+ self._logger.warning(f'unknown cookie version: "{version}"', only_once=True)
+ self._cookie_counts['other'] += 1
+ return None
+
+
+class MacChromeCookieDecryptor(ChromeCookieDecryptor):
+ def __init__(self, browser_keyring_name, logger, meta_version=None):
+ self._logger = logger
+ password = _get_mac_keyring_password(browser_keyring_name, logger)
+ self._v10_key = None if password is None else self.derive_key(password)
+ self._cookie_counts = {'v10': 0, 'other': 0}
+ self._meta_version = meta_version or 0
+
+ @staticmethod
+ def derive_key(password):
+ # values from
+ # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm
+ return pbkdf2_sha1(password, salt=b'saltysalt', iterations=1003, key_length=16)
+
+ def decrypt(self, encrypted_value):
+ version = encrypted_value[:3]
+ ciphertext = encrypted_value[3:]
+
+ if version == b'v10':
+ self._cookie_counts['v10'] += 1
+ if self._v10_key is None:
+ self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)
+ return None
+
+ return _decrypt_aes_cbc_multi(
+ ciphertext, (self._v10_key,), self._logger, hash_prefix=self._meta_version >= 24)
+
+ else:
+ self._cookie_counts['other'] += 1
+ # other prefixes are considered 'old data' which were stored as plaintext
+ # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_mac.mm
+ return encrypted_value
+
+
+class WindowsChromeCookieDecryptor(ChromeCookieDecryptor):
+ def __init__(self, browser_root, logger, meta_version=None):
+ self._logger = logger
+ self._v10_key = _get_windows_v10_key(browser_root, logger)
+ self._cookie_counts = {'v10': 0, 'other': 0}
+ self._meta_version = meta_version or 0
+
+ def decrypt(self, encrypted_value):
+ version = encrypted_value[:3]
+ ciphertext = encrypted_value[3:]
+
+ if version == b'v10':
+ self._cookie_counts['v10'] += 1
+ if self._v10_key is None:
+ self._logger.warning('cannot decrypt v10 cookies: no key found', only_once=True)
+ return None
+
+ # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc
+ # kNonceLength
+ nonce_length = 96 // 8
+ # boringssl
+ # EVP_AEAD_AES_GCM_TAG_LEN
+ authentication_tag_length = 16
+
+ raw_ciphertext = ciphertext
+ nonce = raw_ciphertext[:nonce_length]
+ ciphertext = raw_ciphertext[nonce_length:-authentication_tag_length]
+ authentication_tag = raw_ciphertext[-authentication_tag_length:]
+
+ return _decrypt_aes_gcm(
+ ciphertext, self._v10_key, nonce, authentication_tag, self._logger,
+ hash_prefix=self._meta_version >= 24)
+
+ else:
+ self._cookie_counts['other'] += 1
+ # any other prefix means the data is DPAPI encrypted
+ # https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc
+ return _decrypt_windows_dpapi(encrypted_value, self._logger).decode()
+
+
+def _extract_safari_cookies(profile, logger):
+ if sys.platform != 'darwin':
+ raise ValueError(f'unsupported platform: {sys.platform}')
+
+ if profile:
+ cookies_path = os.path.expanduser(profile)
+ if not os.path.isfile(cookies_path):
+ raise FileNotFoundError('custom safari cookies database not found')
+
+ else:
+ cookies_path = os.path.expanduser('~/Library/Cookies/Cookies.binarycookies')
+
+ if not os.path.isfile(cookies_path):
+ logger.debug('Trying secondary cookie location')
+ cookies_path = os.path.expanduser('~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies')
+ if not os.path.isfile(cookies_path):
+ raise FileNotFoundError('could not find safari cookies database')
+
+ with open(cookies_path, 'rb') as f:
+ cookies_data = f.read()
+
+ jar = parse_safari_cookies(cookies_data, logger=logger)
+ logger.info(f'Extracted {len(jar)} cookies from safari')
+ return jar
+
+
+class ParserError(Exception):
+ pass
+
+
+class DataParser:
+ def __init__(self, data, logger):
+ self._data = data
+ self.cursor = 0
+ self._logger = logger
+
+ def read_bytes(self, num_bytes):
+ if num_bytes < 0:
+ raise ParserError(f'invalid read of {num_bytes} bytes')
+ end = self.cursor + num_bytes
+ if end > len(self._data):
+ raise ParserError('reached end of input')
+ data = self._data[self.cursor:end]
+ self.cursor = end
+ return data
+
+ def expect_bytes(self, expected_value, message):
+ value = self.read_bytes(len(expected_value))
+ if value != expected_value:
+ raise ParserError(f'unexpected value: {value} != {expected_value} ({message})')
+
+ def read_uint(self, big_endian=False):
+ data_format = '>I' if big_endian else '<I'
+ return struct.unpack(data_format, self.read_bytes(4))[0]
+
+ def read_double(self, big_endian=False):
+ data_format = '>d' if big_endian else '<d'
+ return struct.unpack(data_format, self.read_bytes(8))[0]
+
+ def read_cstring(self):
+ buffer = []
+ while True:
+ c = self.read_bytes(1)
+ if c == b'\x00':
+ return b''.join(buffer).decode()
+ else:
+ buffer.append(c)
+
+ def skip(self, num_bytes, description='unknown'):
+ if num_bytes > 0:
+ self._logger.debug(f'skipping {num_bytes} bytes ({description}): {self.read_bytes(num_bytes)!r}')
+ elif num_bytes < 0:
+ raise ParserError(f'invalid skip of {num_bytes} bytes')
+
+ def skip_to(self, offset, description='unknown'):
+ self.skip(offset - self.cursor, description)
+
+ def skip_to_end(self, description='unknown'):
+ self.skip_to(len(self._data), description)
+
+
+def _mac_absolute_time_to_posix(timestamp):
+ return int((dt.datetime(2001, 1, 1, 0, 0, tzinfo=dt.timezone.utc) + dt.timedelta(seconds=timestamp)).timestamp())
+
+
+def _parse_safari_cookies_header(data, logger):
+ p = DataParser(data, logger)
+ p.expect_bytes(b'cook', 'database signature')
+ number_of_pages = p.read_uint(big_endian=True)
+ page_sizes = [p.read_uint(big_endian=True) for _ in range(number_of_pages)]
+ return page_sizes, p.cursor
+
+
+def _parse_safari_cookies_page(data, jar, logger):
+ p = DataParser(data, logger)
+ p.expect_bytes(b'\x00\x00\x01\x00', 'page signature')
+ number_of_cookies = p.read_uint()
+ record_offsets = [p.read_uint() for _ in range(number_of_cookies)]
+ if number_of_cookies == 0:
+ logger.debug(f'a cookies page of size {len(data)} has no cookies')
+ return
+
+ p.skip_to(record_offsets[0], 'unknown page header field')
+
+ if(True):
+ for i, record_offset in enumerate(record_offsets):
+ p.skip_to(record_offset, 'space between records')
+ record_length = _parse_safari_cookies_record(data[record_offset:], jar, logger)
+ p.read_bytes(record_length)
+ p.skip_to_end('space in between pages')
+
+
+def _parse_safari_cookies_record(data, jar, logger):
+ p = DataParser(data, logger)
+ record_size = p.read_uint()
+ p.skip(4, 'unknown record field 1')
+ flags = p.read_uint()
+ is_secure = bool(flags & 0x0001)
+ p.skip(4, 'unknown record field 2')
+ domain_offset = p.read_uint()
+ name_offset = p.read_uint()
+ path_offset = p.read_uint()
+ value_offset = p.read_uint()
+ p.skip(8, 'unknown record field 3')
+ expiration_date = _mac_absolute_time_to_posix(p.read_double())
+ _creation_date = _mac_absolute_time_to_posix(p.read_double()) # noqa: F841
+
+ try:
+ p.skip_to(domain_offset)
+ domain = p.read_cstring()
+
+ p.skip_to(name_offset)
+ name = p.read_cstring()
+
+ p.skip_to(path_offset)
+ path = p.read_cstring()
+
+ p.skip_to(value_offset)
+ value = p.read_cstring()
+ except UnicodeDecodeError:
+ logger.warning('failed to parse Safari cookie because UTF-8 decoding failed', only_once=True)
+ return record_size
+
+ p.skip_to(record_size, 'space at the end of the record')
+
+ cookie = http.cookiejar.Cookie(
+ version=0, name=name, value=value, port=None, port_specified=False,
+ domain=domain, domain_specified=bool(domain), domain_initial_dot=domain.startswith('.'),
+ path=path, path_specified=bool(path), secure=is_secure, expires=expiration_date, discard=False,
+ comment=None, comment_url=None, rest={})
+ jar.set_cookie(cookie)
+ return record_size
+
+
+def parse_safari_cookies(data, jar=None, logger=YDLLogger()):
+ """
+ References:
+ - https://github.com/libyal/dtformats/blob/main/documentation/Safari%20Cookies.asciidoc
+ - this data appears to be out of date but the important parts of the database structure is the same
+ - there are a few bytes here and there which are skipped during parsing
+ """
+ if jar is None:
+ jar = YoutubeDLCookieJar()
+ page_sizes, body_start = _parse_safari_cookies_header(data, logger)
+ p = DataParser(data[body_start:], logger)
+ for page_size in page_sizes:
+ _parse_safari_cookies_page(p.read_bytes(page_size), jar, logger)
+ p.skip_to_end('footer')
+ return jar
+
+
+class _LinuxDesktopEnvironment(Enum):
+ """
+ https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.h
+ DesktopEnvironment
+ """
+ OTHER = auto()
+ CINNAMON = auto()
+ DEEPIN = auto()
+ GNOME = auto()
+ KDE3 = auto()
+ KDE4 = auto()
+ KDE5 = auto()
+ KDE6 = auto()
+ PANTHEON = auto()
+ UKUI = auto()
+ UNITY = auto()
+ XFCE = auto()
+ LXQT = auto()
+
+
+class _LinuxKeyring(Enum):
+ """
+ https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.h
+ SelectedLinuxBackend
+ """
+ KWALLET = auto() # KDE4
+ KWALLET5 = auto()
+ KWALLET6 = auto()
+ GNOMEKEYRING = auto()
+ BASICTEXT = auto()
+
+
+SUPPORTED_KEYRINGS = _LinuxKeyring.__members__.keys()
+
+
+def _get_linux_desktop_environment(env, logger):
+ """
+ https://chromium.googlesource.com/chromium/src/+/refs/heads/main/base/nix/xdg_util.cc
+ GetDesktopEnvironment
+ """
+ xdg_current_desktop = env.get('XDG_CURRENT_DESKTOP', None)
+ desktop_session = env.get('DESKTOP_SESSION', None)
+ if xdg_current_desktop is not None:
+ for part in map(str.strip, xdg_current_desktop.split(':')):
+ if part == 'Unity':
+ if desktop_session is not None and 'gnome-fallback' in desktop_session:
+ return _LinuxDesktopEnvironment.GNOME
+ else:
+ return _LinuxDesktopEnvironment.UNITY
+ elif part == 'Deepin':
+ return _LinuxDesktopEnvironment.DEEPIN
+ elif part == 'GNOME':
+ return _LinuxDesktopEnvironment.GNOME
+ elif part == 'X-Cinnamon':
+ return _LinuxDesktopEnvironment.CINNAMON
+ elif part == 'KDE':
+ kde_version = env.get('KDE_SESSION_VERSION', None)
+ if kde_version == '5':
+ return _LinuxDesktopEnvironment.KDE5
+ elif kde_version == '6':
+ return _LinuxDesktopEnvironment.KDE6
+ elif kde_version == '4':
+ return _LinuxDesktopEnvironment.KDE4
+ else:
+ logger.info(f'unknown KDE version: "{kde_version}". Assuming KDE4')
+ return _LinuxDesktopEnvironment.KDE4
+ elif part == 'Pantheon':
+ return _LinuxDesktopEnvironment.PANTHEON
+ elif part == 'XFCE':
+ return _LinuxDesktopEnvironment.XFCE
+ elif part == 'UKUI':
+ return _LinuxDesktopEnvironment.UKUI
+ elif part == 'LXQt':
+ return _LinuxDesktopEnvironment.LXQT
+ logger.info(f'XDG_CURRENT_DESKTOP is set to an unknown value: "{xdg_current_desktop}"')
+
+ elif desktop_session is not None:
+ if desktop_session == 'deepin':
+ return _LinuxDesktopEnvironment.DEEPIN
+ elif desktop_session in ('mate', 'gnome'):
+ return _LinuxDesktopEnvironment.GNOME
+ elif desktop_session in ('kde4', 'kde-plasma'):
+ return _LinuxDesktopEnvironment.KDE4
+ elif desktop_session == 'kde':
+ if 'KDE_SESSION_VERSION' in env:
+ return _LinuxDesktopEnvironment.KDE4
+ else:
+ return _LinuxDesktopEnvironment.KDE3
+ elif 'xfce' in desktop_session or desktop_session == 'xubuntu':
+ return _LinuxDesktopEnvironment.XFCE
+ elif desktop_session == 'ukui':
+ return _LinuxDesktopEnvironment.UKUI
+ else:
+ logger.info(f'DESKTOP_SESSION is set to an unknown value: "{desktop_session}"')
+
+ else:
+ if 'GNOME_DESKTOP_SESSION_ID' in env:
+ return _LinuxDesktopEnvironment.GNOME
+ elif 'KDE_FULL_SESSION' in env:
+ if 'KDE_SESSION_VERSION' in env:
+ return _LinuxDesktopEnvironment.KDE4
+ else:
+ return _LinuxDesktopEnvironment.KDE3
+ return _LinuxDesktopEnvironment.OTHER
+
+
+def _choose_linux_keyring(logger):
+ """
+ SelectBackend in [1]
+
+ There is currently support for forcing chromium to use BASIC_TEXT by creating a file called
+ `Disable Local Encryption` [1] in the user data dir. The function to write this file (`WriteBackendUse()` [1])
+ does not appear to be called anywhere other than in tests, so the user would have to create this file manually
+ and so would be aware enough to tell yt-dlp to use the BASIC_TEXT keyring.
+
+ References:
+ - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/key_storage_util_linux.cc
+ """
+ desktop_environment = _get_linux_desktop_environment(os.environ, logger)
+ logger.debug(f'detected desktop environment: {desktop_environment.name}')
+ if desktop_environment == _LinuxDesktopEnvironment.KDE4:
+ linux_keyring = _LinuxKeyring.KWALLET
+ elif desktop_environment == _LinuxDesktopEnvironment.KDE5:
+ linux_keyring = _LinuxKeyring.KWALLET5
+ elif desktop_environment == _LinuxDesktopEnvironment.KDE6:
+ linux_keyring = _LinuxKeyring.KWALLET6
+ elif desktop_environment in (
+ _LinuxDesktopEnvironment.KDE3, _LinuxDesktopEnvironment.LXQT, _LinuxDesktopEnvironment.OTHER,
+ ):
+ linux_keyring = _LinuxKeyring.BASICTEXT
+ else:
+ linux_keyring = _LinuxKeyring.GNOMEKEYRING
+ return linux_keyring
+
+
+def _get_kwallet_network_wallet(keyring, logger):
+ """ The name of the wallet used to store network passwords.
+
+ https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/kwallet_dbus.cc
+ KWalletDBus::NetworkWallet
+ which does a dbus call to the following function:
+ https://api.kde.org/frameworks/kwallet/html/classKWallet_1_1Wallet.html
+ Wallet::NetworkWallet
+ """
+ default_wallet = 'kdewallet'
+ try:
+ if keyring == _LinuxKeyring.KWALLET:
+ service_name = 'org.kde.kwalletd'
+ wallet_path = '/modules/kwalletd'
+ elif keyring == _LinuxKeyring.KWALLET5:
+ service_name = 'org.kde.kwalletd5'
+ wallet_path = '/modules/kwalletd5'
+ elif keyring == _LinuxKeyring.KWALLET6:
+ service_name = 'org.kde.kwalletd6'
+ wallet_path = '/modules/kwalletd6'
+ else:
+ raise ValueError(keyring)
+
+ stdout, _, returncode = Popen.run([
+ 'dbus-send', '--session', '--print-reply=literal',
+ f'--dest={service_name}',
+ wallet_path,
+ 'org.kde.KWallet.networkWallet',
+ ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+
+ if returncode:
+ logger.warning('failed to read NetworkWallet')
+ return default_wallet
+ else:
+ logger.debug(f'NetworkWallet = "{stdout.strip()}"')
+ return stdout.strip()
+ except Exception as e:
+ logger.warning(f'exception while obtaining NetworkWallet: {e}')
+ return default_wallet
+
+
+def _get_kwallet_password(browser_keyring_name, keyring, logger):
+ logger.debug(f'using kwallet-query to obtain password from {keyring.name}')
+
+ if shutil.which('kwallet-query') is None:
+ logger.error('kwallet-query command not found. KWallet and kwallet-query '
+ 'must be installed to read from KWallet. kwallet-query should be'
+ 'included in the kwallet package for your distribution')
+ return b''
+
+ network_wallet = _get_kwallet_network_wallet(keyring, logger)
+
+ try:
+ stdout, _, returncode = Popen.run([
+ 'kwallet-query',
+ '--read-password', f'{browser_keyring_name} Safe Storage',
+ '--folder', f'{browser_keyring_name} Keys',
+ network_wallet,
+ ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+
+ if returncode:
+ logger.error(f'kwallet-query failed with return code {returncode}. '
+ 'Please consult the kwallet-query man page for details')
+ return b''
+ else:
+ if stdout.lower().startswith(b'failed to read'):
+ logger.debug('failed to read password from kwallet. Using empty string instead')
+ # this sometimes occurs in KDE because chrome does not check hasEntry and instead
+ # just tries to read the value (which kwallet returns "") whereas kwallet-query
+ # checks hasEntry. To verify this:
+ # dbus-monitor "interface='org.kde.KWallet'" "type=method_return"
+ # while starting chrome.
+ # this was identified as a bug later and fixed in
+ # https://chromium.googlesource.com/chromium/src/+/bbd54702284caca1f92d656fdcadf2ccca6f4165%5E%21/#F0
+ # https://chromium.googlesource.com/chromium/src/+/5463af3c39d7f5b6d11db7fbd51e38cc1974d764
+ return b''
+ else:
+ logger.debug('password found')
+ return stdout.rstrip(b'\n')
+ except Exception as e:
+ logger.warning(f'exception running kwallet-query: {error_to_str(e)}')
+ return b''
+
+
+def _get_gnome_keyring_password(browser_keyring_name, logger):
+ if not secretstorage:
+ logger.error(f'secretstorage not available {_SECRETSTORAGE_UNAVAILABLE_REASON}')
+ return b''
+ # the Gnome keyring does not seem to organise keys in the same way as KWallet,
+ # using `dbus-monitor` during startup, it can be observed that chromium lists all keys
+ # and presumably searches for its key in the list. It appears that we must do the same.
+ # https://github.com/jaraco/keyring/issues/556
+ with contextlib.closing(secretstorage.dbus_init()) as con:
+ col = secretstorage.get_default_collection(con)
+ for item in col.get_all_items():
+ if item.get_label() == f'{browser_keyring_name} Safe Storage':
+ return item.get_secret()
+ logger.error('failed to read from keyring')
+ return b''
+
+
+def _get_linux_keyring_password(browser_keyring_name, keyring, logger):
+ # note: chrome/chromium can be run with the following flags to determine which keyring backend
+ # it has chosen to use
+ # chromium --enable-logging=stderr --v=1 2>&1 | grep key_storage_
+ # Chromium supports a flag: --password-store=<basic|gnome|kwallet> so the automatic detection
+ # will not be sufficient in all cases.
+
+ keyring = _LinuxKeyring[keyring] if keyring else _choose_linux_keyring(logger)
+ logger.debug(f'Chosen keyring: {keyring.name}')
+
+ if keyring in (_LinuxKeyring.KWALLET, _LinuxKeyring.KWALLET5, _LinuxKeyring.KWALLET6):
+ return _get_kwallet_password(browser_keyring_name, keyring, logger)
+ elif keyring == _LinuxKeyring.GNOMEKEYRING:
+ return _get_gnome_keyring_password(browser_keyring_name, logger)
+ elif keyring == _LinuxKeyring.BASICTEXT:
+ # when basic text is chosen, all cookies are stored as v10 (so no keyring password is required)
+ return None
+ assert False, f'Unknown keyring {keyring}'
+
+
+def _get_mac_keyring_password(browser_keyring_name, logger):
+ logger.debug('using find-generic-password to obtain password from OSX keychain')
+ try:
+ stdout, _, returncode = Popen.run(
+ ['security', 'find-generic-password',
+ '-w', # write password to stdout
+ '-a', browser_keyring_name, # match 'account'
+ '-s', f'{browser_keyring_name} Safe Storage'], # match 'service'
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+ if returncode:
+ logger.warning('find-generic-password failed')
+ return None
+ return stdout.rstrip(b'\n')
+ except Exception as e:
+ logger.warning(f'exception running find-generic-password: {error_to_str(e)}')
+ return None
+
+
+def _get_windows_v10_key(browser_root, logger):
+ """
+ References:
+ - [1] https://chromium.googlesource.com/chromium/src/+/refs/heads/main/components/os_crypt/sync/os_crypt_win.cc
+ """
+ path = _newest(_find_files(browser_root, 'Local State', logger))
+ if path is None:
+ logger.error('could not find local state file')
+ return None
+ logger.debug(f'Found local state file at "{path}"')
+ with open(path, encoding='utf8') as f:
+ data = json.load(f)
+ try:
+ # kOsCryptEncryptedKeyPrefName in [1]
+ base64_key = data['os_crypt']['encrypted_key']
+ except KeyError:
+ logger.error('no encrypted key in Local State')
+ return None
+ encrypted_key = base64.b64decode(base64_key)
+ # kDPAPIKeyPrefix in [1]
+ prefix = b'DPAPI'
+ if not encrypted_key.startswith(prefix):
+ logger.error('invalid key')
+ return None
+ return _decrypt_windows_dpapi(encrypted_key[len(prefix):], logger)
+
+
+def pbkdf2_sha1(password, salt, iterations, key_length):
+ return hashlib.pbkdf2_hmac('sha1', password, salt, iterations, key_length)
+
+
+def _decrypt_aes_cbc_multi(ciphertext, keys, logger, initialization_vector=b' ' * 16, hash_prefix=False):
+ for key in keys:
+ plaintext = unpad_pkcs7(aes_cbc_decrypt_bytes(ciphertext, key, initialization_vector))
+ try:
+ if hash_prefix:
+ return plaintext[32:].decode()
+ return plaintext.decode()
+ except UnicodeDecodeError:
+ pass
+ logger.warning('failed to decrypt cookie (AES-CBC) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)
+ return None
+
+
+def _decrypt_aes_gcm(ciphertext, key, nonce, authentication_tag, logger, hash_prefix=False):
+ try:
+ plaintext = aes_gcm_decrypt_and_verify_bytes(ciphertext, key, authentication_tag, nonce)
+ except ValueError:
+ logger.warning('failed to decrypt cookie (AES-GCM) because the MAC check failed. Possibly the key is wrong?', only_once=True)
+ return None
+
+ try:
+ if hash_prefix:
+ return plaintext[32:].decode()
+ return plaintext.decode()
+ except UnicodeDecodeError:
+ logger.warning('failed to decrypt cookie (AES-GCM) because UTF-8 decoding failed. Possibly the key is wrong?', only_once=True)
+ return None
+
+
+def _decrypt_windows_dpapi(ciphertext, logger):
+ """
+ References:
+ - https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata
+ """
+
+ import ctypes
+ import ctypes.wintypes
+
+ class DATA_BLOB(ctypes.Structure):
+ _fields_ = [('cbData', ctypes.wintypes.DWORD),
+ ('pbData', ctypes.POINTER(ctypes.c_char))]
+
+ buffer = ctypes.create_string_buffer(ciphertext)
+ blob_in = DATA_BLOB(ctypes.sizeof(buffer), buffer)
+ blob_out = DATA_BLOB()
+ ret = ctypes.windll.crypt32.CryptUnprotectData(
+ ctypes.byref(blob_in), # pDataIn
+ None, # ppszDataDescr: human readable description of pDataIn
+ None, # pOptionalEntropy: salt?
+ None, # pvReserved: must be NULL
+ None, # pPromptStruct: information about prompts to display
+ 0, # dwFlags
+ ctypes.byref(blob_out), # pDataOut
+ )
+ if not ret:
+ message = 'Failed to decrypt with DPAPI. See https://github.com/yt-dlp/yt-dlp/issues/10927 for more info'
+ logger.error(message)
+ raise DownloadError(message) # force exit
+
+ result = ctypes.string_at(blob_out.pbData, blob_out.cbData)
+ ctypes.windll.kernel32.LocalFree(blob_out.pbData)
+ return result
+
+
+def _config_home():
+ return os.environ.get('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
+
+
+def _open_database_copy(database_path, tmpdir):
+ # cannot open sqlite databases if they are already in use (e.g. by the browser)
+ database_copy_path = os.path.join(tmpdir, 'temporary.sqlite')
+ shutil.copy(database_path, database_copy_path)
+ conn = sqlite3.connect(database_copy_path)
+ return conn.cursor()
+
+
+def _get_column_names(cursor, table_name):
+ table_info = cursor.execute(f'PRAGMA table_info({table_name})').fetchall()
+ return [row[1].decode() for row in table_info]
+
+
+def _newest(files):
+ return max(files, key=lambda path: os.lstat(path).st_mtime, default=None)
+
+
+def _find_files(root, filename, logger):
+ # if there are multiple browser profiles, take the most recently used one
+ i = 0
+ if(True):
+ for curr_root, _, files in os.walk(root):
+ for file in files:
+ i += 1
+ if file == filename:
+ yield os.path.join(curr_root, file)
+
+
+def _merge_cookie_jars(jars):
+ output_jar = YoutubeDLCookieJar()
+ for jar in jars:
+ for cookie in jar:
+ output_jar.set_cookie(cookie)
+ if jar.filename is not None:
+ output_jar.filename = jar.filename
+ return output_jar
+
+
+def _is_path(value):
+ return any(sep in value for sep in (os.path.sep, os.path.altsep) if sep)
+
+
+def _parse_browser_specification(browser_name, profile=None, keyring=None, container=None):
+ if browser_name not in SUPPORTED_BROWSERS:
+ raise ValueError(f'unsupported browser: "{browser_name}"')
+ if keyring not in (None, *SUPPORTED_KEYRINGS):
+ raise ValueError(f'unsupported keyring: "{keyring}"')
+ if profile is not None and _is_path(expand_path(profile)):
+ profile = expand_path(profile)
+ return browser_name, profile, keyring, container
+
+
+class LenientSimpleCookie(http.cookies.SimpleCookie):
+ """More lenient version of http.cookies.SimpleCookie"""
+ # From https://github.com/python/cpython/blob/v3.10.7/Lib/http/cookies.py
+ # We use Morsel's legal key chars to avoid errors on setting values
+ _LEGAL_KEY_CHARS = r'\w\d' + re.escape('!#$%&\'*+-.:^_`|~')
+ _LEGAL_VALUE_CHARS = _LEGAL_KEY_CHARS + re.escape('(),/<=>?@[]{}')
+
+ _RESERVED = {
+ 'expires',
+ 'path',
+ 'comment',
+ 'domain',
+ 'max-age',
+ 'secure',
+ 'httponly',
+ 'version',
+ 'samesite',
+ }
+
+ _FLAGS = {'secure', 'httponly'}
+
+ # Added 'bad' group to catch the remaining value
+ _COOKIE_PATTERN = re.compile(r'''
+ \s* # Optional whitespace at start of cookie
+ (?P<key> # Start of group 'key'
+ [''' + _LEGAL_KEY_CHARS + r''']+?# Any word of at least one letter
+ ) # End of group 'key'
+ ( # Optional group: there may not be a value.
+ \s*=\s* # Equal Sign
+ ( # Start of potential value
+ (?P<val> # Start of group 'val'
+ "(?:[^\\"]|\\.)*" # Any doublequoted string
+ | # or
+ \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr
+ | # or
+ [''' + _LEGAL_VALUE_CHARS + r''']* # Any word or empty string
+ ) # End of group 'val'
+ | # or
+ (?P<bad>(?:\\;|[^;])*?) # 'bad' group fallback for invalid values
+ ) # End of potential value
+ )? # End of optional value group
+ \s* # Any number of spaces.
+ (\s+|;|$) # Ending either at space, semicolon, or EOS.
+ ''', re.ASCII | re.VERBOSE)
+
+ def load(self, data):
+ # Workaround for https://github.com/yt-dlp/yt-dlp/issues/4776
+ if not isinstance(data, str):
+ return super().load(data)
+
+ morsel = None
+ for match in self._COOKIE_PATTERN.finditer(data):
+ if match.group('bad'):
+ morsel = None
+ continue
+
+ key, value = match.group('key', 'val')
+
+ is_attribute = False
+ if key.startswith('$'):
+ key = key[1:]
+ is_attribute = True
+
+ lower_key = key.lower()
+ if lower_key in self._RESERVED:
+ if morsel is None:
+ continue
+
+ if value is None:
+ if lower_key not in self._FLAGS:
+ morsel = None
+ continue
+ value = True
+ else:
+ value, _ = self.value_decode(value)
+
+ morsel[key] = value
+
+ elif is_attribute:
+ morsel = None
+
+ elif value is not None:
+ morsel = self.get(key, http.cookies.Morsel())
+ real_value, coded_value = self.value_decode(value)
+ morsel.set(key, real_value, coded_value)
+ self[key] = morsel
+
+ else:
+ morsel = None
+
+
+class YoutubeDLCookieJar(http.cookiejar.MozillaCookieJar):
+ """
+ See [1] for cookie file format.
+
+ 1. https://curl.haxx.se/docs/http-cookies.html
+ """
+ _HTTPONLY_PREFIX = '#HttpOnly_'
+ _ENTRY_LEN = 7
+ _HEADER = '''# Netscape HTTP Cookie File
+# This file is generated by yt-dlp. Do not edit.
+
+'''
+ _CookieFileEntry = collections.namedtuple(
+ 'CookieFileEntry',
+ ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
+
+ def __init__(self, filename=None, *args, **kwargs):
+ super().__init__(None, *args, **kwargs)
+ if is_path_like(filename):
+ filename = os.fspath(filename)
+ self.filename = filename
+
+ @staticmethod
+ def _true_or_false(cndn):
+ return 'TRUE' if cndn else 'FALSE'
+
+ @contextlib.contextmanager
+ def open(self, file, *, write=False):
+ if is_path_like(file):
+ with open(file, 'w' if write else 'r', encoding='utf-8') as f:
+ yield f
+ else:
+ if write:
+ file.truncate(0)
+ yield file
+
+ def _really_save(self, f, ignore_discard, ignore_expires):
+ now = time.time()
+ for cookie in self:
+ if ((not ignore_discard and cookie.discard)
+ or (not ignore_expires and cookie.is_expired(now))):
+ continue
+ name, value = cookie.name, cookie.value
+ if value is None:
+ # cookies.txt regards 'Set-Cookie: foo' as a cookie
+ # with no name, whereas http.cookiejar regards it as a
+ # cookie with no value.
+ name, value = '', name
+ f.write('{}\n'.format('\t'.join((
+ cookie.domain,
+ self._true_or_false(cookie.domain.startswith('.')),
+ cookie.path,
+ self._true_or_false(cookie.secure),
+ str_or_none(cookie.expires, default=''),
+ name, value,
+ ))))
+
+ def save(self, filename=None, ignore_discard=True, ignore_expires=True):
+ """
+ Save cookies to a file.
+ Code is taken from CPython 3.6
+ https://github.com/python/cpython/blob/8d999cbf4adea053be6dbb612b9844635c4dfb8e/Lib/http/cookiejar.py#L2091-L2117 """
+
+ if filename is None:
+ if self.filename is not None:
+ filename = self.filename
+ else:
+ raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
+
+ # Store session cookies with `expires` set to 0 instead of an empty string
+ for cookie in self:
+ if cookie.expires is None:
+ cookie.expires = 0
+
+ with self.open(filename, write=True) as f:
+ f.write(self._HEADER)
+ self._really_save(f, ignore_discard, ignore_expires)
+
+ def load(self, filename=None, ignore_discard=True, ignore_expires=True):
+ """Load cookies from a file."""
+ if filename is None:
+ if self.filename is not None:
+ filename = self.filename
+ else:
+ raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
+
+ def prepare_line(line):
+ if line.startswith(self._HTTPONLY_PREFIX):
+ line = line[len(self._HTTPONLY_PREFIX):]
+ # comments and empty lines are fine
+ if line.startswith('#') or not line.strip():
+ return line
+ cookie_list = line.split('\t')
+ if len(cookie_list) != self._ENTRY_LEN:
+ raise http.cookiejar.LoadError(f'invalid length {len(cookie_list)}')
+ cookie = self._CookieFileEntry(*cookie_list)
+ if cookie.expires_at and not cookie.expires_at.isdigit():
+ raise http.cookiejar.LoadError(f'invalid expires at {cookie.expires_at}')
+ return line
+
+ cf = io.StringIO()
+ with self.open(filename) as f:
+ for line in f:
+ try:
+ cf.write(prepare_line(line))
+ except http.cookiejar.LoadError as e:
+ if f'{line.strip()} '[0] in '[{"':
+ raise http.cookiejar.LoadError(
+ 'Cookies file must be Netscape formatted, not JSON. See '
+ 'https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp')
+ write_string(f'WARNING: skipping cookie file entry due to {e}: {line!r}\n')
+ continue
+ cf.seek(0)
+ self._really_load(cf, filename, ignore_discard, ignore_expires)
+ # Session cookies are denoted by either `expires` field set to
+ # an empty string or 0. MozillaCookieJar only recognizes the former
+ # (see [1]). So we need force the latter to be recognized as session
+ # cookies on our own.
+ # Session cookies may be important for cookies-based authentication,
+ # e.g. usually, when user does not check 'Remember me' check box while
+ # logging in on a site, some important cookies are stored as session
+ # cookies so that not recognizing them will result in failed login.
+ # 1. https://bugs.python.org/issue17164
+ for cookie in self:
+ # Treat `expires=0` cookies as session cookies
+ if cookie.expires == 0:
+ cookie.expires = None
+ cookie.discard = True
+
+ def get_cookie_header(self, url):
+ """Generate a Cookie HTTP header for a given url"""
+ cookie_req = urllib.request.Request(url)
+ self.add_cookie_header(cookie_req)
+ return cookie_req.get_header('Cookie')
+
+ def get_cookies_for_url(self, url):
+ """Generate a list of Cookie objects for a given url"""
+ # Policy `_now` attribute must be set before calling `_cookies_for_request`
+ # Ref: https://github.com/python/cpython/blob/3.7/Lib/http/cookiejar.py#L1360
+ self._policy._now = self._now = int(time.time())
+ return self._cookies_for_request(urllib.request.Request(url))
+
+ def clear(self, *args, **kwargs):
+ with contextlib.suppress(KeyError):
+ return super().clear(*args, **kwargs)
+
+validbrowsers=['brave', 'chrome', 'chromium', 'edge', 'firefox', 'opera', 'safari', 'vivaldi', 'whale']
diff --git a/dank.png b/dank.png
new file mode 100644
index 0000000..0b80468
Binary files /dev/null and b/dank.png differ
diff --git a/frozen.png b/frozen.png
new file mode 100644
index 0000000..b901909
Binary files /dev/null and b/frozen.png differ
diff --git a/gtk.py b/gtk.py
new file mode 100755
index 0000000..0e1ab45
--- /dev/null
+++ b/gtk.py
@@ -0,0 +1,447 @@
+#!/usr/bin/env python3
+# wlchat, a chat client for WhiteLeaf's fork of MemeLabs.
+# Copyright (C) 2022-2025 Alicia <...>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import gi
+gi.require_version('Gtk', '3.0')
+from gi.repository import Gtk
+from gi.repository import Gdk
+from gi.repository import GdkPixbuf
+from gi.repository import GLib
+from gi.repository import Gio
+import json
+import wlchat
+import base64
+import time
+
+def gprint_(c, text, tag=None):
+ i=c['chat'].get_end_iter()
+ if(tag):
+ c['chat'].insert_with_tags_by_name(i, text, (tag))
+ else:
+ c['chat'].insert(i, text)
+ adj=c['scroll'].get_vadjustment()
+ if(adj.get_value()+adj.get_page_size()+50>=adj.get_upper()):
+ GLib.idle_add(scrollchat, 0, 0, c)
+ lines=c['chat'].get_line_count()
+ if(lines>2048): # Limit scrollback. TODO: Make 2048 lines configurable
+ start=c['chat'].get_start_iter()
+ end=c['chat'].get_iter_at_line(lines-2048)
+ c['chat'].delete(start, end)
+
+def gprint(c, text, tag=None):
+ GLib.idle_add(lambda:gprint_(c, text, tag))
+
+def insertimg(c, imgfile, tooltip):
+ img=Gtk.Image.new_from_file(imgfile)
+ img.set_tooltip_text(tooltip)
+ anchor=c['chat'].create_child_anchor(c['chat'].get_end_iter())
+ c['chattext'].add_child_at_anchor(img, anchor)
+ img.show()
+ c['emotefreeze'].append([anchor, img]) # Add to the queue to be frozen when scrolled out of view. TODO: Make this optional
+
+def insertpronoun(c, pronoun):
+ pronoun=wlchat.pronouns[int(pronoun)].split('/')
+ tag=pronoun[0]+pronoun[1] # Tag for pronoun color
+ pronoun=pronoun[0][0]+'/'+pronoun[1][0]
+ gprint(c, ' '+pronoun, tag)
+
+def msg(c, chan, nick, data):
+ if(data['data'].startswith('/me ')): # According to cripton86 webclient doesn't do greentext for /me
+ gprint(c, '\n* ')
+ gprint(c, data['nick'], 'name')
+ if(data.get('pronouns') and int(data['pronouns'])>0 and int(data['pronouns'])<len(wlchat.pronouns)): insertpronoun(c, data['pronouns'])
+ data['data']=data['data'][3:]
+ wlchat.findemotes(data, c['emotes']) # Do it here so we get the right positions
+ else:
+ wlchat.findemotes(data, c['emotes'])
+ gprint(c, '\n'+data['nick'], 'name')
+ if(data.get('pronouns') and int(data['pronouns'])>0 and int(data['pronouns'])<len(wlchat.pronouns)): insertpronoun(c, data['pronouns'])
+ gprint(c, ': ')
+ if(data.get('nodes') and data['nodes'].get('emotes')):
+ last=0
+ green=None
+ for emote in data['nodes']['emotes']:
+ start=emote['bounds'][0]
+ end=emote['bounds'][1]
+ if(not green and data['data'][last:start].count('>')>0):
+ green='greentext'
+ gt=data['data'][last:start].index('>')
+ gprint(c, data['data'][last:last+gt])
+ gprint(c, data['data'][last+gt:start], green)
+ else:
+ gprint(c, data['data'][last:start], green)
+ imgfile=wlchat.get_emote_img(emote, c['emotes'], chan)
+ tooltip=emote['name']
+ if(emote.get('modifiers')):
+ tooltip+=':'+(':'.join(emote['modifiers']))
+ GLib.idle_add(insertimg, c, imgfile, tooltip)
+ last=end
+ data['data']=data['data'][last:]
+ if(data['data'].count('>')>0): # Greentext
+ gt=data['data'].index('>')
+ gprint(c, data['data'][:gt])
+ gprint(c, data['data'][gt:], 'greentext')
+ else:
+ gprint(c, data['data'])
+
+def privmsg(c, chan, nick, data):
+ gprint(c, '\nPrivate message from '+data['nick']+': '+data['data'])
+
+def broadcast(c, chan, nick, data):
+ gprint(c, '\nBroadcast: '+data['data'])
+ if(data.get('data')=='emoteupdate'): # Try to update emotes without a restart
+ c['emotes']=wlchat.fetch_emotes(c['site'])
+
+def namelist_del(nl, user):
+ i=0
+ x=nl.get_row_at_index(i)
+ while(x):
+ txt=x.get_child()
+ if(txt.get_text()==user['nick']):
+ txt.destroy()
+ nl.remove(x)
+ x.destroy()
+ else:
+ i+=1
+ x=nl.get_row_at_index(i)
+
+def namelist_add(nl, user):
+ namelist_del(nl, user) # Prevent duplicates
+ label=Gtk.Label.new(user['nick'])
+ label.set_halign(Gtk.Align.START)
+ nl.add(label)
+ label.show()
+
+def namelist(c, chan, nick, data):
+ for user in data:
+ GLib.idle_add(namelist_add, c['users'], user)
+
+def join(c, chan, nick, data):
+ gprint(c, '\nJoin: '+data['nick'], 'join')
+ if(data.get('pronouns') and int(data['pronouns'])>0 and int(data['pronouns'])<len(wlchat.pronouns)): insertpronoun(c, data['pronouns'])
+ GLib.idle_add(namelist_add, c['users'], data)
+
+def quitmsg(c, chan, nick, data):
+ gprint(c, '\nQuit: '+data['nick'], 'quit')
+ GLib.idle_add(namelist_del, c['users'], data)
+
+def notice(c, chan, nick, data):
+ gprint(c, '\nNotice: '+data)
+
+def register(c, chan, formdata, captcha):
+ window=Gtk.ApplicationWindow(application=app)
+ window.set_title('WLChat Register ('+chan+')')
+ grid=Gtk.Grid()
+ # Username
+ grid.attach(Gtk.Label.new('Username:'), 0,0,1,1)
+ username=Gtk.Entry.new()
+ grid.attach(username, 1,0,1,1)
+ # Agreement
+ agreement=Gtk.CheckButton.new_with_label('Accept agreement')
+ grid.attach(agreement, 0,1,1,1)
+ link=Gtk.Label.new()
+ link.set_markup('<a href="https://'+chan+'/agreement">Agreement</a>')
+ grid.attach(link, 1,1,2,1)
+ # Captcha
+ captchabin=base64.decodebytes(bytes(captcha.split(',')[1], 'utf8'))
+ loader=GdkPixbuf.PixbufLoader.new()
+ loader.write(captchabin)
+ loader.close()
+ img=loader.get_pixbuf()
+ img=Gtk.Image.new_from_pixbuf(img)
+ grid.attach(img, 0,2,1,1)
+ captcha=Gtk.Entry.new()
+ grid.attach(captcha, 1,2,1,1)
+ # Button
+ btn=Gtk.Button.new_with_label('Register')
+ def doregister(x,w, username, captcha, agreement, formdata):
+ formdata['username']=username.get_text()
+ formdata['catch']=captcha.get_text()
+ if(agreement.get_active()):
+ formdata['agreement']='on'
+ w.destroy()
+ btn.connect('clicked', doregister, window, username, captcha, agreement, formdata)
+ grid.attach(btn, 0,3,2,1)
+ window.add(grid)
+ window.show_all()
+ while(window.get_visible()):
+ time.sleep(0.1)
+ while(Gtk.events_pending()): Gtk.main_iteration()
+
+interface={
+ 'msg': msg,
+ 'privmsg': privmsg,
+ 'broadcast': broadcast,
+ 'namelist': namelist,
+ 'join': join,
+ 'quit': quitmsg,
+ 'notice': notice,
+ 'register': register,
+}
+
+def scrollchat(x, y, c):
+ adj=c['scroll'].get_vadjustment()
+ adj.set_value(adj.get_upper()+1000)
+ while(len(c['emotefreeze'])>0): # Freeze emotes scrolled out of view
+ if(not c['emotefreeze'][0][0].get_deleted()):
+ itr=c['chat'].get_iter_at_child_anchor(c['emotefreeze'][0][0])
+ rect=c['chattext'].get_iter_location(itr)
+ x,y=c['chattext'].buffer_to_window_coords(Gtk.TextWindowType.TEXT, rect.x, rect.y)
+ if(y>-200): break # Not far enough out of view
+ pb=c['emotefreeze'][0][1].get_animation()
+ if(pb):
+ pb=pb.get_static_image()
+ c['emotefreeze'][0][1].set_from_pixbuf(pb)
+ c['emotefreeze'].remove(c['emotefreeze'][0])
+
+def sortnames(row1, row2):
+ a=row1.get_child().get_text()
+ b=row2.get_child().get_text()
+ if(a<b): return -1
+ if(a>b): return 1
+ return 0
+
+def sendmsg(entry, c):
+ txt=entry.get_text()
+ if(txt=='/emoteupdate'):
+ c['emotes']=wlchat.fetch_emotes(c['site'])
+ else:
+ c['conn'][0].send('MSG '+json.dumps({'data':txt}))
+ entry.set_text('')
+
+def searchemote(entry, emotes):
+ q=entry.get_text().lower()
+ for e in emotes:
+ if(emotes[e].get('prefix')):
+ if(emotes[e]['prefix'].lower().count(q)>0):
+ emotes[e]['widget'].show()
+ else:
+ emotes[e]['widget'].hide()
+
+def insertemote(x, name, inputfield, search):
+ search.set_text('')
+ inputfield.set_text(inputfield.get_text()+name)
+ inputfield.set_position(len(inputfield.get_text()))
+
+def inputkeyevent(field, event, c):
+ if(event.keyval==Gdk.KEY_Tab or event.keyval==Gdk.KEY_KP_Tab):
+ pos=field.get_position()
+ text=field.get_text()
+ start=pos
+ while(start>0 and text[start-1:start]!=' '):
+ start-=1
+ query=text[start:pos]
+ casesensitive=(query!=query.lower())
+ match=False
+ fullmatch=False
+ # Look for matching users
+ i=0
+ x=c['users'].get_row_at_index(i)
+ while(x):
+ txt=x.get_child()
+ txt=txt.get_text()
+ txtorig=txt
+ if(not casesensitive): txt=txt.lower()
+ if(txt.startswith(query)):
+ if(match==False):
+ match=txt
+ else:
+ j=1
+ while(j<len(match)):
+ if(txt[:j]!=match[:j]):
+ match=match[:j-1]
+ j+=1
+ if(match==txt): fullmatch=txtorig
+ i+=1
+ x=c['users'].get_row_at_index(i)
+ # Look for matching emotes
+ for txt in c['emotes']:
+ txtorig=txt
+ if(not casesensitive): txt=txt.lower()
+ if(txt.startswith(query)):
+ if(match==False):
+ match=txt
+ else:
+ j=1
+ while(j<len(match)):
+ if(txt[:j]!=match[:j]):
+ match=match[:j-1]
+ j+=1
+ if(match==txt): fullmatch=txtorig
+ if(not match): return True
+ if(fullmatch and not casesensitive and fullmatch.lower()==match.lower()): match=fullmatch+' '
+ elif(fullmatch and casesensitive and fullmatch==match): match=fullmatch+' '
+ # Insert completion
+ text=text[:start]+match+text[pos:]
+ field.set_text(text)
+ field.set_position(start+len(match))
+ return True
+ return False
+
+def app_join(button, siteentry, browser, browserprofile, authmethod):
+ site=siteentry.get_text()
+ siteentry.set_text('')
+ browser=browser.get_active_text()
+ browserprofile=browserprofile.get_filename()
+ authmethod=authmethod.get_active_text().lower()
+ textview=Gtk.TextView()
+ textview.set_editable(False)
+ textview.set_wrap_mode(Gtk.WrapMode.WORD_CHAR)
+ textview.set_can_focus(False)
+ textstyle=textview.get_style_context()
+ css=Gtk.CssProvider()
+ css.load_from_data('* {background-color:#202020;color:#ffffff;}');
+ textstyle.add_provider(css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
+ chatscroll=Gtk.ScrolledWindow.new(None, None)
+ chatscroll.add(textview)
+ chatscroll.set_hexpand(True)
+ chatscroll.set_vexpand(True)
+ userlist=Gtk.ListBox()
+ userlist.set_sort_func(sortnames)
+ userscroll=Gtk.ScrolledWindow.new(None, None)
+ userscroll.add(userlist)
+ inputfield=Gtk.Entry()
+ inputfield.add_events(Gdk.EventMask.KEY_PRESS_MASK)
+ emotebutton=Gtk.MenuButton.new()
+ emotebutton.add(Gtk.Label.new('Emotes'))
+ emotemenu=Gtk.Menu()
+ emotebutton.set_popup(emotemenu)
+ emotesearch=Gtk.Entry()
+ emotesearchitem=Gtk.MenuItem.new()
+ emotesearchitem.add(emotesearch)
+ emotemenu.attach(emotesearchitem, 0, 10, 0, 1)
+ emotebutton.connect('clicked', lambda x, search: search.grab_focus(), emotesearch)
+ grid=Gtk.Grid()
+ grid.attach(chatscroll, 0,0,1,1)
+ grid.attach(userscroll, 1,0,2,1)
+ grid.attach(inputfield, 0,1,2,1)
+ grid.attach(emotebutton, 2,1,1,1)
+ tab=Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 0)
+ tab.pack_start(Gtk.Label.new(site.replace('www.','')), False, False, 0)
+ # Add a close button
+ closebtn=Gtk.Button.new_from_icon_name('window-close', Gtk.IconSize.LARGE_TOOLBAR)
+ tab.pack_start(closebtn, False, False, 0)
+ tab.show_all()
+ pagenum=chatlist.append_page(grid, tab)
+ grid.show_all()
+ chatlist.set_current_page(pagenum)
+ conn=[None]
+ chatbuf=textview.get_buffer()
+ tags=chatbuf.get_tag_table()
+ tag=Gtk.TextTag.new('join')
+ tag.set_property('foreground', '#0080ff')
+ tags.add(tag)
+ tag=Gtk.TextTag.new('quit')
+ tag.set_property('foreground', '#000080')
+ tags.add(tag)
+ tag=Gtk.TextTag.new('greentext')
+ tag.set_property('foreground', '#00a000')
+ tags.add(tag)
+ tag=Gtk.TextTag.new('name')
+ tag.set_property('weight', 800)
+ tags.add(tag)
+ # Pronoun color tags, colors found from grep -o 'pronoun\.[a-z]*:after{content:"[a-zA-Z/]*";color:#[0-9a-f]*;background-color:#[0-9a-f]*}' /tmp/chat.e7d595.css | sed -e 's/.*content:"//; s/".*background-color:/ = /; s/}//'
+ for pn in [('Any/All','#ff8686'),('She/Her','#f286ff'),('He/Him','#86b6ff'),('They/Them','#86ff8f'),('It/Its','#fffb86'),('He/They','#86fff9'),('She/They','#ca78ff'),('Ask/Me','#bcbcbc'),('Name/They','#d8ffa5')]:
+ tag=Gtk.TextTag.new(pn[0].replace('/','').lower())
+ tag.set_property('foreground', pn[1])
+ tags.add(tag)
+ # Chat-specific context
+ c={'chat':chatbuf,'chattext':textview,'users':userlist,'scroll':chatscroll,'emotes':wlchat.fetch_emotes(site),'site':site,'conn':conn,'emotefreeze':[]}
+ emotesearch.connect('changed', searchemote, c['emotes'])
+ i=0
+ for e in c['emotes']:
+ emote=Gtk.MenuItem.new()
+ img=wlchat.get_emote_img({'name':c['emotes'][e]['prefix']}, c['emotes'], site)
+ # Sometimes int, sometimes string with additional junk, so we end up converting to string first
+ if(int(str(c['emotes'][e]['imageWidth']).strip('px'))>32):
+ try:
+ pb=GdkPixbuf.Pixbuf.new_from_file(img)
+ pb=GdkPixbuf.Pixbuf.new_subpixbuf(pb, (pb.get_width()-32)/2, 0, 32, 32)
+ img=Gtk.Image.new_from_pixbuf(pb)
+ except:
+ print('Fell back on fullsize for '+img+' ('+c['emotes'][e]['prefix']+')')
+ img=Gtk.Image.new_from_file(img)
+ else:
+ img=Gtk.Image.new_from_file(img)
+ img.set_tooltip_text(c['emotes'][e]['prefix'])
+ emote.add(img)
+ emote.connect('activate', insertemote, c['emotes'][e]['prefix'], inputfield, emotesearch)
+ c['emotes'][e]['widget']=emote # For search
+ emotemenu.attach(emote, i%10, (i%10)+1, int(i/10)+1, int(i/10)+2)
+ i+=1
+ emotemenu.show_all()
+ adj=chatscroll.get_vadjustment()
+ inputfield.connect('activate', sendmsg, c)
+ inputfield.connect('key-press-event', inputkeyevent, c)
+ def closetab(page,c):
+ chatlist.remove_page(page)
+ c['conn'][0].on_close=None
+ c['conn'][0].on_error=None
+ c['conn'][0].on_message=None
+ c['conn'][0].close()
+ closebtn.connect('clicked', lambda x,page,c: closetab(page,c), pagenum, c)
+ wlchat.joinchat(site, browser, browserprofile, '', conn, interface, c, authmethod)
+
+def app_jointab(app):
+ auth=Gtk.ComboBoxText()
+ for x in wlchat.authmethods:
+ auth.insert(-1, None, x[0].upper()+x[1:])
+ auth.set_active(0)
+ site=Gtk.Entry()
+ browser=Gtk.ComboBoxText()
+ for b in wlchat.cookies.validbrowsers:
+ browser.insert(-1, None, b)
+ browserprofile=Gtk.FileChooserButton(title='Select browser profile', action=Gtk.FileChooserAction.SELECT_FOLDER)
+ button=Gtk.Button.new_with_label('Join chat')
+ button.connect('clicked', app_join, site, browser, browserprofile, auth)
+ grid=Gtk.Grid()
+ label=Gtk.Label.new('Website: ')
+ label.set_halign(Gtk.Align.END)
+ grid.attach(label, 0,0,1,1)
+ grid.attach(site, 1,0,1,1)
+ label=Gtk.Label.new('Authentication method: ')
+ label.set_halign(Gtk.Align.END)
+ grid.attach(label, 0,1,1,1)
+ grid.attach(auth, 1,1,1,1)
+ label=Gtk.Label.new('Browser to grab login: ')
+ label.set_halign(Gtk.Align.END)
+ grid.attach(label, 0,2,1,1)
+ grid.attach(browser, 1,2,1,1)
+ label=Gtk.Label.new('Browser profile: ')
+ label.set_halign(Gtk.Align.END)
+ grid.attach(label, 0,3,1,1)
+ grid.attach(browserprofile, 1,3,1,1)
+ grid.attach(button, 0,4,2,1)
+ chatlist.append_page(grid, Gtk.Image.new_from_icon_name('list-add', Gtk.IconSize.LARGE_TOOLBAR))
+ grid.show_all()
+ site.grab_focus()
+
+def app_init(app):
+ global chatlist
+ global chatwindow
+ chatwindow=Gtk.ApplicationWindow(application=app)
+ chatwindow.set_title('WLChat')
+ chatlist=Gtk.Notebook()
+ chatwindow.add(chatlist)
+ chatwindow.connect('delete-event', lambda x, y: app.quit())
+ app_jointab(app)
+ chatwindow.show_all()
+
+app=Gtk.Application(application_id='org.ion.wlchat', flags=Gio.ApplicationFlags.NON_UNIQUE)
+app.connect('activate', app_init)
+
+app.run(None)
diff --git a/irc.py b/irc.py
new file mode 100755
index 0000000..b07dde4
--- /dev/null
+++ b/irc.py
@@ -0,0 +1,224 @@
+#!/usr/bin/env python3
+# wlchat, a chat client for WhiteLeaf's fork of MemeLabs.
+# Copyright (C) 2022-2025 Alicia <...>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import wlchat
+import socket
+import threading
+import sys
+import json
+port=3333
+pcolors=[ # Pronoun color associations
+ '00', # 1-indexed, so pad 0
+ '12',
+ '13',
+ '06',
+ '02',
+ '04',
+ '15',
+ '00',
+ '08',
+ '06'
+]
+
+def irc_msg(c, chan, nick, data):
+ if(data['nick']==nick): # IRC client prints our messages, don't re-send them
+ return
+ data['data']=data['data'].replace('\n', ' ')
+ # Process emotes
+ if(data.get('nodes') and data['nodes'].get('emotes')):
+ emoteoffset=0
+ for emote in data['nodes']['emotes']:
+ start=emote['bounds'][0]+emoteoffset
+ end=emote['bounds'][1]+emoteoffset
+ data['data']=data['data'][0:start]+'[\x02'+data['data'][start:end]+'\x02]'+data['data'][end:]
+ emoteoffset+=4
+ if(data.get("pronouns") and int(data['pronouns'])>0 and int(data['pronouns'])<len(wlchat.pronouns)):
+ pos=0
+ if(data['data'].startswith('/me ')):
+ pos+=4
+ # Instead of full pronouns, just add initials and color to the beginning of the message
+ pronoun=wlchat.pronouns[int(data['pronouns'])].split('/')
+ pronoun=pronoun[0][0]+'/'+pronoun[1][0]
+ data['data']=data['data'][0:pos]+'\x03'+pcolors[int(data['pronouns'])]+pronoun+'\x0f '+data['data'][pos:]
+ # Translate /me
+ if(data['data'].startswith('/me ')):
+ data['data']='\x01ACTION '+data['data'][4:]+'\x01'
+ # Send to IRC
+ c['irc'].send(bytes(':'+data['nick']+'!user@host PRIVMSG #'+chan+' :'+data['data']+'\n', 'utf-8'))
+
+def irc_privmsg(c, chan, nick, data):
+ c['irc'].send(bytes(':'+chan+'|'+data['nick']+'!user@host PRIVMSG '+nick+' :'+data['data']+'\n', 'utf-8'))
+
+def irc_broadcast(c, chan, nick, data):
+ c['irc'].send(bytes(':wlchat NOTICE #'+chan+' :Broadcast: '+data['data']+'\n', 'utf-8'))
+
+def irc_namelist(c, chan, nick, userlist):
+ ulist=''
+ for user in userlist:
+ if(ulist!=''):
+ ulist+=' '
+ if(user.get('features') and user['features'].count('moderator')>0):
+ ulist+='@'+user['nick']
+ else:
+ ulist+=user['nick']
+ c['irc'].send(bytes(':wlchat 353 '+nick+' = #'+chan+' :'+ulist+'\n', 'utf-8'))
+ c['irc'].send(bytes(':wlchat 366 '+nick+' #'+chan+' :End of /NAMES list.\n', 'utf-8'))
+
+def irc_join(c, chan, nick, data):
+ if(data['nick']==nick):
+ if(not c['firstjoin']): return
+ c['firstjoin']=False
+ c['irc'].send(bytes(':'+data['nick']+'!user@host JOIN #'+chan+'\n', 'utf-8'))
+ if(data.get('features') and data['features'].count('moderator')>0):
+ c['irc'].send(bytes(':wlchat MODE #'+chan+' +o '+data['nick']+'\n', 'utf-8'))
+
+def irc_quit(c, chan, nick, data):
+ if(data['nick']==nick): return
+ c['irc'].send(bytes(':'+data['nick']+'!user@host PART #'+chan+' :\n', 'utf-8'))
+
+def irc_notice(c, chan, nick, data):
+ c['irc'].send(bytes(':wlchat NOTICE #'+chan+' :'+data+'\n', 'utf-8'))
+
+def irc_register(c, chan, formdata, captcha):
+ c['irc'].send(bytes(':wlchat NOTICE #'+chan+' :Captcha: '+captcha+' (reply to answer, and implicitly agree to the user agreement at https://'+chan+'/agreement)\n', 'utf-8'))
+ while(True):
+ line=c['irc'].recv(1024)
+ if(line.startswith(b'PRIVMSG ')):
+ chanmsg=bytes.decode(line.split(b' ')[1])
+ if(chanmsg.startswith('#')):
+ chanmsg=chanmsg[1:]
+ if(chanmsg!=chan):
+ c['irc'].send(bytes(':wlchat NOTICE #'+chanmsg+' :Failed to send message. Awaiting captcha response for #'+chan+'\n', 'utf-8'))
+ else:
+ msg=bytes.decode(line[line.find(b' ', 8)+1:])
+ if(msg.startswith(':')):
+ msg=msg[1:]
+ formdata['catch']=msg.replace('\n','').replace('\r','')
+ formdata['agreement']='on'
+ break
+ elif(line.startswith(b'PING ')):
+ conn.send(b':wlchat PONG '+line[5:]+b'\n')
+
+def irc_topic(c, chan, nick, data):
+ c['irc'].send(bytes(':wlchat TOPIC #'+chan+' :'+data+'\n', 'utf-8'))
+
+def irc_mainloop(conn):
+# TODO: Also keep a timestamp of the latest ping received from wl (but local time, not ping's), reconnect if 30s old
+ browser=''
+ browserprofile=''
+ nick=''
+ ctx=None
+ while(True):
+ try:
+ line=conn.recv(1024)
+ except Exception: break
+ if(line==b''): # EOF
+ break
+ for line in line.split(b'\n'):
+ if(line.startswith(b'CAP ')):
+ conn.send(b'CAP * LS :\n')
+ elif(line.startswith(b'PRIVMSG ')):
+ chan=bytes.decode(line.split(b' ')[1])
+ if(ctx!=None):
+ msg=bytes.decode(line[line.find(b' ', 8)+1:]).strip('\r\n')
+ if(msg.startswith(':')):
+ msg=msg[1:]
+ # Translate /me
+ if(msg.startswith('\x01ACTION ')):
+ msg='/me '+msg[8:]
+ if(msg.endswith('\x01')):
+ msg=msg[0:-1]
+ # Send to wl
+ try:
+ if(chan.startswith('#')):
+ ctx['wl'][0].send('MSG '+json.dumps({'data':msg}))
+ else:
+ ctx['wl'][0].send('PRIVMSG '+json.dumps({'nick':chan,'data':msg}))
+ except Exception as e:
+ x=sys.exc_info()
+ conn.send(bytes(':wlchat NOTICE '+chan+' :Exception(2): "'+str(e)+'" Line '+str(x[2].tb_lineno)+'\n', 'utf-8'))
+ sys.stdout.flush()
+ elif(line.startswith(b'PING ')):
+ conn.send(b':wlchat PONG '+line[5:]+b'\n')
+ elif(line.startswith(b'USER ')):
+ browser=bytes.decode(line.split(b' ')[1])
+ elif(line.startswith(b'PASS ')):
+ browserprofile=bytes.decode(line[5:].strip())
+ if(browserprofile.startswith(':')):
+ browserprofile=browserprofile[1:]
+ elif(line.startswith(b'NICK ')):
+ newnick=line[5:].strip()
+ if(newnick.startswith(b':')):
+ newnick=newnick[1:]
+ if(nick==''):
+ conn.send(b':wlchat 001 '+newnick+b' :Welcome\n')
+ else:
+ conn.send(b':'+bytes(nick, 'utf-8')+b'!user@host NICK :'+newnick+b'\n')
+ nick=bytes.decode(newnick)
+ elif(line.startswith(b'JOIN ')):
+ chan=bytes.decode(line[5:].strip())
+ if(chan.startswith(':')):
+ chan=chan[1:]
+ if(chan.startswith('#')):
+ chan=chan[1:]
+ if(chan==''): # Ignore weird empty joins
+ continue
+ if(ctx!=None): # Send ERR_TOOMANYCHANNELS
+ conn.send(b':wlchat 405 #'+chan.encode('UTF-8')+b' :Can\'t join more than one site per connect if we want to keep track of DMs\n')
+ continue
+ ctx={'irc':conn, 'channel':chan, 'wl':[None], 'firstjoin':True}
+ wlchat.joinchat(chan, browser, browserprofile, nick, ctx['wl'], interface, ctx)
+ conn.send(b':'+nick.encode('UTF-8')+b'!user@host JOIN #'+chan.encode('UTF-8')+b'\n')
+ elif(line.startswith(b'PART ')):
+ chan=bytes.decode(line[5:].strip())
+ if(chan.startswith(':')):
+ chan=chan[1:]
+ if(chan.startswith('#')):
+ chan=chan[1:]
+ if(chan==''): # Ignore weird empty parts (inherited from JOIN, not sure empty parts happen)
+ continue
+ ctx[0].close()
+ ctx[0]=None
+ print('Disconnected from IRC. Closing wl connections...')
+ ctx['wl'][0].on_close=None
+ ctx['wl'][0].on_error=None
+ ctx['wl'][0].on_message=None
+ ctx['wl'][0].close()
+
+interface={
+ 'msg': irc_msg,
+ 'privmsg': irc_privmsg,
+ 'broadcast': irc_broadcast,
+ 'namelist': irc_namelist,
+ 'join': irc_join,
+ 'quit': irc_quit,
+ 'notice': irc_notice,
+ 'register': irc_register,
+ 'topic': irc_topic,
+}
+
+# Set up server-based interface
+s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+s.bind(('127.0.0.1', port))
+s.listen()
+print('Listening to localhost:'+str(port))
+while(True):
+ conn, addr=s.accept()
+ print('Got connection')
+ thread=threading.Thread(target=irc_mainloop, args=[conn])
+ thread.daemon=True
+ thread.start()
diff --git a/snow.png b/snow.png
new file mode 100644
index 0000000..e4da4c1
Binary files /dev/null and b/snow.png differ
diff --git a/terminal.py b/terminal.py
new file mode 100755
index 0000000..5b0857b
--- /dev/null
+++ b/terminal.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+# wlchat, a chat client for WhiteLeaf's fork of MemeLabs.
+# Copyright (C) 2022-2025 Alicia <...>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import wlchat
+import sys
+import os
+import requests
+import json
+import signal
+if(os.environ.get('TERMINOLOGY')):
+ import PIL.ImageFile
+
+def terminal_print(txt):
+ lines=os.get_terminal_size().lines
+ sys.stdout.write('\x1b[s')
+ sys.stdout.write('\x1b[0;'+str(lines-2)+'r')
+ sys.stdout.write('\x1b['+str(lines-2)+';0H')
+ sys.stdout.write('\n'+txt)
+ sys.stdout.write('\x1b['+str(lines)+';'+str(lines)+'r')
+ sys.stdout.write('\x1b['+str(lines)+';0H> ')
+ sys.stdout.write('\x1b[u')
+ sys.stdout.flush()
+
+def terminal_msg(emotes, chan, nick, data):
+ wlchat.findemotes(data, emotes)
+ # Download and cache emotes
+ if(data.get('nodes') and data['nodes'].get('emotes')):
+ emoteoffset=0
+ for emote in data['nodes']['emotes']:
+ start=emote['bounds'][0]+emoteoffset
+ end=emote['bounds'][1]+emoteoffset
+ if(os.environ.get('TERMINOLOGY')):
+ path=wlchat.get_emote_img(emote, emotes, chan)
+ img=PIL.Image.open(path)
+ width=round(img.size[0]/16)
+ emoteimg='\x1b}is#'+str(width)+';1;'+path+'\x00\x1b}ib\x00'+('#'*width)+'\x1b}ie\x00'
+ else:
+ emoteimg='[\x1b[1m'+emote['name']+'\x1b[0m]'
+ data['data']=data['data'][0:start]+emoteimg+data['data'][end:]
+ emoteoffset+=len(emoteimg)-(end-start)
+ pronoun=''
+ if(data.get("pronouns") and int(data['pronouns'])>0 and int(data['pronouns'])<len(wlchat.pronouns)):
+ pronoun=wlchat.pronouns[int(data['pronouns'])]
+ if(data['data'].startswith('/me ')):
+ data['data']=data['data'][4:]
+ if(pronoun!=''): pronoun=' ('+pronoun+')'
+ terminal_print(' \x1b[1m'+data['nick']+'\x1b[0m'+pronoun+' '+data['data'])
+ else:
+ if(pronoun!=''): pronoun=' '+pronoun
+ terminal_print('<\x1b[1m'+data['nick']+'\x1b[0m'+pronoun+'> '+data['data'])
+
+def terminal_privmsg(c, chan, nick, data):
+ True
+
+def terminal_broadcast(c, chan, nick, data):
+ True
+
+def terminal_namelist(c, chan, nick, userlist):
+ ulist=''
+ for user in userlist:
+ if(ulist!=''):
+ ulist+=', '
+ ulist+=user['nick']
+ terminal_print('Users online:')
+ terminal_print(ulist)
+
+def terminal_join(c, chan, nick, data):
+ terminal_print('Join: '+data['nick'])
+
+def terminal_quit(c, chan, nick, data):
+ terminal_print('Quit: '+data['nick'])
+
+def terminal_notice(c, chan, nick, data):
+ terminal_print('Notice: '+data)
+
+def terminal_register(c, chan, formdata, captcha):
+ print('New account')
+ print('Site username:')
+ formdata['username']=sys.stdin.readline().replace('\n', '')
+ print(captcha)
+ print('Captcha:')
+ formdata['catch']=sys.stdin.readline().replace('\n', '')
+ print('Accept user agreement? (https://'+chan+'/agreement)')
+ if(sys.stdin.readline()[0].lower()=='y'):
+ formdata['agreement']='on'
+
+def terminal_mainloop():
+ print('Chat to join: (full domain)')
+ domain=sys.stdin.readline().replace('\n', '')
+ browser='_'
+ browserprofile=''
+ while(browser!='' and wlchat.cookies.validbrowsers.count(browser)==0):
+ print('Browser (one of '+(', '.join(wlchat.cookies.validbrowsers))+', or empty for no login):')
+ browser=sys.stdin.readline().replace('\n', '')
+ if(browser!=''):
+ print('Browser profile (or empty for default):')
+ browserprofile=sys.stdin.readline().replace('\n', '')
+ nick=''
+ conn=[None]
+ # Gather emote data
+ emotelist=wlchat.fetch_emotes(domain)
+ lines=os.get_terminal_size().lines
+ wlchat.joinchat(domain, browser, browserprofile, nick, conn, interface, emotelist)
+ sys.stdout.write('\x1b[2J\x1b['+str(lines)+';3H') # Clear screen
+ sys.stdout.write('\x1b['+str(lines)+';0H> ') # Input prompt
+ msg=sys.stdin.readline()
+ while(msg!=''):
+ sys.stdout.write('\n> ')
+ sys.stdout.flush()
+ msg=msg.replace('\n','')
+ if(msg!=''):
+ # Send to wl
+ conn[0].send('MSG '+json.dumps({'data':msg}))
+ msg=sys.stdin.readline()
+ print('\x1b[r\n')
+
+interface={
+ 'msg': terminal_msg,
+ 'privmsg': terminal_privmsg,
+ 'broadcast': terminal_broadcast,
+ 'namelist': terminal_namelist,
+ 'join': terminal_join,
+ 'quit': terminal_quit,
+ 'notice': terminal_notice,
+ 'register': terminal_register,
+}
+
+def handle_sigint(a,b):
+ sys.stdout.write('\n\n> ')
+
+signal.signal(signal.SIGINT, handle_sigint)
+terminal_mainloop()
diff --git a/wlchat.py b/wlchat.py
new file mode 100644
index 0000000..a9a2b02
--- /dev/null
+++ b/wlchat.py
@@ -0,0 +1,473 @@
+# wlchat, a chat client for WhiteLeaf's fork of MemeLabs.
+# Copyright (C) 2022-2025 Alicia <...>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import requests
+import json
+import re
+import threading
+import websocket
+import socket
+import sys
+import os
+import time
+import math
+import cookies
+
+useragent='wlchat 0.1'
+pronouns=[ # Pronoun list
+ '0', # 1-indexed, so pad 0
+ 'he/him',
+ 'she/her',
+ 'they/them',
+ 'he/they',
+ 'she/they',
+ 'it/its',
+ 'any/all',
+ 'ask/me',
+ 'name/they'
+]
+
+authmethods=[ # Supported authentication methods
+ 'reddit',
+# Experimental, probably broken:
+ 'google',
+ 'twitter',
+ 'twitch',
+]
+
+def readform(page, formstr):
+ form=re.split(formstr, page)
+ if(len(form)<=1): return False
+ form=re.split('</form', form[1])[0]
+ formdata={}
+ for field in re.findall('name="[^"]*" value="[^"]*"', form):
+ field=re.split('"', field)
+ formdata[field[1]]=field[3]
+ return formdata
+
+# The websocket is returned in conn[0]
+def joinchat(domain, browser, browserprofile, nick, conn, ui, uictx, authmethod='reddit', localctx={}):
+ session=requests.Session()
+ # Get whiteleaf config
+ try:
+ chatinfo=session.get('https://'+domain+'/api/chat/getinfo', headers={'User-agent': useragent})
+ if(chatinfo.content.decode()[0]=='{'):
+ chatinfo=json.loads(chatinfo.content)
+ wsurl='wss://'+chatinfo['chatURL']+'/'+chatinfo['chatKey']
+ else:
+ chatinfo=session.get('https://'+domain+'/embed/chat', headers={'User-agent': useragent})
+ wsurl=chatinfo.content.decode()
+ wsurl=wsurl[wsurl.find('data-ws-url="'):]
+ wsurl=wsurl.split('"')[1]
+ except: # Wait 1s and retry
+ time.sleep(1)
+ return joinchat(domain, browser, browserprofile, nick, conn, ui, uictx, authmethod)
+
+ headers={}
+ if(browser!='' and browser!=None and cookies.validbrowsers.count(browser)>0):
+ if(authmethod=='reddit'):
+ # Reddit seems to have added a captcha for logins now? So we have to resort to extracting cookies (borrowed that code from yt-dlp)
+ cookiesobj=cookies.load_cookies(None, (browser,browserprofile), None)
+ cookieslist=cookiesobj.get_cookies_for_url('https://reddit.com')
+ for c in cookieslist:
+ if(c.name=='reddit_session'):
+ session.cookies.set(c.name, c.value, domain='reddit.com')
+ elif(authmethod=='google'):
+ cookiesobj=cookies.load_cookies(None, (browser,browserprofile), None)
+ cookieslist=cookiesobj.get_cookies_for_url('https://www.youtube.com')
+ for c in cookieslist:
+ if(c.name=='SAPISID' or c.name=='__Secure-3PAPISID' or c.name=='__Secure-1PAPISID'):
+ session.cookies.set(c.name, c.value, domain='www.youtube.com')
+ elif(authmethod=='twitter'):
+ cookiesobj=cookies.load_cookies(None, (browser,browserprofile), None)
+ cookieslist=cookiesobj.get_cookies_for_url('https://api.x.com/1.1/')
+ for c in cookieslist:
+ if(c.name=='auth_token'):
+ session.cookies.set(c.name, c.value, domain='x.com')
+ elif(authmethod=='twitch'):
+ cookiesobj=cookies.load_cookies(None, (browser,browserprofile), None)
+ cookieslist=cookiesobj.get_cookies_for_url('https://gql.twitch.tv')
+ for c in cookieslist:
+ if(c.name=='auth_token'):
+ session.cookies.set(c.name, c.value, domain='gql.twitch.tv')
+# TODO: Do the same for discord
+ # Request whiteleaf auth
+ x=session.post('https://'+domain+'/login', headers={'User-agent': useragent}, params={'authProvider': authmethod})
+ # Find the form, or fall back on read-only chat
+ auth=False
+ if(authmethod=='reddit'):
+ formdata=readform(x.content.decode(), 'action="/api/v1/authorize"')
+ if(formdata):
+ x=session.post('https://ssl.reddit.com/api/v1/authorize', headers={'User-agent': useragent}, params=formdata)
+ auth=True
+ # TODO: Deal with equivalent forms on other platforms
+
+ if(auth):
+ # Check for new account form
+ formdata=readform(x.content.decode(), '<form action="/register"')
+ if(formdata and ui.get('register')):
+ page=x.content.decode().split('<div class=\'catchImage\'>')
+ captcha=re.findall('data:[^\'"]*', page[1])[0]
+ formdata['username']=nick
+ ui['register'](uictx, domain, formdata, captcha)
+ # 'register' needs to set 'username', 'catch' (the captcha answer), and 'agreement' (to 'on')
+ x=session.post('https://'+domain+'/register', headers={'User-agent': useragent}, params=formdata)
+ elif(x.content.decode().find('<div class="alert alert-danger')>=0):
+ err=x.content.decode()
+ start=err.find('<div class="alert alert-danger')
+ err=err[:err.find('</div>',start)]
+ err=err[err.rfind('>')+1:]
+ ui['notice'](uictx, domain, nick, 'Error: '+err)
+
+ cookieslist=session.cookies.get_dict()
+ headers['Cookie']=''
+ for c in cookieslist:
+ if(c.count('reddit')>0): continue # Skip auth source cookies
+ if(headers['Cookie']!=''): headers['Cookie']=headers['Cookie']+';'
+ headers['Cookie']=headers['Cookie']+c+'='+cookieslist[c]
+
+ localctx['namelist']=[] # To deal with bans and renames mostly
+ def readws(c, msg):
+ namelist=localctx['namelist']
+ chan=domain
+ if(msg.startswith('SMSG ')): # It's just a message, isn't it?
+ msg='MSG '+msg[5:]
+ if(msg.startswith('CMSG ')):
+ msg='MSG '+msg[5:]
+ if(msg.startswith('SMUTE ')): # Just mute, right?
+ msg='MUTE '+msg[6:]
+ if(msg.startswith('SBAN ')): # Just ban, right?
+ msg='BAN '+msg[5:]
+ if(msg.startswith('AWARE ')):
+ data=json.loads(msg[6:])
+ if(data['data']=='ping'):
+ c.send(msg.replace('ping','pong'))
+ else:
+ try: dd=json.loads(data['data'])
+ except Exception: dd=False
+ if(dd and dd.get('embedStatus') and dd.get('embedPlatform') and dd.get(dd['embedStatus'][0]+'Info')):
+ info=dd[dd['embedStatus'][0]+'Info']
+ value=info[dd['embedPlatform'][0]]
+ if(dd['embedPlatform'][0]=='twitchChannel'):
+ ui['notice'](uictx, chan, nick, dd['embedStatus'][0]+': https://twitch.tv/'+value)
+ elif(dd['embedPlatform'][0]=='youtubeChannel'):
+ ui['notice'](uictx, chan, nick, dd['embedStatus'][0]+': https://youtube.com/embed/live_stream?channel='+value)
+ elif(dd['embedPlatform'][0]=='youtubeVOD'):
+ ui['notice'](uictx, chan, nick, dd['embedStatus'][0]+': https://youtube.com/watch?v='+value)
+ else:
+ print('Unknown embedStatus: '+dd['embedStatus'][0]+', '+value)
+ else:
+ print('Unknown AWARE: '+msg)
+ elif(msg.startswith('MSG ')):
+ data=json.loads(msg[4:])
+ ui['msg'](uictx, chan, nick, data)
+ elif(msg.startswith('BROADCAST ')):
+ data=json.loads(msg[10:])
+ ui['broadcast'](uictx, chan, nick, data)
+ elif(msg.startswith('PRIVMSG ')):
+ data=json.loads(msg[8:])
+ ui['privmsg'](uictx, chan, nick, data)
+ elif(msg.startswith('NAMES ')):
+ data=json.loads(msg[6:])
+ ui['namelist'](uictx, chan, nick, data['users'])
+ namelist.clear()
+ for user in data['users']:
+ namelist.append(user['nick'])
+ elif(msg.startswith('JOIN ')):
+ data=json.loads(msg[5:])
+ ui['join'](uictx, chan, nick, data)
+ namelist.append(data['nick'])
+ elif(msg.startswith('QUIT ')):
+ data=json.loads(msg[5:])
+ ui['quit'](uictx, chan, nick, data)
+ if(namelist.count(data['nick'])):
+ namelist.remove(data['nick'])
+ elif(msg.startswith('ERR ')):
+ ui['notice'](uictx, chan, nick, msg)
+ elif(msg.startswith('RENAME ')):
+ data=json.loads(msg[7:])
+ newnamelist=[]
+ for user in data['users']:
+ if(namelist.count(user['nick'])==0):
+ namelist.append(user['nick'])
+ ui['join'](uictx, chan, nick, user)
+ newnamelist.append(user['nick'])
+ for user in namelist:
+ if(newnamelist.count(user)==0 and namelist.count(user)):
+ namelist.remove(user)
+ ui['quit'](uictx, chan, nick, {'nick':user})
+ elif(msg.startswith('BAN ')):
+ data=json.loads(msg[4:])
+ ui['notice'](uictx, chan, nick, data['nick']+' bans '+data['data']+' for '+str(int(data['extradata'])/1000000000)+' seconds')
+ elif(msg.startswith('MUTE ')):
+ data=json.loads(msg[5:])
+ ui['notice'](uictx, chan, nick, data['nick']+' mutes '+data['data']+' for '+str(int(data['extradata'])/1000000000)+' seconds')
+ elif(msg.startswith('UNMUTE ')):
+ data=json.loads(msg[7:])
+ ui['notice'](uictx, chan, nick, data['nick']+' unmutes '+data['data'])
+ elif(msg.startswith('MSGPIN ') and ui.get('topic')):
+ ui['topic'](uictx, chan, nick, msg[7:])
+ else:
+ print('Unknown message: '+msg)
+ def onclose(x,y,z):
+ print('onclose')
+ print(y)
+ print(z)
+ x.on_close=None
+ x.on_message=None
+ x.close()
+ # TODO: Use the notice callback for these?
+ print('Connection closed, attempting to reconnect ('+domain+')')
+ joinchat(domain, browser, browserprofile, nick, conn, ui, uictx, authmethod)
+ def onerror(x,y):
+ print('onerror')
+ print(y)
+ x.on_close=None
+ x.on_message=None
+ x.close()
+ print('Connection closed (onerror), attempting to reconnect ('+domain+')')
+ joinchat(domain, browser, browserprofile, nick, conn, ui, uictx, authmethod)
+ ws=websocket.WebSocketApp(wsurl, header=headers, on_message=readws, on_close=onclose, on_error=onerror)
+ conn[0]=ws
+ def run_forever(x):
+ ws.run_forever()
+ thread=threading.Thread(target=run_forever, args={'reconnect':5})
+ thread.daemon=True
+ thread.start()
+ return True
+
+def fetch_emotes(domain):
+ # Try whiteleaf path
+ emotes=requests.get('https://'+domain+'/for/apiAssets/static/images/emotes/info.json', headers={'User-agent': useragent})
+ if(not emotes.ok): # Try other path (original memelabs? idk)
+ emotes=requests.get('https://'+domain+'/embed/chat/', headers={'User-agent': useragent})
+ if(not emotes.ok): return {}
+ try:
+ page=emotes.content.decode()
+ cdn=page.index('data-cdn=')
+ cdn=page[cdn+10:page.index(' ',cdn)-1]
+ emotes=requests.get(cdn+'/emotes/emotes.json', headers={'User-agent': useragent})
+ except: return {}
+ emotelist={}
+ if(emotes.ok):
+ emotes=json.loads(emotes.content)
+ for emote in emotes:
+ if(not isinstance(emote, dict)): emote=emotes[emote]
+ if(not isinstance(emote, dict)):
+ continue
+ if(not emote.get('prefix')):
+ continue
+ if(not emote.get('imageWidth')):
+ emote['imageWidth']=emote['image'][0]['width']
+ emote['imageHeight']=emote['image'][0]['height']
+ emotelist[emote['prefix']]=emote
+ return emotelist
+
+def emote_mkflag(colors):
+ import PIL.ImageFile
+ img=PIL.Image.new('RGBA', (1,len(colors)))
+ y=0
+ for color in colors:
+ r=int(color/0x10000)%0x100
+ g=int(color/0x100)%0x100
+ b=int(color)%0x100
+ img.putpixel((0,y), (r,g,b))
+ y+=1
+ return img
+
+def emotemods(img, mods, frame=0):
+ import PIL.ImageFile
+ # :flip turns upside down
+ # :mirror mirrors
+ # :wide scales to 150% width
+ # :cancelled grays out and puts an X over
+ # :pride puts a rainbow flag in the background, presumably
+ # :bi
+ # :trans do eqivalent
+ # :dank adds a rainbowy multi-striped V in the background
+ # :spin adds a rotation animation, seems to be ~60 RPM clockwise
+ # :frozen overlays an icecube and shifts color channels to BRGA
+ # :snow
+ # TODO: Handle remaining modifiers:
+ # :worth seems to cycle through color hues reciprocally?
+ # :rustle seems to make the emote shake side to side 2 or 3 pixels each
+ # :love adds hearts on the sides, spawning and floating up
+ # :hop
+ img=img.convert('RGBA')
+ if(mods.count('wide')>0):
+ img=img.resize((int(img.size[0]*1.5), img.size[1]))
+ if(mods.count('mirror')>0):
+ img=img.transpose(PIL.Image.Transpose.FLIP_LEFT_RIGHT)
+ if(mods.count('flip')>0):
+ img=img.transpose(PIL.Image.Transpose.FLIP_TOP_BOTTOM)
+ if(mods.count('cancelled')>0): # TODO: Add an X
+ img=img.convert('L').convert('RGBA')
+ if(mods.count('trans')>0): # Colors helpfully provided by https://www.flagcolorcodes.com/
+ flag=emote_mkflag([0x5BCEFA, 0xF5A9B8, 0xFFFFFF, 0xF5A9B8, 0x5BCEFA])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('enby')>0):
+ flag=emote_mkflag([0xFCF434, 0xFFFFFF, 0x9C59D1, 0x2C2C2C])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('bi')>0):
+ flag=emote_mkflag([0xD60270, 0xD60270, 0x9B4F96, 0x0038A8, 0x0038A8])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('lesbian')>0):
+ flag=emote_mkflag([0xD52D00, 0xEF7627, 0xFF9A56, 0xFFFFFF, 0xD162A4, 0xB55690, 0xA30262])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('asex')>0):
+ flag=emote_mkflag([0x000000, 0xA3A3A3, 0xFFFFFF, 0x800080])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('genderfluid')>0):
+ flag=emote_mkflag([0xFF76A4, 0xFFFFFF, 0xC011D7, 0x000000, 0x2F3CBE])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('pan')>0):
+ flag=emote_mkflag([0xFF218C, 0xFFD800, 0x21B1FF])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('pride')>0):
+ flag=emote_mkflag([0xE40303, 0xFF8C00, 0xFFED00, 0x008026, 0x24408E, 0x732982])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('mlm')>0):
+ flag=emote_mkflag([0x078D70, 0x26CEAA, 0x98E8C1, 0xFFFFFF, 0x7BADE2, 0x5049CC, 0x3D1A78])
+ flag=flag.resize(img.size, resample=PIL.Image.Resampling.NEAREST)
+ flag.alpha_composite(img)
+ img=flag
+ if(mods.count('spin')>0):
+ img=img.rotate(-frame*360, resample=PIL.Image.Resampling.BICUBIC)
+ if(mods.count('rustle')>0):
+ rps=5 # Rustles per second
+ rx=4 # Amount of rustle movement
+ img=img.crop(((frame*rps*rx)%rx-rx/2,0,img.width+(frame*rps*rx)%rx-rx/2,img.height))
+ if(mods.count('dank')>0):
+ dank=PIL.Image.open('dank.png') # TODO: Better path
+ x=int((dank.width-img.width)/2)
+ y=int((dank.height-img.height)/2)
+ dank.alpha_composite(img, dest=(x,y))
+ img=dank
+ if(mods.count('frozen')>0):
+ r=img.getchannel('R')
+ g=img.getchannel('G')
+ b=img.getchannel('B')
+ a=img.getchannel('A')
+ img=PIL.Image.merge('RGBA', (b,r,g,a))
+ if(mods.count('love')==0): # Love removes icecube? idk
+ frozen=PIL.Image.open('frozen.png') # TODO: Better path
+ frozen=frozen.resize((img.width, img.height))
+ img.alpha_composite(frozen, dest=(0,0))
+ if(mods.count('snow')>0):
+ snow=PIL.Image.open('snow.png') # TODO: Better path
+ snow=snow.resize((img.width, snow.height))
+ img.alpha_composite(snow, dest=(0,int(-snow.height+(snow.height+img.height)*frame)))
+ return img
+
+def get_emote_img(emote, emotelist, domain):
+ import PIL.ImageFile
+ e=emotelist[emote['name']]
+ if(e.get('id')):
+ path=os.environ['HOME']+'/.cache/wlchat/'+e['id']+'.png'
+ else:
+ path=os.environ['HOME']+'/.cache/wlchat/'+e['image'][0]['name']
+ if(emote.get('modifiers')):
+ mods=emote['modifiers'].copy()
+ for mod in mods: # Avoid duplicates
+ if(mods.count(mod)>1): mods.remove(mod)
+ mods.sort()
+ path=path[0:path.rindex('.')]+(''.join(mods)+path[path.rindex('.'):]).replace('/','')
+ if(not os.path.exists(path)):
+ if(not os.path.exists(os.environ['HOME']+'/.cache/wlchat')):
+ os.mkdir(os.environ['HOME']+'/.cache/wlchat')
+ # TODO: If modified, reuse local base instead of fetching again? Though that's complicated by the fact we turn animated spritesheets into gifs
+ if(e.get('id')):
+ r=requests.get('https://'+domain+'/for/apiAssets/stage/images/emotes/aaa/1/'+e['id']+'.png', headers={'User-agent': useragent})
+ else:
+ r=requests.get(e['image'][0]['url'], headers={'User-agent': useragent})
+ if(r.status_code==200):
+ if(e.get('animated')): # Turn sprite into animated gif
+ parser=PIL.ImageFile.Parser()
+ parser.feed(r.content)
+ img=parser.close()
+ frames=[]
+ i=0
+ sec=int(e['animationLength']/1000) # For long animations, do animationmods multiple times
+ if(sec==0): sec=1 # Do at least one, even if fast
+ framecount=img.size[0]/e['imageWidth']
+ # For animation modifiers, ensure that we have enough frames for a smooth animation
+ framemultiplier=1
+ if(emote.get('modifiers') and emote['modifiers'].count('spin')>0 and framecount<12):
+ framemultiplier=math.ceil(12/framecount)
+ while(i<framecount*framemultiplier):
+ j=i/framemultiplier
+ jf=math.floor(j)
+ frame=img.crop((jf*e['imageWidth'],0,(jf+1)*e['imageWidth'],e['imageHeight']))
+ if(emote.get('modifiers')):
+ frame=emotemods(frame, emote['modifiers'], (j*sec/framecount)%1)
+ frames.append(frame)
+ i+=1
+ if(e['animationFrames']==0): e['animationFrames']=1 # No /0
+ duration=e['animationLength']/e['animationFrames']/framemultiplier # total length to frame length (milliseconds)
+ frames[0].save(path, format='gif', save_all=True, append_images=frames[1:], optimize=False, loop=0, disposal=2, duration=duration)
+ elif(emote.get('modifiers')): # Not animated, but we still need to apply modifiers
+ parser=PIL.ImageFile.Parser()
+ parser.feed(r.content)
+ img=parser.close()
+ if(emote['modifiers'].count('spin')<1 and emote['modifiers'].count('rustle')<1 and emote['modifiers'].count('snow')<1 and emote['modifiers'].count('love')<1):
+ img=emotemods(img, emote['modifiers'])
+ img.save(path)
+ else: # Spin and rustle needs to make it animated
+ i=0
+ frames=[]
+ while(i<36):
+ frame=emotemods(img, emote['modifiers'], i/36)
+ frames.append(frame)
+ i+=1
+ frames[0].save(path, format='gif', save_all=True, append_images=frames[1:], optimize=False, loop=0, disposal=2, duration=1000/36)
+ else:
+ f=open(path, 'wb')
+ f.write(r.content)
+ f.close()
+ return path
+
+def findemotes(data, emotes):
+ pos=0
+ if(data.get('nodes') and data['nodes'].get('emotes')):
+ data['nodes']['emotes']=[]
+ for word in data['data'].replace('\n',' ').split(' '):
+ wordlen=len(word)
+ word=word.split(':')
+ if(emotes.get(word[0])):
+ if(not data.get('nodes')): data['nodes']={}
+ if(not data['nodes'].get('emotes')): data['nodes']['emotes']=[]
+ e={'name':word[0],'bounds':[pos,pos+wordlen]}
+ if(len(word)>1):
+ e['modifiers']=word[1:]
+ e['modifiers'].sort()
+ data['nodes']['emotes'].append(e)
+ pos+=wordlen+1