File localslackirc-1.33+git.1739989938.1a93818.obscpio of Package localslackirc

07070100000000000081A400000000000000000000000167B623B20000010F000000000000000000000000000000000000003500000000localslackirc-1.33+git.1739989938.1a93818/.gitignoretoken.txt
__pycache__/
.mypy_cache/
.kdev4/
localslackirc.kdev4
debian/.debhelper/
debian/debhelper-build-stamp
debian/files
debian/localslackirc.postinst.debhelper
debian/localslackirc.prerm.debhelper
debian/localslackirc.substvars
debian/localslackirc/
deb-pkg/
*token
07070100000001000081A400000000000000000000000167B623B200001079000000000000000000000000000000000000003400000000localslackirc-1.33+git.1739989938.1a93818/CHANGELOG1.33
* Use new API from websockets module

1.32
* Move project to codeberg
* Install systemd stuff under usr/ to make Debian happy

1.31
* Store state into /var/lib/localslackirc when started from systemd

1.30
* Do not crash when encountering graves of deleted files

1.29
* Do not crash when encountering deleted files

1.28
* Do not crash on errors with last known timestamp
* Stop using match statement, so it can work with pypy

1.27
* New group chats are automatically joined rather than ignored
  This used to work but slack changed API

1.26
* Add experimental command lsi-getconf to read the slack
  token from the browser
* Install correct manpage for lsi-write
* Improve descriptions
* Improve --help output
* Do not crash when messages cannot be parsed

1.25
* Fix crash when sending a non existing file

1.24
* Add /dropautoreact command
* Add /listautoreact command
* Add /listannoy command
* Add /dropannoy command
* Store annoy and autoreact in state, so they are preserved
* Allow unlimited timeout for annoy and autoreact

1.23
* Add /autoreact command to automatically put reactions
  to messages.

1.22
* Fetch only the list of joined channels if the full list
  is not needed.
  Thanks to: Jiri Bohac <jbohac@suse.cz>
* Ignore chats with deleted users when downloading history
* Remove calls to removed API calls

1.21
* Introduce lsi-send to send files from the shell
* Introduce lsi-write to send messages from the shell

1.20
* Fix crash when slack sends ids of channels that do not exist
* Automatically create the download directory for the preformatted text

1.19
* Send token and cookie to authenticate to websocket as well

1.18
* Once leaving a thread, you won't get autojoined every new message
* Leaving a channel but not a thread leaves the threads working
* Can now automatically rejoin channels/threads when mentioned directly

1.17
* Improve handling of UNIX signals
* More readable names for thread channels
* Reduce CPU usage to parse messages

1.16
* Can ignore yelling (@here and such) for entire channels

1.15
* Map slack threads to IRC channels
* Rewritten parser for slack messages

1.14
* Write "LINK" instead of the URL when slack labels a URL with another URL

1.13
* New /annoy command to annoy people, showing self as typing when they are.
* Make mypy happy

1.12
* Option to save long formatted text as .txt files
* Download history for direct messages too
* Unicode emoji!
* Improved diff
* Improved compatibility with IRC
* Able to prevent selected users from abusing general mentions

1.11
* Greatly reduced CPU usage
* Remove support for RocketChat.
  I have no way of testing it and it requires severe changes.
* Only tag users that are in the same channel
* Handle more exceptions with non existing users/channels or malformed commands
* Handle cursor over conversations list
* New setting to not join channels when autojoin is set
* Diff of edit shows the entire word being edited

1.10
* Do not insert mentions inside URLs
* Support /whois

1.9
* Chat history is held and injected when the IRC client is ready
* Remove attr dependency

1.8
* Chat and thread history is retrieved and injected
* Aware of new channels the user is added to
* Parse URLs sent from slack with a label
* Requires at least python3.8
* Improved documentation
* Improved logging
* Various crashes fixed
* Better handling of signals
* Can join slack channels without doing so from the app
* Support @everyone

1.7
* Logs are more useful
* Ship with systemd service to run instances from configuration files
* Support for xoxc tokens in slack

1.6
* Useless release because of mypy

1.5
* Useless release because of mypy

1.4
* Support for /kick
* Support for /invite
* Handle people leaving rooms

1.3
* Experimental support for Rocket.Chat added
* Support for /me
* Support for /topic
* Own messages sent from other clients appear in IRC

1.2
* Initial support for rocketchat
* Fixed issue with messages being shown with a delay
* Notifications for user joins
* Pagination for channels with several users
* Do not hide errors in the main loop

1.1
* Added manpage
* Improved debian packaging
* Force correct IRC nickname
* Send files
* Faster query message send

1.0
* Initial release
07070100000002000081A400000000000000000000000167B623B200000CE6000000000000000000000000000000000000003D00000000localslackirc-1.33+git.1739989938.1a93818/CODE_OF_CONDUCT.mdInternational code of conduct
=============================

No USA cultural imperialism allowed
-----------------------------------

This project welcomes every contributor from any background. For this reason we can't let the USA and USA influenced politically correct culture dictate conduct for everyone. Diversity is beautiful, let's not ask of people to forgo their culture to contribute.

Achieving social justice is important. Being superficial about it only to feel morally superior is not the way to achieve it and is not tolerated here.


The code of conduct only pertains this project
----------------------------------------------

This document only applies to the project and the communication channels.

It does not apply to anything any contributor might say or do outside of project channels.

It only applies to contributors. People whose only contribution is a code of conduct complaint are not contributors.


Language
--------

Try to be nice and constructive.

Harassing and intentionally offending other people is not allowed.

Foul language is allowed.

People often contribute to this project in their own time and are not paid, for this reason asking contributors to behave "professionally" makes no sense. Hobbies do not require professionality.

Jokes are allowed.

It can happen to unintentionally offend someone. Do not reiterate the offensive behaviour, provided that the request is reasonable.

People who are easily offended by things not intended to be offensive must try to become more tolerant towards other people, other cultures and their ways of expressing themselves.

For example, a person might consider offensive the sight of a woman with or without a headscarf. This person needs to try to become more tolerant to other people's culture.

It is not allowed to be offended on behalf of others. Please do not presume to know what others are thinking.

Examples of allowed language:

* This software is retarded
* This program runs like shit
* This bug is annoying

Examples of disallowed language:

* You are retarded
* You are shitty and so is your program


Skill discrimination is absolutely fine
---------------------------------------

Unlike other code of conducts, this allows skill discrimination.

Everyone is welcome to contribute according to their skill level and more experienced contributors are encouraged to act as mentors.

It is nice if they have time and patience to mentor potential contributors, but since time is a limited resource, it is also fine to turn down low quality and low effort contributions with little explaination.

New contributors are expected to respond to comments and be willing to improve the quality of their contribution.

Conflict resolution
-------------------

This code of conduct is inevitably vague. Follow the intention rather than the letter.

The final word rests with the project owners or their delegates.


Changes to license
------------------

It is not allowed to ask for license change and complain about copyleft.

If you disagree with the license, feel free to start your own project from scratch without getting in touch and never look at the source code, to avoid copyright issues.

See also
--------

* [International code of conduct](https://codeberg.org/ltworf/international_code_of_conduct)
07070100000003000081A400000000000000000000000167B623B20000894B000000000000000000000000000000000000003200000000localslackirc-1.33+git.1739989938.1a93818/LICENSE                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
07070100000004000081A400000000000000000000000167B623B200000E4D000000000000000000000000000000000000003300000000localslackirc-1.33+git.1739989938.1a93818/Makefileall:
	@echo Nothing to do

.PHONY: lint
lint:
	mypy --config-file mypy.conf *.py slackclient localslackirc lsi-getconf

.PHONY: test
test: lint
	python3 -m tests

.PHONY: install
install:
	#Install slackclient
	install -d $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
	install -m644 slackclient/exceptions.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
	install -m644 slackclient/http.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
	install -m644 slackclient/client.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
	install -m644 slackclient/__init__.py $${DESTDIR:-/}/usr/share/localslackirc/slackclient/
	# Install files from the root dir
	install -m644 diff.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m644 log.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m644 msgparsing.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m644 slack.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m644 irc.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m644 control.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m755 lsi-cli.py $${DESTDIR:-/}/usr/share/localslackirc/
	install -m755 lsi-getconf $${DESTDIR:-/}/usr/share/localslackirc/
	install localslackirc $${DESTDIR:-/}/usr/share/localslackirc/
	# Install command
	install -d $${DESTDIR:-/}/usr/bin/
	ln -s ../share/localslackirc/localslackirc $${DESTDIR:-/}/usr/bin/localslackirc
	ln -s ../share/localslackirc/lsi-cli.py $${DESTDIR:-/}/usr/bin/lsi-send
	ln -s ../share/localslackirc/lsi-cli.py $${DESTDIR:-/}/usr/bin/lsi-write
	ln -s ../share/localslackirc/lsi-getconf $${DESTDIR:-/}/usr/bin/lsi-getconf
	# install extras
	install -m644 -D CHANGELOG $${DESTDIR:-/}/usr/share/doc/localslackirc/CHANGELOG
	install -m644 -D README.md $${DESTDIR:-/}/usr/share/doc/localslackirc/README.md
	install -m644 -D SECURITY.md $${DESTDIR:-/}/usr/share/doc/localslackirc/SECURITY.md
	install -m644 -D man/localslackirc.1 $${DESTDIR:-/}/usr/share/man/man1/localslackirc.1
	install -m644 -D man/lsi-send.1 $${DESTDIR:-/}/usr/share/man/man1/lsi-send.1
	install -m644 -D man/lsi-write.1 $${DESTDIR:-/}/usr/share/man/man1/lsi-write.1
	install -m644 -D man/lsi-getconf.1 $${DESTDIR:-/}/usr/share/man/man1/lsi-getconf.1
	install -m644 -D localslackirc.d/example $${DESTDIR:-/}/etc/localslackirc.d/example
	install -m644 -D systemd/localslackirc@.service $${DESTDIR:-/}/usr/lib/systemd/system/localslackirc@.service
	install -m644 -D systemd/localslackirc.service $${DESTDIR:-/}/usr/lib/systemd/system/localslackirc.service

.PHONY: dist
dist:
	cd ..; tar -czvvf localslackirc.tar.gz \
		localslackirc/localslackirc \
		localslackirc/*.py \
		localslackirc/lsi-getconf \
		localslackirc/slackclient/*.py \
		localslackirc/Makefile \
		localslackirc/CHANGELOG \
		localslackirc/LICENSE \
		localslackirc/README.md \
		localslackirc/SECURITY.md \
		localslackirc/requirements.txt \
		localslackirc/docker/Dockerfile \
		localslackirc/man \
		localslackirc/tests/*.py \
		localslackirc/localslackirc.d \
		localslackirc/systemd \
		localslackirc/mypy.conf
	mv ../localslackirc.tar.gz localslackirc_`head -1 CHANGELOG`.orig.tar.gz
	gpg --detach-sign -a *.orig.tar.gz

deb-pkg: dist
	mv localslackirc_`head -1 CHANGELOG`.orig.tar.gz* /tmp
	cd /tmp; tar -xf localslackirc*.orig.tar.gz
	cp -r debian /tmp/localslackirc/
	cd /tmp/localslackirc/; dpkg-buildpackage --changes-option=-S
	install -d deb-pkg
	mv /tmp/localslackirc_* deb-pkg
	$(RM) -r /tmp/localslackirc
	lintian --pedantic -E --color auto -i -I deb-pkg/*changes deb-pkg/*deb

.PHONY: clean
clean:
	$(RM) -r deb-pkg
	$(RM) -r tests/__pycache__
	$(RM) -r slackclient/__pycache__
	$(RM) -r __pycache__
	$(RM) -r .mypy_cache
07070100000005000081A400000000000000000000000167B623B200001F24000000000000000000000000000000000000003400000000localslackirc-1.33+git.1739989938.1a93818/README.mdlocalslackirc
=============

The idea of this project is to create a localhost IRC server that functions as
a gateway for one user of slack, that can connect to it with whatever IRC
client they prefer or a bouncer like ZNC and keep using slack from IRC even
after they shut down their IRC gateway.

[![Donate to LtWorf](docs/donate.svg)](https://liberapay.com/ltworf/donate)

Why? Peace of mind!
-------------------

Using slack from IRC instead of web app offers several advantages:

* You do not see all the gifs other people post.
* You can silence @here notifications for selected users and channels where they
  are abused.
* You can `/ignore` users who bother you (can't do that on slack).
* Leaving channels on slack is hard, normally I get invited back continuously
  on the off topic channels. With *localslackirc* you can leave them on the IRC
  client without people knowing that you won't be reading any of that.
* IRC clients allow to customise notifications. For example I have set mine to
  just blink in the tray area and do no sounds or popups.
* Any IRC client is faster than the web ui slack has, and it will respect your
  colour and style settings.
* Power savings. Because that's a logical consequence of not doing something
  in the browser.

Running localslackirc
=====================

The preferred way is to have Debian Testing and install from the repository.
You can grab the latest .deb and sources from:
https://codeberg.org/ltworf/localslackirc/releases

All the options are documented in the man page. Execute

```bash
man man/localslackirc.1
```

To read the page without installing localslackirc on the system.

There is a`localslackirc` binary but the preferred way is to run it
using systemd.

Systemd
-------

When installed from the .deb you will find a configuration template file in
`/etc/localslackirc.d/example`.

Create a copy of it in the same directory and edit the copy.

You can create several copies to use several slack workspaces.

Tell systemd to start localslackirc and make sure the ports do not collide.

`instancename` is the name of the file.

```bash
# To start the instance
sudo systemctl start localslackirc@instancename.service
# To start the instance at every boot
sudo systemctl enable localslackirc@instancename.service
```

Docker
------

Create a configuration file basing it on `localslackirc.d/example`

```bash
# Create the container
docker build -t localslackirc -f docker/Dockerfile .

# Run localslackirc
docker run -d -p 9007:9007 --name=mylocalslackirc --env-file configfile localslackirc
```

Sources
-------

### Requirements

* At least Python 3.10
* The modules indicated in `requirements.txt`

Check the manpage for the parameters.

```bash
./localslackirc
```

Obtain a token
==============

Before localslackirc can do anything useful, you need to obtain a token.

Your token should be placed inside the configuration file.

Use lsi-getconf
---------------

After logging in slack with firefox, run `lsi-getconf`.

This tool is experimental. If it fails to work you need to do it manually.

Obtain a token from the browser
-------------------------------

* Open firefox
* Open slack
* Login
* Open developer mode
* Go to "network" tab
* Click on "WS", that means websocket
* Select the connection, right click and copy value > copy with cURL.
  If there is no connection, refresh the page and it will appear.

It will be something like this:

```
curl 'wss://wss-primary.slack.com/?token=xoxc-1111111111-111111111111-1111111111111-11111111111111111&sync_desync=1&start_args=%3Fagent%3Dclient%26org_wide_aware%3Dtrue%26agent_version%111111111111%26eac_cache_ts%3Dtrue' \
  -H 'User-Agent: Mozilla/5.0' \
  -H 'Accept: */*' \
  -H 'Accept-Language: en-US,en;q=0.5' \
  -H 'Accept-Encoding: gzip, deflate, br' -H 'Sec-WebSocket-Version: 13' \
  -H 'Origin: https://app.slack.com' \
  -H 'Sec-WebSocket-Extensions: permessage-deflate' \
  -H 'Sec-WebSocket-Key: 111111111111111111111111' \
  -H 'DNT: 1' \
  -H 'Connection: keep-alive, Upgrade' \
  -H 'Cookie: b=1111111111111111; d=xoxd-1111111111111111111111111111111; tz=60; OptanonConsent=isGpcEnabled=0&datestamp=Wed+Feb+07+2024+15%3A37%3A16+GMT%2B0100+(Ora+standard+dell%E2%80%99Europa+centrale)&version=202211.1.0&isIABGlobal=false&hosts=&consentId=11111111-1111-1111-1111-111111111111&interactionCount=1&landingPath=NotLandingPage&groups=1%3A1%2C3%3A0%2C2%3A0%2C4%3A0&AwaitingReconsent=false; lc=1111111111; shown_download_ssb_modal=1; d-s=1111111111; x=11111111111111111111111111111111.1111111111' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: websocket' \
  -H 'Sec-Fetch-Site: same-site' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'Upgrade: websocket'
```

The `token=` part of the URL (terminated by `&`) and the `Cookie:` header are the parts that are important.

The cookie header contains more than one cookie, we want the one starting with `d=`. The value for the cookie must include the initial `d=` and the final `;`.

So, for example (the real values will be longer):

```
TOKEN=xoxc-1111111
COOKIE=d=xoxd-1111111;
```

Remember to quote if you pass them in a shell.

Using localslackirc
===================

After installing localslackirc and obtaining the token, it is the time
to connect to localslackirc with the IRC client.

* Connect to the IRC server created by localslackirc (by default 127.0.0.1:9007)
* Use your Slack username as your nickname
* If you left autojoin on, your client will automatically join your slack channels.

## Sending files
You can use `/sendfile #destination filepath` to send files. Destination can be a channel or a user.

From the shell you can do `lsi-send -F file '#general'`

## Annoying people
You can use `/annoy user` to send typing notifications whenever the specified user sends a typing notification.

## Discussion threads
There is some support for discussion threads.
They are mapped as irc channels that get automatically joined when a message is received. The channel of origin is specified in the topic.
Until a thread has some activity you can't write to it.
They are only tested for channels, not private groups or chats.

## Leaving channels
Leaving a discussion thread means that you will no longer receive updates within that thread
Leaving a regular channel means that discussion threads from that channel will no longer appear
After leaving a channel, a personal mention in that channel will automatically join it again. @here will be ignored.

## Reacting to messages
Since I don't feel like manually wasting time to do it, a very nice `/autoreact` command is available to automate reacting.

## Instructions for irssi

If you need to refresh your memory about connecting in general, this is a good guide: https://pthree.org/2010/02/02/irssis-channel-network-server-and-connect-what-it-means/

Here's a list of irssi commands to set up a network and a localhost server:

```
/network add -user <you> -realname "<your name>" -nick <your nick> <slackname>
/server add -auto -port 9007 -network <slackname> localhost
/save
```

Then, start localslackirc in your terminal if you haven't already. (Just type `./localslackirc`).

After localslackirc is running, and you have seen the connection
message seen above, you can just connect to the localhost IRC network
in irssi. Like this:

```
/connect <slackname>
```

And you should see the following message in your irssi:
```
22:15:35 [<slackname>] -!- Irssi: Looking up localhost
22:15:35 [<slackname>] -!- Irssi: Connecting to localhost [127.0.0.1] port 9007
22:15:35 [<slackname>] -!- Irssi: Connection to localhost established
22:15:36 [<slackname>] -!- Hi, welcome to IRC
22:15:36 [<slackname>] -!- Your host is serenity, running version miniircd-1.2.1
22:15:36 [<slackname>] -!- This server was created sometime
22:15:36 [<slackname>] -!- serenity miniircd-1.2.1 o o
22:15:36 [<slackname>] -!- There are 1 users and 0 services on 1 server
...
```

IRC Channel
===========

#localslackirc on oftc
07070100000006000081A400000000000000000000000167B623B2000000F1000000000000000000000000000000000000003600000000localslackirc-1.33+git.1739989938.1a93818/SECURITY.md# Security Policy

## Supported Versions

Only the latest release is supported. I will not backport fixes.

## Reporting a Vulnerability

Contact me at tiposchi@tiscali.it

My PGP key is on this file, on git.
debian/upstream/signing-key.asc
07070100000007000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003400000000localslackirc-1.33+git.1739989938.1a93818/abandoned07070100000008000081A400000000000000000000000167B623B20000319B000000000000000000000000000000000000003E00000000localslackirc-1.33+git.1739989938.1a93818/abandoned/rocket.py# localslackirc
# Copyright (C) 2018-2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>


import json
from functools import lru_cache
from ssl import SSLWantReadError
from enum import Enum
from time import sleep, monotonic
from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Union, Iterator
import uuid

import websockets
import typedload.dataloader

from slack import Channel, File, FileShared, IM, Message, MessageEdit, Profile, SlackEvent, Topic, User, NoChanMessage
from slackclient.client import Team, Self, LoginInfo
from log import *

CALL_TIMEOUT = 10


class ChannelType(Enum):
    CHANNEL = 'p'
    QUERY = 'd'
    PUBLIC_CHANNEL = 'c'


class ChannelUser(NamedTuple):
    id_: str
    username: str
    name: str =  'noname'
    status: str = 'auto'


class ChannelUsers(NamedTuple):
    total: int
    records: List[ChannelUser]


class DirectChannel(NamedTuple):
    rid: str


class Rocket:
    def __init__(self, url: str, token: str, previous_status: Optional[bytes]) -> None:
        self.url = url
        self.token  = token
        self._call_id = 100
        self._internalevents: List[Dict[str, Any]] = []
        self._channels: List[Channel] = []
        self._users: Dict[str, User] = {}
        self._id_prefix = 'lsi' + str(uuid.uuid1()) + '_'

        # WORKAROUND
        # The NamedTuple module can't have a field called _id, so I rename it to id_
        self.loader = typedload.dataloader.Loader()
        index = self.loader.index(ChannelUsers)
        _original_handler = self.loader.handlers[index][1]
        def _namedtuplehandler(l: typedload.dataloader.Loader, d, t):
            if '_id' in d:
                d['id_'] = d['_id']
                del d['_id']
            return  _original_handler(l, d, t)
        self.loader.handlers[index] = (self.loader.handlers[index][0], _namedtuplehandler)
        self._connect()

    def get_status(self) -> bytes:
        return b''

    @property
    def login_info(self) -> LoginInfo:
        #TODO
        return LoginInfo(
            team=Team(
                id='',
                name='',
                domain='',
            ),
            self=Self(
                id='',
                name='LtWorf',
            ),
            url='',
        )

    def _update_channels(self) -> None:
        data: Optional[List[Dict[str, Any]]] = self._call('rooms/get', [], True)
        if not data:
            raise Exception('No channel list was returned')
        self._channels.clear()

        for i in data:
            # Subscribe to it
            self._subscribe('stream-room-messages', [
                            i['_id'],
                            {
                                'useCollection': False,
                                'args':[]
                            }
                        ]
            )

            # If it's a real channel
            channel_type = ChannelType(i.get('t'))
            if channel_type == ChannelType.CHANNEL:
                self._channels.append(Channel(
                    id=i['_id'],
                    name_normalized=i['fname'],
                    purpose=Topic(i.get('topic', '')),
                    topic=Topic(i.get('topic', '')),
                ))
            elif channel_type == ChannelType.PUBLIC_CHANNEL:
                self._channels.append(Channel(
                    id=i['_id'],
                    name_normalized=i['name'],
                    purpose=Topic(i.get('topic', '')),
                    topic=Topic(i.get('topic', '')),
                ))
            elif channel_type == ChannelType.QUERY:
                pass
            else:
                log('Unknown data %s' % repr(i))

    def _send_json(self, data: Dict[str, Any]) -> None:
        """
        Sends something raw over the websocket (normally a dictionary)
        """
        self._websocket.send(json.dumps(data).encode('utf8'))

    def _connect(self) -> None:
        '''
        Create the websocket
        login
        and update channels
        '''
        self._websocket = websockets.connect(self.url)
        self._websocket.sock.setblocking(0)
        self._send_json(
            {
                'msg': 'connect',
                'version': '1',
                'support': ['1']
            }
        )
        self._call('login', [{"resume": self.token}], False)
        self._update_channels()

    def _subscribe(self, name: str, params: List[Any]) -> bool:
        self._call_id += 1
        self._send_json(
            {
                'id': str(self._call_id),
                'msg': 'sub',
                'name': name,
                'params': params,
            }
        )
        initial = monotonic()
        while initial + CALL_TIMEOUT > monotonic():
            r = self._read(subs_id=str(self._call_id))
            if r:
                if r.get('msg') == 'ready':
                    return True
                return False
            sleep(0.05)
        raise TimeoutError()

    def _call(self, method: str, params: List[Any], wait_return: bool) -> Optional[Any]:
        """
        Does a remote call.

        if wait_return is true, it will wait for the response and
        return it. Otherwise the response will be ignored.
        """
        self._call_id += 1
        data = {
            'msg':'method',
            'method': method,
            'params': params,
            'id': str(self._call_id),
        }
        self._send_json(data)

        if wait_return:
            initial = monotonic()
            while initial + CALL_TIMEOUT > monotonic():
                r = self._read(str(self._call_id))
                if r:
                    return r
                sleep(0.05)
            raise TimeoutError()
        else:
            return None


    def topic(self, channel: Channel, topic: str) -> None:
        raise NotImplementedError()

    def kick(self, channel: Channel, user: User) -> None:
        raise NotImplementedError()

    def away(self, is_away: bool) -> None:
        raise NotImplementedError()

    def join(self, channel: Channel) -> None:
        raise NotImplementedError()

    def invite(self, channel: Channel, user: Union[User, List[User]]) -> None:
        raise NotImplementedError()

    @lru_cache()
    def get_members(self, id_: str) -> Set[str]:
        data = self.loader.load(self._call('getUsersOfRoom', [id_, True], True), ChannelUsers)
        for i in data.records:
            if i.id_ not in self._users:
                self._users[i.id_] = User(
                    id=i.id_,
                    name=i.username,
                    profile=Profile(real_name=i.name),
                )
        return {i.id_ for i in data.records}

    def channels(self, refresh: bool=False) -> List[Channel]:
        if refresh:
            self._update_channels()
        return self._channels

    def get_channel(self, id_: str) -> Channel:
        for i in self._channels:
            if i.id == id_:
                return i
        raise KeyError()

    def get_channel_by_name(self, name: str) -> Channel:
        for i in self._channels:
            if i.name == name:
                return i
        raise KeyError()

    def get_ims(self) -> List[IM]:
        raise NotImplementedError()

    def get_user_by_name(self, name: str) -> User:
        for i in self._users.values():
            if i.name == name:
                return i
        raise KeyError()

    def get_usernames(self) -> List[str]:
        names = set()
        for i in self._users.values():
            names.add(i.name)
        return list(names)

    def prefetch_users(self) -> None:
        pass

    def get_user(self, id_: str) -> User:
        return self._users[id_]

    def get_file(self, f: Union[FileShared, str]) -> File:
        raise NotImplementedError()

    def send_file(self, channel_id: str, filename: str) -> None:
        raise NotImplementedError()

    def send_message(self, channel_id: str, msg: str, action: bool) -> None:
        self._call_id += 1
        self._call('sendMessage', [
            {
                '_id': self._id_prefix + str(uuid.uuid1()),
                'msg': msg,
                'rid': channel_id,
            }
        ], False)

    def send_message_to_user(self, user_id: str, msg: str, action: bool):
        self._call_id += 1
        u = self.get_user(user_id)
        data = self.loader.load(self._call('createDirectMessage', [u.name], True), DirectChannel)
        self.send_message(data.rid, msg, action)

    def _read(self, event_id: Optional[str] = None, subs_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
        try:
            _, raw_data = self._websocket.recv_data()
            if raw_data == b'\x03\xe8Normal closure':
                log('Server triggered a disconnect. Reaconnecting')
                raise Exception('Trigger reconnect')
        except SSLWantReadError:
            return None
        except Exception:
            self._connect()
            return None

        try:
            data = json.loads(raw_data)
        except Exception:
            log(f'Failed to decode json: {repr(raw_data)}')
            raise


        # Handle the stupid ping thing directly here
        if data == {'msg': 'ping'}:
            self._send_json({'msg': 'pong'})
            return None

        # Search for results of function calls
        if data is not None and (event_id is not None or subs_id is not None):
            if data.get('msg') == 'result' and data.get('id') == event_id:
                return data.get('result')
            elif data.get('subs') == [subs_id]:
                return data
            else:
                # Not the needed item, append it there so it will be returned by the iterator later
                self._internalevents.append(data)
                return None
        else:
            return data

    def events_iter(self) -> Iterator[Optional[SlackEvent]]:
        while True:
            if self._internalevents:
                data: Optional[Dict[str, Any]] = self._internalevents.pop()
            else:
                data = self._read()

            if not data:
                yield None
                continue

            r: Optional[SlackEvent] = None
            log('Scanning ', data)
            if not isinstance(data, dict):
                continue

            # Skip stuff sent by this client
            try:
                if data['fields']['args'][0]['_id'].startswith(self._id_prefix):
                    continue
            except Exception:
                pass

            if data.get('msg') == 'changed' and data.get('collection') == 'stream-room-messages': # New message
                try:
                    # If the sender is unknown, add it
                    if data['fields']['args'][0]['u']['_id'] not in self._users:
                        self._users[data['fields']['args'][0]['u']['_id']] = User(
                            id=data['fields']['args'][0]['u']['_id'],
                            name=data['fields']['args'][0]['u']['username'],
                            profile=Profile(real_name='noname'),
                        )
                    r = Message(
                        channel=data['fields']['args'][0]['rid'],
                        user=data['fields']['args'][0]['u']['_id'],
                        text=data['fields']['args'][0]['msg'],
                    )
                    if 'editedBy' in data['fields']['args'][0]:
                        r = MessageEdit(
                            type='message',
                            subtype='message_changed',
                            channel=r.channel,
                            previous=NoChanMessage(user=r.user, text=''),
                            current=NoChanMessage(user=r.user, text=r.text)
                        )
                except Exception:
                    pass

            if r is None:
                log('Not handled: ', data)
            else:
                yield r
07070100000009000081A400000000000000000000000167B623B2000007D1000000000000000000000000000000000000003500000000localslackirc-1.33+git.1739989938.1a93818/control.py# localslackirc
# Copyright (C) 2023 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>


import asyncio
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from irc import Client as IrcClient

from log import *

async def handle_write(ircclient: "IrcClient", reader, writer) -> None:
    dest = (await reader.readline()).strip()
    msg = await reader.read()

    await ircclient.send_slack_message(dest, msg, action=False, re_send_to_irc=True)

async def handle_sendfile(ircclient: "IrcClient", reader, writer) -> None:
    dest = (await reader.readline()).strip()
    filename = (await reader.readline()).strip().decode('utf8')
    content = await reader.read()

    if await ircclient.send_file(dest, content, filename=filename):
        writer.write(b"ok")
    else:
        writer.write(b"fail")

async def handle_client(ircclient: "IrcClient", reader, writer) -> None:
    command = (await reader.readline()).strip()

    if command == b"sendfile":
        await handle_sendfile(ircclient, reader, writer)
    elif command == b"write":
        await handle_write(ircclient, reader, writer)

async def listen(socket_path: str, ircclient: "IrcClient") -> None:
    server = await asyncio.start_unix_server(lambda r,w: handle_client(ircclient, r, w), socket_path)
    async with server:
        await server.serve_forever()
0707010000000A000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003100000000localslackirc-1.33+git.1739989938.1a93818/debian0707010000000B000081A400000000000000000000000167B623B200000477000000000000000000000000000000000000003600000000localslackirc-1.33+git.1739989938.1a93818/debian/NEWSlocalslackirc (1.31-1) unstable; urgency=low

  Due to changes in Debian, the default state directory is being moved from
  /var/tmp to /var/lib/localslackirc.
  If you want to preserve the status, stop the localslackirc service and move
  the status files to the new location, then start the service.

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 06 May 2024 17:35:13 +0200

localslackirc (1.11-1) unstable; urgency=medium

  Rocket.Chat support was removed.

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 05 Jul 2020 11:00:40 +0200

localslackirc (1.7-1) unstable; urgency=medium

  To simplify running several instances of localslackirc, a new systemd
  service is provided.
  There is a main service called localslackirc.service, that does nothing but
  group all the instances.
  Instances are called with localslackirc@instance_name and require a file
  named in the same way in /etc/localslackirc.d
  This file acts like a configuration file and defines environment variables
  that are loaded by systemd and passed to localslackirc-

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 01 Mar 2020 12:31:01 +0100
0707010000000C000081A400000000000000000000000167B623B200001DF7000000000000000000000000000000000000003B00000000localslackirc-1.33+git.1739989938.1a93818/debian/changeloglocalslackirc (1.33-1) unstable; urgency=high

  * New upstream release, fixes FTBFS
  * Bump Standards-Version to 4.7.0

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 01 Dec 2024 10:43:13 +0100

localslackirc (1.32-1) unstable; urgency=low

  * New upstream release (Closes: #1073649)
  * Add Vcs-Git field
  * Point to new project URL

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 06 May 2024 19:27:05 +0200

localslackirc (1.31-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 06 May 2024 17:34:45 +0200

localslackirc (1.30-1) unstable; urgency=medium

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Wed, 20 Mar 2024 15:49:45 +0100

localslackirc (1.29-1) unstable; urgency=medium

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 10 Mar 2024 19:33:14 +0100

localslackirc (1.28-2) unstable; urgency=medium

  * Drop build dependency on python3-distutils (Closes: #1065898)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 10 Mar 2024 19:26:28 +0100

localslackirc (1.28-1) unstable; urgency=low

  * New upstream release (Closes: #1065051)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Fri, 08 Mar 2024 14:30:28 +0100

localslackirc (1.27-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 29 Feb 2024 15:57:56 +0100

localslackirc (1.26-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Wed, 28 Feb 2024 17:40:27 +0100

localslackirc (1.25-1) unstable; urgency=medium

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 29 Jan 2024 16:08:41 +0100

localslackirc (1.24-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sat, 02 Dec 2023 16:46:36 +0100

localslackirc (1.23-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 14 Nov 2023 20:26:31 +0100

localslackirc (1.22-1) unstable; urgency=medium

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Fri, 10 Nov 2023 19:54:39 +0100

localslackirc (1.21-1) unstable; urgency=medium

  * New upstream release
  * Change maintainer field to point to the debian email alias

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Fri, 10 Nov 2023 11:22:57 +0100

localslackirc (1.20-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 24 Sep 2023 19:11:33 +0200

localslackirc (1.19-1) unstable; urgency=high

  * New upstream release
  * Set to urgent because slack changed their authentication and this fixes it

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 19 Sep 2023 09:34:44 +0200

localslackirc (1.18-1) unstable; urgency=low

  * New upstream release
  * Can be rebuilt (Closes: #1045470)
  * Remove X-Python3-Version: >= 3.10 from control file
  * Bump Standards-Version to 4.6.2
  * Bump debhelper dependency
  * Remove minimum typedload version

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Wed, 13 Sep 2023 17:50:39 +0200

localslackirc (1.17-1.1) unstable; urgency=medium

  * Non-maintainer upload.
  * No source change upload to rebuild with debhelper 13.10.

 -- Michael Biebl <biebl@debian.org>  Sat, 15 Oct 2022 12:17:10 +0200

localslackirc (1.17-1) unstable; urgency=medium

  * New upstream release
  * Bump required typedload version to 2.16
  * Bump Standards-Version: 4.6.1.0
  * Add metadata file

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 13 Sep 2022 09:07:56 +0200

localslackirc (1.16-1) unstable; urgency=medium

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 20 Jun 2022 23:43:36 +0200

localslackirc (1.15-4) unstable; urgency=low

  * Upload for source only upload

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 09 Jun 2022 10:42:05 +0200

localslackirc (1.15-3) unstable; urgency=medium

  * Fix the fix with autopkgtest

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 05 Jun 2022 09:09:53 +0200

localslackirc (1.15-2) unstable; urgency=medium

  * Fix autotest

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 05 Jun 2022 01:09:02 +0200

localslackirc (1.15-1) unstable; urgency=medium

  * New upstream release
  * Simpler test/control file (thanks to Antonio Terceiro)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 26 May 2022 10:44:03 +0200

localslackirc (1.14-1) unstable; urgency=high

  * New upstream version
  * Bump Standards-Version to 4.6.0
  * Fix debian/watch
  * Fix test (Closes: #998013)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 14 Oct 2021 10:25:26 +0200

localslackirc (1.13-1) unstable; urgency=high

  * New upstream release
  * Add debian tests (run the testsuite and localslackirc --help)
  * Work again with new mypy version
  * Build depend python3 → python3:any

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 23 Aug 2021 09:17:52 +0200

localslackirc (1.12-1) unstable; urgency=low

  * New upstream release
  * Depend on python3-emoji

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 27 Oct 2020 19:17:11 +0100

localslackirc (1.11-1) unstable; urgency=medium

  * New upstream release
  * Depend on python3-websockets instead of python3-websocket
  * No longer supports Rocket.Chat
  * New style compat
  * Drop dependency on python3-requests

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 22 Jun 2020 07:26:52 +0200

localslackirc (1.10-1) unstable; urgency=high

  * New upstream release (Closes: #963308)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 30 Apr 2020 16:06:15 +0200

localslackirc (1.9-2) unstable; urgency=high

  * Add needed build-deps (Closes: #959089)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 30 Apr 2020 15:56:23 +0200

localslackirc (1.9-1) unstable; urgency=high

  * New upstream release
  * Do not depend on python3-attr (Closes: #959036)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 28 Apr 2020 20:26:35 +0200

localslackirc (1.8-1) unstable; urgency=medium

  * New upstream release
  * Require python3.8 at least
  * Depend on python3-attr
  * Bump dependency on typedload

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 21 Apr 2020 14:32:17 +0100

localslackirc (1.7-1) unstable; urgency=medium

  * New upstream release
  * Adds localslackirc@.service file

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sat, 29 Feb 2020 01:57:40 +0100

localslackirc (1.6-1) unstable; urgency=low

  * New upstream release
  * Bump Standards-Version to 4.5.0
  * Define Rules-Requires-Root: no

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 23 Feb 2020 11:29:48 +0100

localslackirc (1.5-1) unstable; urgency=low

  * New upstream release

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sun, 10 Nov 2019 20:51:16 +0100

localslackirc (1.4-1) unstable; urgency=low

  * New upstream release
  * Bump Standards-Version to 4.4.0
  * Bump compat level to 12

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Mon, 16 Sep 2019 20:38:02 +0200

localslackirc (1.3-1) unstable; urgency=medium

  * New upstream release (Closes: #926320)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Tue, 16 Apr 2019 20:05:22 +0200

localslackirc (1.2-1) unstable; urgency=medium

  * New upstream release
  * Bump Standards-Version to 4.3.0

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Sat, 26 Jan 2019 10:12:13 +0100

localslackirc (1.1-1) unstable; urgency=low

  * Initial release. (Closes: #905021)

 -- Salvo 'LtWorf' Tomaselli <ltworf@debian.org>  Thu, 14 Jun 2018 16:03:09 +0200
0707010000000D000081A400000000000000000000000167B623B200000383000000000000000000000000000000000000003900000000localslackirc-1.33+git.1739989938.1a93818/debian/controlSource: localslackirc
Section: net
Priority: optional
Maintainer: Salvo 'LtWorf' Tomaselli <ltworf@debian.org>
Build-Depends: debhelper (>= 13), python3:any, dh-python,
 mypy, python3-typedload, python3-websockets, python3-emoji,
 debhelper-compat (= 13)
Standards-Version: 4.7.0
Homepage: https://codeberg.org/ltworf/localslackirc
Vcs-Browser: https://codeberg.org/ltworf/localslackirc
Vcs-Git: https://codeberg.org/ltworf/localslackirc.git
Rules-Requires-Root: no

Package: localslackirc
Architecture: all
Depends: ${misc:Depends}, ${python3:Depends}, python3-typedload,
 python3-websockets (>= 14.1-1)
Recommends:
 python3-emoji
Description: IRC gateway for slack, running on localhost for one user
 This project is a replacement for slack's IRC gateway that they dropped.
 .
 One instance of localslackirc connects to one slack account and one
 IRC client, passing the messages between the two.
0707010000000E000081A400000000000000000000000167B623B2000001DB000000000000000000000000000000000000003B00000000localslackirc-1.33+git.1739989938.1a93818/debian/copyrightFormat: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Author: Salvo "LtWorf" Tomaselli <ltworf@debian.org>
Source: https://codeberg.org/ltworf/localslackirc

Files: *
Copyright: 2018-2024 Salvo "LtWorf" Tomaselli <ltworf@debian.org>
License: GPL-3
 This software is released under the GNU General Public License 3.
 .
 On Debian systems, the complete text of the GNU General Public License
 can be found in the /usr/share/common-licenses/GPL-3 file and.
0707010000000F000081ED00000000000000000000000167B623B20000002D000000000000000000000000000000000000003700000000localslackirc-1.33+git.1739989938.1a93818/debian/rules#!/usr/bin/make -f

%:
	dh $@ --with python3
07070100000010000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003800000000localslackirc-1.33+git.1739989938.1a93818/debian/source07070100000011000081A400000000000000000000000167B623B20000000C000000000000000000000000000000000000003F00000000localslackirc-1.33+git.1739989938.1a93818/debian/source/format3.0 (quilt)
07070100000012000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003700000000localslackirc-1.33+git.1739989938.1a93818/debian/tests07070100000013000081A400000000000000000000000167B623B200000105000000000000000000000000000000000000003F00000000localslackirc-1.33+git.1739989938.1a93818/debian/tests/controlTest-Command: export PYTHONPATH=/usr/share/localslackirc && cp -r tests $AUTOPKGTEST_TMP && cd $AUTOPKGTEST_TMP && python3 -m tests
Restrictions: allow-stderr
Depends: python3-emoji, localslackirc

Test-Command: ./localslackirc --help
Restrictions: superficial
07070100000014000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003A00000000localslackirc-1.33+git.1739989938.1a93818/debian/upstream07070100000015000081A400000000000000000000000167B623B20000016F000000000000000000000000000000000000004300000000localslackirc-1.33+git.1739989938.1a93818/debian/upstream/metadataDonation: https://liberapay.com/ltworf
Repository-Browse: https://codeberg.org/ltworf/localslackirc
Repository: https://codeberg.org/ltworf/localslackirc.git
Changelog: https://codeberg.org/ltworf/localslackirc/src/branch/master/CHANGELOG
Bug-Database: https://codeberg.org/ltworf/localslackirc/issues
Bug-Submit: https://codeberg.org/ltworf/localslackirc/issues/new
07070100000016000081A400000000000000000000000167B623B200003A1D000000000000000000000000000000000000004A00000000localslackirc-1.33+git.1739989938.1a93818/debian/upstream/signing-key.asc-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1

mQINBEoFq2sBEAC1nrBLTaM2KWj+L944ImJ8Jy0+pmpUuRu2H963/Fbd0oh3APPZ
FvaWJ1YphsRJz0FgJyLqeTGRSTCqdI5WO223mdJY3+sP5hycYuUemTyCaAEn9SLn
AFVK507SCCSVduzbhw1H7ZqFk8730tyJDjkhxdh9Ag9TjS2/VcwNL0wEzOkB4xtX
JJofqJGySpZxLf+3t8kLcgchwrpB4oEQqswplvcwi71Uzfr1eHfsqz+sHeS1DFQV
8QrqH4mBG3DB3cezyk/gPIpH2E7zdV9CgP/3SzBBfbst83q7/uWFhsLyFlmS4RxE
FQcrl6EfYUO6usZyaBlt2LB1IMY8+yOgykhniYcX42EDDu/c9zyD4wMe3u+Kzl+B
AvDk9dCPw5RqRFL4xsM9tYZWPJgwhTvM6MMbtANGWkpqG2ZrZf7xbOSTzOpbJ59o
uVH31rv+nF133Es2oRZZ4OGBgD5e1iRstVeK9bq6XnWSMGDc9zNJheATJSKb80ed
IDOFGmicy/B7E78r/64yJ6acOGo2Tz/Cib/ZIWEtopWpfYKA+eI14a7nM+W6ean8
mK0qPuo4VH13KeS0hbTZRKOh6Z+ScYgglG7ZQ5CdGRRM+2GlWHZycM3B4uUhF1xI
ax3mdo1nGnYmjaVNOs3vdaX32dX3dU3HsgMKisXWyvYagOvFtX5N+xwnyQARAQAB
tDZTYWx2byAnTHRXb3JmJyBUb21hc2VsbGkgPGx0d29yZkBnYWxpbGVvLmRtaS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IP9+2g==
=nBaG
-----END PGP PUBLIC KEY BLOCK-----
07070100000017000081A400000000000000000000000167B623B200000074000000000000000000000000000000000000003700000000localslackirc-1.33+git.1739989938.1a93818/debian/watchversion=4

opts=pgpmode=auto \
https://codeberg.org/ltworf/localslackirc/tags (?:.*?/)?v?@ANY_VERSION@@ARCHIVE_EXT@
07070100000018000081A400000000000000000000000167B623B200000797000000000000000000000000000000000000003200000000localslackirc-1.33+git.1739989938.1a93818/diff.py# localslackirc
# Copyright (C) 2018-2022 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>


from typing import Iterable
from itertools import count

__all__ = [
    'seddiff',
]

_SEPARATORS = frozenset(' .,:;\t\n()[]{}')


def wordsplit(word: str) -> Iterable[str]:
    bucket = ''
    for i in word:
        if i in _SEPARATORS:
            yield bucket
            bucket = ''
        bucket += i
    if bucket:
        yield bucket


def seddiff(a: str, b: str) -> str:
    """
    Original string, changed string

    This is meant to operate on simple word changes
    or similar. Returns the IRC style correction
    format.
    """
    if a == b:
        return ''

    l1 = list(wordsplit(a))
    l2 = list(wordsplit(b))

    for prefix in count():
        try:
            if l1[prefix] != l2[prefix]:
                break
        except:
            break
    for postfix in count(1):
        try:
            if l1[-postfix] != l2[-postfix]:
                break
        except Exception:
            break
    postfix -= 1

    if prefix and postfix and len(l1) != len(l2):
        prefix -= 1
        postfix -= 1
    px = None if postfix == 0 else -postfix

    return 's/%s/%s/' % (''.join(l1[prefix:px]).strip() or '$', ''.join(l2[prefix:px]).strip())
07070100000019000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003100000000localslackirc-1.33+git.1739989938.1a93818/docker0707010000001A000081A400000000000000000000000167B623B2000001AA000000000000000000000000000000000000003C00000000localslackirc-1.33+git.1739989938.1a93818/docker/DockerfileFROM python:3.10-slim
RUN mkdir -p /localslackirc/slackclient
RUN adduser --group --system localslackirc
COPY requirements.txt /localslackirc
RUN python3 -m pip install -r /localslackirc/requirements.txt a
COPY *.py /localslackirc/
COPY localslackirc /localslackirc/
COPY slackclient/*.py /localslackirc/slackclient/
USER localslackirc
ENTRYPOINT PYTHONPATH=/localslackirc python3 /localslackirc/localslackirc -o -i "0.0.0.0"
0707010000001B000081A400000000000000000000000167B623B20000BAD7000000000000000000000000000000000000003100000000localslackirc-1.33+git.1739989938.1a93818/irc.py# localslackirc
# Copyright (C) 2018-2025 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import asyncio
import datetime
from enum import Enum
from pathlib import Path
import re
import signal
import socket
import argparse
from typing import NamedTuple, Iterable
import os
from os import environ
from os.path import expanduser
import pwd
from socket import gethostname
import sys
import time


import slack
from log import *
import msgparsing
from diff import seddiff


VERSION = '1.33'


class IrcDisconnectError(Exception): ...


class Replies(Enum):
    RPL_LUSERCLIENT = 251
    RPL_USERHOST = 302
    RPL_UNAWAY = 305
    RPL_NOWAWAY = 306
    RPL_WHOISUSER = 311
    RPL_WHOISSERVER = 312
    RPL_WHOISOPERATOR = 313
    RPL_ENDOFWHO = 315
    RPL_WHOISIDLE = 317
    RPL_ENDOFWHOIS = 318
    RPL_WHOISCHANNELS = 319
    RPL_LIST = 322
    RPL_LISTEND = 323
    RPL_CHANNELMODEIS = 324
    RPL_TOPIC = 332
    RPL_WHOREPLY = 352
    RPL_NAMREPLY = 353
    RPL_ENDOFNAMES = 366
    ERR_NOSUCHNICK = 401
    ERR_NOSUCHCHANNEL = 403
    ERR_CANNOTSENDTOCHAN = 404
    ERR_UNKNOWNCOMMAND = 421
    ERR_FILEERROR = 424
    ERR_ERRONEUSNICKNAME = 432


class Provider(Enum):
    SLACK = 0


#: Inactivity days to hide a MPIM
MPIM_HIDE_DELAY = datetime.timedelta(days=50)


class ClientSettings(NamedTuple):
    nouserlist: bool
    autojoin: bool
    no_rejoin_on_mention: bool
    provider: Provider
    ignored_channels: set[bytes]
    silenced_yellers: set[bytes]
    downloads_directory: Path
    formatted_max_lines: int = 0

    def verify(self) -> str | None:
        '''
        Make sure that the configuration is correct.

        In that case return None. Otherwise an error string.
        '''
        if not self.downloads_directory.exists():
            try:
                self.downloads_directory.mkdir(parents=True)
            except Exception:
                return f'Unable to create {self.downloads_directory}'
        elif not self.downloads_directory.is_dir():
            return f'{self.downloads_directory} is not a directory'
        return None


class Client:
    def __init__(
                    self,
                    s: asyncio.streams.StreamWriter,
                    sl_client: slack.Slack,
                    settings: ClientSettings,

    ):
        self.nick = b''
        self.username = b''
        self.realname = b''
        self.parted_channels: set[bytes] = settings.ignored_channels
        self.known_threads: dict[bytes, slack.MessageThread] = {}
        self.hostname = gethostname().encode('utf8')

        self.settings = settings
        self.s = s
        self.sl_client = sl_client
        self._usersent = False # Used to hold all events until the IRC client sends the initial USER message
        self._held_events: list[slack.SlackEvent] = []
        self._mentions_regex_cache: dict[str, re.Pattern | None] = {}  # Cache for the regexp to perform mentions. Key is channel id

    def get_mention_str(self) -> str:
        '''
        Returns the string that is present in messages when the user is getting mentioned
        '''
        return f'<@{self.sl_client.login_info.self.id if self.sl_client.login_info else ""}>'

    async def _nickhandler(self, cmd: bytes) -> None:
        if b' ' not in cmd:
            self.nick = b'localslackirc'
        else:
            _, nick = cmd.split(b' ', 1)
            self.nick = nick.strip()
        assert self.sl_client.login_info
        if self.nick != self.sl_client.login_info.self.name.encode('ascii'):
            await self._sendreply(Replies.ERR_ERRONEUSNICKNAME, 'Incorrect nickname, use %s' % self.sl_client.login_info.self.name)

    async def _sendreply(self, code: int|Replies, message: str|bytes, extratokens: Iterable[str|bytes] = []) -> None:
        codeint = code if isinstance(code, int) else code.value
        bytemsg = message if isinstance(message, bytes) else message.encode('utf8')

        extratokens = list(extratokens)

        extratokens.insert(0, self.nick)

        self.s.write(b':%s %03d %s :%s\r\n' % (
            self.hostname,
            codeint,
            b' '.join(i if isinstance(i, bytes) else i.encode('utf8') for i in extratokens),
            bytemsg,
        ))
        await self.s.drain()


    async def _userhandler(self, cmd: bytes) -> None:
        #TODO USER salvo 8 * :Salvatore Tomaselli
        assert self.sl_client.login_info
        await self._sendreply(1, 'Welcome to localslackirc')
        await self._sendreply(2, 'Your team name is: %s' % self.sl_client.login_info.team.name)
        await self._sendreply(2, 'Your team domain is: %s' % self.sl_client.login_info.team.domain)
        await self._sendreply(2, 'Your nickname must be: %s' % self.sl_client.login_info.self.name)
        await self._sendreply(2, f'Version: {VERSION}')
        await self._sendreply(Replies.RPL_LUSERCLIENT, 'There are 1 users and 0 services on 1 server')
        await self._sendreply(2, '============= Extra IRC commands supported =============')
        await self._sendreply(2, '/annoy')
        await self._sendreply(2, '/dropannoy')
        await self._sendreply(2, '/listannoy')
        await self._sendreply(2, '/autoreact')
        await self._sendreply(2, '/dropautoreact')
        await self._sendreply(2, '/listautoreact')
        await self._sendreply(2, '/sendfile')

        if self.settings.autojoin and not self.settings.nouserlist:
            # We're about to load many users for each chan; instead of requesting each
            # profile on its own, batch load the full directory.
            await self.sl_client.prefetch_users()

        if self.settings.autojoin:
            mpim_cutoff = datetime.datetime.utcnow() - MPIM_HIDE_DELAY

            for sl_chan in await self.sl_client.joined_channels():
                if not sl_chan.is_member:
                    continue

                if sl_chan.is_mpim and ((sl_chan.updated / 1000) < mpim_cutoff.timestamp()):
                    continue

                channel_name = '#%s' % sl_chan.name_normalized
                channel_name_b = channel_name.encode('ascii')
                if channel_name_b in self.parted_channels:
                    log(f'Not joining {channel_name} on IRC, marked as parted')
                    continue
                await self._send_chan_info(channel_name_b, sl_chan)
        else:
            for sl_chan in await self.sl_client.joined_channels():
                channel_name = '#%s' % sl_chan.name_normalized
                self.parted_channels.add(channel_name.encode('utf-8'))

        # Eventual channel joining done, sending the held events
        self._usersent = True
        for ev in self._held_events:
            await self.slack_event(ev)
        self._held_events = []

    async def _pinghandler(self, cmd: bytes) -> None:
        _, lbl = cmd.split(b' ', 1)
        self.s.write(b':%s PONG %s %s\r\n' % (self.hostname, self.hostname, lbl))
        await self.s.drain()

    async def _joinhandler(self, cmd: bytes) -> None:
        _, channel_names_b = cmd.split(b' ', 1)

        for channel_name_b in channel_names_b.split(b','):
            if channel_name_b in self.parted_channels:
                self.parted_channels.remove(channel_name_b)

            channel_name = channel_name_b[1:].decode()
            try:
                slchan = await self.sl_client.get_channel_by_name(channel_name)
            except Exception:
                await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find channel: {channel_name}')
                continue

            if not slchan.is_member:
                try:
                    await self.sl_client.join(slchan)
                except Exception:
                    await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to join server channel: {channel_name}')

            try:
                await self._send_chan_info(channel_name_b, slchan)
            except Exception:
                await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to join channel: {channel_name}')

    async def _send_chan_info(self, channel_name: bytes, slchan: slack.Channel|slack.MessageThread):
        if not self.settings.nouserlist:
            l = await self.sl_client.get_members(slchan.id)

            userlist: list[bytes] = []
            for i in l:
                try:
                    u = await self.sl_client.get_user(i)
                except Exception:
                    continue
                if u.deleted:
                    # Disabled user, skip it
                    continue
                name = u.name.encode('utf8')
                prefix = b'@' if u.is_admin else b''
                userlist.append(prefix + name)

            users = b' '.join(userlist)
        try:
            yelldest = b'#' + (await self.sl_client.get_channel(slchan.id)).name.encode('utf8')
        except KeyError:
            yelldest = b''

        topic = (await self.parse_message(slchan.real_topic, b'', yelldest)).replace('\n', ' | ')
        self.s.write(b':%s!%s@127.0.0.1 JOIN %s\r\n' % (self.nick, self.nick, channel_name))
        await self.s.drain()
        await self._sendreply(Replies.RPL_TOPIC, topic, [channel_name])
        await self._sendreply(Replies.RPL_NAMREPLY, b'' if self.settings.nouserlist else users, ['=', channel_name])
        await self._sendreply(Replies.RPL_ENDOFNAMES, 'End of NAMES list', [channel_name])

    async def _privmsghandler(self, cmd: bytes) -> None:
        _, dest, msg = cmd.split(b' ', 2)
        if msg.startswith(b':'):
            msg = msg[1:]

        # Handle sending "/me does something"
        # b'PRIVMSG #much_private :\x01ACTION saluta tutti\x01'
        if msg.startswith(b'\x01ACTION ') and msg.endswith(b'\x01'):
            action = True
            _, msg = msg.split(b' ', 1)
            msg = msg[:-1]
        else:
            action = False
        await self.send_slack_message(dest, msg, action, False)

    async def send_slack_message(self, dest: bytes, msg: bytes, action: bool, re_send_to_irc: bool) -> None:
        if dest in self.known_threads:
            dest_object: slack.User|slack.Channel|slack.MessageThread = self.known_threads[dest]
        elif dest.startswith(b'#'):
            try:
                dest_object = await self.sl_client.get_channel_by_name(dest[1:].decode())
            except KeyError:
                await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel {dest.decode()}')
                return
        else:
            try:
                dest_object = await self.sl_client.get_user_by_name(dest.decode())
            except KeyError:
                await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user {dest.decode()}')
                return

        message = await self._addmagic(msg.decode('utf8'), dest_object)

        try:
            if isinstance(dest_object, slack.User):
                await self.sl_client.send_message_to_user(
                    dest_object,
                    message,
                    action,
                    re_send_to_irc,
                )
            else:
                await self.sl_client.send_message(
                    dest_object,
                    message,
                    action,
                    re_send_to_irc
                )
        except Exception as e:
            await self._sendreply(Replies.ERR_CANNOTSENDTOCHAN, f'Message sending failed: {e}')

    async def _listhandler(self, cmd: bytes) -> None:
        for c in await self.sl_client.channels(refresh=True):
            topic = (await self.parse_message(c.real_topic, b'', b'')).replace('\n', ' | ')
            await self._sendreply(Replies.RPL_LIST, topic, ['#' + c.name, str(c.num_members)])
        await self._sendreply(Replies.RPL_LISTEND, 'End of LIST')

    async def _modehandler(self, cmd: bytes) -> None:
        params = cmd.split(b' ', 2)
        await self._sendreply(Replies.RPL_CHANNELMODEIS, '', [params[1], '+'])

    async def _autoreacthandler(self, cmd: bytes) -> None:
        params = cmd.split(b' ')
        params.pop(0)

        try:
            username = params.pop(0).decode('utf8')
            probability = float(params.pop(0))

            if params:
                reaction = msgparsing.get_emoji_code(params.pop(0).decode('utf8'))
            else:
                reaction = 'thumbsup'

            if params:
                duration = int(params.pop(0))
            else:
                duration = 10

            if duration < 1 and duration != -1:
                raise ValueError('Duration must be >0 or = -1')

            # async def add_autoreact(self, username: str, reaction: str, probability: float, expiration: int) -> None:
            await self.sl_client.add_autoreact(username, reaction, probability, time.time() + duration * 60 if duration != -1 else -1)
        except Exception as e:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /autoreact user probability [reaction] [duration]')
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, f'error: {e}')
            return
        await self._sendreply(0, f'Will react to {username} for {duration} minutes')


    async def _annoyhandler(self, cmd: bytes) -> None:
        params = cmd.split(b' ')
        params.pop(0)

        try:
            user = params.pop(0).decode('utf8')
            if params:
                duration = int(params.pop())
            else:
                duration = 10 # 10 minutes default

            if duration < 1 and duration != -1:
                raise ValueError("Duration must be positive or -1")

            await self.sl_client.add_annoy(user, time.time() + (duration * 60) if duration > 0 else duration)

        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}')
            return
        except Exception:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /annoy user [duration]')
            return
        await self._sendreply(0, f'Will annoy {user} for {duration} minutes')

    async def _dropannoyhandler(self, cmd: bytes) -> None:
        try:
            user = cmd.split(b' ', 1)[1].decode('utf8')
            await self.sl_client.drop_annoy(user)

        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}')
            return
        except Exception:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /dropannoy user')
            return
        await self._sendreply(0, f'No longer annoying {user}')

    async def _dropautoreacthandler(self, cmd: bytes) -> None:
        try:
            user = cmd.split(b' ', 1)[1].decode('utf8')
            await self.sl_client.drop_autoreact(user)

        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find user: {user}')
            return
        except Exception:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /dropautoreact user')
            return
        await self._sendreply(0, f'No longer reacting to {user}')

    async def _listannoyhandler(self, _: bytes) -> None:
        for i in await self.sl_client.get_annoy():
            await self._sendreply(0, f'Annoying {i}')

    async def _listautoreacthandler(self, _: bytes) -> None:
        for k, v in (await self.sl_client.get_autoreact()).items():
            await self._sendreply(0, f'Reactions for {k}')
            for i in v:
                await self._sendreply(0, str(i))

    async def _sendfilehandler(self, cmd: bytes) -> None:
        #/sendfile #destination filename
        try:
            params = cmd.split(b' ', 2)
            filename = params[2].decode('utf8')
        except IndexError:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /sendfile #channel filename')
            return

        try:
            with open(filename, 'rb') as f:
                content = f.read()
                await self.send_file(params[1], content=content, filename=filename)
        except Exception as e:
            await self._sendreply(Replies.ERR_FILEERROR, f'Error: {e}')


    async def send_file(self, bchannel_name: bytes, content: bytes, filename: str) -> bool:
        channel_name = bchannel_name.decode('utf8')

        if bchannel_name in self.known_threads:
            dest_channel = self.known_threads[bchannel_name]
            dest = dest_channel.id
            thread_ts = dest_channel.thread_ts
        else:
            thread_ts = None
            try:
                if channel_name.startswith('#'):
                    dest = (await self.sl_client.get_channel_by_name(channel_name[1:])).id
                else:
                    dest = (await self.sl_client.get_user_by_name(channel_name)).id
            except KeyError:
                await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unable to find destination: {channel_name}')
                return False

        try:
            await self.sl_client.send_file(dest, content=content, filename=filename, thread_ts=thread_ts)
            await self._sendreply(0, 'Upload completed')
            return True
        except Exception as e:
            await self._sendreply(Replies.ERR_FILEERROR, f'Unable to send file {e}')
            return False

    async def _parthandler(self, cmd: bytes) -> None:
        name = cmd.split(b' ')[1]
        self.parted_channels.add(name)
        if name in self.known_threads:
            del self.known_threads[name]

    async def _awayhandler(self, cmd: bytes) -> None:
        is_away = b' ' in cmd
        await self.sl_client.away(is_away)
        response = Replies.RPL_NOWAWAY if is_away else Replies.RPL_UNAWAY
        await self._sendreply(response, 'Away status changed')

    async def _topichandler(self, cmd: bytes) -> None:
        try:
            _, channel_b, topic_b = cmd.split(b' ', 2)
            channel_name = channel_b.decode()[1:]
            topic = topic_b.decode()[1:]
        except Exception as e:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)
            return

        try:
            channel = await self.sl_client.get_channel_by_name(channel_name)
        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel: {channel_name}')
            return

        try:
            await self.sl_client.topic(channel, topic)
        except Exception:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, f'Unable to set topic to {topic}')

    async def _whoishandler(self, cmd: bytes) -> None:
        users = cmd.split(b' ')
        del users[0]

        if len(users) != 1:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Syntax: /whois nickname')
            return

        # Seems that oftc only responds to the last one
        username = users.pop()

        if b'*' in username:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Wildcards are not supported')
            return
        uusername = username.decode()
        try:
            user = await self.sl_client.get_user_by_name(uusername)
        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user {uusername}')
            return

        await self._sendreply(Replies.RPL_WHOISUSER, user.real_name, [username, '', 'localhost'])
        if user.profile.email:
            await self._sendreply(Replies.RPL_WHOISUSER, f'email: {user.profile.email}', [username, '', 'localhost'])
        if user.is_admin:
            await self._sendreply(Replies.RPL_WHOISOPERATOR, f'{uusername} is an IRC operator', [username])
        await self._sendreply(Replies.RPL_ENDOFWHOIS, '', extratokens=[username])

    async def _kickhandler(self, cmd: bytes) -> None:
        try:
            _, channel_b, username_b, message = cmd.split(b' ', 3)
            channel_name = channel_b.decode()[1:]
            username = username_b.decode()
        except Exception as e:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)
            return

        try:
            channel = await self.sl_client.get_channel_by_name(channel_name)
        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel: {channel_name}')
            return

        try:
            user = await self.sl_client.get_user_by_name(username)
        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user: {username}')
            return

        try:
            await self.sl_client.kick(channel, user)
        except Exception as e:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)

    async def _quithandler(self, cmd: bytes) -> None:
        raise IrcDisconnectError()

    async def _userhosthandler(self, cmd: bytes) -> None:
        nicknames = cmd.split(b' ')
        del nicknames[0] # Remove the command itself
        #TODO replace + with - in case of away
        #TODO append a * to the nickname for OP

        replies = (b'%s=+unknown' % i for i in nicknames)
        await self._sendreply(Replies.RPL_USERHOST, '', replies)

    async def _invitehandler(self, cmd: bytes) -> None:
        try:
            _, username_b, channel_b = cmd.split(b' ', 2)
            username = username_b.decode()
            channel_name = channel_b.decode()[1:]
        except Exception as e:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)
            return

        try:
            channel = await self.sl_client.get_channel_by_name(channel_name)
        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHCHANNEL, f'Unknown channel: {channel_name}')
            return

        try:
            user = await self.sl_client.get_user_by_name(username)
        except KeyError:
            await self._sendreply(Replies.ERR_NOSUCHNICK, f'Unknown user: {username}')
            return

        try:
            await self.sl_client.invite(channel, user)
        except Exception as e:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Error: %s' % e)

    async def _whohandler(self, cmd: bytes) -> None:
        _, name = cmd.split(b' ', 1)
        if not name.startswith(b'#'):
            try:
                user = await self.sl_client.get_user_by_name(name.decode())
            except KeyError:
                return
            await self._sendreply(Replies.RPL_WHOREPLY, '0 %s' % user.real_name, [name, user.name, '127.0.0.1', self.hostname, user.name, 'H'])
            return

        try:
            channel = await self.sl_client.get_channel_by_name(name.decode()[1:])
        except KeyError:
            return

        for i in await self.sl_client.get_members(channel.id):
            try:
                user = await self.sl_client.get_user(i)
                await self._sendreply(Replies.RPL_WHOREPLY, '0 %s' % user.real_name, [name, user.name, '127.0.0.1', self.hostname, user.name, 'H'])
            except Exception:
                pass
        await self._sendreply(Replies.RPL_ENDOFWHO, 'End of WHO list', [name])

    async def sendmsg(self, from_: bytes, to: bytes, message: bytes) -> None:
        self.s.write(b':%s!%s@127.0.0.1 PRIVMSG %s :%s\r\n' % (
            from_,
            from_,
            to, #private message, or a channel
            message,
        ))
        await self.s.drain()

    async def _get_regexp(self, dest: slack.User|slack.Channel) -> re.Pattern | None:
        #del self._mentions_regex_cache[sl_ev.channel]
        # No nick substitutions for private chats
        if isinstance(dest, slack.User):
            return None

        dest_id = dest.id
        # Return from cache
        if dest_id in self._mentions_regex_cache:
            return self._mentions_regex_cache[dest_id]

        usernames = []
        for j in await self.sl_client.get_members(dest):
            u = await self.sl_client.get_user(j)
            usernames.append(u.name)

        if len(usernames) == 0:
            self._mentions_regex_cache[dest_id] = None
            return None

        # Extremely inefficient code to generate mentions
        # Just doing them client-side on the receiving end is too mainstream
        regexs = (r'((://\S*){0,1}\b%s\b)' % username for username in usernames)
        regex = re.compile('|'.join(regexs))
        self._mentions_regex_cache[dest_id] = regex
        return regex

    async def _addmagic(self, msg: str, dest: slack.User|slack.Channel) -> str:
        """
        Adds magic codes and various things to
        outgoing messages
        """
        for i in msgparsing.SLACK_SUBSTITUTIONS:
            msg = msg.replace(i[1], i[0])
        if self.settings.provider == Provider.SLACK:
            msg = msg.replace('@here', '<!here>')
            msg = msg.replace('@channel', '<!channel>')
            msg = msg.replace('@everyone', '<!everyone>')

        regex = await self._get_regexp(dest)
        if regex is None:
            return msg

        matches = list(re.finditer(regex, msg))
        matches.reverse() # I want to replace from end to start or the positions get broken
        for m in matches:
            username = m.string[m.start():m.end()]
            if username.startswith('://'):
                continue # Match inside a url
            elif self.settings.provider == Provider.SLACK:
                msg = msg[0:m.start()] + '<@%s>' % (await self.sl_client.get_user_by_name(username)).id + msg[m.end():]
        return msg

    async def parse_message(self, i: str, source: bytes, destination: bytes) -> str:
        """
        This converts a slack message into a message for IRC.

        It will replace mentions and shouts with the IRC equivalent.

        It will save preformatted text into txt files and link them
        if the settings are such.

        It will put the links at the end like with emails.
        """

        r = ''

        # Url replacing
        links = ''
        refs = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
        refn = 1

        for t in msgparsing.tokenize(i):
            if isinstance(t, str): # A normal nice string
                r += t
            elif isinstance(t, msgparsing.PreBlock): # Preformatted block
                # Store long formatted text into txt files
                if self.settings.formatted_max_lines and t.lines > self.settings.formatted_max_lines:
                    import tempfile
                    with tempfile.NamedTemporaryFile(
                            mode='wt',
                            dir=self.settings.downloads_directory,
                            suffix='.txt',
                            prefix='localslackirc-attachment-',
                            delete=False) as tmpfile:
                        tmpfile.write(t.txt)
                        r += f'\n === PREFORMATTED TEXT AT file://{tmpfile.name}\n'
                else: # Do not store to file
                    r += f'```{t.txt}```'
            elif isinstance(t, msgparsing.SpecialItem):
                if t.kind == msgparsing.Itemkind.MENTION: # User mention
                    r += (await self.sl_client.get_user(t.val)).name
                elif t.kind == msgparsing.Itemkind.CHANNEL: # Channel mention
                    try:
                        r += '#' + (await self.sl_client.get_channel(t.val)).name_normalized
                    except KeyError:
                        # Slack might decide to send id of channels that do not exist, yes…
                        r += '#ERROR_MISSING_CHANNEL'
                elif t.kind == msgparsing.Itemkind.YELL: # Channel shouting
                    if (source not in self.settings.silenced_yellers) and (destination not in self.settings.silenced_yellers):
                         yell = ' [%s]:' % self.nick.decode('utf8')
                    else:
                        yell = ':'
                    if t.val == 'here':
                        r += 'yelling' + yell
                    elif t.val == 'channel':
                        r += 'YELLING LOUDER' + yell
                    else:
                        r += 'DEAFENING YELL' + yell
                else: # Link
                    label = t.human
                    if label is None:
                        r += t.val
                    else:
                        if '://' in label:
                            label = 'LINK'
                        ref = str(refn).translate(refs)
                        links += f'\n  {ref} {t.val}'
                        r += label + ref
                        refn += 1
        return r + links

    async def _messageedit(self, sl_ev: slack.MessageEdit) -> None:
        if not sl_ev.is_changed:
            return
        try:
            yelldest = b'#' + (await self.sl_client.get_channel(sl_ev.channel)).name.encode('utf8')
        except KeyError:
            yelldest = b''
        source = (await self.sl_client.get_user(sl_ev.previous.user)).name.encode('utf8')
        previous = await self.parse_message(sl_ev.previous.text, source, yelldest)
        current = await self.parse_message(sl_ev.current.text, source, yelldest)

        diffmsg = slack.Message(
            text=seddiff(sl_ev.previous.text, sl_ev.current.text),
            channel=sl_ev.channel,
            user=sl_ev.previous.user,
            thread_ts=sl_ev.previous.thread_ts,
            ts=sl_ev.previous.ts,
        )

        await self._message(diffmsg)

    async def _message(self, sl_ev: slack.Message|slack.MessageDelete|slack.MessageBot|slack.ActionMessage, prefix: str=''):
        """
        Sends a message to the irc client
        """
        if not isinstance(sl_ev, slack.MessageBot):
            source = (await self.sl_client.get_user(sl_ev.user)).name.encode('utf8')
        else:
            source = b'bot'

        try:
            yelldest = dest = b'#' + (await self.sl_client.get_channel(sl_ev.channel)).name.encode('utf8')
        except KeyError:
            dest = self.nick
            yelldest = b''
        except Exception as e:
            log('Error: ', str(e))
            return

        text = sl_ev.text

        mentioned = (not self.settings.no_rejoin_on_mention) and self.get_mention_str() in text

        if sl_ev.thread_ts:
            # Threaded message, rewriting the dest
            thread = await self.sl_client.get_thread(sl_ev.thread_ts, sl_ev.channel)
            original_dest = dest
            dest = b'#' + thread.name.encode('utf8')

            if dest in self.parted_channels:
                if mentioned:
                    self.parted_channels.remove(dest)
                else:
                    # This thread is being ignored
                    return

            # Join thread channel if needed
            if dest not in self.known_threads:
                if original_dest in self.parted_channels and not mentioned:
                    # Ignoring new threads from a parted channel
                    # but keeping the known ones active
                    return
                await self._send_chan_info(dest, self.known_threads.get(dest, thread))
                self.known_threads[dest] = self.known_threads.get(dest, thread)
        elif dest in self.parted_channels:
            if mentioned:
                # rejoin channel
                slchan = await self.sl_client.get_channel(sl_ev.channel)
                await self._send_chan_info(dest, slchan)
            else:
                # Ignoring messages, channel was left on IRC
                # This ignores also threads on those channels
                return

        if sl_ev.files:
            for f in sl_ev.files:
                text+=f'\n[file upload] {f.name}\n{f.mimetype} {f.size} bytes\n{f.url_private}'

        lines = (await self.parse_message(prefix + text, source, yelldest)).encode('utf-8')
        for i in lines.split(b'\n'):
            if not i:
                continue
            if isinstance(sl_ev, slack.ActionMessage):
                i = b'\x01ACTION ' + i + b'\x01'
            await self.sendmsg(
                source,
                dest,
                i
            )

    async def _joined_parted(self, sl_ev: slack.Join|slack.Leave, joined: bool) -> None:
        """
        Handle join events from slack, by sending a JOIN notification
        to IRC.
        """

        #Invalidate cache since the users in the channel changed
        if sl_ev.channel in self._mentions_regex_cache:
            del self._mentions_regex_cache[sl_ev.channel]

        user = await self.sl_client.get_user(sl_ev.user)
        if user.deleted:
            return
        channel = await self.sl_client.get_channel(sl_ev.channel)
        dest = b'#' + channel.name.encode('utf8')
        if dest in self.parted_channels:
            return
        name = user.name.encode('utf8')
        rname = user.real_name.replace(' ', '_').encode('utf8')
        if joined:
            self.s.write(b':%s!%s@127.0.0.1 JOIN :%s\r\n' % (name, rname, dest))
        else:
            self.s.write(b':%s!%s@127.0.0.1 PART %s\r\n' % (name, rname, dest))
        await self.s.drain()

    async def slack_event(self, sl_ev: slack.SlackEvent) -> None:
        if not self._usersent:
            self._held_events.append(sl_ev)
            return

        if isinstance(sl_ev, slack.MessageDelete):
            await self._message(sl_ev, '[deleted] ')
        elif isinstance(sl_ev, slack.Message):
            await self._message(sl_ev)
        elif isinstance(sl_ev, slack.ActionMessage):
            await self._message(sl_ev)
        elif isinstance(sl_ev, slack.MessageEdit):
            await self._messageedit(sl_ev)
        elif isinstance(sl_ev, slack.MessageBot):
            await self._message(sl_ev, '[%s] ' % sl_ev.username)
        elif isinstance(sl_ev, slack.Join):
            await self._joined_parted(sl_ev, True)
        elif isinstance(sl_ev, slack.Leave):
            await self._joined_parted(sl_ev, False)
        elif isinstance(sl_ev, slack.TopicChange):
            await self._sendreply(Replies.RPL_TOPIC, sl_ev.topic, ['#' + (await self.sl_client.get_channel(sl_ev.channel)).name])
        elif isinstance(sl_ev, slack.GroupJoined) or isinstance(sl_ev, slack.MpimJoined):
            channel_name = '#%s' % sl_ev.channel.name_normalized
            await self._send_chan_info(channel_name.encode('utf-8'), sl_ev.channel)

    async def command(self, cmd: bytes) -> None:
        if b' ' in cmd:
            cmdid, _ = cmd.split(b' ', 1)
        else:
            cmdid = cmd

        # commands are case insensitive
        cmdid = cmdid.upper()

        handlers = {
            b'NICK': self._nickhandler,
            b'USER': self._userhandler,
            b'PING': self._pinghandler,
            b'JOIN': self._joinhandler,
            b'PRIVMSG': self._privmsghandler,
            b'LIST': self._listhandler,
            b'WHO': self._whohandler,
            b'MODE': self._modehandler,
            b'PART': self._parthandler,
            b'AWAY': self._awayhandler,
            b'TOPIC': self._topichandler,
            b'KICK': self._kickhandler,
            b'INVITE': self._invitehandler,
            b'SENDFILE': self._sendfilehandler,
            b'ANNOY': self._annoyhandler,
            b'LISTANNOY': self._listannoyhandler,
            b'DROPANNOY': self._dropannoyhandler,
            b'AUTOREACT': self._autoreacthandler,
            b'LISTAUTOREACT': self._listautoreacthandler,
            b'DROPAUTOREACT': self._dropautoreacthandler,
            b'QUIT': self._quithandler,
            #CAP LS
            b'USERHOST': self._userhosthandler,
            b'WHOIS': self._whoishandler,
        }

        if cmdid in handlers:
            await handlers[cmdid](cmd)
        else:
            await self._sendreply(Replies.ERR_UNKNOWNCOMMAND, 'Unknown command', [cmdid])
            log('Unknown command: ', cmd)


def su() -> None:
    """
    switch user. Useful when starting localslackirc
    as a service as root user.
    """
    if sys.platform.startswith('win'):
        return

    # Nothing to do, already not root
    if os.getuid() != 0:
        return

    username = environ.get('PROCESS_OWNER', 'nobody')
    userdata = pwd.getpwnam(username)
    os.setgid(userdata.pw_gid)
    os.setegid(userdata.pw_gid)
    os.setuid(userdata.pw_uid)
    os.seteuid(userdata.pw_uid)


def main() -> None:
    su()

    parser = argparse.ArgumentParser(
        description='Creates an IRC server running locally, which acts as a gateway to slack for one user.'
    )
    parser.add_argument('-v', '--version', action='version', version=f'''localslackirc {VERSION}''')
    parser.add_argument('-p', '--port', type=int, action='store', dest='port',
                                default=9007, required=False,
                                help='set port number. Defaults to 9007')
    parser.add_argument('-i', '--ip', type=str, action='store', dest='ip',
                                default='127.0.0.1', required=False,
                                help='set ip address')
    parser.add_argument('-t', '--tokenfile', type=str, action='store', dest='tokenfile',
                                default=expanduser('~')+'/.localslackirc',
                                required=False,
                                help='set the token file')
    parser.add_argument('-c', '--cookiefile', type=str, action='store', dest='cookiefile',
                                default=None,
                                required=False,
                                help='set the cookie file (for slack only, for xoxc tokens)')
    parser.add_argument('-u', '--nouserlist', action='store_true',
                                dest='nouserlist', required=False,
                                help='don\'t display userlist')
    parser.add_argument('--no-rejoin-on-mention', action='store_true', dest='no_rejoin_on_mention',
                                help='If set, mentions of the username will not cause the channel to be re-joined')
    parser.add_argument('-j', '--autojoin', action='store_true',
                                dest='autojoin', required=False,
                                help="Automatically join all remote channels")
    parser.add_argument('-o', '--override', action='store_true',
                                dest='overridelocalip', required=False,
                                help='allow non 127. addresses, this is potentially dangerous')
    parser.add_argument('-f', '--status-file', type=str, action='store', dest='status_file', required=False, default=None,
                                help='Path to the file to keep the internal status.')
    parser.add_argument('-d', '--debug', action='store_true', dest='debug', required=False, default=False,
                                help='Enables debugging logs.')
    parser.add_argument('--log-suffix', type=str, action='store', dest='log_suffix', default='',
                                help='Set a suffix for the syslog identifier')
    parser.add_argument('--ignored-channels', type=str, action='store', dest='ignored_channels', default='',
                                help='Comma separated list of channels to not join when autojoin is enabled')
    parser.add_argument('--downloads-directory', type=str, action='store', dest='downloads_directory', default='/tmp',
                                help='Where to create files for automatic downloads')
    parser.add_argument('--formatted-max-lines', type=int, action='store', dest='formatted_max_lines', default=0,
                                help='Maximum amount of lines in a formatted text to send to the client rather than store in a file.\n'
                                'Setting to 0 (the default) will send everything to the client')
    parser.add_argument('--silenced-yellers', type=str, action='store', dest='silenced_yellers', default='',
                                help='Comma separated list of nicknames that won\'t generate notifications when using @channel and @here')
    parser.add_argument('--control-socket', type=str, action='store', dest='control_socket', default=None,
                                help='Path to where the unix control socket will be')

    args = parser.parse_args()

    openlog(environ.get('LOG_SUFFIX', args.log_suffix))
    set_debug(environ.get('DEBUG', args.debug))

    status_file_str: str | None = environ.get('STATUS_FILE', args.status_file)
    status_file = None
    if status_file_str is not None:
        log('Status file at:', status_file_str)
        status_file = Path(status_file_str)

    ip: str = environ.get('IP_ADDRESS', args.ip)
    overridelocalip: bool = environ['OVERRIDE_LOCAL_IP'].lower() == 'true' if 'OVERRIDE_LOCAL_IP' in environ else args.overridelocalip

    # Exit if their chosden ip isn't local. User can override with -o if they so dare
    if not ip.startswith('127') and not overridelocalip:
        exit('supplied ip isn\'t local\nlocalslackirc has no encryption or ' \
                'authentication, it\'s recommended to only allow local connections\n' \
                'you can override this with -o')

    port = int(environ.get('PORT', args.port))

    autojoin: bool = environ['AUTOJOIN'].lower() == 'true' if 'AUTOJOIN' in environ else args.autojoin
    nouserlist: bool = environ['NOUSERLIST'].lower() == 'true' if 'NOUSERLIST' in environ else args.nouserlist
    no_rejoin_on_mention: bool = environ['NO_REJOIN_ON_MENTION'].lower() == 'true' if 'NO_REJOIN_ON_MENTION' in environ else args.no_rejoin_on_mention

    # Splitting ignored channels
    ignored_channels_str = environ.get('IGNORED_CHANNELS', args.ignored_channels)
    if autojoin and len(ignored_channels_str):
        ignored_channels: set[bytes] = {
            (b'' if i.startswith('#') else b'#') + i.encode('ascii')
            for i in ignored_channels_str.split(',')
        }
    else:
        ignored_channels = set()

    if 'DOWNLOADS_DIRECTORY' in environ:
        downloads_directory = Path(environ['DOWNLOADS_DIRECTORY'])
    else:
        downloads_directory = Path(args.downloads_directory)

    try:
        formatted_max_lines = int(environ.get('FORMATTED_MAX_LINES', args.formatted_max_lines))
    except:
        exit('FORMATTED_MAX_LINES is not a valid int')

    yellers_str = environ.get('SILENCED_YELLERS', args.silenced_yellers)
    if yellers_str:
        silenced_yellers = {i.strip().encode('utf8') for i in yellers_str.split(',')}
    else:
        silenced_yellers = set()

    control_socket = environ.get('CONTROL_SOCKET', args.control_socket)

    if 'TOKEN' in environ:
        token = environ['TOKEN']
    else:
        try:
            with open(args.tokenfile) as f:
                token = f.readline().strip()
        except IsADirectoryError:
            exit(f'Not a file {args.tokenfile}')
        except (FileNotFoundError, PermissionError):
            exit(f'Unable to open the token file {args.tokenfile}')

    if 'COOKIE' in environ:
        cookie: str | None = environ['COOKIE']
    else:
        try:
            if args.cookiefile:
                with open(args.cookiefile) as f:
                    cookie = f.readline().strip()
            else:
                cookie = None
        except (FileNotFoundError, PermissionError):
            exit(f'Unable to open the cookie file {args.cookiefile}')
        except IsADirectoryError:
            exit(f'Not a file {args.cookiefile}')

    if token.startswith('xoxc-') and not cookie:
        exit('The cookie is needed for this kind of slack token')

    provider = Provider.SLACK

    # Parameters are dealt with

    async def irc_listener() -> None:
        loop = asyncio.get_running_loop()

        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        serversocket.bind((ip, port))
        serversocket.listen(1)
        serversocket.setblocking(False)

        s, _ = await loop.sock_accept(serversocket)
        serversocket.close()
        reader, writer = await asyncio.open_connection(sock=s)

        previous_status = None
        if status_file is not None and status_file.exists():
            previous_status = status_file.read_bytes()
        sl_client = slack.Slack(token, cookie, previous_status)
        await sl_client.login()

        clientsettings = ClientSettings(
            nouserlist=nouserlist,
            no_rejoin_on_mention=no_rejoin_on_mention,
            autojoin=autojoin,
            provider=provider,
            ignored_channels=ignored_channels,
            downloads_directory=downloads_directory,
            formatted_max_lines=formatted_max_lines,
            silenced_yellers=silenced_yellers,
        )
        verify = clientsettings.verify()
        if verify is not None:
            exit(verify)
        ircclient = Client(writer, sl_client, clientsettings)

        try:
            from_irc_task = asyncio.create_task(from_irc(reader, ircclient))
            to_irc_task = asyncio.create_task(to_irc(sl_client, ircclient))

            if control_socket:
                import control
                control_task = asyncio.create_task(control.listen(control_socket, ircclient))
            else:
                control_task = None

            if control_task:
                await asyncio.gather(
                    from_irc_task,
                    to_irc_task,
                    control_task,
                )
            else:
                await asyncio.gather(
                    from_irc_task,
                    to_irc_task,
                )
        finally:
            log('Closing connections')
            sl_client.close()
            if status_file:
                log(f'Writing status to {status_file}')
                status_file.write_bytes(sl_client.get_status())
            writer.close()
            log('Cancelling running tasks')
            from_irc_task.cancel()
            to_irc_task.cancel()
            if control_task:
                control_task.cancel()

    async def restart_listener_loop():
        loop = asyncio.get_running_loop()

        loop.add_signal_handler(signal.SIGHUP, term_f)
        loop.add_signal_handler(signal.SIGTERM, term_f)
        loop.add_signal_handler(signal.SIGINT, term_f)

        while True:
            try:
                await irc_listener()
            except IrcDisconnectError:
                log('IRC disconnected')

    asyncio.run(restart_listener_loop())


async def from_irc(reader, ircclient: Client):
    while True:
        try:
            cmd = await reader.readline()
        except Exception:
            raise IrcDisconnectError()
        await ircclient.command(cmd.strip())


async def to_irc(sl_client: slack.Slack, ircclient: Client):
    while True:
        ev = await sl_client.event()
        if ev:
            log(ev)
            await ircclient.slack_event(ev)


def term_f(*args):
    sys.exit(0)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
0707010000001C000081ED00000000000000000000000167B623B200000381000000000000000000000000000000000000003800000000localslackirc-1.33+git.1739989938.1a93818/localslackirc#!/usr/bin/env python3
# localslackirc
# Copyright (C) 2021 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

from irc import main

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
0707010000001D000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003A00000000localslackirc-1.33+git.1739989938.1a93818/localslackirc.d0707010000001E000081A400000000000000000000000167B623B2000007FD000000000000000000000000000000000000004200000000localslackirc-1.33+git.1739989938.1a93818/localslackirc.d/example# Example configuration file for localslackirc.
#
# The instances are to be launched with:
#
# systemctl start localslackirc@filename.service
#
# filename must be replaced with the filename of the
# configuration file in /etc/localslackirc.d
#
# Make sure that the file is not world readable, since
# it contains the access token.
#
# To start the instance at every boot
# sudo systemctl enable localslackirc@filename.service


# The port to listen to, for the IRC client to connect to
#PORT=9007

# You can try using lsi-getconf to automatically obtain TOKEN and COOKIE from firefox

# The token string
#TOKEN=xxxx

# The cookie string (Not always needed)
#COOKIE=xxxx

# The user that will be used to run this process.
# Using nobody is fine, but it might be desirable to
# change this to be able to send files which might not
# be readable otherwise
#PROCESS_OWNER=nobody

# Auto join channels
AUTOJOIN=true

# Stops rejoining channel on a mention (@here is not considered)
#NO_REJOIN_ON_MENTION=true

# Networking
#IP_ADDRESS=127.0.0.1
# Do not enable this unless you know what you are doing!
#OVERRIDE_LOCAL_IP=false

# Do not fetch the user list (for huge instances)
#NOUSERLIST=true

# Comma separated list of channels to ignore and not automatically
# join on IRC.
# Ignored unless autojoin is set
# They can be joined again later on with a /join #channel command
#
# A personal mention on one of these will trigger a channel join, while
# general mentions are ignored.
#IGNORED_CHANNELS=#general,#chat

# Where to create files for automatic downloads.
# Make sure it is writable and has space
#DOWNLOADS_DIRECTORY=/tmp/

# Maximum amount of lines for formatted messages # (the ones with ```) to be
# allowed within IRC.
# Messages exceeding the limit will be stored as # text files in
# DOWNLOADS_DIRECTORY.
# 0 means no limit
#FORMATTED_MAX_LINES=0

# Comma separated list of nicknames and channels not allowed to use general mentions
#SILENCED_YELLERS="rose.adams,alfio.cuttigghiu,#sales"

# Debugging (disabled by default)
# DEBUG=1
0707010000001F000081A400000000000000000000000167B623B2000006AC000000000000000000000000000000000000003100000000localslackirc-1.33+git.1739989938.1a93818/log.py# localslackirc
# Copyright (C) 2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

from os import isatty
from syslog import LOG_INFO, LOG_DEBUG, syslog
from syslog import openlog as _openlog

__all__ = [
    'log',
    'openlog',
    'set_debug',
    'debug',
]


tty = isatty(1) and isatty(2)
debug_enabled = False


def openlog(suffix: str) -> None:
    """
    Opens the syslog connection if needed
    otherwise does nothing.
    """
    if tty:
        return
    if suffix:
        suffix = f'-{suffix}'
    _openlog(f'localslackirc{suffix}')


def log(*args) -> None:
    """
    Logs to stdout or to syslog depending on if
    running with a terminal attached.
    """
    if tty:
        print(*args)
        return
    syslog(LOG_INFO, ' '.join(str(i) for i in args))


def set_debug(state: str|bool) -> None:
    global debug_enabled
    debug_enabled = bool(state)


def debug(*args) -> None:
    if not debug_enabled:
        return
    if tty:
        print(*args)
    syslog(LOG_DEBUG, ' '.join(str(i) for i in args))
07070100000020000081ED00000000000000000000000167B623B20000109F000000000000000000000000000000000000003500000000localslackirc-1.33+git.1739989938.1a93818/lsi-cli.py#!/usr/bin/env python3
# localslackirc
# Copyright (C) 2023-2024 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import argparse
import os
import sys
import socket


def lsi_write():
    parser = argparse.ArgumentParser(
        description='Send a message to a slack user or channel.'
    )
    parser.add_argument('--control-socket', type=str, action='store', dest='control_socket', default=None,
                        help='Path to the localslackirc unix control socket')
    parser.add_argument(type=str, action='store', dest='destination',
                        help='Destination user or channel')
    args = parser.parse_args()
    control_socket = args.control_socket or find_socket()

    if not control_socket:
        sys.exit('Please specify the path to the socket')

    while data := sys.stdin.readline():
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.connect(control_socket)

        s.send(b'write\n')
        s.send(args.destination.encode('utf8') + b'\n')
        s.send(data.encode('utf8'))
        s.shutdown(socket.SHUT_WR)


def lsi_send():
    parser = argparse.ArgumentParser(
        description='Send a file to a slack user or channel.'
    )
    parser.add_argument('-f', '--filename', type=str, action='store', dest='filename',
                        help='Name to give to the file', default='filename')
    parser.add_argument('--control-socket', type=str, action='store', dest='control_socket', default=None,
                        help='Path to the localslackirc unix control socket')
    parser.add_argument('-F', '--file', type=str, action='store', dest='source',
                        help='Path of the file to send. If not specified stdin is used', default=None)
    parser.add_argument(type=str, action='store', dest='destination',
                        help='Destination user or channel')


    args = parser.parse_args()

    if args.source:
        args.filename = args.source.split('/')[-1]

    control_socket = args.control_socket or find_socket()

    if not control_socket:
        sys.exit('Please specify the path to the socket')

    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.connect(control_socket)

    assert '\n' not in args.destination
    assert '\n' not in args.filename
    s.send(b'sendfile\n')
    s.send(args.destination.encode('utf8') + b'\n')
    s.send(args.filename.encode('utf8') + b'\n')

    if args.source:
        with open(args.source, "rb") as f:
            while chunk := f.read(4096):
                s.send(chunk)
    else:
        while chunk := sys.stdin.buffer.read(1024):
            s.send(chunk)
    s.shutdown(socket.SHUT_WR)

    response = s.recv(1024).decode('utf8')

    print(response)

    if response != 'ok':
        sys.exit(1)


def main() -> None:
    cmdname = sys.argv[0].split('/')[-1]
    if cmdname == 'lsi-send':
        lsi_send()
    elif cmdname == 'lsi-write':
        lsi_write()


def find_socket() -> None | str:
    '''
    Returns the control socket of localslackirc or raises

    It looks in the runtime directory used in the .service file
    and looks for sockets in that directory.
    '''
    RUNDIR = '/run/localslackirc/'
    candidates = []

    try:
        for s in os.listdir(RUNDIR):
            if os.access(RUNDIR + s, os.W_OK | os.R_OK | os.X_OK):
                candidates.append(RUNDIR + s)
        if len(candidates) == 1:
            return candidates[0]
    except Exception:
        pass
    return None


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
07070100000021000081ED00000000000000000000000167B623B200000E10000000000000000000000000000000000000003600000000localslackirc-1.33+git.1739989938.1a93818/lsi-getconf#!/usr/bin/env python3
# localslackirc
# Copyright (C) 2024 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import os
import sys
import sqlite3
import argparse
from pathlib import Path


HOME = Path(os.environ.get('HOME', ''))
MOZILLA_CONF = HOME / '.mozilla'

def log(*args):
    print(*args, file=sys.stderr)

def get_mozilla_localstorage_tokens(ls: Path) -> list[str]:
    '''
    Pass the path of a possible local storage file and get slack tokens
    '''

    db = sqlite3.connect(ls)
    try:
        s = db.execute('select value from data where key="localConfig_v2";')
    except Exception:
        return []

    r = []
    for i in s:
        # Some magic crap, it's a readable json polluted with unreadable crap…
        # No idea if this will work in other cases than on my machine

        i = i[0]
        i = i.split(b'"toke', 1)[1].split(b'"', 1)[0]
        i = i[i.index(b'xox'):]
        r.append(i.decode('ascii'))

    return r


def get_mozilla_cookies(jar: Path) -> list[str]:
    '''
    Pass the path of a cookie jar and receive a list of slack cookies
    '''
    db = sqlite3.connect(jar)
    return [i[0] for i in db.execute('select value from moz_cookies WHERE host= ".slack.com" and name="d";')]

def mozilla(cfgdir: Path) -> tuple[list[str], list[str]]:
    '''
    returns cookies, tokens
    '''
    log(f'Scanning {cfgdir} as a Mozilla directory')
    cookiefiles = cfgdir.rglob('cookies.sqlite')
    other_files = cfgdir.rglob('*.sqlite')

    cookies = []
    tokens = []

    for i in cookiefiles:
        log(f'Scanning possible cookie jar {i}')
        try:
            cookies += get_mozilla_cookies(i)
        except Exception as e:
            sys.exit(str(e))

    for i in other_files:
        log(f'Scanning possible local storage file {i}')
        try:
            tokens += get_mozilla_localstorage_tokens(i)
        except Exception as e:
            sys.exit(str(e))

    return cookies, tokens

def main() -> None:
    parser = argparse.ArgumentParser(
        description='Read the browser database to try to find the cookie and token that are necessary to set up localslackirc.'
    )
    parser.add_argument('--mozilla-dir', type=Path, action='store', dest='mozilla_dir',
                                default=MOZILLA_CONF)
    args = parser.parse_args()

    cookies = []
    tokens = []

    c, t = mozilla(args.mozilla_dir)
    cookies += c
    tokens += t

    # TODO chromium

    if not cookies and not tokens:
        sys.exit('Fail: Nothing was found')

    print('# ==============')
    if tokens:
        print('# Tokens found:')
    for i in tokens:
        print(f'TOKEN={i}')
    if cookies:
        print('# Cookies found:')
    for i in cookies:
        print(f'COOKIE="d={i};"')

    if len(tokens) > 1 or len(cookies) > 1:
        print('# Try deleting all cookies from your browsers and logging into slack again')

if __name__ == '__main__':
    main()
07070100000022000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000002E00000000localslackirc-1.33+git.1739989938.1a93818/man07070100000023000081A400000000000000000000000167B623B200001EA6000000000000000000000000000000000000003E00000000localslackirc-1.33+git.1739989938.1a93818/man/localslackirc.1.TH localslackirc 1 "Sep 13, 2024" "IRC gateway for slack"
.SH NAME
localslackirc
\- Creates an IRC server running locally, which acts as a gateway to slack for one user.

.SH SYNOPSIS
localslackirc [OPTIONS]

.SH DESCRIPTION
This command starts an IRC server running on 127.0.0.1:9007 which acts as a gateway to slack for one user.
.br
To connect to multiple instances it is necessary to run multiple instances of this software.
.TP
.SS
.SS Options:
.TP
.B -h, --help
Show the help message and exit.
.TP
.B -v, --version
Show the version and exit.
.TP
.B -p PORT, --port PORT
Set the port number. The default is 9007.
.br
.TP
.B -i IP, --ip IP
Set the IP (Ipv4 only) address to listen to. The default is 127.0.0.1.
.TP
.B -t TOKENFILE, --tokenfile TOKENFILE
Set the token file. The default is ~/.localslackirc.
.TP
.B -c TOKENFILE, --cookiefile TOKENFILE
Set the cookie file. This is only used on slack, and is only useful if your token starts with "xoxc".
.TP
.B -u, --nouserlist
Don't display userlist in the IRC client.
.TP
.B -j, --autojoin
Automatically join all remote channels.
.TP
.B -o, --override
Allow listening on addresses that do not start with 127.*
.br
This is potentially dangerous.
.TP
.B --downloads-directory
Where to create files for automatic downloads. It defaults to /tmp.
.br
The directory must exist and be writeable. Files will automatically be downloaded in it.
.br
No cleaning is automatically performed on it by localslackirc.
.TP
.B --formatted-max-lines
Maximum amount of lines in a formatted text to send to the client rather than store in a file.
.br
When people send logs or otherwise long text content as formatted text, the end result is usually hardly readable in IRC, having the username of the sender and the time in each line.
.br
This option sets a limit for formatted content to be sent as text.
.br
When the limit is exceeded, the formatted text will be stored as a .txt file instead and its URL will be shown in the IRC client.
.br
The files will be saved in the path specified by "downloads directory".
.br
The files are not automatically removed.
.br
Setting to 0 (the default) will send everything to the client and create no text files.
.TP
.B -f --status-file
Path to the file keeping the status. When this is set, it allows for the history to be loaded on start.
.TP
.B --silenced-yellers
Comma separated list of nicknames and channels that are prevented from using general mentions (@here, @channel, @everyone, and the likes).
.br
Since some people are greatly abusing the feature, this is to make them less annoying.
.br
Their messages aren't blocked and are shown as "yelling MESSAGE", but the nickname of the user won't be injected in the message, so the IRC client won't create a notification.
.br
The channels must begin with #.
.br
The threads created from a silenced channel will also be silenced.
.TP
.B -d --debug
Enables debugging logs.
.TP
.B --log-suffix
Instead of using localslackirc as ident for syslog, this appends a custom string, separated by a -.
.br
This is useful when running several instances, to be able to distinguish the logs.
.br
The default .service file uses this. Of course journald keeps track of the services but this makes it easier to have the information on text dumps or other logging daemons such as rsyslog.
.TP
.B --ignored-channels
Comma separated list of channels to ignore and not automatically join on IRC.
.br
It is ignored unless autojoin is set.
.br
If a channel is in this list, the IRC client will not automatically join it, but on slack you will still be inside the channel
.br
This is useful to avoid off topic channels in which coworkers who can't take a hint keep re-inviting.
.br
The ignored channels can be joined again if needed, with a /join #channel command. However the conversation history will not be fetched.
.br
For channel names containing non ascii characters, their ascii representation needs to be used. Use /list to see which that is.
.br
If the user gets personally mentioned in one of the ignored channels, it will be joined anyway. General mentions will be ignored.
.TP
.B --no-rejoin-on-mention
Normally localslackirc will automatically join channel and threads if someone mentions the user.
.br
When this is set the mentions will be ignored and no channels or threads will be joined upon mention.
.TP
.B --control-socket CONTROL_SOCKET
When used, localslackirc will create a unix socket in the specified path, that can be used by the various lsi-* commands to interact with localslackirc.
.br
Before an IRC client connects to localslackirc, the process is in a dormant unconnected state and is not connected to slack. For this reason the control socket exists only when an IRC client is connected.
.SH TOKEN
The easiest way to obtain the COOKIE and the TOKEN, is to login in slack using Firefox, closing Firefox and running lsi-getconf.
.br
It will parse your saved cookies and try to find the values.
.br
If that should fail, the README contains the procedure to manually extract them from the browser.
.SH ENVIRONMENT
The following environment variables are used. They override command line settings. The alternatives to switches must contain "true" to work.
.TP
.B COOKIE
Alternative to --cookiefile
.TP
.B DOWNLOADS_DIRECTORY
Alternative to --downloads-directory
.TP
.B FORMATTED_MAX_LINES
Alternative to --formatted-max-lines
.TP
.B PORT
Alternative to --port
.TP
.B TOKEN
Alternative to --tokenfile
.TP
.B PROCESS_OWNER
If running as root, this is the name of the user to switch to. If this is not specified, "nobody" will be used.
.br
This is very useful to start localslackirc as a service and configure which user to use in the configuration file.
.TP
.B IP_ADDRESS
Alternative to --ip
.TP
.B OVERRIDE_LOCAL_IP
Alternative to --override
.TP
.B STATUS_FILE
Path to the status file
.TP
.B AUTOJOIN
Alternative to --autojoin
.br
Set to "true" to enable.
.TP
.B NOUSERLIST
Alternative to --nouserlist
.br
Set to "true" to enable.
.TP
.B DEBUG
Alternative to --debug
.TP
.B LOG_SUFFIX
Alternative to --log-suffix
.TP
.B IGNORED_CHANNELS
Alternative to --ignored-channels
.TP
.B NO_REJOIN_ON_MENTION
Alternative to --no-rejoin-on-mention
.br
Set to "true" to enable.
.TP
.B SILENCED_YELLERS
Alternative to --silenced-yellers
.TP
.B CONTROL_SOCKET
Alternative to --control-socket
.SH Additional IRC commands
Some commands are added, to use some additional features that are present in slack but not IRC.
.SS
.TP
.B /sendfile destination /path/to/file
Sends the specified file to destination.
.br
The destination can be a user or a channel, in which case it must begin with #.
.TP
.B /annoy user [duration]
The indicated user will be annoyed.
.br
This means that whenever a typing event is received from that user, on any channel, a type event on the same channel will be sent back, making the user think you are about to write something too.
.br
duration is the duration of the annoyance in minutes. It defaults to 10.
.SS
.TP
.B /autoreact user probability [reaction] [duration]
To automate reacting to messages, this nice feature is available.
.br
user is the username of the user that we want to react to.
.br
probability is a number between 0 and 1, to decide how much to react.
.br
reaction is the reaction to use. The default is "thumbsup".
.br
duration indicates when to stop doing it, in minutes. Defaults to 10. Setting it to -1 makes it never expire.
.SS

.TP
.B /dropautoreact user
Deletes all the automatic reacts for a given user
.SS

.TP
.B /dropannoy user
Stops annoying the given user
.SS

.TP
.B /listannoy
Lists the users that are currently being annoyed
.SS

.TP
.B /listautoreact
Lists the automatic reactions
.SS


.SH "SEE ALSO"
.BR lsi-getconf(1), lsi-send (1), lsi-write (1)


.SH WEB
.BR https://codeberg.org/ltworf/localslackirc

.SH AUTHOR
.nf
Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
07070100000024000081A400000000000000000000000167B623B2000003B3000000000000000000000000000000000000003C00000000localslackirc-1.33+git.1739989938.1a93818/man/lsi-getconf.1.TH lsi-getconf 1 "Jun 18, 2024" "Send files to slack"

.SH NAME
lsi-getconf
\- Read the browser database to try to find the cookie and token that are necessary to set up localslackirc.

.SH SYNOPSIS
lsi-getconf [OPTIONS]

.SH DESCRIPTION
This command reads the browser database to try to find token and cookie that are necessary to localslackirc.
.br
For now it only supports Firefox.
.br
This is experimental. It might not work on your machine. In which case you should fall back to extracting the data directly from the browser.
.SS Options:
.TP
.B -h, --help
Show the help message and exit.

.TP
.B --mozilla-dir DIRECTORY
Alternative search path for the mozilla directory. It defaults to ~/.mozilla.

.SH "Known errors"
.TP
.B database is locked
Close the browser to solve this issue.

.SH "SEE ALSO"
.BR localslackirc (1)


.SH WEB
.BR https://codeberg.org/ltworf/localslackirc

.SH AUTHOR
.nf
Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
07070100000025000081A400000000000000000000000167B623B2000005B6000000000000000000000000000000000000003900000000localslackirc-1.33+git.1739989938.1a93818/man/lsi-send.1.TH lsi-send 1 "Jun 18, 2024" "Send files to slack"

.SH NAME
lsi-send
\- Send a file to a slack user or channel.

.SH SYNOPSIS
lsi-send [OPTIONS] DESTINATION < file
.br
lsi-send [OPTIONS] -F file DESTINATION

.SH DESCRIPTION
This command sends files to an instance of localslackirc that is running locally.
.br
DESTINATION indicates a channel or user to send the file to.
.br
When using the provided .service file and starting localslackirc with systemd, this command should be able to autodetect the location of the socket.
.br
In case the same user is running multiple instances, then it is possible that the path to the unix socket must be provides as a parameter.
.br
NOTE: the files are entirely loaded in RAM before sending.

.SS Options:
.TP
.B -h, --help
Show the help message and exit.

.TP
.B -f FILENAME, --filename FILENAME
The name to give to the filename.
.br
It will appear on slack.

.TP
.B --control-socket CONTROL_SOCKET
If the path to the socket cannot be auto-detected, this option must be used to indicate the path to connect to the control socket.

.TP
.B -F SOURCE, --file SOURCE
When used, instead of reading from stdin, lsi-send will read from the specified file.
.br
The --filename option will be ignored in this case, and the real name of the file will be used.

.SH "SEE ALSO"
.BR localslackirc (1), lsi-write (1)


.SH WEB
.BR https://codeberg.org/ltworf/localslackirc

.SH AUTHOR
.nf
Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
07070100000026000081A400000000000000000000000167B623B2000002F0000000000000000000000000000000000000003A00000000localslackirc-1.33+git.1739989938.1a93818/man/lsi-write.1.TH lsi-write 1 "Jun 18, 2024" "Send files to slack"

.SH NAME
lsi-write
\- Send a message to a slack user or channel.

.SH SYNOPSIS
lsi-send [OPTIONS] user

.SH DESCRIPTION
Inspired by the classical write, this works more or less in the same way.
.br
It uses the control socket of a localslackirc instance to send messages to a user or channel.

.SS Options:
.TP
.B -h, --help
Show the help message and exit.

.TP
.B --control-socket CONTROL_SOCKET
If the path to the socket cannot be auto-detected, this option must be used to indicate the path to connect to the control socket.

.SH "SEE ALSO"
.BR localslackirc (1), lsi-send (1)


.SH WEB
.BR https://codeberg.org/ltworf/localslackirc

.SH AUTHOR
.nf
Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
07070100000027000081A400000000000000000000000167B623B200001540000000000000000000000000000000000000003800000000localslackirc-1.33+git.1739989938.1a93818/msgparsing.py# localslackirc
# Copyright (C) 2022-2025 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

from enum import Enum
from typing import Iterable, NamedTuple

try:
    from emoji import emojize, demojize # type: ignore
except ModuleNotFoundError:
    def emojize(string:str, *args, **kwargs) -> str:  # type: ignore
        return string
    def demojize(string, str, delimiters: tuple[str, str]) -> str:  # type: ignore
        return string


SLACK_SUBSTITUTIONS = [
    ('&amp;', '&'),
    ('&gt;', '>'),
    ('&lt;', '<'),
]

__all__ = [
    'SLACK_SUBSTITUTIONS',
    'tokenize',
    'Itemkind',
    'PreBlock',
    'SpecialItem',
    'get_emoji_code',
]


def get_emoji_code(msg: str) -> str:
    '''
    Pass a single emoji and get the code without delimiters.
    '''
    return demojize(msg, ('', ''))


def preblocks(msg: str) -> Iterable[tuple[str, bool]]:
    """
    Iterates the preformatted and normal text blocks
    in the message.

    The boolean indicates if the block is preformatted.

    The three ``` ticks are removed by this.
    """
    pre = False

    while True:
        try:
            p = msg.index('```')
        except ValueError:
            break

        yield msg[0:p], pre
        pre = not pre
        msg = msg[p+3:]
    yield msg, pre


class Itemkind(Enum):
    YELL = 0  # HERE, EVERYONE and such
    MENTION = 1 # @user
    CHANNEL = 2 # #channel
    OTHER = 3 # Everything else


class PreBlock(NamedTuple):
    """
    Block of preformatted text
    """
    txt: str

    @property
    def lines(self) -> int:
        return self.txt.count('\n')


class SpecialItem(NamedTuple):
    """
    A link or a mention
    """
    txt: str

    @property
    def kind(self) -> Itemkind:
        k = self.txt[1]
        if k == '!':
            return Itemkind.YELL
        elif k == '@':
            return Itemkind.MENTION
        elif k == '#':
            return Itemkind.CHANNEL
        return Itemkind.OTHER

    @property
    def val(self) -> str:
        """
        Return the value
        """

        sep = self.txt.find('|')

        # No human readable, just take the whole thing
        if sep == -1:
            sep = len(self.txt) - 1


        if self.kind != Itemkind.OTHER:
            return self.txt[2:sep]
        return self.txt[1:sep]

    @property
    def human(self) -> str | None:
        """
        Return the eventual human readable
        message
        """
        sep = self.txt.find('|')

        if sep == -1:
            return None
        return self.txt[sep+1:-1]


def split_tokens(msg: str) -> Iterable[SpecialItem|str]:
    """
    yields separately the normal text and the special slack
    <stuff> items
    """
    while True:
        try:
            begin = msg.index('<')
        except ValueError:
            break

        if begin != 0: # There is stuff before
            yield msg[0:begin]
            msg = msg[begin:]
        else: # Tag at the beginning
            end = msg.index('>')
            block = msg[0:end + 1]
            msg = msg[end + 1:]
            yield SpecialItem(block)
    if msg:
        yield msg


def convertpre(msg: str) -> str:
    """
    Fixes a preformatted block so that it can
    be displayed by an irc client.

    Links can be present in preformatted blocks
    with the format <http://> and MAYBE with
    <http://blabla|bla> but no channel or user
    mentions are allowed, and emoji substitution
    should not happen here.
    """
    r = []

    for t in split_tokens(msg):
        if isinstance(t, str):
            r.append(t)
            continue

        if t.kind != Itemkind.OTHER:
            raise ValueError(f'Unexpected slack item in preformatted block {t}')
        elif t.human: # For some very strange reason slack converts text like "asd.com" into links
            r.append(t.human)
        else:
            r.append(t.val)

    l = ''.join(r)
    for s in SLACK_SUBSTITUTIONS:
        l = l.replace(s[0], s[1])
    return l


def tokenize(msg: str) -> Iterable[PreBlock|SpecialItem|str]:
    """
    Yields the various possible tokens

    Changes the &gt; codes

    Puts the emoji in place
    """
    try:
        for txt, pre in preblocks(msg):
            if pre:
                yield PreBlock(convertpre(txt))
            else:
                for t in split_tokens(txt):
                    if isinstance(t, str):
                        # Replace emoji codes (e.g. :thumbsup:)
                        t = emojize(t, language='alias')
                        # Usual substitutions
                        for s in SLACK_SUBSTITUTIONS:
                            t = t.replace(s[0], s[1])  # type: ignore
                    yield  t
    except Exception as e:
        yield f'ERROR: cannot parse: {msg!r}'
07070100000028000081A400000000000000000000000167B623B200000095000000000000000000000000000000000000003400000000localslackirc-1.33+git.1739989938.1a93818/mypy.conf[mypy]
python_version=3.10
warn_unused_ignores=False
warn_redundant_casts=True
strict_optional=True
scripts_are_modules=True
check_untyped_defs=True
07070100000029000081A400000000000000000000000167B623B200000034000000000000000000000000000000000000003B00000000localslackirc-1.33+git.1739989938.1a93818/requirements.txttypedload>=2.16
emoji>=2.0.0
types-emoji
websockets
0707010000002A000081A400000000000000000000000167B623B2000089D7000000000000000000000000000000000000003300000000localslackirc-1.33+git.1739989938.1a93818/slack.py# localslackirc
# Copyright (C) 2018-2025 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import asyncio
import datetime
from dataclasses import dataclass, field
import json
from time import time
from typing import Literal, Any, NamedTuple, Sequence, Type, TypeVar

from typedload import dataloader

from slackclient import SlackClient
from slackclient.client import LoginInfo
from log import log, debug


T = TypeVar('T')

USELESS_EVENTS = frozenset((
    'user_interaction_changed', # undocumented event
    'clear_mention_notification', # undocumented event
    'update_global_thread_state', # undocumented event
    'update_thread_state', # undocumented event
    'thread_marked', # undocumented event
    'im_marked',
    'pref_change',
    'draft_create',
    'draft_delete',
    'accounts_changed',
    'channel_marked',
    'group_marked',
    'mpim_marked',
    'hello',
    'dnd_updated_user',
    'reaction_added',
    'file_deleted',
    'file_public',
    'file_created',
    'file_shared',
    'desktop_notification',
    'mobile_in_app_notification',
    'goodbye', # Server is disconnecting us
))


class ResponseException(Exception):
    pass


class Response(NamedTuple):
    """
    Internally used to parse a response from the API.
    """
    ok: bool
    headers: dict[str, str]
    ts: float | None = None
    error: str | None = None


@dataclass
class DeletedFile:
    file_access: Literal['file_not_found']

@dataclass
class File:
    file_access: Literal['visible']
    id: str
    url_private: str
    size: int
    user: str
    name: str | None = None
    title: str | None = None
    mimetype: str | None = None

@dataclass
class TabutuFile:
    """
    'un sacciu chi minchia è sta cosa.

    Sacciu sulu ca slack u manna
    """
    id: str
    mode: Literal['tombstone']


class Topic(NamedTuple):
    """
    In slack, topic is not just a string, but has other fields.
    """
    value: str


class LatestMessage(NamedTuple):
    ts: float

    @property
    def timestamp(self):
        return datetime.datetime.utcfromtimestamp(self.ts)


@dataclass(frozen=True)
class Channel:
    """
    A channel description.

    real_topic tries to use the purpose if the topic is missing
    """
    id: str
    name_normalized: str
    purpose: Topic
    topic: Topic
    num_members: int = 0
    #: Membership: present on channels, not on groups - but True there.
    is_member: bool = True

    #: Object type. groups have is_group=True, channels is_channel=True
    is_channel: bool = False
    is_group: bool = False
    is_mpim: bool = False

    # Last updated?
    updated: int = 0

    latest: LatestMessage | None = None

    @property
    def name(self):
        return self.name_normalized

    @property
    def real_topic(self) -> str:
        if self.topic.value:
            t = self.topic.value
        else:
            t = self.purpose.value
        return t

@dataclass(frozen=True)
class MessageThread(Channel):
    thread_ts: str = ''


@dataclass(frozen=True)
class Message:
    channel: str  # The channel id
    user: str  # The user id
    text: str
    ts: float
    thread_ts: str | None = None
    files: list[File] = field(default_factory=list)


class NoChanMessage(NamedTuple):
    user: str
    text: str
    ts: float
    thread_ts: str | None = None


class ActionMessage(Message):
    pass


@dataclass
class GroupJoined:
    type: Literal['group_joined']
    channel: Channel


@dataclass
class MpimJoined:
    type: Literal['mpim_joined']
    channel: Channel


@dataclass
class MessageEdit:
    type: Literal['message']
    subtype: Literal['message_changed']
    channel: str
    previous: NoChanMessage = field(metadata={'name': 'previous_message'})
    current: NoChanMessage = field(metadata={'name': 'message'})

    @property
    def is_changed(self) -> bool:
        return self.previous.text != self.current.text


@dataclass
class MessageDelete:
    type: Literal['message']
    subtype: Literal['message_deleted']
    channel: str
    previous_message: NoChanMessage
    files: list[File] = field(default_factory=list)

    @property
    def thread_ts(self) -> str | None:
        return self.previous_message.thread_ts

    @property
    def user(self) -> str:
        return self.previous_message.user

    @property
    def text(self) -> str:
        return self.previous_message.text


class UserTyping(NamedTuple):
    type: Literal['user_typing']
    user: str
    channel: str


class Profile(NamedTuple):
    real_name: str = 'noname'
    email: str | None = None
    status_text: str = ''
    is_restricted: bool = False
    is_ultra_restricted: bool = False


@dataclass
class MessageBot:
    type: Literal['message']
    subtype: Literal['bot_message']
    _text: str = field(metadata={'name': 'text'})
    username: str
    channel: str
    bot_id: str | None = None
    attachments: list[dict[str, Any]] = field(default_factory=list)
    thread_ts: str | None = None
    files: list[File] = field(default_factory=list)

    @property
    def text(self):
        r = [self._text]
        for i in self.attachments:
            t = ""
            if 'text' in i:
                t = i['text']
            elif 'fallback' in i:
                t = i['fallback']
            for line in t.split("\n"):
                r.append("| " + line)
        return '\n'.join(r)


class User(NamedTuple):
    id: str
    name: str
    profile: Profile
    is_admin: bool = False
    deleted: bool = False

    @property
    def real_name(self) -> str:
        return self.profile.real_name


class IM(NamedTuple):
    id: str
    user: str
    is_user_deleted: bool


class Join(NamedTuple):
    type: Literal['member_joined_channel']
    user: str
    channel: str


class Leave(NamedTuple):
    type: Literal['member_left_channel']
    user: str
    channel: str


@dataclass
class TopicChange:
    type: Literal['message']
    subtype: Literal['group_topic']
    topic: str
    channel: str
    user: str


@dataclass
class HistoryBotMessage:
    type: Literal['message']
    subtype: Literal['bot_message']
    text: str
    bot_id: str | None
    username: str = 'bot'
    ts: float = 0
    files: list[File | DeletedFile | TabutuFile] = field(default_factory=list)
    thread_ts: str | None = None
    attachments: list[dict[str, Any]] = field(default_factory=list)


@dataclass
class HistoryMessage:
    type: Literal['message']
    user: str
    text: str
    ts: float
    files: list[File | DeletedFile | TabutuFile] = field(default_factory=list)
    thread_ts: str | None = None


class NextCursor(NamedTuple):
    next_cursor: str


class History(NamedTuple):
    ok: Literal[True]
    messages: list[HistoryMessage|HistoryBotMessage]
    has_more: bool
    response_metadata: NextCursor | None = None


class Conversations(NamedTuple):
    channels: list[Channel]
    response_metadata: NextCursor | None = None


SlackEvent = (
    TopicChange|
    MessageDelete|
    MessageEdit|
    Message|
    ActionMessage|
    MessageBot|
    Join|
    Leave|
    GroupJoined|
    MpimJoined|
    UserTyping
)


class Autoreaction(NamedTuple):
    reaction: str
    probability: float
    expiration: float

    @property
    def expired(self) -> bool:
        if self.expiration == -1:
            return False
        return time() > self.expiration

    def random_reaction(self) -> bool:
        import random
        return random.random() < self.probability

    def __str__(self):
        return f'{self.reaction} at {self.probability * 100}%'


@dataclass
class SlackStatus:
    """
    Not related to the slack API.
    This is a structure used internally by this module to
    save the status on disk.
    """
    last_timestamp: float = 0.0
    autoreactions: dict[str, list[Autoreaction]] = field(default_factory=dict)
    annoy: dict[str, float] = field(default_factory=dict)


class Slack:
    def __init__(self, token: str, cookie: str | None, previous_status: bytes | None) -> None:
        """
        A slack client object.

        token: The slack token
        cookie: If the slack instance also uses a cookie, it must be passed here
        previous_status: Opaque bytestring to restore internal status
                from a different object. Obtained from get_status()
        """
        self.client = SlackClient(token, cookie)
        self._usercache: dict[str, User] = {}
        self._usermapcache: dict[str, User] = {}
        self._imcache: dict[str, str] = {}
        self._channelscache: list[Channel] = []
        self._joinedchannelscache: list[Channel] = []
        self._get_members_cache: dict[str, set[str]] = {}
        self._get_members_cache_cursor: dict[str, str | None] = {}
        self._internalevents: list[SlackEvent] = []
        self._sent_by_self: set[float] = set()
        self._wsblock: int = 0 # Semaphore to block the socket and avoid events being received before their API call ended.
        self.login_info: LoginInfo | None = None
        self.loader = dataloader.Loader()

        if previous_status is None:
            self._status = SlackStatus()
        else:
            self._status = self.tload(json.loads(previous_status), SlackStatus)

    def close(self):
        del self.client

    def tload(self, data: Any, type_: Type[T]) -> T:
        return self.loader.load(data, type_)

    async def login(self) -> None:
        """
        Set the login_info field
        """
        log('Login in slack')
        self.login_info = await self.client.login(15)

    async def get_history(self, channel: Channel|IM|str, ts: str, cursor: NextCursor | None=None, limit: int=1000, inclusive: bool=False) -> History:
        p = await self.client.api_call(
            'conversations.history',
            channel=channel if isinstance(channel, str) else channel.id,
            oldest=ts,
            limit=limit,
            cursor=cursor.next_cursor if cursor else None,
            inclusive=inclusive,
        )
        return self.tload(p, History)

    async def _thread_history(self, channel: str, thread_id: str) -> list[HistoryMessage|HistoryBotMessage]:
        r: list[HistoryMessage|HistoryBotMessage] = []
        cursor = None
        log('Thread history', channel, thread_id)
        while True:
            log('Cursor')
            p = await self.client.api_call(
                'conversations.replies',
                channel=channel,
                ts=thread_id,
                limit=1000,
                cursor=cursor,
            )
            try:
                response = self.tload(p, History)
            except Exception as e:
                    log('Failed to parse', e)
                    log(p)
                    break
            r += [i for i in response.messages if i.ts != i.thread_ts]
            if response.has_more and response.response_metadata:
                cursor = response.response_metadata.next_cursor
            else:
                break
        log('Thread fetched')
        r[0].thread_ts = None
        return r

    async def _history(self) -> None:
        '''
        Obtain the history from the last known event and
        inject fake events as if the messages are coming now.
        '''
        if self._status.last_timestamp == 0:
            log('No last known timestamp. Unable to fetch history')
            return

        log('Fetching history...')

        last_timestamp = self._status.last_timestamp
        FOUR_DAYS = 60 * 60 * 24 * 4
        if time() - last_timestamp > FOUR_DAYS:
            log('Last timestamp is too old. Defaulting to 4 days.')
            last_timestamp = time() - FOUR_DAYS
        try:
            dt = datetime.datetime.fromtimestamp(last_timestamp)
        except ValueError:
            log(f'Unable to parse timestamp {last_timestamp}')
            return
        log(f'Last known timestamp {dt}')

        chats: Sequence[IM|Channel] = []
        chats += await self.channels() + await self.get_ims()  # type: ignore
        for channel in chats:
            if isinstance(channel, Channel):
                if not channel.is_member:
                    continue

                log(f'Downloading logs from channel {channel.name_normalized}')
            else:
                log(f'Downloading logs from IM {channel.user}')

            cursor = None
            while True: # Loop to iterate the cursor
                log('Calling cursor')
                try:
                    response = await self.get_history(channel, str(last_timestamp))
                except Exception as e:
                    log('Failed to parse', e)
                    break
                msg_list = list(response.messages)
                while msg_list:
                    msg = msg_list.pop(0)

                    # The last seen message is sent again, skip it
                    if msg.ts == last_timestamp:
                        continue
                    # Update the last seen timestamp
                    if self._status.last_timestamp < msg.ts:
                        self._status.last_timestamp = msg.ts

                    # History for the thread
                    if msg.thread_ts and float(msg.thread_ts) == msg.ts:
                        l = await self._thread_history(channel.id, msg.thread_ts)
                        l.reverse()
                        msg_list = l + msg_list
                        continue

                    # Inject the events
                    if isinstance(msg, HistoryMessage):
                        self._internalevents.append(Message(
                            channel=channel.id,
                            text=msg.text,
                            user=msg.user,
                            thread_ts=msg.thread_ts,
                            files=[i for i in msg.files if isinstance(i, File)],
                            ts=msg.ts,
                        ))
                    elif isinstance(msg, HistoryBotMessage):
                        self._internalevents.append(MessageBot(
                            type='message', subtype='bot_message',
                            _text=msg.text,
                            attachments=msg.attachments,
                            username=msg.username,
                            channel=channel.id,
                            bot_id=msg.bot_id,
                            thread_ts=msg.thread_ts,
                        ))

                if response.has_more and response.response_metadata:
                    next_cursor = response.response_metadata.next_cursor
                    if next_cursor == cursor:
                        break
                    cursor = next_cursor
                else:
                    break

    def get_status(self) -> bytes:
        '''
        A status string that will be passed back when this is started again
        '''
        from typedload import dump
        return json.dumps(dump(self._status), ensure_ascii=True).encode('ascii')


    async def away(self, is_away: bool) -> None:
        """
        Forces the aways status or lets slack decide
        """
        status = 'away' if is_away else 'auto'
        r = await self.client.api_call('users.setPresence', presence=status)
        response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

    async def typing(self, channel: Channel|str) -> None:
        """
        Sends a typing event to slack
        """
        if isinstance(channel, Channel):
            ch_id = channel.id
        else:
            ch_id = channel
        await self.client.wspacket(type='typing', channel=ch_id)

    async def add_reaction(self, msg: Message, reaction: str) -> None:
        r = await self.client.api_call(
            'reactions.add',
            channel=msg.channel,
            timestamp=msg.ts,
            name=reaction,
        )
        response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

    async def add_annoy(self, username, expiration: float) -> None:
        user_id = (await self.get_user_by_name(username)).id
        self._status.annoy[user_id] = expiration

    async def drop_annoy(self, username: str) -> None:
        user_id = (await self.get_user_by_name(username)).id
        del self._status.annoy[user_id]

    async def drop_autoreact(self, username: str) -> None:
        user_id = (await self.get_user_by_name(username)).id
        del self._status.autoreactions[user_id]

    async def get_annoy(self) -> list[str]:
        r = []
        for i in self._status.annoy.keys():
            try:
                u = await self.get_user(i)
                r.append(u.name)
            except KeyError:
                # The user is gone, expire it
                self._status.annoy[i] = 1
        r.sort()
        return r

    async def get_autoreact(self) -> dict[str, list[Autoreaction]]:
        return {(await self.get_user(k)).name: v for k, v in self._status.autoreactions.items()}

    async def add_autoreact(self, username: str, reaction: str, probability: float, expiration: float) -> None:

        if probability > 1 or probability < 0:
            raise ValueError(f'Probability must be comprised between 0 and 1')
        user_id = (await self.get_user_by_name(username)).id

        a = Autoreaction(
            reaction=reaction,
            probability=probability,
            expiration=expiration,
        )

        if a.expired:
            raise ValueError('Expired')

        if user_id not in self._status.autoreactions:
            self._status.autoreactions[user_id] = []
        self._status.autoreactions[user_id].append(a)

    async def _annoy(self, typing: UserTyping) -> None:
        if typing.user not in self._status.annoy:
            return
        expiration = self._status.annoy[typing.user]
        if expiration > 0 and time() > expiration:
            del self._status.annoy[typing.user]
        await self.typing(typing.channel)

    async def _autoreact(self, msg: Message) -> None:
        for i in (rlist := self._status.autoreactions.get(msg.user, [])):
            # Clean up
            if i.expired:
                rlist.remove(i)
                return

            if i.random_reaction():
                try:
                    await self.add_reaction(msg, i.reaction)
                except:
                    # Remove reactions that fail
                    rlist.remove(i)
                    return

    async def topic(self, channel: Channel, topic: str) -> None:
        r = await self.client.api_call('conversations.setTopic', channel=channel.id, topic=topic)
        response: Response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

    async def kick(self, channel: Channel, user: User) -> None:
        r = await self.client.api_call('conversations.kick', channel=channel.id, user=user.id)
        response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

    async def join(self, channel: Channel) -> None:
        r = await self.client.api_call('conversations.join', channel=channel.id)
        response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

    async def invite(self, channel: Channel, user: User|list[User]) -> None:
        if isinstance(user, User):
            ids = user.id
        else:
            if len(user) > 30:
                raise ValueError('No more than 30 users allowed')
            ids = ','.join(i.id for i in user)

        r = await self.client.api_call('conversations.invite', channel=channel.id, users=ids)
        response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

    async def get_members(self, channel: str|Channel) -> set[str]:
        """
        Returns the list (as a set) of users in a channel.

        It performs caching. Every time the function is called, a new batch is
        requested, until all the users are cached, and then no new requests
        are performed, and the same data is returned.

        When events happen, the cache needs to be updated or cleared.
        """
        if isinstance(channel, Channel):
            id_ = channel.id
        else:
            id_ = channel

        cached = self._get_members_cache.get(id_, set())
        cursor = self._get_members_cache_cursor.get(id_)
        if cursor == '':
            # The cursor is fully iterated
            return cached
        kwargs = {}
        if cursor:
            kwargs['cursor'] = cursor
        r = await self.client.api_call('conversations.members', channel=id_, limit=5000, **kwargs)  # type: ignore
        response = self.tload(r, Response)
        if not response.ok:
            raise ResponseException(response.error)

        newusers = self.tload(r['members'], set[str])

        # Generate all the Join events, if this is not the 1st iteration
        if id_ in self._get_members_cache:
            for i in newusers.difference(cached):
                self._internalevents.append(Join('member_joined_channel', user=i, channel=id_))

        self._get_members_cache[id_] = cached.union(newusers)
        self._get_members_cache_cursor[id_] = r.get('response_metadata', {}).get('next_cursor')
        return self._get_members_cache[id_]

    async def channels(self, refresh: bool = False) -> list[Channel]:
        """
        Returns the list of all slack channels

        if refresh is set, the local cache is cleared

        This is prone to fail due to being rate limited.
        """
        try:
            return await self._list_channels('conversations.list', refresh, self._channelscache)
        except Exception:
            # Best effort, if it failed due to rate limit, just return what
            # we have got so far and move on.
            return self._channelscache

    async def joined_channels(self, refresh: bool = False) -> list[Channel]:
        """
        Returns the list of joined slack channels

        if refresh is set, the local cache is cleared
        """
        return await self._list_channels('users.conversations', refresh, self._joinedchannelscache)


    async def _list_channels(self, method: str, refresh: bool, cacheobj: list[Channel]) -> list[Channel]:
        if refresh:
            cacheobj.clear()

        if cacheobj:
            return cacheobj

        cursor = None
        while True:
            r = await self.client.api_call(
                method,
                cursor=cursor,
                exclude_archived=True,
                types='public_channel,private_channel,mpim',
                limit=1000, # In vain hope that slack would not ignore this
            )
            response = self.tload(r, Response)

            if response.ok:
                conv = self.tload(r, Conversations)
                cacheobj += conv.channels
                # For this API, slack sends an empty string as next cursor, just to show off their programming "skillz"
                if not conv.response_metadata or not conv.response_metadata.next_cursor:
                    break
                cursor = conv.response_metadata.next_cursor
            else:
                raise ResponseException(response.error)
        return cacheobj

    async def get_channel(self, id_: str) -> Channel:
        """
        Returns a channel object from a slack channel id

        raises KeyError if it doesn't exist.
        """
        for i in range(2):
            for c in await self.joined_channels(refresh=bool(i)):
                if c.id == id_:
                    return c
        # Failed, we try all the channels
        for i in range(2):
            for c in await self.channels(refresh=bool(i)):
                if c.id == id_:
                    return c
        raise KeyError()

    async def get_channel_by_name(self, name: str) -> Channel:
        """
        Returns a channel object from a slack channel id

        raises KeyError if it doesn't exist.
        """
        for i in range(2):
            for c in await self.joined_channels(refresh=bool(i)):
                if c.name == name:
                    return c
        # Failed, we try all the channels
        for i in range(2):
            for c in await self.channels(refresh=bool(i)):
                if c.name == name:
                    return c
        raise KeyError()

    async def get_thread(self, thread_ts: str, original_channel: str) -> MessageThread:
        """
        Creates a fake channel class for a chat thread
        """
        channel = (await self.get_channel(original_channel)).name_normalized

        # Get head message
        history = await self.get_history(original_channel, thread_ts, None, 1, True)

        msg = history.messages.pop()
        user = (await self.get_user(msg.user)).name if isinstance(msg, HistoryMessage) else 'bot'

        # Top message is a file
        if msg.text == '' and msg.files and isinstance(msg.files[0], File):
            f = msg.files[0]
            original_txt = f'{f.title} {f.mimetype} {f.url_private}'
        else:
            original_txt = msg.text.strip().replace('\n', ' | ')

        t = Topic(f'{user} in {channel}: {original_txt}')
        return MessageThread(
            id=original_channel,
            name_normalized=f't-{channel}-{thread_ts}',
            purpose=t,
            topic=t,
            thread_ts=thread_ts,
        )

    async def get_im(self, im_id: str) -> IM | None:
        if not im_id.startswith('D'):
            return None
        for uid, imid in self._imcache.items():
            if im_id == imid:
                return IM(user=uid, id=imid, is_user_deleted=False)

        for im in await self.get_ims():
            self._imcache[im.user] = im.id
            if im.id == im_id:
                return im;
        return None

    async def get_ims(self) -> list[IM]:
        """
        Returns a list of the IMs

        Some bullshit slack invented because 1 to 1 conversations
        need to have an ID to send to, you can't send directly to
        a user.
        """
        r = await self.client.api_call(
            "conversations.list",
            exclude_archived=True,
            types='im', limit=1000
        )
        response = self.tload(r, Response)
        if response.ok:
            return [i for i in self.tload(r['channels'], list[IM]) if not i.is_user_deleted]
        raise ResponseException(response.error)

    async def get_user_by_name(self, name: str) -> User:
        return self._usermapcache[name]

    async def prefetch_users(self) -> None:
        """
        Prefetch all team members for the slack team.
        """
        r = await self.client.api_call("users.list")
        response = self.tload(r, Response)
        if response.ok:
            for user in self.tload(r['members'], list[User]):
                self._usercache[user.id] = user
                self._usermapcache[user.name] = user

    async def get_user(self, id_: str) -> User:
        """
        Returns a user object from a slack user id

        raises KeyError if it does not exist
        """
        if id_ in self._usercache:
            return self._usercache[id_]

        r = await self.client.api_call("users.info", user=id_)
        response = self.tload(r, Response)
        if response.ok:
            u = self.tload(r['user'], User)
            self._usercache[id_] = u
            self._usermapcache[u.name] = u
            return u
        else:
            raise KeyError(response)

    async def send_file(self, channel_id: str, filename: str, content: bytes, thread_ts: str | None) -> None:
        """
        Send a file to a channel or group or whatever.

        Otherwise filename is just used to give a name to the file on slack.
        """
        import io
        f=io.BytesIO(content)
        f.name = filename
        r = await self.client.api_call(
            'files.upload',
            channels=channel_id,
            thread_ts=thread_ts,
            file=f,
        )
        response = self.tload(r, Response)
        if response.ok:
            return
        raise ResponseException(response.error)

    def _triage_sent_by_self(self) -> None:
        """
        Clear all the old leftovers in
        _sent_by_self
        """
        r = []
        for i in self._sent_by_self:
            if time() - i >= 10:
                r.append(i)
        for i in r:
            self._sent_by_self.remove(i)

    async def send_message(self, channel: Channel|MessageThread, msg: str, action: bool, re_send_to_irc: bool) -> None:
        thread_ts = channel.thread_ts if isinstance(channel, MessageThread) else None
        return await self._send_message(channel.id, msg, action, thread_ts, re_send_to_irc)

    async def _send_message(self, channel_id: str, msg: str, action: bool, thread_ts: str | None, re_send_to_irc: bool) -> None:
        """
        Send a message to a channel or group or whatever

        action must be true for /me messages

        thread_ts must be set to reply in a thread

        re_send_to_irc, if true the message will be forwarded to the IRC client
        as if it was sent via a different client.
        """
        if action:
            api = 'chat.meMessage'
        else:
            api = 'chat.postMessage'

        try:
            kwargs = {}

            if thread_ts:
                kwargs['thread_ts'] = thread_ts

            self._wsblock += 1
            r = await self.client.api_call(
                api,
                channel=channel_id,
                text=msg,
                as_user=True,
                **kwargs,  # type: ignore
            )
            response = self.tload(r, Response)
            if response.ok and response.ts and not re_send_to_irc:
                self._sent_by_self.add(response.ts)
                return
            raise ResponseException(response.error)
        finally:
            self._wsblock -= 1

    async def send_message_to_user(self, user: User, msg: str, action: bool, re_send_to_irc: bool):
        """
        Send a message to a user, pass the user id
        """

        # 1 to 1 chats are like channels, but use a dedicated API,
        # so to deliver a message to them, a channel id is required.
        # Those are called IM.

        if user.id in self._imcache:
            # channel id is cached
            channel_id = self._imcache[user.id]
        else:
            # If the conversation is not in cache, reopen it
            # It is faster than querying the list of conversations
            # anyway
            r = await self.client.api_call(
                "conversations.open",
                prevent_creation=False,
                users=user.id,
            )
            response = self.tload(r, Response)
            if not response.ok:
                raise ResponseException(response.error)
            channel_id = r['channel']['id']

            self._imcache[user.id] = channel_id

        await self._send_message(channel_id, msg, action, None, re_send_to_irc)

    async def event(self) -> SlackEvent | None:
        """
        This returns the events from the slack websocket
        """
        if self._internalevents:
            return self._internalevents.pop()

        try:
            events = await self.client.rtm_read()
        except Exception:
            log('Connecting to slack...')
            self.login_info = await self.client.rtm_connect(5)
            await self._history()
            log('Connected to slack')
            return None

        while self._wsblock: # Retry until the semaphore is free
            await asyncio.sleep(0.01)

        for event in events:
            t = event.get('type')
            ts = float(event.get('ts', 0))

            if ts > self._status.last_timestamp:
                self._status.last_timestamp = ts

            if t in USELESS_EVENTS:
                continue

            debug(event)
            loadable_events = TopicChange|MessageBot|MessageEdit|MessageDelete|GroupJoined|Join|Leave|UserTyping|MpimJoined
            try:
                ev: loadable_events | None = self.tload(
                    event,
                    loadable_events  # type: ignore
                )
            except Exception:
                ev = None

            if isinstance(ev, (Join, Leave)) and ev.channel in self._get_members_cache:
                if isinstance(ev, Join):
                    self._get_members_cache[ev.channel].add(ev.user)
                else:
                    self._get_members_cache[ev.channel].discard(ev.user)
            elif isinstance(ev, UserTyping):
                await self._annoy(ev)
                continue

            if ev:
                return ev

            subt = event.get('subtype')

            try:
                if t == 'message' and (not subt or subt == 'me_message'):
                    msg = self.tload(event, Message)

                    # In private chats, pretend that my own messages
                    # sent from another client actually come from
                    # the other user, and prepend them with "I say: "
                    im = await self.get_im(msg.channel)
                    if im and im.user != msg.user:
                        msg = Message(user=im.user, text='I say: ' + msg.text, channel=im.id, thread_ts=msg.thread_ts, ts=msg.ts)

                    await self._autoreact(msg)

                    if ts in self._sent_by_self:
                        self._sent_by_self.remove(ts)
                        continue

                    if subt == 'me_message':
                        return ActionMessage(*msg)  # type: ignore
                    else:
                        return msg
                elif t == 'message' and subt == 'slackbot_response':
                    return self.tload(event, Message)
                elif t == 'user_change':
                    # Changes in the user, drop it from cache
                    u = self.tload(event['user'], User)
                    if u.id in self._usercache:
                        del self._usercache[u.id]
                        #FIXME don't know if it is wise, maybe it gets lost forever del self._usermapcache[u.name]
                    #TODO make an event for this
                else:
                    log(event)
            except Exception as e:
                log('Exception: %s' % e)
            self._triage_sent_by_self()
        return None
0707010000002B000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003600000000localslackirc-1.33+git.1739989938.1a93818/slackclient0707010000002C000081A400000000000000000000000167B623B200000020000000000000000000000000000000000000004200000000localslackirc-1.33+git.1739989938.1a93818/slackclient/__init__.pyfrom .client import SlackClient
0707010000002D000081A400000000000000000000000167B623B2000016D2000000000000000000000000000000000000004000000000localslackirc-1.33+git.1739989938.1a93818/slackclient/client.py# localslackirc
# Copyright (C) 2018-2021 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
#
# This file was part of python-slackclient
# (https://github.com/slackapi/python-slackclient)
# But has been copied and relicensed under GPL. The copyright applies only
# to the changes made since it was copied.

import asyncio
import json
from typing import Any, NamedTuple, Optional

from typedload import load
from websockets.asyncio.client import connect as wsconnect, ClientConnection

from .exceptions import *
from .http import Request


class Team(NamedTuple):
    id: str
    name: str
    domain: str


class Self(NamedTuple):
    id: str
    name: str


class LoginInfo(NamedTuple):
    team: Team
    self: Self
    url: str


class SlackClient:
    """
    The SlackClient object owns the websocket connection and all attached channel information.
    """

    def __init__(self, token: str, cookie: Optional[str]) -> None:
        # Slack client configs
        self._token = token
        self._cookie = cookie

        # RTM configs
        self._websocket: Optional[ClientConnection] = None
        self._request = Request('https://slack.com/api/')
        self._wsid = 0

    async def wspacket(self, **kwargs) -> None:
        """
        Send data over websocket
        """
        if self._websocket is None:
            raise Exception('No websocket at this point')
        kwargs['id'] = self._wsid
        self._wsid += 1
        await self._websocket.send(json.dumps(kwargs))

    def __del__(self):
        try:
            asyncio.get_running_loop()
            loop = True
        except RuntimeError:
            loop = False

        if self._websocket and loop:
            asyncio.create_task(self._websocket.close())

    async def _do(self, request: str, post_data: dict[str, Any], timeout: float):
        """
        Perform a POST request to the Slack Web API

        Args:
            request (str): the method to call from the Slack API. For example: 'channels.list'
            timeout (float): stop waiting for a response after a given number of seconds
            post_data (dict): key/value arguments to pass for the request. For example:
                {'channel': 'CABC12345'}
        """
        # Set user-agent and auth headers
        headers = {
            'user-agent': 'localslackirc',
            'Authorization': f'Bearer {self._token}'
        }
        if self._cookie:
            headers['cookie'] = self._cookie

        return await self._request.post(request, headers, post_data, timeout)

    async def login(self, timeout: float = 0.0) -> LoginInfo:
        """
        Performs a login to slack.
        """
        reply = await self._do('rtm.connect', {}, timeout=timeout)
        if reply.status != 200:
            raise SlackConnectionError("RTM connection attempt failed")
        login_data = reply.json()
        if not login_data["ok"]:
            raise SlackLoginError(reply=login_data)
        return load(login_data, LoginInfo)

    async def rtm_connect(self, timeout: float = 0.0) -> LoginInfo:
        """
        Connects to the RTM API - https://api.slack.com/rtm
        :Args:
            timeout: in seconds
        """
        r = await self.login(timeout=timeout)
        headers = {
            'user-agent': 'localslackirc',
            'Authorization': f'Bearer {self._token}',
        }
        if self._cookie:
            headers['cookie'] = self._cookie
        self._websocket = await wsconnect(r.url, close_timeout=0.2, additional_headers=headers)
        return r


    async def api_call(self, method: str, timeout: float = 0.0, **kwargs) -> dict[str, Any]:
        """
        Call the Slack Web API as documented here: https://api.slack.com/web

        :Args:
            method (str): The API Method to call. See here for a list: https://api.slack.com/methods
        :Kwargs:
            (optional) timeout: stop waiting for a response after a given number of seconds
            (optional) kwargs: any arguments passed here will be bundled and sent to the api
            requester as post_data
                and will be passed along to the API.

        Example::
            sc.server.api_call(
                "channels.setPurpose",
                channel="CABC12345",
                purpose="Writing some code!"
            )

        Returns:
            str -- returns HTTP response text and headers as JSON.

            Examples::

                u'{"ok":true,"purpose":"Testing bots"}'
                or
                u'{"ok":false,"error":"channel_not_found"}'

            See here for more information on responses: https://api.slack.com/web
        """
        response = await self._do(method, kwargs, timeout)
        response_json = response.json()
        response_json["headers"] = dict(response.headers)
        return response_json

    async def rtm_read(self) -> list[dict[str, Any]]:
        assert self._websocket
        json_data: str = await self._websocket.recv()  # type: ignore
        data = []
        if json_data != '':
            for d in json_data.split('\n'):
                data.append(json.loads(d))
        return data
0707010000002E000081A400000000000000000000000167B623B2000006BD000000000000000000000000000000000000004400000000localslackirc-1.33+git.1739989938.1a93818/slackclient/exceptions.py# localslackirc
# Copyright (C) 2018-2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>
#
# This file was part of python-slackclient
# (https://github.com/slackapi/python-slackclient)
# But has been copied and relicensed under GPL. The copyright applies only
# to the changes made since it was copied.

class SlackClientError(Exception):
    """
    Base exception for all errors raised by the SlackClient library
    """
    def __init__(self, msg: str) -> None:
        super(SlackClientError, self).__init__(msg)

    def __str__(self) -> str:
        reply = getattr(self, 'reply', None)
        msg = getattr(self, 'msg', None)
        return f'message={msg} reply={reply}'


class SlackConnectionError(SlackClientError):
    def __init__(self, message='', reply=None) -> None:
        super(SlackConnectionError, self).__init__(message)
        self.reply = reply


class SlackLoginError(SlackClientError):
    def __init__(self, message='', reply=None) -> None:
        super(SlackLoginError, self).__init__(message)
        self.reply = reply
0707010000002F000081A400000000000000000000000167B623B200001BE7000000000000000000000000000000000000003E00000000localslackirc-1.33+git.1739989938.1a93818/slackclient/http.py# localslackirc
# Copyright (C) 2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import asyncio
import gzip
import json
from typing import Optional, NamedTuple, Any
from uuid import uuid1
from urllib import parse


def multipart_form(form_fields: dict[str, Any]) -> tuple[str, bytes]:
    """
    Convert a dictionary to post data and returns relevant headers.

    The dictionary can contain values as open files, or anything else.
    None values are skipped.
    Anything that is not an open file is cast to str
    """
    data = {}
    has_files = False
    for k, v in form_fields.items():
        if v is not None:
            data[k] = v
        if hasattr(v, 'read') and hasattr(v, 'name'):
            has_files = True

    if not has_files:
        return (
            'Content-Type: application/x-www-form-urlencoded\r\n',
            parse.urlencode(data).encode('ascii')
        )

    boundary = str(uuid1()).encode('ascii')

    form_data = b''
    for k, v in data.items():
        form_data += b'--' + boundary + b'\r\n'
        if hasattr(v, 'read') and hasattr(v, 'name'):
            form_data += f'Content-Disposition: form-data; name="{k}"; filename="{v.name}"\r\n'.encode('ascii')
            form_data += b'\r\n' + v.read() + b'\r\n'
        else:
            strv = str(v)
            form_data += f'Content-Disposition: form-data; name="{k}"\r\n'.encode('ascii')
            form_data += b'\r\n' + strv.encode('ascii') + b'\r\n'

    form_data += b'--' + boundary + b'\r\n'

    header = f'Content-Type: multipart/form-data; boundary={boundary.decode("ascii")}\r\n'
    return header, form_data


class Response(NamedTuple):
    status: int
    headers: dict[str, str]
    data: bytes

    def json(self):
        return json.loads(self.data)


class Request:
    def __init__(self, base_url: str) -> None:
        """https://slack.com/api/
        In my case, base_url is "https://slack.com/api/"
        """
        self.base_url = parse.urlsplit(base_url)
        if self.base_url.scheme == 'https':
            self.ssl = True
            self.port = 443
        else:
            self.ssl = False
            self.port = 80

        # Override port if explicitly defined
        if self.base_url.port:
            self.port = self.base_url.port
        self.hostname = self.base_url.hostname
        self.path = self.base_url.path
        self._connections: dict[str, tuple[asyncio.streams.StreamReader, asyncio.streams.StreamWriter]] = {}

    def __del__(self):
        for i in self._connections.values():
            i[1].close()

    async def _connect(self) -> tuple[asyncio.streams.StreamReader, asyncio.streams.StreamWriter]:
        """
        Get a connection.

        It can be an already cached one or a new one.
        """
        task = asyncio.tasks.current_task()
        assert task is not None # Mypy doesn't notice this is in an async
        key = task.get_name()

        r = self._connections.get(key)

        if r is None:
            r = await asyncio.open_connection(self.hostname, self.port, ssl=self.ssl)
            self._connections[key] = r
        return r

    async def post(self, path: str, headers: dict[str, str], data: dict[str,  Any], timeout: float=0) -> Response:
        """
        post a request.

        data will be sent as a form. Fields are converted to str, except for
        open files, which are read and sent. Open files must be opened in
        binary mode.

        Due to the possibility that the cached connection got closed, it will do
        one retry before raising the exception
        """
        try:
            return await self._post(path, headers, data, timeout)
        except (BrokenPipeError, ConnectionResetError, asyncio.IncompleteReadError):
            # Clear connection from pool
            task = asyncio.tasks.current_task()
            assert task is not None # Mypy doesn't notice this is in an async
            key = task.get_name()
            r, w = self._connections.pop(key)
            w.close()
            return await self._post(path, headers, data, timeout)

    async def _post(self, path: str, headers: dict[str, str], data: dict[str,  Any], timeout: float=0) -> Response:
        # Prepare request
        req = f'POST {self.path + path} HTTP/1.1\r\n'
        req += f'Host: {self.hostname}\r\n'
        req += 'Connection: keep-alive\r\n'
        req += 'Accept-Encoding: gzip\r\n'
        for k, v in headers.items():
            req += f'{k}: {v}\r\n'

        header, post_data = multipart_form(data)
        req += header
        req += f'Content-Length: {len(post_data)}\r\n'
        req += '\r\n'

        # Send request
        # 1 retry in case the keep alive connection was closed
        reader, writer = await self._connect()
        writer.write(req.encode('ascii'))
        writer.write(post_data)
        await writer.drain()

        # Read response
        line = await reader.readline()
        if len(line) == 0:
            raise BrokenPipeError()
        try:
            status = int(line.split(b' ')[1])
        except Exception as e:
            raise Exception(f'Invalid data {line!r} {e}')

        # Read headers
        headers = {}
        while True:
            line = await reader.readline()
            if line == b'\r\n':
                break
            elif len(line) == 0:
                raise BrokenPipeError()
            k, v = line.decode('ascii').split(':', 1)
            headers[k.lower()] = v.strip()

        # Read data
        read_data = b''
        if headers.get('transfer-encoding') == 'chunked':
            while True:
                line = await reader.readline()
                if len(line) == 0:
                    raise BrokenPipeError()
                if not line.endswith(b'\r\n'):
                    raise Exception('Unexpected end of chunked data')
                size = int(line, 16)
                read_data += (await reader.readexactly(size + 2))[:-2]
                if size == 0:
                    break
        elif 'content-length' in headers:
            size = int(headers['content-length'])
            read_data = await reader.readexactly(size)
        else:
            raise NotImplementedError('Can only handle chunked or content length' + repr(headers))

        # decompress if needed
        if headers.get('content-encoding') == 'gzip':
            read_data = gzip.decompress(read_data)
        return Response(status, headers, read_data)
07070100000030000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003200000000localslackirc-1.33+git.1739989938.1a93818/systemd07070100000031000081A400000000000000000000000167B623B20000046B000000000000000000000000000000000000004800000000localslackirc-1.33+git.1739989938.1a93818/systemd/localslackirc.service# localslackirc
# Copyright (C) 2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

# systemd service for managing all localslackirc instances on the system. This
# service is actually a systemd target, but we are using a service since
# targets cannot be reloaded.

[Unit]
Description=Localslackirc
Documentation=man:localslackirc(1)

[Service]
Type=oneshot
ExecStart=/bin/true
ExecReload=/bin/true
RemainAfterExit=on

[Install]
WantedBy=multi-user.target
07070100000032000081A400000000000000000000000167B623B200000673000000000000000000000000000000000000004900000000localslackirc-1.33+git.1739989938.1a93818/systemd/localslackirc@.service# localslackirc
# Copyright (C) 2020-2023 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

[Install]
WantedBy=multi-user.target

[Unit]
Description=Localslackirc
Documentation=man:localslackirc(1)
AssertPathExists=/etc/localslackirc.d/%i
PartOf=localslackirc.service
ReloadPropagatedFrom=localslackirc.service
Before=localslackirc.service

[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/localslackirc --status-file ${STATE_DIRECTORY}/localslackirc-status-%i --log-suffix %i --control-socket ${RUNTIME_DIRECTORY}/localslackirc-%i.sock
# Using the same mode as /tmp so that after changing uid a control socket can still be created
RuntimeDirectory=localslackirc
RuntimeDirectoryMode=1777
StateDirectory=localslackirc
StateDirectoryMode=1777
# Log
StandardOutput=journal
StandardError=journal
SyslogIdentifier=localslackirc-%i
# Config
EnvironmentFile=/etc/localslackirc.d/%i
# Security
ProtectSystem=strict
ReadWritePaths=/var/tmp
PrivateDevices=true
LockPersonality=true
07070100000033000041ED00000000000000000000000267B623B200000000000000000000000000000000000000000000003000000000localslackirc-1.33+git.1739989938.1a93818/tests07070100000034000081A400000000000000000000000167B623B200000000000000000000000000000000000000000000003C00000000localslackirc-1.33+git.1739989938.1a93818/tests/__init__.py07070100000035000081A400000000000000000000000167B623B2000003C6000000000000000000000000000000000000003C00000000localslackirc-1.33+git.1739989938.1a93818/tests/__main__.py# localslackirc
# Copyright (C) 2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import unittest

from .test_diff import *
from .test_executable import *
from .test_message_bot import *
from .test_irc import *
from .test_msgparsing import *

if __name__ == '__main__':
    unittest.main()
07070100000036000081A400000000000000000000000167B623B200000AAE000000000000000000000000000000000000003D00000000localslackirc-1.33+git.1739989938.1a93818/tests/test_diff.py# localslackirc
# Copyright (C) 2020-2021 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import unittest

from diff import seddiff


class TestDiff(unittest.TestCase):

    def test_no_crash(self):
        seddiff('', 'lalala')
        seddiff('lalala', 'lalala')
        seddiff('lalala', '')
        seddiff('lalala', 'lalala allelolela')
        seddiff('lalala allelolela', 'allelolela')
        seddiff('lalala allelolela', 'lalala')

    def test_no_diff(self):
        assert seddiff('ciao', 'ciao') == ''
        assert seddiff('', '') == ''
        assert seddiff('la la', 'la la') == ''

    def test_full_replace(self):
        assert seddiff('vado al mare', 'dormo la sera') == 's/vado al mare/dormo la sera/'
        assert seddiff('ciae å tuttï', 'ciao a tutti') == 's/ciae å tuttï/ciao a tutti/'

    def test_partials(self):
        assert seddiff('vado a dormire al mare', 'vado a nuotare al mare') == 's/dormire/nuotare/'
        assert seddiff('ciae a tutti', 'ciao a tutti') == 's/ciae/ciao/'
        assert seddiff('ciae å tutti', 'ciao a tutti') == 's/ciae å/ciao a/'

    def test_with_ltgt(self):
        assert seddiff('Optional<IntegerZ>', 'Optional<Integer>') == 's/Optional<IntegerZ>/Optional<Integer>/'
        assert seddiff('`Optional<IntegerZ>`', '`Optional<Integer>`') == 's/`Optional<IntegerZ>`/`Optional<Integer>`/'

    def test_insertion(self):
        assert seddiff('il numero dei fili', 'il numero massimo dei fili') == 's/numero dei/numero massimo dei/'
        assert seddiff('mangio del formaggio e pere', 'mangio del formaggio con le pere') == 's/formaggio e pere/formaggio con le pere/'
        assert seddiff('mangio del formaggio e pere per cena', 'mangio del formaggio con le pere per cena') == 's/formaggio e pere/formaggio con le pere/'
        assert seddiff('mare blu', 'il mare blu') == 's/mare/il mare/'
        assert seddiff('mare, blu', 'il mare, blu') == 's/mare/il mare/'

    def test_append(self):
        assert seddiff('XYZ', 'XYZ (meaning "bla bla bla")') == 's/$/(meaning "bla bla bla")/'
07070100000037000081A400000000000000000000000167B623B20000046F000000000000000000000000000000000000004300000000localslackirc-1.33+git.1739989938.1a93818/tests/test_executable.py# localslackirc
# Copyright (C) 2020 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# author Salvo "LtWorf" Tomaselli <tiposchi@tiscali.it>

import os
import unittest
import subprocess


if os.path.exists("./localslackirc"):
    # inside source directory
    localslackirc = "./localslackirc"
else:
    # test installed program
    localslackirc = "localslackirc"


class TestStart(unittest.TestCase):

    def test_print_help(self):
        subprocess.check_call([localslackirc, '--help'], stdout=subprocess.DEVNULL)
07070100000038000081A400000000000000000000000167B623B20000109F000000000000000000000000000000000000003C00000000localslackirc-1.33+git.1739989938.1a93818/tests/test_irc.py# localslackirc
# Copyright (C) 2021 Antonio Terceiro
# Copyright (C) 2022 Salvo "LtWorf" Tomaselli
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from unittest import IsolatedAsyncioTestCase, mock
from irc import Client, Provider

class TestIRC(IsolatedAsyncioTestCase):
    def setUp(self):
        stream_writer = mock.AsyncMock()
        slack_client = mock.AsyncMock()
        settings = mock.MagicMock()
        settings.silenced_yellers = set()
        settings.provider = Provider.SLACK
        self.client = Client(stream_writer, slack_client, settings)


class TestAnnoyanceAvoidance(TestIRC):
    async def test_yelling_prevention(self):
        self.client.nick = b'aldo'

        # Mention generated
        msg = await self.client.parse_message("<!here> watch this!", b'rose.adams',b'#asd')
        assert msg == 'yelling [aldo]: watch this!'

        # Add rose.adams to silenced yellers
        self.client.settings.silenced_yellers.add(b'rose.adams')

        # Mention no longer generated
        msg = await self.client.parse_message("<!here> watch this!", b'rose.adams', b'#asd')
        assert msg == 'yelling: watch this!'

        # No effect on regular messages
        msg = await self.client.parse_message("hello world", b'rose.adams', b'#asd')
        assert msg == 'hello world'


class TestParseMessage(TestIRC):
    async def test_simple_message(self):
        msg = await self.client.parse_message("hello world", b'ciccio', b'#asd')
        self.assertEqual(msg, "hello world")

    async def test_url(self):
        msg = await self.client.parse_message("See <https://example.com/docs/|the documentation>", b'ciccio', b'#asd')
        self.assertEqual(msg, "See the documentation¹\n  ¹ https://example.com/docs/")

    async def test_url_aggressive_shortening(self):
        msg = await self.client.parse_message("See <https://example.com/docs/iqjweoijsodijijaoij?oiwje|https://example.com/docs/iqjweoijsodijijaoij>", b'ciccio', b'#asd')
        self.assertEqual(msg, "See LINK¹\n  ¹ https://example.com/docs/iqjweoijsodijijaoij?oiwje")

    async def test_multiple_urls(self):
        msg = await self.client.parse_message("See <https://example.com/docs/|the documentation>. Try also the <https://example.com/faq/|FAQ>", b'ciccio', b'#asd')
        self.assertEqual(msg, "See the documentation¹. Try also the FAQ²\n  ¹ https://example.com/docs/\n  ² https://example.com/faq/")

    async def test_a_lot_of_urls(self):
        input_msg = "<https://example.com/|url> " * 10
        output = "\n".join([
            "url¹ url² url³ url⁴ url⁵ url⁶ url⁷ url⁸ url⁹ url¹⁰ ",
            "  ¹ https://example.com/",
            "  ² https://example.com/",
            "  ³ https://example.com/",
            "  ⁴ https://example.com/",
            "  ⁵ https://example.com/",
            "  ⁶ https://example.com/",
            "  ⁷ https://example.com/",
            "  ⁸ https://example.com/",
            "  ⁹ https://example.com/",
            "  ¹⁰ https://example.com/",
        ])
        msg = await self.client.parse_message(input_msg, b'ciccio', b'#asd')
        self.assertEqual(msg, output)

    async def test_url_with_no_label_just_goes_inline(self):
        msg = await self.client.parse_message("Please look at <https://example.com/>", b'ciccio', b'#asd')
        self.assertEqual(msg, "Please look at https://example.com/")

    async def test_replace_label_for_urls_with_no_different_text(self):
        msg = await self.client.parse_message("<https://example.com/|https://example.com/>", b'ciccio', b'#asd')
        self.assertEqual(msg, "LINK¹\n  ¹ https://example.com/")
07070100000039000081A400000000000000000000000167B623B200000A2A000000000000000000000000000000000000004400000000localslackirc-1.33+git.1739989938.1a93818/tests/test_message_bot.py# localslackirc
# Copyright (C) 2021 Antonio Terceiro
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from typedload import load
from slack import MessageBot

template = {
    "type": "message",
    "subtype": "bot_message",
    "text": "This is a message with attachments",
    "username": "BotExample",
    "channel": "XYZ123456",
    "bot_id": "ABC123456",
}


class TestMessageBot(unittest.TestCase):
    def test_without_attachments(self):
        event = template.copy()
        event.update({"text": "Message without attachments"})
        msg = load(event, MessageBot)
        self.assertEqual(msg.text, "Message without attachments")

    def test_message_with_attachments(self):
        event = template.copy()
        event.update({
            "attachments": [
                {"text": "First attachment"},
                {"text": "Second attachment"},
            ]
        })
        msg = load(event, MessageBot)
        assert (
            msg.text
            == "This is a message with attachments\n| First attachment\n| Second attachment"
        )

    def test_attachment_with_fallback(self):
        event = template.copy()
        event.update({
            "attachments": [
                {"fallback": "First attachment"},
                {"fallback": "Second attachment"},
            ],
        })
        msg = load(event, MessageBot)
        assert (
            msg.text
            == "This is a message with attachments\n| First attachment\n| Second attachment"
        )

    def test_multiline_attachment_text(self):
        event = template.copy()
        event.update({
            "attachments": [
                {"text": "code example:\n```\nprint('Hello world')\n```"},
            ]
        })
        msg = load(event, MessageBot)
        self.assertEqual(msg.text.split("\n"), [
            "This is a message with attachments",
            "| code example:",
            "| ```",
            "| print('Hello world')",
            "| ```"
        ])
0707010000003A000081A400000000000000000000000167B623B200000A7A000000000000000000000000000000000000004300000000localslackirc-1.33+git.1739989938.1a93818/tests/test_msgparsing.py# localslackirc
# Copyright (C) 2021 Antonio Terceiro
#
# localslackirc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest

from msgparsing import preblocks, split_tokens, SpecialItem, Itemkind, convertpre, tokenize, PreBlock


class TestMsgParsing(unittest.TestCase):

    def test_preblocks(self):
        assert list(preblocks('')) == [('', False)]
        assert list(preblocks('asd')) == [('asd', False)]
        assert list(preblocks('a ```a``` a')) == [('a ', False), ('a', True), (' a', False)]
        assert list(preblocks('```a``` a')) == [('', False), ('a', True), (' a', False)]
        assert list(preblocks('```a')) == [('', False), ('a', True)]

    def test_split_tokens(self):
        assert list(split_tokens('a b c d')) == ['a b c d']
        assert list(split_tokens('a <b> <c> d')) == ['a ', SpecialItem('<b>'), ' ', SpecialItem('<c>'), ' d']

    def test_special_item(self):
        c = SpecialItem('<@ciccio>')
        assert c.kind == Itemkind.MENTION
        assert c.human is None
        assert c.val == 'ciccio'

        c = SpecialItem('<http://ciccio|link>')
        assert c.kind == Itemkind.OTHER
        assert c.human == 'link'
        assert c.val == 'http://ciccio'

        c = SpecialItem('<#ciccio>')
        assert c.kind == Itemkind.CHANNEL
        assert c.human is None
        assert c.val == 'ciccio'

        c = SpecialItem('<!here>')
        assert c.kind == Itemkind.YELL
        assert c.human is None
        assert c.val == 'here'

    def test_convertpre(self):
        assert convertpre('asd') == 'asd'
        assert convertpre('asd <http://ciccio> &gt;') == 'asd http://ciccio >'
        assert convertpre(':coffin:') == ':coffin:'

    def test_tokenize(self):
        assert list(tokenize('a')) == ['a']
        assert list(tokenize('a ```ciao```')) == ['a ', PreBlock('ciao')]
        assert list(tokenize(':coffin:')) == ['⚰️']
        assert list(tokenize('&gt;')) == ['>']
        assert list(tokenize('a <b> <c> d ```<http://ciccio>```')) == ['a ', SpecialItem('<b>'), ' ', SpecialItem('<c>'), ' d ', PreBlock('http://ciccio')]
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!493 blocks
openSUSE Build Service is sponsored by