Initial commit (split from slidge core)
This commit is contained in:
commit
f0ffdaa0be
|
@ -0,0 +1,53 @@
|
|||
image: debian/bookworm
|
||||
packages:
|
||||
- curl
|
||||
- golang
|
||||
- python-is-python3
|
||||
- python3-dev
|
||||
- python3-pybindgen
|
||||
secrets:
|
||||
- 3ecea679-dec7-4ac0-8821-75d0f4fe0773
|
||||
- dc710d9d-8043-4e1d-9837-b35bfa02800a
|
||||
artifacts:
|
||||
- ./docs.tar.gz
|
||||
- ./package.tar.gz
|
||||
- ./package.whl
|
||||
tasks:
|
||||
- install-poetry: |
|
||||
curl -sSL https://install.python-poetry.org | python3 -
|
||||
sudo ln -s ~/.local/bin/poetry /usr/local/bin
|
||||
- set-project: |
|
||||
echo PROJECT=$(ls ~) >> ~/.buildenv
|
||||
echo MODULE=slidge_whatsapp >> ~/.buildenv
|
||||
- install: |
|
||||
cd slidge-whatsapp
|
||||
poetry install
|
||||
poetry run c3p0 slidge-whatsapp
|
||||
poetry run set_version
|
||||
poetry build
|
||||
cp dist/*.tar.gz ~/package.tar.gz
|
||||
cp dist/*.whl ~/package.whl
|
||||
- tests: |
|
||||
cd slidge-whatsapp
|
||||
poetry run ruff .
|
||||
poetry run mypy .
|
||||
poetry run pytest tests
|
||||
poetry run black --check .
|
||||
poetry run isort --check .
|
||||
- docs: |
|
||||
cd slidge-whatsapp/docs
|
||||
make html
|
||||
cd build/html
|
||||
tar cvzf ~/docs.tar.gz .
|
||||
- publish: |
|
||||
if [ -z "$PYPI" ]; then
|
||||
echo Not on master, not publishing
|
||||
exit
|
||||
fi
|
||||
|
||||
set +x
|
||||
export POETRY_PYPI_TOKEN_PYPI=$(cat ~/.pypi-token)
|
||||
set -x
|
||||
|
||||
cd $PROJECT
|
||||
poetry publish
|
|
@ -0,0 +1,28 @@
|
|||
image: alpine/3.17
|
||||
packages:
|
||||
- docker
|
||||
- docker-cli-buildx
|
||||
- python3
|
||||
- curl
|
||||
secrets:
|
||||
- 173244e1-c233-43de-969f-65965c5487e1
|
||||
environment:
|
||||
REGISTRY_PREFIX: docker.io/nicocool84
|
||||
SET_VERSION_URL: https://git.sr.ht/~nicoco/slidge-dev-helpers/blob/master/slidge_dev_helpers/set_version.py
|
||||
tasks:
|
||||
- version: |
|
||||
cd slidge-whatsapp
|
||||
curl -sSL $SET_VERSION_URL | python -
|
||||
- setup-docker1: |
|
||||
sudo service docker start
|
||||
sudo addgroup build docker
|
||||
- setup-docker2: |
|
||||
while ! test -e /var/run/docker.sock; do sleep 1; done
|
||||
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes -c yes
|
||||
docker buildx create --use
|
||||
- build: |
|
||||
cd slidge-whatsapp
|
||||
export NAME=$REGISTRY_PREFIX/slidge-whatsapp:$CONTAINER_TAG
|
||||
export ARGS="--platform linux/arm64,linux/amd64 --tag $NAME --target slidge-whatsapp ."
|
||||
docker buildx build $ARGS
|
||||
docker buildx build --push $ARGS || echo "We can't push to docker.io, continuing anyway"
|
|
@ -0,0 +1,45 @@
|
|||
image: alpine/3.17
|
||||
packages:
|
||||
- docker
|
||||
- docker-cli-buildx
|
||||
- poetry
|
||||
secrets:
|
||||
- 173244e1-c233-43de-969f-65965c5487e1
|
||||
- 3ecea679-dec7-4ac0-8821-75d0f4fe0773
|
||||
artifacts:
|
||||
- ./package.whl
|
||||
environment:
|
||||
SET_VERSION_URL: https://git.sr.ht/~nicoco/slidge-dev-helpers/blob/master/slidge_dev_helpers/set_version.py
|
||||
tasks:
|
||||
- set-project: |
|
||||
echo PROJECT=$(ls ~) >> ~/.buildenv
|
||||
- version: |
|
||||
cd $PROJECT
|
||||
curl -sSL $SET_VERSION_URL | python -
|
||||
- setup-docker1: |
|
||||
sudo service docker start
|
||||
sudo addgroup build docker
|
||||
- setup-docker2: |
|
||||
while ! test -e /var/run/docker.sock; do sleep 1; done
|
||||
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes -c yes
|
||||
docker buildx create --use
|
||||
- build: |
|
||||
cd $PROJECT
|
||||
docker buildx build . \
|
||||
--target wheel \
|
||||
-o ./dist/ \
|
||||
--platform linux/arm64
|
||||
cp ./dist/*.whl ~/package.whl
|
||||
- publish: |
|
||||
if [ -z "$PYPI" ]; then
|
||||
echo Not on master, not publishing
|
||||
exit
|
||||
fi
|
||||
|
||||
set +x
|
||||
export POETRY_PYPI_TOKEN_PYPI=$(cat ~/.pypi-token)
|
||||
set -x
|
||||
|
||||
cd $PROJECT
|
||||
|
||||
poetry publish
|
|
@ -0,0 +1,52 @@
|
|||
# Changes here will be overwritten by Copier; NEVER EDIT MANUALLY
|
||||
_commit: 5ac5e6f
|
||||
_src_path: git+https://git.sr.ht/~nicoco/slidge-template
|
||||
author: deuill
|
||||
author_email: [email protected]
|
||||
author_website: https://deuill.org
|
||||
dockerhub_username: nicocool84
|
||||
legacy_lib: whatsmeow
|
||||
legacy_lib_website: https://github.com/tulir/whatsmeow
|
||||
legacy_service: Whatsapp
|
||||
legacy_service_website: https://whatsapp.com
|
||||
module_name: slidge_whatsapp
|
||||
project_name: slidge-whatsapp
|
||||
python_version: '3.9'
|
||||
srht_secret_c3p0: dc710d9d-8043-4e1d-9837-b35bfa02800a
|
||||
srht_secret_docker: 173244e1-c233-43de-969f-65965c5487e1
|
||||
srht_secret_pypi: 3ecea679-dec7-4ac0-8821-75d0f4fe0773
|
||||
srht_username: nicoco
|
||||
xeps:
|
||||
- note: Participating in groups work, but creation/deletion/moderation is not yet
|
||||
possible from slidge.
|
||||
number: 45
|
||||
status: partial
|
||||
- note: Typing notifications only.
|
||||
number: 85
|
||||
status: complete
|
||||
- note: Whatsapp has proper recipient-generated delivery receipts, and slidge supports
|
||||
them.
|
||||
number: 184
|
||||
status: complete
|
||||
- note: Only available if you chose to share your presence info in the Whatsapp
|
||||
app.
|
||||
number: 256
|
||||
status: complete
|
||||
- note: null
|
||||
number: 308
|
||||
status: planned
|
||||
- note: Displayed and received markers are supported.
|
||||
number: 333
|
||||
status: complete
|
||||
- note: null
|
||||
number: 363
|
||||
status: complete
|
||||
- note: null
|
||||
number: 424
|
||||
status: complete
|
||||
- note: null
|
||||
number: 444
|
||||
status: complete
|
||||
- note: null
|
||||
number: 461
|
||||
status: complete
|
|
@ -0,0 +1,9 @@
|
|||
.mypy_cache
|
||||
.ruff_cache
|
||||
dist
|
||||
persistent
|
||||
.idea
|
||||
.pytest_cache
|
||||
docs/build
|
||||
__pycache__
|
||||
generated
|
|
@ -0,0 +1,37 @@
|
|||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.4.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-added-large-files
|
||||
- id: check-merge-conflict
|
||||
args: [--assume-in-merge]
|
||||
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.0.261
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
|
||||
- repo: https://github.com/rcmdnk/pyproject-pre-commit
|
||||
rev: v0.0.1
|
||||
hooks:
|
||||
- id: isort
|
||||
- id: black
|
||||
- id: mypy
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: pytest-check
|
||||
name: pytest-check
|
||||
entry: poetry run pytest tests
|
||||
language: system
|
||||
pass_filenames: false
|
||||
always_run: true
|
||||
- id: forbidden-files
|
||||
name: forbidden files
|
||||
entry: found Copier update rejection files; review them and remove them
|
||||
language: fail
|
||||
files: "\\.rej$"
|
|
@ -0,0 +1,70 @@
|
|||
FROM docker.io/nicocool84/slidge-builder AS base
|
||||
|
||||
ENV GOBIN="/usr/local/bin"
|
||||
|
||||
RUN echo "deb http://deb.debian.org/debian bullseye-backports main" > /etc/apt/sources.list.d/backports.list && \
|
||||
apt update -y && \
|
||||
apt install -yt bullseye-backports golang
|
||||
|
||||
RUN go install github.com/go-python/gopy@latest
|
||||
RUN go install golang.org/x/tools/cmd/goimports@latest
|
||||
|
||||
ENV PATH="/root/.local/bin:$PATH"
|
||||
COPY poetry.lock pyproject.toml /build/
|
||||
|
||||
RUN poetry export --without-hashes > requirements.txt
|
||||
RUN python3 -m pip install --requirement requirements.txt
|
||||
|
||||
FROM base as go
|
||||
COPY go.* .
|
||||
COPY slidge_whatsapp/*.go .
|
||||
RUN gopy build -output=generated -no-make=true .
|
||||
|
||||
# main container
|
||||
FROM docker.io/nicocool84/slidge-base AS slidge-whatsapp
|
||||
|
||||
COPY --from=base /venv /venv
|
||||
COPY ./slidge_whatsapp/*.py /venv/lib/python/site-packages/legacy_module/
|
||||
COPY --from=go /build/generated /venv/lib/python/site-packages/legacy_module/generated
|
||||
|
||||
# dev container
|
||||
FROM builder AS dev
|
||||
|
||||
USER root
|
||||
|
||||
COPY --from=docker.io/nicocool84/slidge-dev-prosody:latest /etc/prosody/certs/localhost.crt /usr/local/share/ca-certificates/
|
||||
RUN update-ca-certificates
|
||||
|
||||
RUN pip install watchdog[watchmedo]
|
||||
ENV SLIDGE_LEGACY_MODULE=slidge_whatsapp
|
||||
#RUN ln -s /venv/lib/python3.11 /venv/lib/python
|
||||
|
||||
COPY ./watcher.py /
|
||||
|
||||
ENTRYPOINT python3 /build/build.py && python \
|
||||
/watcher.py \
|
||||
/venv/lib/python/site-packages/slidge_whatsapp \
|
||||
python -m slidge\
|
||||
--jid slidge.localhost\
|
||||
--secret secret \
|
||||
--debug
|
||||
|
||||
# wheel builder
|
||||
# docker buildx build . --target wheel \
|
||||
# --platform linux/arm64,linux/amd64 \
|
||||
# -o ./dist/
|
||||
FROM base AS builder-wheel
|
||||
|
||||
RUN pip install pybindgen
|
||||
COPY go.* /build/
|
||||
COPY README.md /build/
|
||||
COPY slidge_whatsapp/*.py /build/slidge_whatsapp/
|
||||
COPY slidge_whatsapp/*.go /build/slidge_whatsapp/
|
||||
COPY build.py /build/
|
||||
|
||||
RUN poetry build
|
||||
RUN ls -l ./dist
|
||||
RUN python --version
|
||||
|
||||
FROM scratch as wheel
|
||||
COPY --from=builder-wheel ./build/dist/* /
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
|
@ -0,0 +1,46 @@
|
|||
# slidge-whatsapp
|
||||
|
||||
A
|
||||
[feature-rich](https://slidge.im/slidge-whatsapp/features.html)
|
||||
[Whatsapp](https://whatsapp.com) to
|
||||
[XMPP](https://xmpp.org/) puppeteering
|
||||
[gateway](https://xmpp.org/extensions/xep-0100.html), based on
|
||||
[slidge](https://slidge.im) and
|
||||
[whatsmeow](https://github.com/tulir/whatsmeow).
|
||||
|
||||
[![builds.sr.ht status](https://builds.sr.ht/~nicoco/slidge-whatsapp/commits/master/ci.yml.svg)](https://builds.sr.ht/~nicoco/slidge-whatsapp/commits/master/ci.yml)
|
||||
[![containers status](https://builds.sr.ht/~nicoco/slidge-whatsapp/commits/master/container.yml.svg)](https://builds.sr.ht/~nicoco/slidge-whatsapp/commits/master/container.yml)
|
||||
[![pypi status](https://badge.fury.io/py/slidge-whatsapp.svg)](https://pypi.org/project/slidge-whatsapp/)
|
||||
|
||||
## Installation
|
||||
|
||||
Refer to the [slidge admin documentation](https://slidge.im/core/admin/)
|
||||
for general info on how to set up an XMPP server component.
|
||||
|
||||
### Containers
|
||||
|
||||
From [dockerhub](https://hub.docker.com/r/nicocool84/slidge-whatsapp)
|
||||
|
||||
```sh
|
||||
docker run docker.io/nicocool84/slidge-whatsapp
|
||||
```
|
||||
|
||||
### Python package
|
||||
|
||||
With [pipx](https://pypa.github.io/pipx/):
|
||||
|
||||
```sh
|
||||
pipx install slidge-whatsapp # for the latest tagged release
|
||||
slidge-whatsapp --help
|
||||
```
|
||||
|
||||
For the bleeding edge, download artifacts of
|
||||
[this build job](https://builds.sr.ht/~nicoco/slidge-whatsapp/commits/master/ci.yml).
|
||||
|
||||
## Dev
|
||||
|
||||
```sh
|
||||
git clone https://git.sr.ht/~nicoco/slidge-whatsapp
|
||||
cd slidge-whatsapp
|
||||
docker-compose up
|
||||
```
|
|
@ -0,0 +1,28 @@
|
|||
# build script for whatsapp extensions
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
os.environ["PATH"] = os.path.expanduser("~/go/bin") + ":" + os.environ["PATH"]
|
||||
subprocess.run(["go", "install", "github.com/go-python/gopy@latest"], check=True)
|
||||
subprocess.run(
|
||||
["go", "install", "golang.org/x/tools/cmd/goimports@latest"], check=True
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
"gopy",
|
||||
"build",
|
||||
"-output=generated",
|
||||
"-no-make=true",
|
||||
".",
|
||||
],
|
||||
cwd=Path(".") / "slidge_whatsapp",
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,120 @@
|
|||
<?xml version="1.0"?>
|
||||
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<Project xmlns="http://usefulinc.com/ns/doap#" xmlns:foaf="http://xmlns.com/foaf/0.1/"
|
||||
xmlns:xmpp="https://linkmauve.fr/ns/xmpp-doap#">
|
||||
<name>slidge-whatsapp</name>
|
||||
|
||||
<created>2023-04-18</created>
|
||||
|
||||
<shortdesc xml:lang="en">A feature-rich Whatsapp/XMPP gateway</shortdesc>
|
||||
|
||||
<homepage rdf:resource="https://sr.ht/~nicoco/slidge-whatsapp" />
|
||||
<download-page rdf:resource="https://git.sr.ht/~nicoco/slidge-whatsapp/refs" />
|
||||
<bug-database rdf:resource="https://todo.sr.ht/~nicoco/slidge" />
|
||||
<developer-forum rdf:resource="xmpp:[email protected]?join" />
|
||||
<support-forum rdf:resource="xmpp:[email protected]?join" />
|
||||
|
||||
<license
|
||||
rdf:resource="https://sr.ht/~nicoco/slidge-whatsapp/tree/master/item/LICENSE" />
|
||||
|
||||
<language>en</language>
|
||||
|
||||
<programming-language>Python</programming-language>
|
||||
|
||||
<os>Linux</os>
|
||||
|
||||
<category rdf:resource="https://linkmauve.fr/ns/xmpp-doap#category-component" />
|
||||
|
||||
<maintainer>
|
||||
<foaf:Person>
|
||||
<foaf:name>deuill</foaf:name>
|
||||
<foaf:homepage rdf:resource="https://deuill.org" />
|
||||
</foaf:Person>
|
||||
</maintainer>
|
||||
|
||||
<repository>
|
||||
<GitRepository>
|
||||
<browse rdf:resource="https://git.sr.ht/~nicoco/slidge-whatsapp" />
|
||||
<location rdf:resource="https://git.sr.ht/~nicoco/slidge-whatsapp.git" />
|
||||
</GitRepository>
|
||||
</repository>
|
||||
|
||||
<implements rdf:resource="https://xmpp.org/rfcs/rfc6120.html" />
|
||||
<implements rdf:resource="https://xmpp.org/rfcs/rfc6121.html" />
|
||||
<implements rdf:resource="https://xmpp.org/rfcs/rfc6122.html" />
|
||||
<implements rdf:resource="https://xmpp.org/rfcs/rfc7590.html" />
|
||||
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0045.html" />
|
||||
<xmpp:status>partial</xmpp:status>
|
||||
<xmpp:note>Participating in groups work, but creation/deletion/moderation is not yet possible from slidge.</xmpp:note>
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0085.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
<xmpp:note>Typing notifications only.</xmpp:note>
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0184.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
<xmpp:note>Whatsapp has proper recipient-generated delivery receipts, and slidge supports them.</xmpp:note>
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0256.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
<xmpp:note>Only available if you chose to share your presence info in the Whatsapp app.</xmpp:note>
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0308.html" />
|
||||
<xmpp:status>planned</xmpp:status>
|
||||
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0333.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
<xmpp:note>Displayed and received markers are supported.</xmpp:note>
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0363.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0424.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0444.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
<implements>
|
||||
<xmpp:SupportedXep>
|
||||
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0461.html" />
|
||||
<xmpp:status>complete</xmpp:status>
|
||||
|
||||
</xmpp:SupportedXep>
|
||||
</implements>
|
||||
|
||||
|
||||
</Project>
|
||||
</rdf:RDF>
|
|
@ -0,0 +1,21 @@
|
|||
version: "3.9"
|
||||
services:
|
||||
slidge:
|
||||
build:
|
||||
context: .
|
||||
target: dev
|
||||
network_mode: service:prosody
|
||||
volumes:
|
||||
- ./slidge_whatsapp:/venv/lib/python/site-packages/slidge_whatsapp
|
||||
- ./persistent:/var/lib/slidge
|
||||
depends_on:
|
||||
prosody:
|
||||
condition: service_started
|
||||
|
||||
prosody:
|
||||
image: docker.io/nicocool84/slidge-prosody-dev:latest
|
||||
ports:
|
||||
- "127.0.0.1:5281:5281" # XMPP port for clients to connect to
|
||||
- "127.0.0.1:5222:5222" # prosody's http_file_share
|
||||
- "127.0.0.1:4444:4444" # for nginx (optional, no-upload)
|
||||
- "127.0.0.1:8888:80" # for movim (optional)
|
|
@ -0,0 +1,20 @@
|
|||
# Minimal makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line, and also
|
||||
# from the environment for the first two.
|
||||
SPHINXOPTS ?=
|
||||
SPHINXBUILD ?= poetry run sphinx-build
|
||||
SOURCEDIR = source
|
||||
BUILDDIR = build
|
||||
|
||||
# Put it first so that "make" without argument is like "make help".
|
||||
help:
|
||||
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||
|
||||
.PHONY: help Makefile
|
||||
|
||||
# Catch-all target: route all unknown targets to Sphinx using the new
|
||||
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
||||
%: Makefile
|
||||
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
|
@ -0,0 +1,36 @@
|
|||
project = "slidge-whatsapp"
|
||||
copyright = "2023, deuill"
|
||||
author = "deuill"
|
||||
|
||||
extensions = [
|
||||
"sphinx.ext.autodoc",
|
||||
"sphinx.ext.intersphinx",
|
||||
"sphinx.ext.extlinks",
|
||||
"sphinx.ext.viewcode",
|
||||
"sphinx.ext.autodoc.typehints",
|
||||
"sphinxarg.ext",
|
||||
"autoapi.extension",
|
||||
"slidge_dev_helpers.doap",
|
||||
"slidge_dev_helpers.sphinx_config_obj",
|
||||
"sphinx_mdinclude",
|
||||
]
|
||||
|
||||
autodoc_typehints = "description"
|
||||
|
||||
# Include __init__ docstrings
|
||||
autoclass_content = "both"
|
||||
autoapi_python_class_content = "both"
|
||||
|
||||
autoapi_type = "python"
|
||||
autoapi_dirs = ["../../slidge_whatsapp"]
|
||||
autoapi_ignore = ["generated/*"]
|
||||
|
||||
intersphinx_mapping = {
|
||||
"python": ("https://docs.python.org/3", None),
|
||||
"slixmpp": ("https://slixmpp.readthedocs.io/en/latest/", None),
|
||||
"slidge": ("https://slidge.im/core/", None),
|
||||
}
|
||||
|
||||
extlinks = {"xep": ("https://xmpp.org/extensions/xep-%s.html", "XEP-%s")}
|
||||
|
||||
html_theme = "furo"
|
|
@ -0,0 +1,14 @@
|
|||
Configuration
|
||||
=============
|
||||
|
||||
Setting up a slidge component
|
||||
-----------------------------
|
||||
|
||||
Refer to the `slidge admin docs <https://slidge.im/admin>`_ for generic
|
||||
instructions on how to set up a slidge component, and for slidge core
|
||||
configuration options.
|
||||
|
||||
slidge-whatsapp-specific config
|
||||
-------------------------------
|
||||
|
||||
.. config-obj:: slidge_whatsapp.config
|
|
@ -0,0 +1,8 @@
|
|||
Features
|
||||
--------
|
||||
|
||||
The table below lists the notable features for slidge-whatsapp.
|
||||
Refer to `xmpp.org <https://xmpp.org/software/slidge/>`_ for a longer version,
|
||||
including all XEPs supported by `slidge <https://slidge.im/>`_.
|
||||
|
||||
.. doap:: ../../doap.xml
|
|
@ -0,0 +1,27 @@
|
|||
slidge-whatsapp
|
||||
===============
|
||||
|
||||
A
|
||||
`feature-rich <https://slidge.im/slidge-whatsapp/features.html>`_
|
||||
`Whatsapp <https://whatsapp.com>`_ to
|
||||
`XMPP <https://xmpp.org/>`_ puppeteering
|
||||
`gateway <https://xmpp.org/extensions/xep-0100.html>`_, based on
|
||||
`slidge <https://slidge.im>`_ and
|
||||
`whatsmeow <https://github.com/tulir/whatsmeow>`_.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 3
|
||||
|
||||
readme
|
||||
features
|
||||
config
|
||||
user
|
||||
autoapi/index
|
||||
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
|
@ -0,0 +1 @@
|
|||
.. mdinclude:: ../../README.md
|
|
@ -0,0 +1,22 @@
|
|||
User docs
|
||||
---------
|
||||
|
||||
.. note::
|
||||
Slidge uses WhatsApp's `Linked Devices <https://faq.whatsapp.com/378279804439436/>`_ feature,
|
||||
which may require perioding re-linking against the official client. However, you can still not
|
||||
use or even uninstall the official client between re-linking.
|
||||
|
||||
Roster
|
||||
******
|
||||
|
||||
Contact JIDs are of the form ``+<phone-number>@slidge-whatsapp.example.org``, where
|
||||
``<phone-number>`` is the contact's phone number in international format (e.g. ``+442087599036``.
|
||||
Contacts will be added to the roster as they engage with your account, and may not all appear at
|
||||
once as they exist in the official client.
|
||||
|
||||
Presences
|
||||
*********
|
||||
|
||||
Your contacts' presence will appear as either "online" when the contact is currently using the
|
||||
WhatsApp client, or "away" otherwise; their last interaction time will also be noted if you've
|
||||
chosen to share this in the privacy settings of the official client.
|
|
@ -0,0 +1,17 @@
|
|||
module git.sr.ht/~nicoco/slidge/slidge/plugins/whatsapp
|
||||
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/go-python/gopy v0.4.5
|
||||
github.com/mattn/go-sqlite3 v1.14.16
|
||||
go.mau.fi/libsignal v0.1.0
|
||||
go.mau.fi/whatsmeow v0.0.0-20230423103937-c40d2f088b8f
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.0.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.0 // indirect
|
||||
golang.org/x/crypto v0.8.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
)
|
|
@ -0,0 +1,22 @@
|
|||
filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek=
|
||||
filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns=
|
||||
github.com/go-python/gopy v0.4.5 h1:cwnd24UKA91vFFZoRvavb/vzBSKV99Gp3+2d5+jTG0U=
|
||||
github.com/go-python/gopy v0.4.5/go.mod h1:tlA/KcD7rM8B+NQJR4SASwiinfKY0aiMFanHszR8BZA=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
go.mau.fi/libsignal v0.1.0 h1:vAKI/nJ5tMhdzke4cTK1fb0idJzz1JuEIpmjprueC+c=
|
||||
go.mau.fi/libsignal v0.1.0/go.mod h1:R8ovrTezxtUNzCQE5PH30StOQWWeBskBsWE55vMfY9I=
|
||||
go.mau.fi/whatsmeow v0.0.0-20230423103937-c40d2f088b8f h1:yPyLZFPk8EHtnP7tjHEOgEJlI+9vozUk4GoMOBpzu6E=
|
||||
go.mau.fi/whatsmeow v0.0.0-20230423103937-c40d2f088b8f/go.mod h1:+ObGpFE6cbbY4hKc1FmQH9MVfqaemmlXGXSnwDvCOyE=
|
||||
golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
|
||||
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
|
||||
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,86 @@
|
|||
[tool.poetry]
|
||||
name = "slidge-whatsapp"
|
||||
version = "0.0.0-dev0"
|
||||
description = "A Whatsapp/XMPP gateway."
|
||||
authors = ["deuill <[email protected]>", "Nicoco <[email protected]>"]
|
||||
readme = "README.md"
|
||||
|
||||
[[tool.poetry.include]]
|
||||
path = "slidge_whatsapp"
|
||||
|
||||
[[tool.poetry.include]]
|
||||
path = "slidge_whatsapp/generated/*.py"
|
||||
format = ["wheel"]
|
||||
|
||||
[[tool.poetry.include]]
|
||||
path = "slidge_whatsapp/generated/*.so"
|
||||
format = ["wheel"]
|
||||
|
||||
[tool.poetry.build]
|
||||
script = "build.py"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.9"
|
||||
linkpreview = "^0.6.5"
|
||||
pybindgen = "^0.22.1"
|
||||
|
||||
[tool.poetry.dependencies.slidge]
|
||||
git = "https://git.sr.ht/~nicoco/slidge"
|
||||
branch = "split"
|
||||
|
||||
[[tool.poetry.source]]
|
||||
name = "slidge-repo"
|
||||
url = "https://slidge.im/repo"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
pytest-asyncio = "^0.21.0"
|
||||
black = "^23.3.0"
|
||||
isort = "^5.12.0"
|
||||
ruff = "^0.0.261"
|
||||
mypy = "^1.2.0"
|
||||
xmldiff = "^2.6.1"
|
||||
pre-commit = "^3.2.2"
|
||||
sphinx = "^6.1.3"
|
||||
furo = "^2023.3.27"
|
||||
sphinx-autoapi = "^2.1.0"
|
||||
sphinx-argparse = "^0.4.0"
|
||||
sphinx-mdinclude = "^0.5.3"
|
||||
|
||||
[tool.poetry.group.dev.dependencies.slidge-dev-helpers]
|
||||
git = "https://git.sr.ht/~nicoco/slidge-dev-helpers"
|
||||
branch = "master"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core", "pybindgen"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
slidge-whatsapp = 'slidge_whatsapp.__main__:main'
|
||||
|
||||
[tool.mypy]
|
||||
files = ["slidge_whatsapp"]
|
||||
exclude = [
|
||||
"tests",
|
||||
"slidge_whatsapp/generated",
|
||||
"watcher.py",
|
||||
]
|
||||
check_untyped_defs = true
|
||||
strict = false
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["linkpreview"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
exclude = [
|
||||
"tests",
|
||||
"slidge_whatsapp/generated",
|
||||
]
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
skip = [
|
||||
"tests",
|
||||
"slidge_whatsapp/generated",
|
||||
]
|
|
@ -0,0 +1,11 @@
|
|||
"""
|
||||
WhatsApp gateway using the multi-device API.
|
||||
"""
|
||||
|
||||
from slidge.util.util import get_version # noqa: F401
|
||||
|
||||
from . import config, contact, group, session
|
||||
from .gateway import Gateway
|
||||
|
||||
__version__ = get_version()
|
||||
__all__ = "Gateway", "session", "contact", "config", "group"
|
|
@ -0,0 +1,12 @@
|
|||
import sys
|
||||
|
||||
from slidge.__main__ import main as slidge_main
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sys.argv.extend(["--legacy", "slidge_whatsapp"])
|
||||
slidge_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
|
@ -0,0 +1,30 @@
|
|||
"""
|
||||
Config contains plugin-specific configuration for WhatsApp, and is loaded automatically by the
|
||||
core configuration framework.
|
||||
"""
|
||||
|
||||
from slidge import global_config
|
||||
|
||||
# FIXME: workaround because global_config.HOME_DIR is not defined unless
|
||||
# called by slidge's main(), which is a problem for test and docs
|
||||
try:
|
||||
DB_PATH = global_config.HOME_DIR / "whatsapp" / "whatsapp.db"
|
||||
DB_PATH__DOC = "The path to the database used for the WhatsApp plugin."
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
ALWAYS_SYNC_ROSTER = False
|
||||
ALWAYS_SYNC_ROSTER__DOC = (
|
||||
"Whether or not to perform a full sync of the WhatsApp roster on startup."
|
||||
)
|
||||
|
||||
SKIP_VERIFY_TLS = False
|
||||
SKIP_VERIFY_TLS__DOC = (
|
||||
"Whether or not HTTPS connections made by this plugin should verify TLS"
|
||||
" certificates."
|
||||
)
|
||||
|
||||
ENABLE_LINK_PREVIEWS = True
|
||||
ENABLE_LINK_PREVIEWS__DOC = (
|
||||
"Whether or not previews for links (URLs) should be generated on outgoing messages"
|
||||
)
|
|
@ -0,0 +1,68 @@
|
|||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from slidge import LegacyContact, LegacyRoster
|
||||
from slixmpp.exceptions import XMPPError
|
||||
|
||||
from . import config
|
||||
from .generated import whatsapp
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .session import Session
|
||||
|
||||
|
||||
class Contact(LegacyContact[str]):
|
||||
# WhatsApp only allows message editing in Beta versions of their app, and support is uncertain.
|
||||
CORRECTION = False
|
||||
REACTIONS_SINGLE_EMOJI = True
|
||||
|
||||
async def update_presence(self, away: bool, last_seen_timestamp: int):
|
||||
last_seen = (
|
||||
datetime.fromtimestamp(last_seen_timestamp, tz=timezone.utc)
|
||||
if last_seen_timestamp > 0
|
||||
else None
|
||||
)
|
||||
if away:
|
||||
self.away(last_seen=last_seen)
|
||||
else:
|
||||
self.online(last_seen=last_seen)
|
||||
|
||||
|
||||
class Roster(LegacyRoster[str, Contact]):
|
||||
session: "Session"
|
||||
|
||||
async def fill(self):
|
||||
"""
|
||||
Retrieve contacts from remote WhatsApp service, subscribing to their presence and adding to
|
||||
local roster.
|
||||
"""
|
||||
contacts = self.session.whatsapp.GetContacts(refresh=config.ALWAYS_SYNC_ROSTER)
|
||||
for ptr in contacts:
|
||||
await self.add_whatsapp_contact(whatsapp.Contact(handle=ptr))
|
||||
|
||||
async def add_whatsapp_contact(self, data: whatsapp.Contact):
|
||||
"""
|
||||
Adds a WhatsApp contact to local roster, filling all required and optional information.
|
||||
"""
|
||||
if data.JID == self.user_legacy_id:
|
||||
# with the current implementation, we don't allow that
|
||||
return
|
||||
contact = await self.by_legacy_id(data.JID)
|
||||
contact.name = data.Name
|
||||
contact.is_friend = True
|
||||
if data.Avatar.URL:
|
||||
avatar_id = data.Avatar.ID if data.Avatar.ID else None
|
||||
await contact.set_avatar(data.Avatar.URL, avatar_id)
|
||||
contact.set_vcard(full_name=contact.name, phone=str(contact.jid.local))
|
||||
contact.is_friend = True
|
||||
await contact.add_to_roster()
|
||||
|
||||
async def legacy_id_to_jid_username(self, legacy_id: str) -> str:
|
||||
return "+" + legacy_id[: legacy_id.find("@")]
|
||||
|
||||
async def jid_username_to_legacy_id(self, jid_username: str) -> str:
|
||||
if jid_username.startswith("#"):
|
||||
raise XMPPError("item-not-found", "Invalid contact ID: group ID given")
|
||||
if not jid_username.startswith("+"):
|
||||
raise XMPPError("item-not-found", "Invalid contact ID, expected '+' prefix")
|
||||
return jid_username.removeprefix("+") + "@" + whatsapp.DefaultUserServer
|
|
@ -0,0 +1,632 @@
|
|||
package whatsapp
|
||||
|
||||
import (
|
||||
// Standard library.
|
||||
"context"
|
||||
"fmt"
|
||||
"mime"
|
||||
|
||||
// Third-party libraries.
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/binary/proto"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
"go.mau.fi/whatsmeow/types/events"
|
||||
)
|
||||
|
||||
// EventKind represents all event types recognized by the Python session adapter, as emitted by the
|
||||
// Go session adapter.
|
||||
type EventKind int
|
||||
|
||||
|
||||
// The event types handled by the overarching session adapter handler.
|
||||
const (
|
||||
EventUnknown EventKind = iota
|
||||
EventQRCode
|
||||
EventPair
|
||||
EventConnected
|
||||
EventLoggedOut
|
||||
EventContact
|
||||
EventPresence
|
||||
EventMessage
|
||||
EventChatState
|
||||
EventReceipt
|
||||
EventGroup
|
||||
EventCall
|
||||
)
|
||||
|
||||
// EventPayload represents the collected payloads for all event types handled by the overarching
|
||||
// session adapter handler. Only specific fields will be populated in events emitted by internal
|
||||
// handlers, see documentation for specific types for more information.
|
||||
type EventPayload struct {
|
||||
QRCode string
|
||||
PairDeviceID string
|
||||
ConnectedJID string
|
||||
Contact Contact
|
||||
Presence Presence
|
||||
Message Message
|
||||
ChatState ChatState
|
||||
Receipt Receipt
|
||||
Group Group
|
||||
Call Call
|
||||
}
|
||||
|
||||
// A Avatar represents a small image representing a Contact or Group.
|
||||
type Avatar struct {
|
||||
ID string // The unique ID for this avatar, used for persistent caching.
|
||||
URL string // The HTTP URL over which this avatar might be retrieved. Can change for the same ID.
|
||||
}
|
||||
|
||||
// A Contact represents any entity that be communicated with directly in WhatsApp. This typically
|
||||
// represents people, but may represent a business or bot as well, but not a group-chat.
|
||||
type Contact struct {
|
||||
JID string // The WhatsApp JID for this contact.
|
||||
Name string // The user-set, human-readable name for this contact.
|
||||
Avatar Avatar // The profile picture for this contact.
|
||||
}
|
||||
|
||||
// NewContactEvent returns event data meant for [Session.propagateEvent] for the contact information
|
||||
// given. Unknown or invalid contact information will return an [EventUnknown] event with nil data.
|
||||
func newContactEvent(c *whatsmeow.Client, jid types.JID, info types.ContactInfo) (EventKind, *EventPayload) {
|
||||
var contact = Contact{
|
||||
JID: jid.ToNonAD().String(),
|
||||
}
|
||||
|
||||
for _, n := range []string{info.FullName, info.FirstName, info.BusinessName, info.PushName} {
|
||||
if n != "" {
|
||||
contact.Name = n
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Don't attempt to synchronize contacts with no user-readable name.
|
||||
if contact.Name == "" {
|
||||
return EventUnknown, nil
|
||||
}
|
||||
|
||||
if p, _ := c.GetProfilePictureInfo(jid, nil); p != nil {
|
||||
contact.Avatar = Avatar{ID: p.ID, URL: p.URL}
|
||||
}
|
||||
|
||||
return EventContact, &EventPayload{Contact: contact}
|
||||
}
|
||||
|
||||
// Precence represents a contact's general state of activity, and is periodically updated as
|
||||
// contacts start or stop paying attention to their client of choice.
|
||||
type Presence struct {
|
||||
JID string
|
||||
Away bool
|
||||
LastSeen int64
|
||||
}
|
||||
|
||||
// NewPresenceEvent returns event data meant for [Session.propagateEvent] for the primitive presence
|
||||
// event given.
|
||||
func newPresenceEvent(evt *events.Presence) (EventKind, *EventPayload) {
|
||||
return EventPresence, &EventPayload{Presence: Presence{
|
||||
JID: evt.From.ToNonAD().String(),
|
||||
Away: evt.Unavailable,
|
||||
LastSeen: evt.LastSeen.Unix(),
|
||||
}}
|
||||
}
|
||||
|
||||
// MessageKind represents all concrete message types (plain-text messages, edit messages, reactions)
|
||||
// recognized by the Python session adapter.
|
||||
type MessageKind int
|
||||
|
||||
// The message types handled by the overarching session event handler.
|
||||
const (
|
||||
MessagePlain MessageKind = 1 + iota
|
||||
MessageRevoke
|
||||
MessageReaction
|
||||
MessageAttachment
|
||||
)
|
||||
|
||||
// A Message represents one of many kinds of bidirectional communication payloads, for example, a
|
||||
// text message, a file (image, video) attachment, an emoji reaction, etc. Messages of different
|
||||
// kinds are denoted as such, and re-use fields where the semantics overlap.
|
||||
type Message struct {
|
||||
Kind MessageKind // The concrete message kind being sent or received.
|
||||
ID string // The unique message ID, used for referring to a specific Message instance.
|
||||
JID string // The JID this message concerns, semantics can change based on IsCarbon.
|
||||
GroupJID string // The JID of the group-chat this message was sent in, if any.
|
||||
OriginJID string // For reactions and replies in groups, the JID of the original user.
|
||||
Body string // The plain-text message body. For attachment messages, this can be a caption.
|
||||
Timestamp int64 // The Unix timestamp denoting when this message was created.
|
||||
IsCarbon bool // Whether or not this message concerns the gateway user themselves.
|
||||
ReplyID string // The unique message ID this message is in reply to, if any.
|
||||
ReplyBody string // The full body of the message this message is in reply to, if any.
|
||||
Attachments []Attachment // The list of file (image, video, etc.) attachments contained in this message.
|
||||
Preview Preview // A short description for the URL provided in the message body, if any.
|
||||
}
|
||||
|
||||
// A Attachment represents additional binary data (e.g. images, videos, documents) provided alongside
|
||||
// a message, for display or storage on the recepient client.
|
||||
type Attachment struct {
|
||||
MIME string // The MIME type for attachment.
|
||||
Filename string // The recommended file name for this attachment. May be an auto-generated name.
|
||||
Caption string // The user-provided caption, provided alongside this attachment.
|
||||
Data []byte // The raw binary data for this attachment. Mutually exclusive with [.URL].
|
||||
URL string // The URL to download attachment data from. Mutually exclusive with [.Data].
|
||||
}
|
||||
|
||||
// A Preview represents a short description for a URL provided in a message body, as usually derived
|
||||
// from the content of the page pointed at.
|
||||
type Preview struct {
|
||||
URL string // The original (or canonical) URL this preview was generated for.
|
||||
Title string // The short title for the URL preview.
|
||||
Description string // The (optional) long-form description for the URL preview.
|
||||
ImageData []byte // The raw binary data for the image associated with the URL. Mutally exclusive with [.ImageURL].
|
||||
ImageURL string // The URL to download an image associated with the URL. Mutually exclusive with [.ImageData].
|
||||
}
|
||||
|
||||
// GenerateMessageID returns a valid, pseudo-random message ID for use in outgoing messages. This
|
||||
// function will panic if there is no entropy available for random ID generation.
|
||||
func GenerateMessageID() string {
|
||||
return whatsmeow.GenerateMessageID()
|
||||
}
|
||||
|
||||
// NewMessageEvent returns event data meant for [Session.propagateEvent] for the primive message
|
||||
// event given. Unknown or invalid messages will return an [EventUnknown] event with nil data.
|
||||
func newMessageEvent(client *whatsmeow.Client, evt *events.Message) (EventKind, *EventPayload) {
|
||||
// Set basic data for message, to be potentially amended depending on the concrete version of
|
||||
// the underlying message.
|
||||
var message = Message{
|
||||
Kind: MessagePlain,
|
||||
ID: evt.Info.ID,
|
||||
JID: evt.Info.Sender.ToNonAD().String(),
|
||||
Body: evt.Message.GetConversation(),
|
||||
Timestamp: evt.Info.Timestamp.Unix(),
|
||||
IsCarbon: evt.Info.IsFromMe,
|
||||
}
|
||||
|
||||
if evt.Info.IsGroup {
|
||||
message.GroupJID = evt.Info.Chat.ToNonAD().String()
|
||||
} else if message.IsCarbon {
|
||||
message.JID = evt.Info.Chat.ToNonAD().String()
|
||||
}
|
||||
|
||||
// Handle handle protocol messages (such as message deletion or editing).
|
||||
if p := evt.Message.GetProtocolMessage(); p != nil {
|
||||
switch p.GetType() {
|
||||
case proto.ProtocolMessage_REVOKE:
|
||||
message.Kind = MessageRevoke
|
||||
message.ID = p.Key.GetId()
|
||||
return EventMessage, &EventPayload{Message: message}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle emoji reaction to existing message.
|
||||
if r := evt.Message.GetReactionMessage(); r != nil {
|
||||
message.Kind = MessageReaction
|
||||
message.ID = r.Key.GetId()
|
||||
message.Body = r.GetText()
|
||||
return EventMessage, &EventPayload{Message: message}
|
||||
}
|
||||
|
||||
// Handle message attachments, if any.
|
||||
if attach, err := getMessageAttachments(client, evt.Message); err != nil {
|
||||
client.Log.Errorf("Failed getting message attachments: %s", err)
|
||||
return EventUnknown, nil
|
||||
} else if len(attach) > 0 {
|
||||
message.Attachments = append(message.Attachments, attach...)
|
||||
message.Kind = MessageAttachment
|
||||
}
|
||||
|
||||
// Get extended information from message, if available. Extended messages typically represent
|
||||
// messages with additional context, such as replies, forwards, etc.
|
||||
if e := evt.Message.GetExtendedTextMessage(); e != nil {
|
||||
if message.Body == "" {
|
||||
message.Body = e.GetText()
|
||||
}
|
||||
if c := e.GetContextInfo(); c != nil {
|
||||
message.ReplyID = c.GetStanzaId()
|
||||
message.OriginJID = c.GetParticipant()
|
||||
if q := c.GetQuotedMessage(); q != nil {
|
||||
if qe := q.GetExtendedTextMessage(); qe != nil {
|
||||
message.ReplyBody = qe.GetText()
|
||||
} else {
|
||||
message.ReplyBody = q.GetConversation()
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.MatchedText != nil {
|
||||
message.Preview = Preview{
|
||||
Title: e.GetTitle(),
|
||||
Description: e.GetDescription(),
|
||||
URL: e.GetMatchedText(),
|
||||
ImageData: e.GetJpegThumbnail(),
|
||||
}
|
||||
if url := e.GetCanonicalUrl(); url != "" {
|
||||
message.Preview.URL = url
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore obviously invalid messages.
|
||||
if message.Kind == MessagePlain && message.Body == "" {
|
||||
return EventUnknown, nil
|
||||
}
|
||||
|
||||
return EventMessage, &EventPayload{Message: message}
|
||||
}
|
||||
|
||||
// GetMessageAttachments fetches and decrypts attachments (images, audio, video, or documents) sent
|
||||
// via WhatsApp. Any failures in retrieving any attachment will return an error immediately.
|
||||
func getMessageAttachments(client *whatsmeow.Client, message *proto.Message) ([]Attachment, error) {
|
||||
var result []Attachment
|
||||
var kinds = []whatsmeow.DownloadableMessage{
|
||||
message.GetImageMessage(),
|
||||
message.GetAudioMessage(),
|
||||
message.GetVideoMessage(),
|
||||
message.GetDocumentMessage(),
|
||||
}
|
||||
|
||||
for _, msg := range kinds {
|
||||
// Handle data for specific attachment type.
|
||||
var a Attachment
|
||||
switch msg := msg.(type) {
|
||||
case *proto.ImageMessage:
|
||||
a.MIME, a.Caption = msg.GetMimetype(), msg.GetCaption()
|
||||
case *proto.AudioMessage:
|
||||
a.MIME = msg.GetMimetype()
|
||||
case *proto.VideoMessage:
|
||||
a.MIME, a.Caption = msg.GetMimetype(), msg.GetCaption()
|
||||
case *proto.DocumentMessage:
|
||||
a.MIME, a.Caption, a.Filename = msg.GetMimetype(), msg.GetCaption(), msg.GetFileName()
|
||||
}
|
||||
|
||||
// Ignore attachments with empty or unknown MIME types.
|
||||
if a.MIME == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Set filename from SHA256 checksum and MIME type, if none is already set.
|
||||
if a.Filename == "" {
|
||||
a.Filename = fmt.Sprintf("%x%s", msg.GetFileSha256(), extensionByType(a.MIME))
|
||||
}
|
||||
|
||||
// Attempt to download and decrypt raw attachment data, if any.
|
||||
data, err := client.Download(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a.Data = data
|
||||
result = append(result, a)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// KnownMediaTypes represents MIME type to WhatsApp media types known to be handled by WhatsApp in a
|
||||
// special way (that is, not as generic file uploads).
|
||||
var knownMediaTypes = map[string]whatsmeow.MediaType{
|
||||
"image/jpeg": whatsmeow.MediaImage,
|
||||
"audio/ogg": whatsmeow.MediaAudio,
|
||||
"application/ogg": whatsmeow.MediaAudio,
|
||||
"video/mp4": whatsmeow.MediaVideo,
|
||||
}
|
||||
|
||||
// UploadAttachment attempts to push the given attachment data to WhatsApp according to the MIME type
|
||||
// specified within. Attachments are handled as generic file uploads unless they're of a specific
|
||||
// format, see [knownMediaTypes] for more information.
|
||||
func uploadAttachment(client *whatsmeow.Client, attach Attachment) (*proto.Message, error) {
|
||||
mediaType := knownMediaTypes[attach.MIME]
|
||||
if mediaType == "" {
|
||||
mediaType = whatsmeow.MediaDocument
|
||||
}
|
||||
|
||||
upload, err := client.Upload(context.Background(), attach.Data, mediaType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var message *proto.Message
|
||||
switch mediaType {
|
||||
case whatsmeow.MediaImage:
|
||||
message = &proto.Message{
|
||||
ImageMessage: &proto.ImageMessage{
|
||||
Url: &upload.URL,
|
||||
DirectPath: &upload.DirectPath,
|
||||
MediaKey: upload.MediaKey,
|
||||
Mimetype: &attach.MIME,
|
||||
FileEncSha256: upload.FileEncSHA256,
|
||||
FileSha256: upload.FileSHA256,
|
||||
FileLength: ptrTo(uint64(len(attach.Data))),
|
||||
},
|
||||
}
|
||||
case whatsmeow.MediaAudio:
|
||||
message = &proto.Message{
|
||||
AudioMessage: &proto.AudioMessage{
|
||||
Url: &upload.URL,
|
||||
DirectPath: &upload.DirectPath,
|
||||
MediaKey: upload.MediaKey,
|
||||
Mimetype: &attach.MIME,
|
||||
FileEncSha256: upload.FileEncSHA256,
|
||||
FileSha256: upload.FileSHA256,
|
||||
FileLength: ptrTo(uint64(len(attach.Data))),
|
||||
},
|
||||
}
|
||||
case whatsmeow.MediaVideo:
|
||||
message = &proto.Message{
|
||||
VideoMessage: &proto.VideoMessage{
|
||||
Url: &upload.URL,
|
||||
DirectPath: &upload.DirectPath,
|
||||
MediaKey: upload.MediaKey,
|
||||
Mimetype: &attach.MIME,
|
||||
FileEncSha256: upload.FileEncSHA256,
|
||||
FileSha256: upload.FileSHA256,
|
||||
FileLength: ptrTo(uint64(len(attach.Data))),
|
||||
}}
|
||||
case whatsmeow.MediaDocument:
|
||||
message = &proto.Message{
|
||||
DocumentMessage: &proto.DocumentMessage{
|
||||
Url: &upload.URL,
|
||||
DirectPath: &upload.DirectPath,
|
||||
MediaKey: upload.MediaKey,
|
||||
Mimetype: &attach.MIME,
|
||||
FileEncSha256: upload.FileEncSHA256,
|
||||
FileSha256: upload.FileSHA256,
|
||||
FileLength: ptrTo(uint64(len(attach.Data))),
|
||||
FileName: &attach.Filename,
|
||||
}}
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// KnownExtensions represents MIME type to file-extension mappings for basic, known media types.
|
||||
var knownExtensions = map[string]string{
|
||||
"image/jpeg": ".jpg",
|
||||
"audio/ogg": ".oga",
|
||||
"video/mp4": ".mp4",
|
||||
}
|
||||
|
||||
// ExtensionByType returns the file extension for the given MIME type, or a generic extension if the
|
||||
// MIME type is unknown.
|
||||
func extensionByType(typ string) string {
|
||||
// Handle common, known MIME types first.
|
||||
if ext := knownExtensions[typ]; ext != "" {
|
||||
return ext
|
||||
}
|
||||
if ext, _ := mime.ExtensionsByType(typ); len(ext) > 0 {
|
||||
return ext[0]
|
||||
}
|
||||
return ".bin"
|
||||
}
|
||||
|
||||
// ChatStateKind represents the different kinds of chat-states possible in WhatsApp.
|
||||
type ChatStateKind int
|
||||
|
||||
// The chat states handled by the overarching session event handler.
|
||||
const (
|
||||
ChatStateComposing ChatStateKind = 1 + iota
|
||||
ChatStatePaused
|
||||
)
|
||||
|
||||
// A ChatState represents the activity of a contact within a certain discussion, for instance,
|
||||
// whether the contact is currently composing a message. This is separate to the concept of a
|
||||
// Presence, which is the contact's general state across all discussions.
|
||||
type ChatState struct {
|
||||
Kind ChatStateKind
|
||||
JID string
|
||||
GroupJID string
|
||||
}
|
||||
|
||||
// NewChatStateEvent returns event data meant for [Session.propagateEvent] for the primitive
|
||||
// chat-state event given.
|
||||
func newChatStateEvent(evt *events.ChatPresence) (EventKind, *EventPayload) {
|
||||
var state = ChatState{JID: evt.MessageSource.Sender.ToNonAD().String()}
|
||||
if evt.MessageSource.IsGroup {
|
||||
state.GroupJID = evt.MessageSource.Chat.ToNonAD().String()
|
||||
}
|
||||
switch evt.State {
|
||||
case types.ChatPresenceComposing:
|
||||
state.Kind = ChatStateComposing
|
||||
case types.ChatPresencePaused:
|
||||
state.Kind = ChatStatePaused
|
||||
}
|
||||
return EventChatState, &EventPayload{ChatState: state}
|
||||
}
|
||||
|
||||
// ReceiptKind represents the different types of delivery receipts possible in WhatsApp.
|
||||
type ReceiptKind int
|
||||
|
||||
// The delivery receipts handled by the overarching session event handler.
|
||||
const (
|
||||
ReceiptDelivered ReceiptKind = 1 + iota
|
||||
ReceiptRead
|
||||
)
|
||||
|
||||
// A Receipt represents a notice of delivery or presentation for [Message] instances sent or
|
||||
// received. Receipts can be delivered for many messages at once, but are generally all delivered
|
||||
// under one specific state at a time.
|
||||
type Receipt struct {
|
||||
Kind ReceiptKind // The distinct kind of receipt presented.
|
||||
MessageIDs []string // The list of message IDs to mark for receipt.
|
||||
JID string
|
||||
GroupJID string
|
||||
Timestamp int64
|
||||
IsCarbon bool
|
||||
}
|
||||
|
||||
// NewReceiptEvent returns event data meant for [Session.propagateEvent] for the primive receipt
|
||||
// event given. Unknown or invalid receipts will return an [EventUnknown] event with nil data.
|
||||
func newReceiptEvent(evt *events.Receipt) (EventKind, *EventPayload) {
|
||||
var receipt = Receipt{
|
||||
MessageIDs: append([]string{}, evt.MessageIDs...),
|
||||
JID: evt.MessageSource.Sender.ToNonAD().String(),
|
||||
Timestamp: evt.Timestamp.Unix(),
|
||||
IsCarbon: evt.MessageSource.IsFromMe,
|
||||
}
|
||||
|
||||
if len(receipt.MessageIDs) == 0 {
|
||||
return EventUnknown, nil
|
||||
}
|
||||
|
||||
if evt.MessageSource.IsGroup {
|
||||
receipt.GroupJID = evt.MessageSource.Chat.ToNonAD().String()
|
||||
} else if receipt.IsCarbon {
|
||||
receipt.JID = evt.MessageSource.Chat.ToNonAD().String()
|
||||
}
|
||||
|
||||
switch evt.Type {
|
||||
case events.ReceiptTypeDelivered:
|
||||
receipt.Kind = ReceiptDelivered
|
||||
case events.ReceiptTypeRead:
|
||||
receipt.Kind = ReceiptRead
|
||||
}
|
||||
|
||||
return EventReceipt, &EventPayload{Receipt: receipt}
|
||||
}
|
||||
|
||||
// GroupAffiliation represents the set of privilidges given to a specific participant in a group.
|
||||
type GroupAffiliation int
|
||||
|
||||
const (
|
||||
GroupAffiliationNone GroupAffiliation = iota // None, or normal member group affiliation.
|
||||
GroupAffiliationAdmin // Can perform some management operations.
|
||||
GroupAffiliationOwner // Can manage group fully, including destroying the group.
|
||||
)
|
||||
|
||||
// A Group represents a named, many-to-many chat space which may be joined or left at will. All
|
||||
// fields apart from the group JID, are considered to be optional, and may not be set in cases where
|
||||
// group information is being updated against previous assumed state. Groups in WhatsApp are
|
||||
// generally invited to out-of-band with respect to overarching adaptor; see the documentation for
|
||||
// [Session.GetGroups] for more information.
|
||||
type Group struct {
|
||||
JID string // The WhatsApp JID for this group.
|
||||
Name string // The user-defined, human-readable name for this group.
|
||||
Subject GroupSubject // The longer-form, user-defined description for this group.
|
||||
Nickname string // Our own nickname in this group-chat.
|
||||
Participants []GroupParticipant // The list of participant contacts for this group, including ourselves.
|
||||
}
|
||||
|
||||
// A GroupSubject represents the user-defined group description and attached metadata thereof, for a
|
||||
// given [Group].
|
||||
type GroupSubject struct {
|
||||
Subject string // The user-defined group description.
|
||||
SetAt int64 // The exact time this group description was set at, as a timestamp.
|
||||
SetByJID string // The JID of the user that set the subject.
|
||||
}
|
||||
|
||||
// GroupParticipantAction represents the distinct set of actions that can be taken when encountering
|
||||
// a group participant, typically to add or remove.
|
||||
type GroupParticipantAction int
|
||||
|
||||
const (
|
||||
GroupParticipantActionAdd GroupParticipantAction = iota // Default action; add participant to list.
|
||||
GroupParticipantActionUpdate // Update existing participant information.
|
||||
GroupParticipantActionRemove // Remove participant from list, if existing.
|
||||
)
|
||||
|
||||
// A GroupParticipant represents a contact who is currently joined in a given group. Participants in
|
||||
// WhatsApp can always be derived back to their individual [Contact]; there are no anonymous groups
|
||||
// in WhatsApp.
|
||||
type GroupParticipant struct {
|
||||
JID string // The WhatsApp JID for this participant.
|
||||
Affiliation GroupAffiliation // The set of priviledges given to this specific participant.
|
||||
Action GroupParticipantAction // The specific action to take for this participant; typically to add.
|
||||
}
|
||||
|
||||
// NewReceiptEvent returns event data meant for [Session.propagateEvent] for the primive group
|
||||
// event given. Group data returned by this function can be partial, and callers should take care
|
||||
// to only handle non-empty values.
|
||||
func newGroupEvent(evt *events.GroupInfo) (EventKind, *EventPayload) {
|
||||
var group = Group{JID: evt.JID.ToNonAD().String()}
|
||||
if evt.Name != nil {
|
||||
group.Name = evt.Name.Name
|
||||
}
|
||||
if evt.Topic != nil {
|
||||
group.Subject = GroupSubject{
|
||||
Subject: evt.Topic.Topic,
|
||||
SetAt: evt.Topic.TopicSetAt.Unix(),
|
||||
SetByJID: evt.Topic.TopicSetBy.ToNonAD().String(),
|
||||
}
|
||||
}
|
||||
for _, p := range evt.Join {
|
||||
group.Participants = append(group.Participants, GroupParticipant{
|
||||
JID: p.ToNonAD().String(),
|
||||
Action: GroupParticipantActionAdd,
|
||||
})
|
||||
}
|
||||
for _, p := range evt.Leave {
|
||||
group.Participants = append(group.Participants, GroupParticipant{
|
||||
JID: p.ToNonAD().String(),
|
||||
Action: GroupParticipantActionRemove,
|
||||
})
|
||||
}
|
||||
for _, p := range evt.Promote {
|
||||
group.Participants = append(group.Participants, GroupParticipant{
|
||||
JID: p.ToNonAD().String(),
|
||||
Action: GroupParticipantActionUpdate,
|
||||
Affiliation: GroupAffiliationAdmin,
|
||||
})
|
||||
}
|
||||
for _, p := range evt.Demote {
|
||||
group.Participants = append(group.Participants, GroupParticipant{
|
||||
JID: p.ToNonAD().String(),
|
||||
Action: GroupParticipantActionUpdate,
|
||||
Affiliation: GroupAffiliationNone,
|
||||
})
|
||||
}
|
||||
return EventGroup, &EventPayload{Group: group}
|
||||
}
|
||||
|
||||
// NewGroup returns a concrete [Group] for the primitive data given. This function will generally
|
||||
// populate fields with as much data as is available from the remote, and is therefore should not
|
||||
// be called when partial data is to be returned.
|
||||
func newGroup(client *whatsmeow.Client, info *types.GroupInfo) Group {
|
||||
var participants []GroupParticipant
|
||||
for _, p := range info.Participants {
|
||||
if p.Error > 0 {
|
||||
continue
|
||||
}
|
||||
var affiliation = GroupAffiliationNone
|
||||
if p.IsSuperAdmin {
|
||||
affiliation = GroupAffiliationOwner
|
||||
} else if p.IsAdmin {
|
||||
affiliation = GroupAffiliationAdmin
|
||||
}
|
||||
participants = append(participants, GroupParticipant{
|
||||
JID: p.JID.ToNonAD().String(),
|
||||
Affiliation: affiliation,
|
||||
})
|
||||
}
|
||||
return Group{
|
||||
JID: info.JID.ToNonAD().String(),
|
||||
Name: info.GroupName.Name,
|
||||
Subject: GroupSubject{
|
||||
Subject: info.Topic,
|
||||
SetAt: info.TopicSetAt.Unix(),
|
||||
SetByJID: info.TopicSetBy.ToNonAD().String(),
|
||||
},
|
||||
Nickname: client.Store.PushName,
|
||||
Participants: participants,
|
||||
}
|
||||
}
|
||||
|
||||
// CallState represents the state of the call to synchronize with.
|
||||
type CallState int
|
||||
|
||||
// The call states handled by the overarching session event handler.
|
||||
const (
|
||||
CallMissed CallState = 1 + iota
|
||||
)
|
||||
|
||||
// A Call represents an incoming or outgoing voice/video call made over WhatsApp. Full support for
|
||||
// calls is currently not implemented, and this structure contains the bare minimum data required
|
||||
// for notifying on missed calls.
|
||||
type Call struct {
|
||||
State CallState
|
||||
JID string
|
||||
Timestamp int64
|
||||
}
|
||||
|
||||
// NewCallEvent returns event data meant for [Session.propagateEvent] for the call metadata given.
|
||||
func newCallEvent(state CallState, meta types.BasicCallMeta) (EventKind, *EventPayload) {
|
||||
return EventCall, &EventPayload{Call: Call{
|
||||
State: state,
|
||||
JID: meta.From.ToNonAD().String(),
|
||||
Timestamp: meta.Timestamp.Unix(),
|
||||
}}
|
||||
}
|
|
@ -0,0 +1,156 @@
|
|||
package whatsapp
|
||||
|
||||
import (
|
||||
// Standard library.
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
// Third-party libraries.
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"go.mau.fi/whatsmeow/store"
|
||||
"go.mau.fi/whatsmeow/store/sqlstore"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
walog "go.mau.fi/whatsmeow/util/log"
|
||||
)
|
||||
|
||||
// A LinkedDevice represents a unique pairing session between the gateway and WhatsApp. It is not
|
||||
// unique to the underlying "main" device (or phone number), as multiple linked devices may be paired
|
||||
// with any main device.
|
||||
type LinkedDevice struct {
|
||||
// ID is an opaque string identifying this LinkedDevice to the Session. Noted that this string
|
||||
// is currently equivalent to a password, and needs to be protected accordingly.
|
||||
ID string
|
||||
}
|
||||
|
||||
// JID returns the WhatsApp JID corresponding to the LinkedDevice ID. Empty or invalid device IDs
|
||||
// may return invalid JIDs, and this function does not handle errors.
|
||||
func (d LinkedDevice) JID() types.JID {
|
||||
jid, _ := types.ParseJID(d.ID)
|
||||
return jid
|
||||
}
|
||||
|
||||
// A ErrorLevel is a value representing the severity of a log message being handled.
|
||||
type ErrorLevel int
|
||||
|
||||
// The log levels handled by the overarching Session logger.
|
||||
const (
|
||||
LevelError ErrorLevel = 1 + iota
|
||||
LevelWarning
|
||||
LevelInfo
|
||||
LevelDebug
|
||||
)
|
||||
|
||||
// HandleLogFunc is the signature for the overarching Gateway log handling function.
|
||||
type HandleLogFunc func(ErrorLevel, string)
|
||||
|
||||
// Errorf handles the given message as representing a (typically) fatal error.
|
||||
func (h HandleLogFunc) Errorf(msg string, args ...interface{}) {
|
||||
h(LevelError, fmt.Sprintf(msg, args...))
|
||||
}
|
||||
|
||||
// Warn handles the given message as representing a non-fatal error or warning thereof.
|
||||
func (h HandleLogFunc) Warnf(msg string, args ...interface{}) {
|
||||
h(LevelWarning, fmt.Sprintf(msg, args...))
|
||||
}
|
||||
|
||||
// Infof handles the given message as representing an informational notice.
|
||||
func (h HandleLogFunc) Infof(msg string, args ...interface{}) {
|
||||
h(LevelInfo, fmt.Sprintf(msg, args...))
|
||||
}
|
||||
|
||||
// Debugf handles the given message as representing an internal-only debug message.
|
||||
func (h HandleLogFunc) Debugf(msg string, args ...interface{}) {
|
||||
h(LevelDebug, fmt.Sprintf(msg, args...))
|
||||
}
|
||||
|
||||
// Sub is a no-op and will return the receiver itself.
|
||||
func (h HandleLogFunc) Sub(string) walog.Logger {
|
||||
return h
|
||||
}
|
||||
|
||||
// A Gateway represents a persistent process for establishing individual sessions between linked
|
||||
// devices and WhatsApp.
|
||||
type Gateway struct {
|
||||
DBPath string // The filesystem path for the client database.
|
||||
Name string // The name to display when linking devices on WhatsApp.
|
||||
SkipVerifyTLS bool // Whether or not our internal HTTP client will skip TLS certificate verification.
|
||||
|
||||
// Internal variables.
|
||||
container *sqlstore.Container
|
||||
httpClient *http.Client
|
||||
logger walog.Logger
|
||||
}
|
||||
|
||||
// NewSession returns a new for the LinkedDevice given. If the linked device does not have a valid
|
||||
// ID, a pair operation will be required, as described in [Session.Login].
|
||||
func (w *Gateway) NewSession(device LinkedDevice) *Session {
|
||||
return &Session{device: device, gateway: w}
|
||||
}
|
||||
|
||||
// CleanupSession will remove all invalid and obsolete references to the given device, and should be
|
||||
// used when pairing a new device or unregistering from the Gateway.
|
||||
func (w *Gateway) CleanupSession(device LinkedDevice) error {
|
||||
devices, err := w.container.GetAllDevices()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, d := range devices {
|
||||
if d.ID == nil {
|
||||
w.logger.Infof("Removing invalid device %s from database", d.ID.String())
|
||||
_ = d.Delete()
|
||||
} else if device.ID != "" {
|
||||
if jid := device.JID(); d.ID.ToNonAD() == jid.ToNonAD() && *d.ID != jid {
|
||||
w.logger.Infof("Removing obsolete device %s from database", d.ID.String())
|
||||
_ = d.Delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Init performs initialization procedures for the Gateway, and is expected to be run before any
|
||||
// calls to [Gateway.Session].
|
||||
func (w *Gateway) Init() error {
|
||||
container, err := sqlstore.New("sqlite3", w.DBPath, w.logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if w.Name != "" {
|
||||
store.SetOSInfo(w.Name, [...]uint32{1, 0, 0})
|
||||
}
|
||||
|
||||
// Set up shared HTTP client with less lenient timeouts.
|
||||
w.httpClient = &http.Client{
|
||||
Timeout: time.Second * 10,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: w.SkipVerifyTLS},
|
||||
},
|
||||
}
|
||||
|
||||
w.container = container
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetLogHandler specifies the log handling function to use for all [Gateway] and [Session] operations.
|
||||
func (w *Gateway) SetLogHandler(h HandleLogFunc) {
|
||||
w.logger = HandleLogFunc(func(level ErrorLevel, message string) {
|
||||
// Don't allow other Goroutines from using this thread, as this might lead to concurrent
|
||||
// use of the GIL, which can lead to crashes.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
h(level, message)
|
||||
})
|
||||
}
|
||||
|
||||
// NewGateway returns a new, un-initialized Gateway. This function should always be followed by calls
|
||||
// to [Gateway.Init], assuming a valid [Gateway.DBPath] is set.
|
||||
func NewGateway() *Gateway {
|
||||
return &Gateway{}
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
from logging import getLogger
|
||||
from pathlib import Path
|
||||
from shelve import open
|
||||
|
||||
from slidge import BaseGateway, GatewayUser, global_config
|
||||
|
||||
from . import config
|
||||
from .generated import whatsapp
|
||||
|
||||
REGISTRATION_INSTRUCTIONS = (
|
||||
"Continue and scan the resulting QR codes on your main device to complete"
|
||||
" registration. More information at https://slidge.im/user/plugins/whatsapp.html"
|
||||
)
|
||||
|
||||
WELCOME_MESSAGE = (
|
||||
"Thank you for registering! Please scan the following QR code on your main device"
|
||||
" to complete registration, or type 'help' to list other available commands."
|
||||
)
|
||||
|
||||
|
||||
class Gateway(BaseGateway):
|
||||
COMPONENT_NAME = "WhatsApp (slidge)"
|
||||
COMPONENT_TYPE = "whatsapp"
|
||||
COMPONENT_AVATAR = "https://www.whatsapp.com/apple-touch-icon.png"
|
||||
|
||||
REGISTRATION_INSTRUCTIONS = REGISTRATION_INSTRUCTIONS
|
||||
WELCOME_MESSAGE = WELCOME_MESSAGE
|
||||
REGISTRATION_FIELDS = []
|
||||
|
||||
ROSTER_GROUP = "WhatsApp"
|
||||
|
||||
MARK_ALL_MESSAGES = True
|
||||
GROUPS = True
|
||||
PROPER_RECEIPTS = True
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
Path(config.DB_PATH.parent).mkdir(exist_ok=True)
|
||||
self.whatsapp = whatsapp.NewGateway()
|
||||
self.whatsapp.SetLogHandler(handle_log)
|
||||
self.whatsapp.DBPath = str(config.DB_PATH)
|
||||
self.whatsapp.SkipVerifyTLS = config.SKIP_VERIFY_TLS
|
||||
self.whatsapp.Name = "Slidge on " + str(global_config.JID)
|
||||
self.whatsapp.Init()
|
||||
|
||||
async def unregister(self, user: GatewayUser):
|
||||
user_shelf_path = (
|
||||
global_config.HOME_DIR / "whatsapp" / (user.bare_jid + ".shelf")
|
||||
)
|
||||
with open(str(user_shelf_path)) as shelf:
|
||||
try:
|
||||
device = whatsapp.LinkedDevice(ID=shelf["device_id"])
|
||||
self.whatsapp.CleanupSession(device)
|
||||
except KeyError:
|
||||
pass
|
||||
except RuntimeError as err:
|
||||
log.error("Failed to clean up WhatsApp session: %s", err)
|
||||
|
||||
|
||||
def handle_log(level, msg: str):
|
||||
"""
|
||||
Log given message of specified level in system-wide logger.
|
||||
"""
|
||||
if level == whatsapp.LevelError:
|
||||
log.error(msg)
|
||||
elif level == whatsapp.LevelWarning:
|
||||
log.warning(msg)
|
||||
elif level == whatsapp.LevelDebug:
|
||||
log.debug(msg)
|
||||
else:
|
||||
log.info(msg)
|
||||
|
||||
|
||||
log = getLogger(__name__)
|
|
@ -0,0 +1,152 @@
|
|||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from slidge.core.muc import LegacyBookmarks, LegacyMUC, LegacyParticipant, MucType
|
||||
from slixmpp.exceptions import XMPPError
|
||||
|
||||
from .generated import whatsapp
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .contact import Contact
|
||||
from .session import Session
|
||||
|
||||
|
||||
class Participant(LegacyParticipant):
|
||||
contact: "Contact"
|
||||
muc: "MUC"
|
||||
|
||||
def send_text(self, body, legacy_msg_id, **kw):
|
||||
super().send_text(body, legacy_msg_id, **kw)
|
||||
self._store(legacy_msg_id)
|
||||
|
||||
async def send_file(self, file_path, legacy_msg_id, **kw):
|
||||
await super().send_file(file_path, legacy_msg_id, **kw)
|
||||
self._store(legacy_msg_id)
|
||||
|
||||
def _store(self, legacy_msg_id: str):
|
||||
if self.is_user:
|
||||
self.muc.sent[legacy_msg_id] = str(self.session.contacts.user_legacy_id)
|
||||
else:
|
||||
self.muc.sent[legacy_msg_id] = self.contact.legacy_id
|
||||
|
||||
|
||||
class MUC(LegacyMUC[str, str, Participant, str]):
|
||||
session: "Session"
|
||||
|
||||
REACTIONS_SINGLE_EMOJI = True
|
||||
type = MucType.GROUP
|
||||
|
||||
_ALL_INFO_FILLED_ON_STARTUP = True
|
||||
|
||||
def __init__(self, *a, **kw):
|
||||
super().__init__(*a, **kw)
|
||||
self.sent = dict[str, str]()
|
||||
|
||||
async def join(self, *a, **kw):
|
||||
await super().join(*a, **kw)
|
||||
try:
|
||||
avatar = self.session.whatsapp.GetAvatar(self.legacy_id, "")
|
||||
except RuntimeError:
|
||||
# no avatar
|
||||
pass
|
||||
else:
|
||||
if avatar.URL:
|
||||
self.avatar = avatar.URL
|
||||
|
||||
def get_message_sender(self, legacy_msg_id: str):
|
||||
sender_legacy_id = self.sent.get(legacy_msg_id)
|
||||
if sender_legacy_id is None:
|
||||
raise XMPPError("internal-server-error", "Unable to find message sender")
|
||||
return sender_legacy_id
|
||||
|
||||
async def update_whatsapp_info(self, info: whatsapp.Group):
|
||||
"""
|
||||
Set MUC information based on WhatsApp group information, which may or may not be partial in
|
||||
case of updates to existing MUCs.
|
||||
"""
|
||||
if info.Nickname:
|
||||
self.user_nick = info.Nickname
|
||||
if info.Name:
|
||||
self.name = info.Name
|
||||
if info.Subject.Subject or info.Subject.SetAt:
|
||||
self.subject = info.Subject.Subject
|
||||
if info.Subject.SetAt:
|
||||
set_at = datetime.fromtimestamp(info.Subject.SetAt, tz=timezone.utc)
|
||||
self.subject_date = set_at
|
||||
if info.Subject.SetByJID:
|
||||
participant = await self.get_participant_by_legacy_id(info.Subject.SetByJID)
|
||||
if name := participant.nickname:
|
||||
self.subject_setter = name
|
||||
for ptr in info.Participants:
|
||||
data = whatsapp.GroupParticipant(handle=ptr)
|
||||
participant = await self.get_participant_by_legacy_id(data.JID)
|
||||
if data.Action == whatsapp.GroupParticipantActionRemove:
|
||||
self.remove_participant(participant)
|
||||
else:
|
||||
participant.affiliation = "member"
|
||||
if data.Affiliation == whatsapp.GroupAffiliationAdmin:
|
||||
participant.affiliation = "admin"
|
||||
elif data.Affiliation == whatsapp.GroupAffiliationOwner:
|
||||
participant.affiliation = "owner"
|
||||
|
||||
def replace_mentions(self, t: str):
|
||||
return replace_mentions(
|
||||
t,
|
||||
participants={
|
||||
c.jid_username: c.name
|
||||
for c, p in self._participants_by_contacts.items()
|
||||
}
|
||||
| {self.session.user_phone: self.user_nick}
|
||||
if self.session.user_phone # user_phone *should* be set at this point,
|
||||
else {}, # but better safe than sorry
|
||||
)
|
||||
|
||||
|
||||
class Bookmarks(LegacyBookmarks[str, MUC]):
|
||||
session: "Session"
|
||||
|
||||
def __init__(self, session: "Session"):
|
||||
super().__init__(session)
|
||||
self.__filled = False
|
||||
|
||||
async def fill(self):
|
||||
groups = self.session.whatsapp.GetGroups()
|
||||
for ptr in groups:
|
||||
await self.add_whatsapp_group(whatsapp.Group(handle=ptr))
|
||||
self.__filled = True
|
||||
|
||||
async def add_whatsapp_group(self, data: whatsapp.Group):
|
||||
muc = await self.by_legacy_id(data.JID)
|
||||
await muc.update_whatsapp_info(data)
|
||||
await muc.add_to_bookmarks()
|
||||
|
||||
async def legacy_id_to_jid_local_part(self, legacy_id: str):
|
||||
return "#" + legacy_id[: legacy_id.find("@")]
|
||||
|
||||
async def jid_local_part_to_legacy_id(self, local_part: str):
|
||||
if not local_part.startswith("#"):
|
||||
raise XMPPError("bad-request", "Invalid group ID, expected '#' prefix")
|
||||
|
||||
if not self.__filled:
|
||||
raise XMPPError(
|
||||
"recipient-unavailable", "Still fetching group info, please retry later"
|
||||
)
|
||||
|
||||
whatsapp_group_id = (
|
||||
local_part.removeprefix("#") + "@" + whatsapp.DefaultGroupServer
|
||||
)
|
||||
|
||||
if whatsapp_group_id not in self._mucs_by_legacy_id:
|
||||
raise XMPPError("item-not-found", f"No group found for {whatsapp_group_id}")
|
||||
|
||||
return whatsapp_group_id
|
||||
|
||||
|
||||
def replace_mentions(t: str, participants: dict[str, str]):
|
||||
def match(m: re.Match):
|
||||
mat = m.group(0)
|
||||
sub = participants.get(mat.replace("@", "+"), mat)
|
||||
return sub
|
||||
|
||||
return re.sub(r"@\d+", match, t)
|
|
@ -0,0 +1,502 @@
|
|||
package whatsapp
|
||||
|
||||
import (
|
||||
// Standard library.
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
// Third-party libraries.
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"go.mau.fi/whatsmeow"
|
||||
"go.mau.fi/whatsmeow/appstate"
|
||||
"go.mau.fi/whatsmeow/binary/proto"
|
||||
"go.mau.fi/whatsmeow/store"
|
||||
"go.mau.fi/whatsmeow/types"
|
||||
"go.mau.fi/whatsmeow/types/events"
|
||||
)
|
||||
|
||||
const (
|
||||
// The default host part for user JIDs on WhatsApp.
|
||||
DefaultUserServer = types.DefaultUserServer
|
||||
|
||||
// The default host part for group JIDs on WhatsApp.
|
||||
DefaultGroupServer = types.GroupServer
|
||||
|
||||
// The number of times keep-alive checks can fail before attempting to re-connect the session.
|
||||
keepAliveFailureThreshold = 3
|
||||
|
||||
// The minimum and maximum wait interval between connection retries after keep-alive check failure.
|
||||
keepAliveMinRetryInterval = 5 * time.Second
|
||||
keepAliveMaxRetryInterval = 5 * time.Minute
|
||||
)
|
||||
|
||||
// HandleEventFunc represents a handler for incoming events sent to the Python Session, accepting an
|
||||
// event type and payload. Note that this is distinct to the [Session.handleEvent] function, which
|
||||
// may emit events into the Python Session event handler but which otherwise does not process across
|
||||
// Python/Go boundaries.
|
||||
type HandleEventFunc func(EventKind, *EventPayload)
|
||||
|
||||
// A Session represents a connection (active or not) between a linked device and WhatsApp. Active
|
||||
// sessions need to be established by logging in, after which incoming events will be forwarded to
|
||||
// the adapter event handler, and outgoing events will be forwarded to WhatsApp.
|
||||
type Session struct {
|
||||
device LinkedDevice // The linked device this session corresponds to.
|
||||
eventHandler HandleEventFunc // The event handler for the overarching Session.
|
||||
client *whatsmeow.Client // The concrete client connection to WhatsApp for this session.
|
||||
gateway *Gateway // The Gateway this Session is attached to.
|
||||
}
|
||||
|
||||
// Login attempts to authenticate the given [Session], either by re-using the [LinkedDevice] attached
|
||||
// or by initiating a pairing session for a new linked device. Callers are expected to have set an
|
||||
// event handler in order to receive any incoming events from the underlying WhatsApp session.
|
||||
func (s *Session) Login() error {
|
||||
var err error
|
||||
var store *store.Device
|
||||
|
||||
// Try to fetch existing device from given device JID.
|
||||
if s.device.ID != "" {
|
||||
store, err = s.gateway.container.GetDevice(s.device.JID())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if store == nil {
|
||||
store = s.gateway.container.NewDevice()
|
||||
}
|
||||
|
||||
s.client = whatsmeow.NewClient(store, s.gateway.logger)
|
||||
s.client.AddEventHandler(s.handleEvent)
|
||||
|
||||
// Simply connect our client if already registered.
|
||||
if s.client.Store.ID != nil {
|
||||
return s.client.Connect()
|
||||
}
|
||||
|
||||
// Attempt out-of-band registration of client via QR code.
|
||||
qrChan, _ := s.client.GetQRChannel(context.Background())
|
||||
if err = s.client.Connect(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
go func() {
|
||||
for e := range qrChan {
|
||||
if !s.client.IsConnected() {
|
||||
return
|
||||
}
|
||||
switch e.Event {
|
||||
case "code":
|
||||
s.propagateEvent(EventQRCode, &EventPayload{QRCode: e.Code})
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Logout disconnects and removes the current linked device locally and initiates a logout remotely.
|
||||
func (s *Session) Logout() error {
|
||||
if s.client == nil || s.client.Store.ID == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := s.client.Logout()
|
||||
s.client = nil
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Disconnects detaches the current connection to WhatsApp without removing any linked device state.
|
||||
func (s *Session) Disconnect() error {
|
||||
if s.client != nil {
|
||||
s.client.Disconnect()
|
||||
s.client = nil
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendMessage processes the given Message and sends a WhatsApp message for the kind and contact JID
|
||||
// specified within. In general, different message kinds require different fields to be set; see the
|
||||
// documentation for the [Message] type for more information.
|
||||
func (s *Session) SendMessage(message Message) error {
|
||||
if s.client == nil || s.client.Store.ID == nil {
|
||||
return fmt.Errorf("Cannot send message for unauthenticated session")
|
||||
}
|
||||
|
||||
jid, err := types.ParseJID(message.JID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not parse sender JID for message: %s", err)
|
||||
}
|
||||
|
||||
var payload *proto.Message
|
||||
var extra whatsmeow.SendRequestExtra
|
||||
|
||||
switch message.Kind {
|
||||
case MessageAttachment:
|
||||
// Handle message with attachment, if any.
|
||||
if len(message.Attachments) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Attempt to download attachment data if URL is set.
|
||||
if url := message.Attachments[0].URL; url != "" {
|
||||
if buf, err := getFromURL(s.gateway.httpClient, url); err != nil {
|
||||
return fmt.Errorf("Failed downloading attachment: %s", err)
|
||||
} else {
|
||||
message.Attachments[0].Data = buf
|
||||
}
|
||||
}
|
||||
|
||||
// Ignore attachments with no data set or downloaded.
|
||||
if len(message.Attachments[0].Data) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Upload attachment into WhatsApp before sending message.
|
||||
if payload, err = uploadAttachment(s.client, message.Attachments[0]); err != nil {
|
||||
return fmt.Errorf("Failed uploading attachment: %s", err)
|
||||
}
|
||||
extra.ID = message.ID
|
||||
case MessageRevoke:
|
||||
// Don't send message, but revoke existing message by ID.
|
||||
payload = s.client.BuildRevoke(s.device.JID().ToNonAD(), types.EmptyJID, message.ID)
|
||||
case MessageReaction:
|
||||
// Send message as emoji reaction to a given message.
|
||||
payload = &proto.Message{
|
||||
ReactionMessage: &proto.ReactionMessage{
|
||||
Key: &proto.MessageKey{
|
||||
RemoteJid: &message.JID,
|
||||
FromMe: &message.IsCarbon,
|
||||
Id: &message.ID,
|
||||
Participant: &message.OriginJID,
|
||||
},
|
||||
Text: &message.Body,
|
||||
SenderTimestampMs: ptrTo(time.Now().UnixMilli()),
|
||||
},
|
||||
}
|
||||
default:
|
||||
// Compose extended message when made as a reply to a different message, otherwise compose
|
||||
// plain-text message for body given for all other message kinds.
|
||||
if message.ReplyID != "" {
|
||||
// Fall back to our own JID if no origin JID has been specified, in which case we assume
|
||||
// we're replying to our own messages.
|
||||
if message.OriginJID == "" {
|
||||
message.OriginJID = s.device.JID().ToNonAD().String()
|
||||
}
|
||||
payload = &proto.Message{
|
||||
ExtendedTextMessage: &proto.ExtendedTextMessage{
|
||||
Text: &message.Body,
|
||||
ContextInfo: &proto.ContextInfo{
|
||||
StanzaId: &message.ReplyID,
|
||||
QuotedMessage: &proto.Message{Conversation: ptrTo(message.ReplyBody)},
|
||||
Participant: &message.OriginJID,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
// Add URL preview, if any was given in message.
|
||||
if message.Preview.URL != "" {
|
||||
if payload == nil {
|
||||
payload = &proto.Message{
|
||||
ExtendedTextMessage: &proto.ExtendedTextMessage{Text: &message.Body},
|
||||
}
|
||||
}
|
||||
payload.ExtendedTextMessage.MatchedText = &message.Preview.URL
|
||||
payload.ExtendedTextMessage.Title = &message.Preview.Title
|
||||
if url := message.Preview.ImageURL; url != "" {
|
||||
if buf, err := getFromURL(s.gateway.httpClient, url); err == nil {
|
||||
payload.ExtendedTextMessage.JpegThumbnail = buf
|
||||
}
|
||||
} else if len(message.Preview.ImageData) > 0 {
|
||||
payload.ExtendedTextMessage.JpegThumbnail = message.Preview.ImageData
|
||||
}
|
||||
}
|
||||
if payload == nil {
|
||||
payload = &proto.Message{Conversation: &message.Body}
|
||||
}
|
||||
extra.ID = message.ID
|
||||
}
|
||||
|
||||
s.gateway.logger.Debugf("Sending message to JID '%s': %+v", jid, payload)
|
||||
_, err = s.client.SendMessage(context.Background(), jid, payload, extra)
|
||||
return err
|
||||
}
|
||||
|
||||
// SendChatState sends the given chat state notification (e.g. composing message) to WhatsApp for the
|
||||
// contact specified within.
|
||||
func (s *Session) SendChatState(state ChatState) error {
|
||||
if s.client == nil || s.client.Store.ID == nil {
|
||||
return fmt.Errorf("Cannot send chat state for unauthenticated session")
|
||||
}
|
||||
|
||||
jid, err := types.ParseJID(state.JID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not parse sender JID for chat state: %s", err)
|
||||
}
|
||||
|
||||
var presence types.ChatPresence
|
||||
switch state.Kind {
|
||||
case ChatStateComposing:
|
||||
presence = types.ChatPresenceComposing
|
||||
case ChatStatePaused:
|
||||
presence = types.ChatPresencePaused
|
||||
}
|
||||
|
||||
return s.client.SendChatPresence(jid, presence, "")
|
||||
}
|
||||
|
||||
// SendReceipt sends a read receipt to WhatsApp for the message IDs specified within.
|
||||
func (s *Session) SendReceipt(receipt Receipt) error {
|
||||
if s.client == nil || s.client.Store.ID == nil {
|
||||
return fmt.Errorf("Cannot send receipt for unauthenticated session")
|
||||
}
|
||||
|
||||
var jid, senderJID types.JID
|
||||
var err error
|
||||
|
||||
if receipt.GroupJID != "" {
|
||||
if senderJID, err = types.ParseJID(receipt.JID); err != nil {
|
||||
return fmt.Errorf("Could not parse sender JID for receipt: %s", err)
|
||||
} else if jid, err = types.ParseJID(receipt.GroupJID); err != nil {
|
||||
return fmt.Errorf("Could not parse group JID for receipt: %s", err)
|
||||
}
|
||||
} else {
|
||||
if jid, err = types.ParseJID(receipt.JID); err != nil {
|
||||
return fmt.Errorf("Could not parse sender JID for receipt: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
ids := append([]types.MessageID{}, receipt.MessageIDs...)
|
||||
return s.client.MarkRead(ids, time.Unix(receipt.Timestamp, 0), jid, senderJID)
|
||||
}
|
||||
|
||||
// GetContacts subscribes to the WhatsApp roster currently stored in the Session's internal state.
|
||||
// If `refresh` is `true`, FetchRoster will pull application state from the remote service and
|
||||
// synchronize any contacts found with the adapter.
|
||||
func (s *Session) GetContacts(refresh bool) ([]Contact, error) {
|
||||
if s.client == nil || s.client.Store.ID == nil {
|
||||
return nil, fmt.Errorf("Cannot get contacts for unauthenticated session")
|
||||
}
|
||||
|
||||
// Synchronize remote application state with local state if requested.
|
||||
if refresh {
|
||||
err := s.client.FetchAppState(appstate.WAPatchCriticalUnblockLow, false, false)
|
||||
if err != nil {
|
||||
s.gateway.logger.Warnf("Could not get app state from server: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Synchronize local contact state with overarching gateway for all local contacts.
|
||||
data, err := s.client.Store.Contacts.GetAllContacts()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed getting local contacts: %s", err)
|
||||
}
|
||||
|
||||
var contacts []Contact
|
||||
for jid, info := range data {
|
||||
if err = s.client.SubscribePresence(jid); err != nil {
|
||||
s.gateway.logger.Warnf("Failed to subscribe to presence for %s", jid)
|
||||
}
|
||||
|
||||
_, c := newContactEvent(s.client, jid, info)
|
||||
contacts = append(contacts, c.Contact)
|
||||
}
|
||||
|
||||
return contacts, nil
|
||||
}
|
||||
|
||||
// GetGroups returns a list of all group-chats currently joined in WhatsApp, along with additional
|
||||
// information on present participants.
|
||||
func (s *Session) GetGroups() ([]Group, error) {
|
||||
if s.client == nil || s.client.Store.ID == nil {
|
||||
return nil, fmt.Errorf("Cannot get groups for unauthenticated session")
|
||||
}
|
||||
|
||||
data, err := s.client.GetJoinedGroups()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed getting groups: %s", err)
|
||||
}
|
||||
|
||||
var groups []Group
|
||||
for _, info := range data {
|
||||
groups = append(groups, newGroup(s.client, info))
|
||||
}
|
||||
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
// GetAvatar fetches a profile picture for the Contact or Group JID given. If a non-empty `avatarID`
|
||||
// is also given, GetAvatar will return an empty [Avatar] instance with no error if the remote state
|
||||
// for the given ID has not changed.
|
||||
func (s *Session) GetAvatar(resourceID, avatarID string) (Avatar, error) {
|
||||
jid, err := types.ParseJID(resourceID)
|
||||
if err != nil {
|
||||
return Avatar{}, fmt.Errorf("Could not parse JID for avatar: %s", err)
|
||||
}
|
||||
|
||||
p, err := s.client.GetProfilePictureInfo(jid, &whatsmeow.GetProfilePictureParams{ExistingID: avatarID})
|
||||
if err != nil {
|
||||
return Avatar{}, fmt.Errorf("Could not get avatar: %s", err)
|
||||
} else if p != nil {
|
||||
return Avatar{ID: p.ID, URL: p.URL}, nil
|
||||
}
|
||||
|
||||
return Avatar{}, nil
|
||||
}
|
||||
|
||||
// SetEventHandler assigns the given handler function for propagating internal events into the Python
|
||||
// gateway. Note that the event handler function is not entirely safe to use directly, and all calls
|
||||
// should instead be made via the [propagateEvent] function.
|
||||
func (s *Session) SetEventHandler(h HandleEventFunc) {
|
||||
s.eventHandler = h
|
||||
}
|
||||
|
||||
// PropagateEvent handles the given event kind and payload with the adapter event handler defined in
|
||||
// SetEventHandler. If no event handler is set, this function will return early with no error.
|
||||
func (s *Session) propagateEvent(kind EventKind, payload *EventPayload) {
|
||||
if s.eventHandler == nil {
|
||||
s.gateway.logger.Errorf("Event handler not set when propagating event %d with payload %v", kind, payload)
|
||||
return
|
||||
} else if kind == EventUnknown {
|
||||
return
|
||||
}
|
||||
|
||||
// Send empty payload instead of a nil pointer, as Python has trouble handling the latter.
|
||||
if payload == nil {
|
||||
payload = &EventPayload{}
|
||||
}
|
||||
|
||||
// Don't allow other Goroutines from using this thread, as this might lead to concurrent use of
|
||||
// the GIL, which can lead to crashes.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
|
||||
s.eventHandler(kind, payload)
|
||||
}
|
||||
|
||||
// HandleEvent processes the given incoming WhatsApp event, checking its concrete type and
|
||||
// propagating it to the adapter event handler. Unknown or unhandled events are ignored, and any
|
||||
// errors that occur during processing are logged.
|
||||
func (s *Session) handleEvent(evt interface{}) {
|
||||
s.gateway.logger.Debugf("Handling event '%T': %+v", evt, evt)
|
||||
|
||||
switch evt := evt.(type) {
|
||||
case *events.AppStateSyncComplete:
|
||||
if len(s.client.Store.PushName) > 0 && evt.Name == appstate.WAPatchCriticalBlock {
|
||||
s.propagateEvent(EventConnected, &EventPayload{ConnectedJID: s.device.JID().ToNonAD().String()})
|
||||
if err := s.client.SendPresence(types.PresenceAvailable); err != nil {
|
||||
s.gateway.logger.Warnf("Failed to send available presence: %s", err)
|
||||
}
|
||||
}
|
||||
case *events.Connected, *events.PushNameSetting:
|
||||
if len(s.client.Store.PushName) == 0 {
|
||||
return
|
||||
}
|
||||
s.propagateEvent(EventConnected, &EventPayload{ConnectedJID: s.device.JID().ToNonAD().String()})
|
||||
if err := s.client.SendPresence(types.PresenceAvailable); err != nil {
|
||||
s.gateway.logger.Warnf("Failed to send available presence: %s", err)
|
||||
}
|
||||
case *events.HistorySync:
|
||||
switch evt.Data.GetSyncType() {
|
||||
case proto.HistorySync_PUSH_NAME:
|
||||
for _, n := range evt.Data.Pushnames {
|
||||
jid, err := types.ParseJID(n.GetId())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
s.propagateEvent(newContactEvent(s.client, jid, types.ContactInfo{FullName: n.GetPushname()}))
|
||||
if err = s.client.SubscribePresence(jid); err != nil {
|
||||
s.gateway.logger.Warnf("Failed to subscribe to presence for %s", jid)
|
||||
}
|
||||
}
|
||||
}
|
||||
case *events.Message:
|
||||
s.propagateEvent(newMessageEvent(s.client, evt))
|
||||
case *events.Receipt:
|
||||
s.propagateEvent(newReceiptEvent(evt))
|
||||
case *events.Presence:
|
||||
s.propagateEvent(newPresenceEvent(evt))
|
||||
case *events.PushName:
|
||||
s.propagateEvent(newContactEvent(s.client, evt.JID, types.ContactInfo{FullName: evt.NewPushName}))
|
||||
case *events.JoinedGroup:
|
||||
s.propagateEvent(EventGroup, &EventPayload{Group: newGroup(s.client, &evt.GroupInfo)})
|
||||
case *events.GroupInfo:
|
||||
s.propagateEvent(newGroupEvent(evt))
|
||||
case *events.ChatPresence:
|
||||
s.propagateEvent(newChatStateEvent(evt))
|
||||
case *events.CallTerminate:
|
||||
if evt.Reason == "timeout" {
|
||||
s.propagateEvent(newCallEvent(CallMissed, evt.BasicCallMeta))
|
||||
}
|
||||
case *events.LoggedOut:
|
||||
s.client.Disconnect()
|
||||
if err := s.client.Store.Delete(); err != nil {
|
||||
s.gateway.logger.Warnf("Unable to delete local device state on logout: %s", err)
|
||||
}
|
||||
s.client = nil
|
||||
s.propagateEvent(EventLoggedOut, nil)
|
||||
case *events.PairSuccess:
|
||||
if s.client.Store.ID == nil {
|
||||
s.gateway.logger.Errorf("Pairing succeeded, but device ID is missing")
|
||||
return
|
||||
}
|
||||
deviceID := s.client.Store.ID.String()
|
||||
s.propagateEvent(EventPair, &EventPayload{PairDeviceID: deviceID})
|
||||
if err := s.gateway.CleanupSession(LinkedDevice{ID: deviceID}); err != nil {
|
||||
s.gateway.logger.Warnf("Failed to clean up devices after pair: %s", err)
|
||||
}
|
||||
case *events.KeepAliveTimeout:
|
||||
if evt.ErrorCount > keepAliveFailureThreshold {
|
||||
s.gateway.logger.Debugf("Forcing reconnection after keep-alive timeouts...")
|
||||
go func() {
|
||||
s.client.Disconnect()
|
||||
|
||||
var interval = keepAliveMinRetryInterval
|
||||
for {
|
||||
err := s.client.Connect()
|
||||
if err == nil || err == whatsmeow.ErrAlreadyConnected {
|
||||
break
|
||||
}
|
||||
|
||||
s.gateway.logger.Errorf("Error reconnecting after keep-alive timeouts, retrying in %s: %s", interval, err)
|
||||
time.Sleep(interval)
|
||||
|
||||
if interval > keepAliveMaxRetryInterval {
|
||||
interval = keepAliveMaxRetryInterval
|
||||
} else if interval < keepAliveMaxRetryInterval {
|
||||
interval *= 2
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetFromURL is a convienience function for fetching the raw response body from the URL given, for
|
||||
// the provided HTTP client.
|
||||
func getFromURL(client *http.Client, url string) ([]byte, error) {
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// PtrTo returns a pointer to the given value, and is used for convenience when converting between
|
||||
// concrete and pointer values without assigning to a variable.
|
||||
func ptrTo[T any](t T) *T {
|
||||
return &t
|
||||
}
|
|
@ -0,0 +1,458 @@
|
|||
from asyncio import iscoroutine, run_coroutine_threadsafe
|
||||
from datetime import datetime, timezone
|
||||
from functools import wraps
|
||||
from os import remove
|
||||
from os.path import basename
|
||||
from re import search
|
||||
from shelve import open
|
||||
from typing import Optional, Union
|
||||
|
||||
from linkpreview import Link, LinkPreview
|
||||
from slidge import BaseSession, GatewayUser, global_config
|
||||
from slidge.core.contact.roster import ContactIsUser
|
||||
from slidge.util.types import LegacyAttachment, MessageReference
|
||||
|
||||
from . import config
|
||||
from .contact import Contact, Roster
|
||||
from .gateway import Gateway
|
||||
from .generated import go, whatsapp
|
||||
from .group import MUC, Bookmarks
|
||||
|
||||
MESSAGE_PAIR_SUCCESS = (
|
||||
"Pairing successful! You might need to repeat this process in the future if the"
|
||||
" Linked Device is re-registered from your main device."
|
||||
)
|
||||
|
||||
MESSAGE_LOGGED_OUT = (
|
||||
"You have been logged out, please use the re-login adhoc command "
|
||||
"and re-scan the QR code on your main device."
|
||||
)
|
||||
|
||||
URL_SEARCH_REGEX = r"(?P<url>https?://[^\s]+)"
|
||||
|
||||
|
||||
Recipient = Union[Contact, MUC]
|
||||
|
||||
|
||||
def ignore_contact_is_user(func):
|
||||
@wraps(func)
|
||||
async def wrapped(self, *a, **k):
|
||||
try:
|
||||
return await func(self, *a, **k)
|
||||
except ContactIsUser as e:
|
||||
self.log.debug("A wild ContactIsUser has been raised!", exc_info=e)
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
class Session(BaseSession[str, Recipient]):
|
||||
xmpp: Gateway
|
||||
contacts: Roster
|
||||
bookmarks: Bookmarks
|
||||
|
||||
def __init__(self, user: GatewayUser):
|
||||
super().__init__(user)
|
||||
self.user_shelf_path = (
|
||||
global_config.HOME_DIR / "whatsapp" / (self.user.bare_jid + ".shelf")
|
||||
)
|
||||
with open(str(self.user_shelf_path)) as shelf:
|
||||
try:
|
||||
device = whatsapp.LinkedDevice(ID=shelf["device_id"])
|
||||
except KeyError:
|
||||
device = whatsapp.LinkedDevice()
|
||||
self.whatsapp = self.xmpp.whatsapp.NewSession(device)
|
||||
self._handle_event = make_sync(self.handle_event, self.xmpp.loop)
|
||||
self.whatsapp.SetEventHandler(self._handle_event)
|
||||
self._connected = self.xmpp.loop.create_future()
|
||||
self.user_phone: Optional[str] = None
|
||||
|
||||
def shutdown(self):
|
||||
for c in self.contacts:
|
||||
c.offline()
|
||||
self.xmpp.loop.create_task(self.disconnect())
|
||||
|
||||
async def login(self):
|
||||
"""
|
||||
Initiate login process and connect session to WhatsApp. Depending on existing state, login
|
||||
might either return having initiated the Linked Device registration process in the background,
|
||||
or will re-connect to a previously existing Linked Device session.
|
||||
"""
|
||||
self.whatsapp.Login()
|
||||
self._connected = self.xmpp.loop.create_future()
|
||||
return await self._connected
|
||||
|
||||
async def logout(self):
|
||||
"""
|
||||
Logout from the active WhatsApp session. This will also force a remote log-out, and thus
|
||||
require pairing on next login. For simply disconnecting the active session, look at the
|
||||
:meth:`.Session.disconnect` function.
|
||||
"""
|
||||
self.whatsapp.Logout()
|
||||
remove(self.user_shelf_path)
|
||||
|
||||
async def disconnect(self):
|
||||
"""
|
||||
Disconnect the active WhatsApp session. This will not remove any local or remote state, and
|
||||
will thus allow previously authenticated sessions to re-authenticate without needing to pair.
|
||||
"""
|
||||
self.whatsapp.Disconnect()
|
||||
|
||||
@ignore_contact_is_user
|
||||
async def handle_event(self, event, ptr):
|
||||
"""
|
||||
Handle incoming event, as propagated by the WhatsApp adapter. Typically, events carry all
|
||||
state required for processing by the Gateway itself, and will do minimal processing themselves.
|
||||
"""
|
||||
data = whatsapp.EventPayload(handle=ptr)
|
||||
if event == whatsapp.EventQRCode:
|
||||
self.send_gateway_status("QR Scan Needed", show="dnd")
|
||||
await self.send_qr(data.QRCode)
|
||||
elif event == whatsapp.EventPair:
|
||||
self.send_gateway_message(MESSAGE_PAIR_SUCCESS)
|
||||
with open(str(self.user_shelf_path)) as shelf:
|
||||
shelf["device_id"] = data.PairDeviceID
|
||||
elif event == whatsapp.EventConnected:
|
||||
if not self._connected.done():
|
||||
self.contacts.user_legacy_id = data.ConnectedJID
|
||||
self.user_phone = "+" + data.ConnectedJID.split("@")[0]
|
||||
self._connected.set_result("Connected")
|
||||
elif event == whatsapp.EventLoggedOut:
|
||||
self.logged = False
|
||||
self.send_gateway_message(MESSAGE_LOGGED_OUT)
|
||||
self.send_gateway_status("Logged out", show="away")
|
||||
elif event == whatsapp.EventContact:
|
||||
await self.contacts.add_whatsapp_contact(data.Contact)
|
||||
elif event == whatsapp.EventGroup:
|
||||
await self.bookmarks.add_whatsapp_group(data.Group)
|
||||
elif event == whatsapp.EventPresence:
|
||||
contact = await self.contacts.by_legacy_id(data.Presence.JID)
|
||||
await contact.update_presence(data.Presence.Away, data.Presence.LastSeen)
|
||||
elif event == whatsapp.EventChatState:
|
||||
await self.handle_chat_state(data.ChatState)
|
||||
elif event == whatsapp.EventReceipt:
|
||||
await self.handle_receipt(data.Receipt)
|
||||
elif event == whatsapp.EventCall:
|
||||
await self.handle_call(data.Call)
|
||||
elif event == whatsapp.EventMessage:
|
||||
await self.handle_message(data.Message)
|
||||
|
||||
async def handle_chat_state(self, state: whatsapp.ChatState):
|
||||
contact = await self.get_contact_or_participant(state.JID, state.GroupJID)
|
||||
if state.Kind == whatsapp.ChatStateComposing:
|
||||
contact.composing()
|
||||
elif state.Kind == whatsapp.ChatStatePaused:
|
||||
contact.paused()
|
||||
|
||||
async def handle_receipt(self, receipt: whatsapp.Receipt):
|
||||
"""
|
||||
Handle incoming delivered/read receipt, as propagated by the WhatsApp adapter.
|
||||
"""
|
||||
contact = await self.get_contact_or_participant(receipt.JID, receipt.GroupJID)
|
||||
for message_id in receipt.MessageIDs:
|
||||
if receipt.Kind == whatsapp.ReceiptDelivered:
|
||||
contact.received(message_id)
|
||||
elif receipt.Kind == whatsapp.ReceiptRead:
|
||||
contact.displayed(legacy_msg_id=message_id, carbon=receipt.IsCarbon)
|
||||
|
||||
async def handle_call(self, call: whatsapp.Call):
|
||||
contact = await self.contacts.by_legacy_id(call.JID)
|
||||
if call.State == whatsapp.CallMissed:
|
||||
text = "Missed call"
|
||||
else:
|
||||
text = "Call"
|
||||
text = (
|
||||
text
|
||||
+ f" from {contact.name or 'tel:' + str(contact.jid.local)} (xmpp:{contact.jid.bare})"
|
||||
)
|
||||
if call.Timestamp > 0:
|
||||
call_at = datetime.fromtimestamp(call.Timestamp, tz=timezone.utc)
|
||||
text = text + f" at {call_at}"
|
||||
self.send_gateway_message(text)
|
||||
|
||||
async def _get_reply_to(self, message: whatsapp.Message):
|
||||
if not message.ReplyID:
|
||||
return
|
||||
reply_to = MessageReference(
|
||||
legacy_id=message.ReplyID,
|
||||
body=message.ReplyBody,
|
||||
)
|
||||
if message.OriginJID == self.contacts.user_legacy_id:
|
||||
reply_to.author = self.user
|
||||
else:
|
||||
reply_to.author = await self.get_contact_or_participant(
|
||||
message.OriginJID, message.GroupJID
|
||||
)
|
||||
return reply_to
|
||||
|
||||
async def _get_preview(self, text: str) -> Optional[whatsapp.Preview]:
|
||||
if not config.ENABLE_LINK_PREVIEWS:
|
||||
return None
|
||||
match = search(URL_SEARCH_REGEX, text)
|
||||
if not match:
|
||||
return None
|
||||
url = match.group("url")
|
||||
async with self.http.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
return None
|
||||
preview = LinkPreview(Link(url, await resp.text()))
|
||||
if not preview.title:
|
||||
return None
|
||||
try:
|
||||
return whatsapp.Preview(
|
||||
Title=preview.title,
|
||||
Description=preview.description or "",
|
||||
URL=url,
|
||||
ImageURL=preview.image or "",
|
||||
)
|
||||
except Exception as e:
|
||||
self.log.debug("Could not generate a preview for %s", url, exc_info=e)
|
||||
return None
|
||||
|
||||
async def handle_message(self, message: whatsapp.Message):
|
||||
"""
|
||||
Handle incoming message, as propagated by the WhatsApp adapter. Messages can be one of many
|
||||
types, including plain-text messages, media messages, reactions, etc., and may also include
|
||||
other aspects such as references to other messages for the purposes of quoting or correction.
|
||||
"""
|
||||
contact = await self.get_contact_or_participant(message.JID, message.GroupJID)
|
||||
reply_to = await self._get_reply_to(message)
|
||||
message_timestamp = (
|
||||
datetime.fromtimestamp(message.Timestamp, tz=timezone.utc)
|
||||
if message.Timestamp > 0
|
||||
else None
|
||||
)
|
||||
if message.Kind == whatsapp.MessagePlain:
|
||||
if hasattr(contact, "muc"):
|
||||
body = contact.muc.replace_mentions(message.Body)
|
||||
else:
|
||||
body = message.Body
|
||||
contact.send_text(
|
||||
body=body,
|
||||
legacy_msg_id=message.ID,
|
||||
when=message_timestamp,
|
||||
reply_to=reply_to,
|
||||
carbon=message.IsCarbon,
|
||||
)
|
||||
elif message.Kind == whatsapp.MessageAttachment:
|
||||
await contact.send_files(
|
||||
attachments=Attachment.convert_list(message.Attachments),
|
||||
legacy_msg_id=message.ID,
|
||||
reply_to=reply_to,
|
||||
when=message_timestamp,
|
||||
carbon=message.IsCarbon,
|
||||
)
|
||||
elif message.Kind == whatsapp.MessageRevoke:
|
||||
contact.retract(legacy_msg_id=message.ID, carbon=message.IsCarbon)
|
||||
elif message.Kind == whatsapp.MessageReaction:
|
||||
emojis = [message.Body] if message.Body else []
|
||||
contact.react(
|
||||
legacy_msg_id=message.ID, emojis=emojis, carbon=message.IsCarbon
|
||||
)
|
||||
|
||||
async def send_text(
|
||||
self,
|
||||
chat: Recipient,
|
||||
text: str,
|
||||
*,
|
||||
reply_to_msg_id: Optional[str] = None,
|
||||
reply_to_fallback_text: Optional[str] = None,
|
||||
reply_to=None,
|
||||
**_,
|
||||
):
|
||||
"""
|
||||
Send outgoing plain-text message to given WhatsApp contact.
|
||||
"""
|
||||
message_id = whatsapp.GenerateMessageID()
|
||||
message_preview = await self._get_preview(text) or whatsapp.Preview()
|
||||
message = whatsapp.Message(
|
||||
ID=message_id, JID=chat.legacy_id, Body=text, Preview=message_preview
|
||||
)
|
||||
set_reply_to(chat, message, reply_to_msg_id, reply_to_fallback_text, reply_to)
|
||||
self.whatsapp.SendMessage(message)
|
||||
return message_id
|
||||
|
||||
async def send_file(
|
||||
self,
|
||||
chat: Recipient,
|
||||
url: str,
|
||||
http_response,
|
||||
reply_to_msg_id: Optional[str] = None,
|
||||
reply_to_fallback_text: Optional[str] = None,
|
||||
reply_to=None,
|
||||
**_,
|
||||
):
|
||||
"""
|
||||
Send outgoing media message (i.e. audio, image, document) to given WhatsApp contact.
|
||||
"""
|
||||
message_id = whatsapp.GenerateMessageID()
|
||||
message_attachment = whatsapp.Attachment(
|
||||
MIME=http_response.content_type, Filename=basename(url), URL=url
|
||||
)
|
||||
message = whatsapp.Message(
|
||||
Kind=whatsapp.MessageAttachment,
|
||||
ID=message_id,
|
||||
JID=chat.legacy_id,
|
||||
ReplyID=reply_to_msg_id if reply_to_msg_id else "",
|
||||
Attachments=whatsapp.Slice_whatsapp_Attachment([message_attachment]),
|
||||
)
|
||||
set_reply_to(chat, message, reply_to_msg_id, reply_to_fallback_text, reply_to)
|
||||
self.whatsapp.SendMessage(message)
|
||||
return message_id
|
||||
|
||||
async def active(self, c: Recipient, thread=None):
|
||||
"""
|
||||
WhatsApp has no equivalent to the "active" chat state, so calls to this function are no-ops.
|
||||
"""
|
||||
pass
|
||||
|
||||
async def inactive(self, c: Recipient, thread=None):
|
||||
"""
|
||||
WhatsApp has no equivalent to the "inactive" chat state, so calls to this function are no-ops.
|
||||
"""
|
||||
pass
|
||||
|
||||
async def composing(self, c: Recipient, thread=None):
|
||||
"""
|
||||
Send "composing" chat state to given WhatsApp contact, signifying that a message is currently
|
||||
being composed.
|
||||
"""
|
||||
state = whatsapp.ChatState(JID=c.legacy_id, Kind=whatsapp.ChatStateComposing)
|
||||
self.whatsapp.SendChatState(state)
|
||||
|
||||
async def paused(self, c: Recipient, thread=None):
|
||||
"""
|
||||
Send "paused" chat state to given WhatsApp contact, signifying that an (unsent) message is no
|
||||
longer being composed.
|
||||
"""
|
||||
state = whatsapp.ChatState(JID=c.legacy_id, Kind=whatsapp.ChatStatePaused)
|
||||
self.whatsapp.SendChatState(state)
|
||||
|
||||
async def displayed(self, c: Recipient, legacy_msg_id: str, thread=None):
|
||||
"""
|
||||
Send "read" receipt, signifying that the WhatsApp message sent has been displayed on the XMPP
|
||||
client.
|
||||
"""
|
||||
receipt = whatsapp.Receipt(
|
||||
MessageIDs=go.Slice_string([legacy_msg_id]),
|
||||
JID=c.get_message_sender(legacy_msg_id)
|
||||
if isinstance(c, MUC)
|
||||
else c.legacy_id,
|
||||
GroupJID=c.legacy_id if c.is_group else "",
|
||||
)
|
||||
self.whatsapp.SendReceipt(receipt)
|
||||
|
||||
async def react(
|
||||
self, c: Recipient, legacy_msg_id: str, emojis: list[str], thread=None
|
||||
):
|
||||
"""
|
||||
Send or remove emoji reaction to existing WhatsApp message.
|
||||
Slidge core makes sure that the emojis parameter is always empty or a
|
||||
*single* emoji.
|
||||
"""
|
||||
is_carbon = self._is_carbon(c, legacy_msg_id)
|
||||
message_sender_id = (
|
||||
c.get_message_sender(legacy_msg_id)
|
||||
if not is_carbon and isinstance(c, MUC)
|
||||
else ""
|
||||
)
|
||||
message = whatsapp.Message(
|
||||
Kind=whatsapp.MessageReaction,
|
||||
ID=legacy_msg_id,
|
||||
JID=c.legacy_id,
|
||||
OriginJID=message_sender_id,
|
||||
Body=emojis[0] if emojis else "",
|
||||
IsCarbon=is_carbon,
|
||||
)
|
||||
self.whatsapp.SendMessage(message)
|
||||
|
||||
async def retract(self, c: Recipient, legacy_msg_id: str, thread=None):
|
||||
"""
|
||||
Request deletion (aka retraction) for a given WhatsApp message.
|
||||
"""
|
||||
message = whatsapp.Message(
|
||||
Kind=whatsapp.MessageRevoke, ID=legacy_msg_id, JID=c.legacy_id
|
||||
)
|
||||
self.whatsapp.SendMessage(message)
|
||||
|
||||
async def correct(self, c: Recipient, text: str, legacy_msg_id: str, thread=None):
|
||||
pass
|
||||
|
||||
async def search(self, form_values: dict[str, str]):
|
||||
self.send_gateway_message("Searching on WhatsApp has not been implemented yet.")
|
||||
|
||||
async def get_contact_or_participant(
|
||||
self, legacy_contact_id: str, legacy_group_jid: str
|
||||
):
|
||||
"""
|
||||
Return either a Contact or a Participant instance for the given contact and group JIDs.
|
||||
"""
|
||||
if legacy_group_jid:
|
||||
muc = await self.bookmarks.by_legacy_id(legacy_group_jid)
|
||||
return await muc.get_participant_by_legacy_id(legacy_contact_id)
|
||||
else:
|
||||
return await self.contacts.by_legacy_id(legacy_contact_id)
|
||||
|
||||
def _is_carbon(self, c: Recipient, legacy_msg_id: str):
|
||||
if c.is_group:
|
||||
return legacy_msg_id in self.muc_sent_msg_ids
|
||||
else:
|
||||
return legacy_msg_id in self.sent
|
||||
|
||||
|
||||
class Attachment(LegacyAttachment):
|
||||
@staticmethod
|
||||
def convert_list(attachments: list):
|
||||
return [
|
||||
Attachment.convert(whatsapp.Attachment(handle=ptr)) for ptr in attachments
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def convert(wa_attachment: whatsapp.Attachment):
|
||||
return Attachment(
|
||||
content_type=wa_attachment.MIME,
|
||||
data=bytes(wa_attachment.Data),
|
||||
caption=wa_attachment.Caption,
|
||||
name=wa_attachment.Filename,
|
||||
)
|
||||
|
||||
|
||||
def make_sync(func, loop):
|
||||
"""
|
||||
Wrap async function in synchronous operation, running against the given loop in thread-safe mode.
|
||||
"""
|
||||
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
result = func(*args, **kwargs)
|
||||
if iscoroutine(result):
|
||||
future = run_coroutine_threadsafe(result, loop)
|
||||
return future.result()
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def strip_quote_prefix(text: str):
|
||||
"""
|
||||
Return multi-line text without leading quote marks (i.e. the ">" character).
|
||||
"""
|
||||
return "\n".join(x.lstrip(">").strip() for x in text.split("\n")).strip()
|
||||
|
||||
|
||||
def set_reply_to(
|
||||
chat: Recipient,
|
||||
message: whatsapp.Message,
|
||||
reply_to_msg_id: Optional[str] = None,
|
||||
reply_to_fallback_text: Optional[str] = None,
|
||||
reply_to=None,
|
||||
):
|
||||
if reply_to_msg_id:
|
||||
message.ReplyID = reply_to_msg_id
|
||||
if reply_to:
|
||||
message.OriginJID = (
|
||||
reply_to.contact.legacy_id if chat.is_group else chat.legacy_id
|
||||
)
|
||||
if reply_to_fallback_text:
|
||||
message.ReplyBody = strip_quote_prefix(reply_to_fallback_text)
|
||||
message.Body = message.Body.lstrip()
|
||||
return message
|
|
@ -0,0 +1,6 @@
|
|||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from slidge import global_config
|
||||
|
||||
global_config.HOME_DIR = Path(tempfile.gettempdir())
|
|
@ -0,0 +1,10 @@
|
|||
from slidge.util.test import SlidgeTest
|
||||
|
||||
import slidge_whatsapp
|
||||
|
||||
|
||||
class TestSlidgeWhatsapp(SlidgeTest):
|
||||
def test_base(self):
|
||||
self.recv("<presence />")
|
||||
reply = self.next_sent()
|
||||
assert reply["type"] == "error"
|
|
@ -0,0 +1,26 @@
|
|||
from slidge_whatsapp.group import replace_mentions
|
||||
|
||||
|
||||
def test_replace_mentions():
|
||||
text = "Hayo @1234, it's cool in here in with @5678!! @123333"
|
||||
|
||||
assert (
|
||||
replace_mentions(
|
||||
text,
|
||||
{"+1234": "bibi", "+5678": "baba"},
|
||||
)
|
||||
== "Hayo bibi, it's cool in here in with baba!! @123333"
|
||||
)
|
||||
|
||||
assert replace_mentions(text, {}) == text
|
||||
|
||||
assert replace_mentions(text, {"+123333": "prout"}) == text.replace(
|
||||
"@123333", "prout"
|
||||
)
|
||||
|
||||
assert replace_mentions("+1234", {"+1234": "bibi", "+5678": "baba"}) == "+1234"
|
||||
|
||||
assert (
|
||||
replace_mentions("@1234@1234@123", {"+1234": "bibi", "+5678": "baba"})
|
||||
== "bibibibi@123"
|
||||
)
|
|
@ -0,0 +1,43 @@
|
|||
"""
|
||||
Hot-reloader for both go and python files (in the docker-compose dev setup)
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.tricks import AutoRestartTrick, ShellCommandTrick
|
||||
|
||||
if __name__ == "__main__":
|
||||
observer = Observer()
|
||||
auto_restart = AutoRestartTrick(
|
||||
command=["python", "-m", "slidge"] + sys.argv[2:] if len(sys.argv) > 2 else [],
|
||||
patterns=["*.py"],
|
||||
ignore_patterns=["generated/*.py"],
|
||||
)
|
||||
gopy_cmd = "gopy build -output=generated -no-make=true ."
|
||||
gopy_build = ShellCommandTrick(
|
||||
shell_command='cd "$(dirname ${watch_src_path})" && '
|
||||
+ gopy_cmd
|
||||
+ ' && touch "$(dirname ${watch_src_path})/__init__.py"',
|
||||
patterns=["*.go"],
|
||||
ignore_patterns=["generated/*.go"],
|
||||
drop_during_process=True,
|
||||
)
|
||||
|
||||
path = sys.argv[1] if len(sys.argv) > 1 else "."
|
||||
observer.schedule(auto_restart, path, recursive=True)
|
||||
observer.schedule(gopy_build, path, recursive=True)
|
||||
observer.start()
|
||||
|
||||
try:
|
||||
for dirpath, _, filenames in os.walk(path):
|
||||
if "go.mod" in filenames:
|
||||
subprocess.run(gopy_cmd, shell=True, cwd=dirpath)
|
||||
auto_restart.start()
|
||||
while observer.is_alive():
|
||||
observer.join(1)
|
||||
finally:
|
||||
observer.stop()
|
||||
observer.join()
|
Loading…
Reference in New Issue