Merge branch 'develop' into kelare-develop

This commit is contained in:
zhaoYangguang 2021-10-27 17:22:53 +08:00
commit a918396f56
62 changed files with 12159 additions and 0 deletions

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM golang:1-alpine3.14 AS builder
RUN apk add --no-cache git ca-certificates build-base su-exec olm-dev
COPY . /build
WORKDIR /build
RUN go build -o /usr/bin/matrix-skype
FROM alpine:3.14
ENV UID=1337 \
GID=1337
RUN apk add --no-cache ffmpeg su-exec ca-certificates olm bash jq yq curl
COPY --from=builder /usr/bin/matrix-skype /usr/bin/matrix-skype
COPY --from=builder /build/example-config.yaml /opt/matrix-skype/example-config.yaml
COPY --from=builder /build/docker-run.sh /docker-run.sh
VOLUME /data
CMD ["/docker-run.sh"]

15
Dockerfile.ci Normal file
View File

@ -0,0 +1,15 @@
FROM alpine:latest
ENV UID=1337 \
GID=1337
RUN echo "@edge_community http://dl-cdn.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
RUN apk add --no-cache su-exec ca-certificates olm@edge_community
ARG EXECUTABLE=./matrix-skype
COPY $EXECUTABLE /usr/bin/matrix-skype
COPY ./example-config.yaml /opt/matrix-skype/example-config.yaml
COPY ./docker-run.sh /docker-run.sh
VOLUME /data
CMD ["/docker-run.sh"]

661
LICENSE Normal file
View File

@ -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/>.

View File

@ -0,0 +1,31 @@
# matrix-skype
matrix-skype is a library for bridging matrix and skype, about matrix, please refer to [matrix.org](http://matrix.org/).
## functions are available
`The following functions are available in both directions without special instructions`
* create private conversation
* create group conversation
* private conversation
* group conversation
* kick/invite/leave/join(group)
* generate invitation link(group)
* quote message(Circular references may have some bugs)
* mention someone(message)
* media message
* picture message
* group avatar/name change
* user name/avatar change
* Typing status
The skype api lib of matrix-skype is [go-skypeapi](https://github.com/kelaresg/go-skypeapi).
[matrix room(#goskypebridge:matrix.org)](https://app.element.io/#/room/#goskypebridge:matrix.org)
This matrix-skype bridge is based on [mautrix-whatsapp](https://github.com/tulir/mautrix-whatsapp),so the installation and usage methods are very similar to mautrix-whatsapp
> # mautrix-whatsapp
> A Matrix-WhatsApp puppeting bridge based on the [Rhymen/go-whatsapp](https://github.com/Rhymen/go-whatsapp)
> implementation of the [sigalor/whatsapp-web-reveng](https://github.com/sigalor/whatsapp-web-reveng) project.
> ### [Wiki](https://github.com/tulir/mautrix-whatsapp/wiki)

2
build.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/sh
go build -ldflags "-X main.Tag=$(git describe --exact-match --tags 2>/dev/null) -X main.Commit=$(git rev-parse HEAD) -X 'main.BuildTime=`date '+%b %_d %Y, %H:%M:%S'`'" "$@"

96
commands-special.go Normal file
View File

@ -0,0 +1,96 @@
// 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/>.
package main
import (
skype "github.com/kelaresg/go-skypeapi"
"strings"
"time"
)
func (handler *CommandHandler) CommandSpecialMux(ce *CommandEvent) {
switch ce.Command {
case "special-create":
if !ce.User.HasSession() {
ce.Reply("You are not logged in. Use the `login` command to log into Skype.")
return
}
switch ce.Command {
case "special-create":
handler.CommandSpecialCreate(ce)
}
default:
ce.Reply("Unknown Command")
}
}
func (handler *CommandHandler) CommandSpecialHelp(ce *CommandEvent) {
cmdPrefix := ""
if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
}
ce.Reply("* " + strings.Join([]string{
cmdPrefix + cmdSpecialCreateHelp,
}, "\n* "))
}
const cmdSpecialCreateHelp = `special-create <_topic_> <_member user id_>,... - Create a group.`
func (handler *CommandHandler) CommandSpecialCreate(ce *CommandEvent) {
if len(ce.Args) < 2 {
ce.Reply("**Usage:** `special-create <topic> <member user id>,...`")
return
}
user := ce.User
topic := ce.Args[0]
members := skype.Members{}
// The user who created the group must be in the members and have "Admin" rights
userId := ce.User.Conn.UserProfile.Username
member2 := skype.Member{
Id: "8:" + userId,
Role: "Admin",
}
members.Members = append(members.Members, member2)
members.Properties = skype.Properties{
HistoryDisclosed: "true",
Topic: topic,
}
handler.log.Debugln("Create Group", topic, "with", members)
err := user.Conn.HandleGroupCreate(members)
inputArr := strings.Split(ce.Args[1], ",")
members = skype.Members{}
for _, memberId := range inputArr {
members.Members = append(members.Members, skype.Member{
Id: memberId,
Role: "Admin",
})
}
conversationId, ok := <-user.Conn.CreateChan
if ok {
err = user.Conn.AddMember(members, conversationId)
}
if err != nil {
ce.Reply("Please confirm that parameters is correct.")
} else {
ce.Reply("Syncing group list...")
time.Sleep(time.Duration(3) * time.Second)
ce.Reply("Syncing group list completed")
}
}

1256
commands.go Normal file

File diff suppressed because it is too large Load Diff

116
community.go Normal file
View File

@ -0,0 +1,116 @@
package main
import (
"fmt"
"net/http"
"maunium.net/go/mautrix"
)
func (user *User) inviteToCommunity() {
url := user.bridge.Bot.BuildURL("groups", user.CommunityID, "admin", "users", "invite", user.MXID)
reqBody := map[string]interface{}{}
_, err := user.bridge.Bot.MakeRequest(http.MethodPut, url, &reqBody, nil)
if err != nil {
user.log.Warnfln("Failed to invite user to personal filtering community %s: %v", user.CommunityID, err)
}
}
func (user *User) updateCommunityProfile() {
url := user.bridge.Bot.BuildURL("groups", user.CommunityID, "profile")
profileReq := struct {
Name string `json:"name"`
AvatarURL string `json:"avatar_url"`
ShortDescription string `json:"short_description"`
}{"Skype", user.bridge.Config.AppService.Bot.Avatar, "Your Skype bridged chats"}
_, err := user.bridge.Bot.MakeRequest(http.MethodPost, url, &profileReq, nil)
if err != nil {
user.log.Warnfln("Failed to update metadata of %s: %v", user.CommunityID, err)
}
}
func (user *User) createCommunity() {
if user.IsRelaybot || !user.bridge.Config.Bridge.EnableCommunities() {
return
}
localpart, server, _ := user.MXID.Parse()
community := user.bridge.Config.Bridge.FormatCommunity(localpart, server)
user.log.Debugln("Creating personal filtering community", community)
bot := user.bridge.Bot
req := struct {
Localpart string `json:"localpart"`
}{community}
resp := struct {
GroupID string `json:"group_id"`
}{}
_, err := bot.MakeRequest(http.MethodPost, bot.BuildURL("create_group"), &req, &resp)
if err != nil {
if httpErr, ok := err.(mautrix.HTTPError); ok {
if httpErr.RespError.Err != "Group already exists" {
user.log.Warnln("Server responded with error creating personal filtering community:", err)
return
} else {
user.log.Debugln("Personal filtering community", resp.GroupID, "already existed")
user.CommunityID = fmt.Sprintf("+%s:%s", req.Localpart, user.bridge.Config.Homeserver.Domain)
}
} else {
user.log.Warnln("Unknown error creating personal filtering community:", err)
return
}
} else {
user.log.Infoln("Created personal filtering community %s", resp.GroupID)
user.CommunityID = resp.GroupID
user.inviteToCommunity()
user.updateCommunityProfile()
}
}
func (user *User) addPuppetToCommunity(puppet *Puppet) bool {
if user.IsRelaybot || len(user.CommunityID) == 0 {
return false
}
bot := user.bridge.Bot
url := bot.BuildURL("groups", user.CommunityID, "admin", "users", "invite", puppet.MXID)
blankReqBody := map[string]interface{}{}
_, err := bot.MakeRequest(http.MethodPut, url, &blankReqBody, nil)
if err != nil {
user.log.Warnfln("Failed to invite %s to %s: %v", puppet.MXID, user.CommunityID, err)
return false
}
reqBody := map[string]map[string]string{
"m.visibility": {
"type": "private",
},
}
url = bot.BuildURLWithQuery(mautrix.URLPath{"groups", user.CommunityID, "self", "accept_invite"}, map[string]string{
"user_id": puppet.MXID.String(),
})
_, err = bot.MakeRequest(http.MethodPut, url, &reqBody, nil)
if err != nil {
user.log.Warnfln("Failed to join %s as %s: %v", user.CommunityID, puppet.MXID, err)
return false
}
user.log.Debugln("Added", puppet.MXID, "to", user.CommunityID)
return true
}
func (user *User) addPortalToCommunity(portal *Portal) bool {
if user.IsRelaybot || len(user.CommunityID) == 0 || len(portal.MXID) == 0 {
return false
}
bot := user.bridge.Bot
url := bot.BuildURL("groups", user.CommunityID, "admin", "rooms", portal.MXID)
reqBody := map[string]map[string]string{
"m.visibility": {
"type": "private",
},
}
_, err := bot.MakeRequest(http.MethodPut, url, &reqBody, nil)
if err != nil {
user.log.Warnfln("Failed to add %s to %s: %v", portal.MXID, user.CommunityID, err)
return false
}
user.log.Debugln("Added", portal.MXID, "to", user.CommunityID)
return true
}

324
config/bridge.go Normal file
View File

@ -0,0 +1,324 @@
package config
import (
"bytes"
skype "github.com/kelaresg/go-skypeapi"
"strconv"
"strings"
"text/template"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"github.com/kelaresg/matrix-skype/types"
)
type BridgeConfig struct {
UsernameTemplate string `yaml:"username_template"`
DisplaynameTemplate string `yaml:"displayname_template"`
CommunityTemplate string `yaml:"community_template"`
ConnectionTimeout int `yaml:"connection_timeout"`
FetchMessageOnTimeout bool `yaml:"fetch_message_on_timeout"`
DeliveryReceipts bool `yaml:"delivery_receipts"`
LoginQRRegenCount int `yaml:"login_qr_regen_count"`
MaxConnectionAttempts int `yaml:"max_connection_attempts"`
ConnectionRetryDelay int `yaml:"connection_retry_delay"`
ReportConnectionRetry bool `yaml:"report_connection_retry"`
ChatListWait int `yaml:"chat_list_wait"`
PortalSyncWait int `yaml:"portal_sync_wait"`
CallNotices struct {
Start bool `yaml:"start"`
End bool `yaml:"end"`
} `yaml:"call_notices"`
InitialChatSync int `yaml:"initial_chat_sync_count"`
InitialHistoryFill int `yaml:"initial_history_fill_count"`
HistoryDisableNotifs bool `yaml:"initial_history_disable_notifications"`
RecoverChatSync int `yaml:"recovery_chat_sync_count"`
RecoverHistory bool `yaml:"recovery_history_backfill"`
SyncChatMaxAge uint64 `yaml:"sync_max_chat_age"`
SyncWithCustomPuppets bool `yaml:"sync_with_custom_puppets"`
LoginSharedSecret string `yaml:"login_shared_secret"`
InviteOwnPuppetForBackfilling bool `yaml:"invite_own_puppet_for_backfilling"`
PrivateChatPortalMeta bool `yaml:"private_chat_portal_meta"`
WhatsappThumbnail bool `yaml:"whatsapp_thumbnail"`
AllowUserInvite bool `yaml:"allow_user_invite"`
CommandPrefix string `yaml:"command_prefix"`
Encryption struct {
Allow bool `yaml:"allow"`
Default bool `yaml:"default"`
KeySharing struct {
Allow bool `yaml:"allow"`
RequireCrossSigning bool `yaml:"require_cross_signing"`
RequireVerification bool `yaml:"require_verification"`
} `yaml:"key_sharing"`
PuppetId struct {
Allow bool `yaml:"allow"`
Key string `yaml:"key"`
UsernameTemplatePrefix string `yaml:"username_template_prefix"`
} `yaml:"puppet_id"`
} `yaml:"encryption"`
Permissions PermissionConfig `yaml:"permissions"`
Relaybot RelaybotConfig `yaml:"relaybot"`
usernameTemplate *template.Template `yaml:"-"`
displaynameTemplate *template.Template `yaml:"-"`
communityTemplate *template.Template `yaml:"-"`
}
func (bc *BridgeConfig) setDefaults() {
bc.ConnectionTimeout = 20
bc.FetchMessageOnTimeout = false
bc.DeliveryReceipts = false
bc.LoginQRRegenCount = 2
bc.MaxConnectionAttempts = 3
bc.ConnectionRetryDelay = -1
bc.ReportConnectionRetry = true
bc.ChatListWait = 30
bc.PortalSyncWait = 600
bc.CallNotices.Start = true
bc.CallNotices.End = true
bc.InitialChatSync = 10
bc.InitialHistoryFill = 20
bc.RecoverChatSync = -1
bc.RecoverHistory = true
bc.SyncChatMaxAge = 259200
bc.SyncWithCustomPuppets = true
bc.LoginSharedSecret = ""
bc.InviteOwnPuppetForBackfilling = true
bc.PrivateChatPortalMeta = false
}
type umBridgeConfig BridgeConfig
func (bc *BridgeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
err := unmarshal((*umBridgeConfig)(bc))
if err != nil {
return err
}
bc.usernameTemplate, err = template.New("username").Parse(bc.UsernameTemplate)
if err != nil {
return err
}
bc.displaynameTemplate, err = template.New("displayname").Parse(bc.DisplaynameTemplate)
if err != nil {
return err
}
if len(bc.CommunityTemplate) > 0 {
bc.communityTemplate, err = template.New("community").Parse(bc.CommunityTemplate)
if err != nil {
return err
}
}
return nil
}
type UsernameTemplateArgs struct {
UserID id.UserID
}
func (bc BridgeConfig) FormatDisplayname(contact skype.Contact) (string, int8) {
var buf bytes.Buffer
if index := strings.IndexRune(contact.PersonId, '@'); index > 0 {
contact.PersonId = "+" + contact.PersonId[:index]
}
bc.displaynameTemplate.Execute(&buf, contact)
var quality int8
switch {
//case len(contact.Notify) > 0:
// quality = 3
case len(contact.DisplayName) > 0:
quality = 3
case len(contact.PersonId) > 0:
quality = 1
default:
quality = 0
}
return buf.String(), quality
}
func (bc BridgeConfig) FormatUsername(userID types.SkypeID) string {
var buf bytes.Buffer
bc.usernameTemplate.Execute(&buf, userID)
return buf.String()
}
type CommunityTemplateArgs struct {
Localpart string
Server string
}
func (bc BridgeConfig) EnableCommunities() bool {
return bc.communityTemplate != nil
}
func (bc BridgeConfig) FormatCommunity(localpart, server string) string {
var buf bytes.Buffer
bc.communityTemplate.Execute(&buf, CommunityTemplateArgs{localpart, server})
return buf.String()
}
type PermissionConfig map[string]PermissionLevel
type PermissionLevel int
const (
PermissionLevelDefault PermissionLevel = 0
PermissionLevelRelaybot PermissionLevel = 5
PermissionLevelUser PermissionLevel = 10
PermissionLevelAdmin PermissionLevel = 100
)
func (pc *PermissionConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
rawPC := make(map[string]string)
err := unmarshal(&rawPC)
if err != nil {
return err
}
if *pc == nil {
*pc = make(map[string]PermissionLevel)
}
for key, value := range rawPC {
switch strings.ToLower(value) {
case "relaybot":
(*pc)[key] = PermissionLevelRelaybot
case "user":
(*pc)[key] = PermissionLevelUser
case "admin":
(*pc)[key] = PermissionLevelAdmin
default:
val, err := strconv.Atoi(value)
if err != nil {
(*pc)[key] = PermissionLevelDefault
} else {
(*pc)[key] = PermissionLevel(val)
}
}
}
return nil
}
func (pc *PermissionConfig) MarshalYAML() (interface{}, error) {
if *pc == nil {
return nil, nil
}
rawPC := make(map[string]string)
for key, value := range *pc {
switch value {
case PermissionLevelRelaybot:
rawPC[key] = "relaybot"
case PermissionLevelUser:
rawPC[key] = "user"
case PermissionLevelAdmin:
rawPC[key] = "admin"
default:
rawPC[key] = strconv.Itoa(int(value))
}
}
return rawPC, nil
}
func (pc PermissionConfig) IsRelaybotWhitelisted(userID id.UserID) bool {
return pc.GetPermissionLevel(userID) >= PermissionLevelRelaybot
}
func (pc PermissionConfig) IsWhitelisted(userID id.UserID) bool {
return pc.GetPermissionLevel(userID) >= PermissionLevelUser
}
func (pc PermissionConfig) IsAdmin(userID id.UserID) bool {
return pc.GetPermissionLevel(userID) >= PermissionLevelAdmin
}
func (pc PermissionConfig) GetPermissionLevel(userID id.UserID) PermissionLevel {
permissions, ok := pc[string(userID)]
if ok {
return permissions
}
_, homeserver, _ := userID.Parse()
permissions, ok = pc[homeserver]
if len(homeserver) > 0 && ok {
return permissions
}
permissions, ok = pc["*"]
if ok {
return permissions
}
return PermissionLevelDefault
}
type RelaybotConfig struct {
Enabled bool `yaml:"enabled"`
ManagementRoom id.RoomID `yaml:"management"`
InviteUsers []id.UserID `yaml:"invites"`
MessageFormats map[event.MessageType]string `yaml:"message_formats"`
messageTemplates *template.Template `yaml:"-"`
}
type umRelaybotConfig RelaybotConfig
func (rc *RelaybotConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
err := unmarshal((*umRelaybotConfig)(rc))
if err != nil {
return err
}
rc.messageTemplates = template.New("messageTemplates")
for key, format := range rc.MessageFormats {
_, err := rc.messageTemplates.New(string(key)).Parse(format)
if err != nil {
return err
}
}
return nil
}
type Sender struct {
UserID id.UserID
*event.MemberEventContent
}
type formatData struct {
Sender Sender
Message string
Content *event.MessageEventContent
}
func (rc *RelaybotConfig) FormatMessage(content *event.MessageEventContent, sender id.UserID, member *event.MemberEventContent) (string, error) {
var output strings.Builder
err := rc.messageTemplates.ExecuteTemplate(&output, string(content.MsgType), formatData{
Sender: Sender{
UserID: sender,
MemberEventContent: member,
},
Content: content,
Message: content.FormattedBody,
})
return output.String(), err
}

110
config/config.go Normal file
View File

@ -0,0 +1,110 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package config
import (
"io/ioutil"
"maunium.net/go/mautrix/patch"
"gopkg.in/yaml.v2"
"maunium.net/go/mautrix/appservice"
)
type Config struct {
Homeserver struct {
Address string `yaml:"address"`
Domain string `yaml:"domain"`
ServerName string `yaml:"server_name"`
} `yaml:"homeserver"`
AppService struct {
Address string `yaml:"address"`
Hostname string `yaml:"hostname"`
Port uint16 `yaml:"port"`
Database struct {
Type string `yaml:"type"`
URI string `yaml:"uri"`
MaxOpenConns int `yaml:"max_open_conns"`
MaxIdleConns int `yaml:"max_idle_conns"`
} `yaml:"database"`
StateStore string `yaml:"state_store_path,omitempty"`
Provisioning struct {
Prefix string `yaml:"prefix"`
SharedSecret string `yaml:"shared_secret"`
} `yaml:"provisioning"`
ID string `yaml:"id"`
Bot struct {
Username string `yaml:"username"`
Displayname string `yaml:"displayname"`
Avatar string `yaml:"avatar"`
} `yaml:"bot"`
ASToken string `yaml:"as_token"`
HSToken string `yaml:"hs_token"`
} `yaml:"appservice"`
Bridge BridgeConfig `yaml:"bridge"`
Logging appservice.LogConfig `yaml:"logging"`
}
func (config *Config) setDefaults() {
config.AppService.Database.MaxOpenConns = 20
config.AppService.Database.MaxIdleConns = 2
config.Bridge.setDefaults()
}
func Load(path string) (*Config, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var config = &Config{}
config.setDefaults()
err = yaml.Unmarshal(data, config)
return config, err
}
func (config *Config) Save(path string) error {
data, err := yaml.Marshal(config)
if err != nil {
return err
}
return ioutil.WriteFile(path, data, 0600)
}
func (config *Config) MakeAppService() (*appservice.AppService, error) {
as := appservice.Create()
as.HomeserverDomain = config.Homeserver.Domain
as.HomeserverURL = config.Homeserver.Address
as.Host.Hostname = config.AppService.Hostname
as.Host.Port = config.AppService.Port
patch.ThirdPartyIdEncrypt = config.Bridge.Encryption.PuppetId.Allow
patch.AsBotName = config.AppService.Bot.Username
patch.AsUserPrefix = config.Bridge.Encryption.PuppetId.UsernameTemplatePrefix
patch.XorKey = config.Bridge.Encryption.PuppetId.Key
var err error
as.Registration, err = config.GetRegistration()
return as, err
}

74
config/registration.go Normal file
View File

@ -0,0 +1,74 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package config
import (
"fmt"
"regexp"
"maunium.net/go/mautrix/appservice"
)
func (config *Config) NewRegistration() (*appservice.Registration, error) {
registration := appservice.CreateRegistration()
err := config.copyToRegistration(registration)
if err != nil {
return nil, err
}
config.AppService.ASToken = registration.AppToken
config.AppService.HSToken = registration.ServerToken
// Workaround for https://github.com/matrix-org/synapse/pull/5758
registration.SenderLocalpart = appservice.RandomString(32)
botRegex := regexp.MustCompile(fmt.Sprintf("^@%s:%s$", config.AppService.Bot.Username, config.Homeserver.Domain))
registration.Namespaces.RegisterUserIDs(botRegex, true)
return registration, nil
}
func (config *Config) GetRegistration() (*appservice.Registration, error) {
registration := appservice.CreateRegistration()
err := config.copyToRegistration(registration)
if err != nil {
return nil, err
}
registration.AppToken = config.AppService.ASToken
registration.ServerToken = config.AppService.HSToken
return registration, nil
}
func (config *Config) copyToRegistration(registration *appservice.Registration) error {
registration.ID = config.AppService.ID
registration.URL = config.AppService.Address
falseVal := false
registration.RateLimited = &falseVal
registration.SenderLocalpart = config.AppService.Bot.Username
userIDRegex, err := regexp.Compile(fmt.Sprintf("^@%s:%s$",
//config.Bridge.FormatUsername("[0-9]+"),
config.Bridge.FormatUsername("(.*)"),
config.Homeserver.Domain))
if err != nil {
return err
}
registration.Namespaces.RegisterUserIDs(userIDRegex, true)
return nil
}

313
crypto.go Normal file
View File

@ -0,0 +1,313 @@
// 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/>.
// +build cgo,!nocrypto
package main
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"fmt"
"time"
"github.com/pkg/errors"
"maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/crypto"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"github.com/kelaresg/matrix-skype/database"
)
var levelTrace = maulogger.Level{
Name: "Trace",
Severity: -10,
Color: -1,
}
type CryptoHelper struct {
bridge *Bridge
client *mautrix.Client
mach *crypto.OlmMachine
store *database.SQLCryptoStore
log maulogger.Logger
baseLog maulogger.Logger
}
func NewCryptoHelper(bridge *Bridge) Crypto {
if !bridge.Config.Bridge.Encryption.Allow {
bridge.Log.Debugln("Bridge built with end-to-bridge encryption, but disabled in config")
return nil
} else if bridge.Config.Bridge.LoginSharedSecret == "" {
bridge.Log.Warnln("End-to-bridge encryption enabled, but login_shared_secret not set")
return nil
}
baseLog := bridge.Log.Sub("Crypto")
return &CryptoHelper{
bridge: bridge,
log: baseLog.Sub("Helper"),
baseLog: baseLog,
}
}
func (helper *CryptoHelper) Init() error {
helper.log.Debugln("Initializing end-to-bridge encryption...")
helper.store = database.NewSQLCryptoStore(helper.bridge.DB, helper.bridge.AS.BotMXID(),
fmt.Sprintf("@%s:%s", helper.bridge.Config.Bridge.FormatUsername("%"), helper.bridge.AS.HomeserverDomain))
var err error
helper.client, err = helper.loginBot()
if err != nil {
return err
}
helper.log.Debugln("Logged in as bridge bot with device ID", helper.client.DeviceID)
logger := &cryptoLogger{helper.baseLog}
stateStore := &cryptoStateStore{helper.bridge}
helper.mach = crypto.NewOlmMachine(helper.client, logger, helper.store, stateStore)
helper.mach.AllowKeyShare = helper.allowKeyShare
helper.client.Syncer = &cryptoSyncer{helper.mach}
helper.client.Store = &cryptoClientStore{helper.store}
return helper.mach.Load()
}
func (helper *CryptoHelper) allowKeyShare(device *crypto.DeviceIdentity, info event.RequestedKeyInfo) *crypto.KeyShareRejection {
cfg := helper.bridge.Config.Bridge.Encryption.KeySharing
if !cfg.Allow {
return &crypto.KeyShareRejectNoResponse
} else if device.Trust == crypto.TrustStateBlacklisted {
return &crypto.KeyShareRejectBlacklisted
} else if device.Trust == crypto.TrustStateVerified || !cfg.RequireVerification {
portal := helper.bridge.GetPortalByMXID(info.RoomID)
if portal == nil {
helper.log.Debugfln("Rejecting key request for %s from %s/%s: room is not a portal", info.SessionID, device.UserID, device.DeviceID)
return &crypto.KeyShareRejection{Code: event.RoomKeyWithheldUnavailable, Reason: "Requested room is not a portal room"}
}
user := helper.bridge.GetUserByMXID(device.UserID)
if !user.IsInPortal(portal.Key) {
helper.log.Debugfln("Rejecting key request for %s from %s/%s: user is not in portal", info.SessionID, device.UserID, device.DeviceID)
return &crypto.KeyShareRejection{Code: event.RoomKeyWithheldUnauthorized, Reason: "You're not in that portal"}
}
helper.log.Debugfln("Accepting key request for %s from %s/%s", info.SessionID, device.UserID, device.DeviceID)
return nil
} else {
return &crypto.KeyShareRejectUnverified
}
}
func (helper *CryptoHelper) loginBot() (*mautrix.Client, error) {
deviceID := helper.store.FindDeviceID()
if len(deviceID) > 0 {
helper.log.Debugln("Found existing device ID for bot in database:", deviceID)
}
client, err := mautrix.NewClient(helper.bridge.AS.HomeserverURL, "", "")
if err != nil {
return nil, fmt.Errorf("failed to initialize client: %w", err)
}
client.Logger = helper.baseLog.Sub("Bot")
client.Client = helper.bridge.AS.HTTPClient
client.DefaultHTTPRetries = helper.bridge.AS.DefaultHTTPRetries
flows, err := client.GetLoginFlows()
if err != nil {
return nil, fmt.Errorf("failed to get supported login flows: %w", err)
}
if !flows.HasFlow(mautrix.AuthTypeHalfyAppservice) {
return nil, fmt.Errorf("homeserver does not support appservice login")
}
// We set the API token to the AS token here to authenticate the appservice login
// It'll get overridden after the login
client.AccessToken = helper.bridge.AS.Registration.AppToken
resp, err := client.Login(&mautrix.ReqLogin{
Type: mautrix.AuthTypeHalfyAppservice,
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(helper.bridge.AS.BotMXID())},
DeviceID: deviceID,
InitialDeviceDisplayName: "Skype Bridge",
StoreCredentials: true,
})
if err != nil {
return nil, fmt.Errorf("failed to log in as bridge bot: %w", err)
}
if len(deviceID) == 0 {
helper.store.DeviceID = resp.DeviceID
}
return client, nil
}
func (helper *CryptoHelper) loginBotOld() (*mautrix.Client, error) {
deviceID := helper.store.FindDeviceID()
if len(deviceID) > 0 {
helper.log.Debugln("Found existing device ID for bot in database:", deviceID)
}
mac := hmac.New(sha512.New, []byte(helper.bridge.Config.Bridge.LoginSharedSecret))
mac.Write([]byte(helper.bridge.AS.BotMXID()))
client, err := mautrix.NewClient(helper.bridge.AS.HomeserverURL, "", "")
if err != nil {
return nil, err
}
resp, err := client.Login(&mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(helper.bridge.AS.BotMXID())},
Password: hex.EncodeToString(mac.Sum(nil)),
DeviceID: deviceID,
InitialDeviceDisplayName: "Skype Bridge",
StoreCredentials: true,
})
if err != nil {
return nil, err
}
if len(deviceID) == 0 {
helper.store.DeviceID = resp.DeviceID
}
return client, nil
}
func (helper *CryptoHelper) Start() {
helper.log.Debugln("Starting syncer for receiving to-device messages")
err := helper.client.Sync()
if err != nil {
helper.log.Errorln("Fatal error syncing:", err)
}
}
func (helper *CryptoHelper) Stop() {
helper.client.StopSync()
}
func (helper *CryptoHelper) Decrypt(evt *event.Event) (*event.Event, error) {
return helper.mach.DecryptMegolmEvent(evt)
}
func (helper *CryptoHelper) Encrypt(roomID id.RoomID, evtType event.Type, content event.Content) (*event.EncryptedEventContent, error) {
encrypted, err := helper.mach.EncryptMegolmEvent(roomID, evtType, &content)
if err != nil {
if err != crypto.SessionExpired && err != crypto.SessionNotShared && err != crypto.NoGroupSession {
return nil, err
}
helper.log.Debugfln("Got %v while encrypting event for %s, sharing group session and trying again...", err, roomID)
users, err := helper.store.GetRoomMembers(roomID)
if err != nil {
return nil, errors.Wrap(err, "failed to get room member list")
}
err = helper.mach.ShareGroupSession(roomID, users)
if err != nil {
return nil, errors.Wrap(err, "failed to share group session")
}
encrypted, err = helper.mach.EncryptMegolmEvent(roomID, evtType, &content)
if err != nil {
return nil, errors.Wrap(err, "failed to encrypt event after re-sharing group session")
}
}
return encrypted, nil
}
func (helper *CryptoHelper) HandleMemberEvent(evt *event.Event) {
helper.mach.HandleMemberEvent(evt)
}
type cryptoSyncer struct {
*crypto.OlmMachine
}
func (syncer *cryptoSyncer) ProcessResponse(resp *mautrix.RespSync, since string) error {
syncer.ProcessSyncResponse(resp, since)
return nil
}
func (syncer *cryptoSyncer) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
syncer.Log.Error("Error /syncing, waiting 10 seconds: %v", err)
return 10 * time.Second, nil
}
func (syncer *cryptoSyncer) GetFilterJSON(_ id.UserID) *mautrix.Filter {
everything := []event.Type{{Type: "*"}}
return &mautrix.Filter{
Presence: mautrix.FilterPart{NotTypes: everything},
AccountData: mautrix.FilterPart{NotTypes: everything},
Room: mautrix.RoomFilter{
IncludeLeave: false,
Ephemeral: mautrix.FilterPart{NotTypes: everything},
AccountData: mautrix.FilterPart{NotTypes: everything},
State: mautrix.FilterPart{NotTypes: everything},
Timeline: mautrix.FilterPart{NotTypes: everything},
},
}
}
type cryptoLogger struct {
int maulogger.Logger
}
func (c *cryptoLogger) Error(message string, args ...interface{}) {
c.int.Errorfln(message, args...)
}
func (c *cryptoLogger) Warn(message string, args ...interface{}) {
c.int.Warnfln(message, args...)
}
func (c *cryptoLogger) Debug(message string, args ...interface{}) {
c.int.Debugfln(message, args...)
}
func (c *cryptoLogger) Trace(message string, args ...interface{}) {
c.int.Logfln(levelTrace, message, args...)
}
type cryptoClientStore struct {
int *database.SQLCryptoStore
}
func (c cryptoClientStore) SaveFilterID(_ id.UserID, _ string) {}
func (c cryptoClientStore) LoadFilterID(_ id.UserID) string { return "" }
func (c cryptoClientStore) SaveRoom(_ *mautrix.Room) {}
func (c cryptoClientStore) LoadRoom(_ id.RoomID) *mautrix.Room { return nil }
func (c cryptoClientStore) SaveNextBatch(_ id.UserID, nextBatchToken string) {
c.int.PutNextBatch(nextBatchToken)
}
func (c cryptoClientStore) LoadNextBatch(_ id.UserID) string {
return c.int.GetNextBatch()
}
var _ mautrix.Storer = (*cryptoClientStore)(nil)
type cryptoStateStore struct {
bridge *Bridge
}
var _ crypto.StateStore = (*cryptoStateStore)(nil)
func (c *cryptoStateStore) IsEncrypted(id id.RoomID) bool {
portal := c.bridge.GetPortalByMXID(id)
if portal != nil {
return portal.Encrypted
}
return false
}
func (c *cryptoStateStore) FindSharedRooms(id id.UserID) []id.RoomID {
return c.bridge.StateStore.FindSharedRooms(id)
}
func (c *cryptoStateStore) GetEncryptionEvent(id.RoomID) *event.EncryptionEventContent {
// TODO implement
return nil
}

266
custompuppet.go Normal file
View File

@ -0,0 +1,266 @@
package main
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"strings"
"time"
"github.com/pkg/errors"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
var (
ErrNoCustomMXID = errors.New("no custom mxid set")
ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
)
func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error {
prevCustomMXID := puppet.CustomMXID
if puppet.customIntent != nil {
puppet.stopSyncing()
}
puppet.CustomMXID = mxid
puppet.AccessToken = accessToken
err := puppet.StartCustomMXID()
if err != nil {
return err
}
if len(prevCustomMXID) > 0 {
delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
}
if len(puppet.CustomMXID) > 0 {
puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
}
puppet.bridge.AS.StateStore.MarkRegistered(puppet.CustomMXID)
puppet.Update()
// TODO leave rooms with default puppet
return nil
}
func (puppet *Puppet) loginWithSharedSecret(mxid id.UserID) (string, error) {
mac := hmac.New(sha512.New, []byte(puppet.bridge.Config.Bridge.LoginSharedSecret))
mac.Write([]byte(mxid))
resp, err := puppet.bridge.AS.BotClient().Login(&mautrix.ReqLogin{
Type: "m.login.password",
Identifier: mautrix.UserIdentifier{Type: "m.id.user", User: string(mxid)},
Password: hex.EncodeToString(mac.Sum(nil)),
DeviceID: "Skype Bridge",
InitialDeviceDisplayName: "Skype Bridge",
})
if err != nil {
return "", err
}
return resp.AccessToken, nil
}
func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
if len(puppet.CustomMXID) == 0 {
return nil, ErrNoCustomMXID
}
client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken)
if err != nil {
return nil, err
}
client.Logger = puppet.bridge.AS.Log.Sub(string(puppet.CustomMXID))
client.Syncer = puppet
client.Store = puppet
ia := puppet.bridge.AS.NewIntentAPI("custom")
ia.Client = client
ia.Localpart, _, _ = puppet.CustomMXID.Parse()
ia.UserID = puppet.CustomMXID
ia.IsCustomPuppet = true
return ia, nil
}
func (puppet *Puppet) clearCustomMXID() {
puppet.CustomMXID = ""
puppet.AccessToken = ""
puppet.customIntent = nil
puppet.customTypingIn = nil
puppet.customUser = nil
}
func (puppet *Puppet) StartCustomMXID() error {
if len(puppet.CustomMXID) == 0 {
puppet.clearCustomMXID()
return nil
}
intent, err := puppet.newCustomIntent()
if err != nil {
puppet.clearCustomMXID()
return err
}
resp, err := intent.Whoami()
if err != nil {
if strings.Index(err.Error(), "M_UNKNOWN_TOKEN (HTTP 401)") > -1 {
puppet.log.Debugln("StartCustomMXID UpdateAccessToken: ", puppet.MXID)
if puppet.customUser != nil {
err, _ = puppet.customUser.UpdateAccessToken(puppet)
}
}
if err != nil {
puppet.clearCustomMXID()
return err
}
}
if resp.UserID != puppet.CustomMXID {
puppet.clearCustomMXID()
return ErrMismatchingMXID
}
puppet.customIntent = intent
puppet.customTypingIn = make(map[id.RoomID]bool)
puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
puppet.startSyncing()
return nil
}
func (puppet *Puppet) startSyncing() {
if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
return
}
go func() {
puppet.log.Debugln("Starting syncing...")
puppet.customIntent.SyncPresence = "offline"
err := puppet.customIntent.Sync()
if err != nil {
puppet.log.Errorln("Fatal error syncing:", err)
}
}()
}
func (puppet *Puppet) stopSyncing() {
if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
return
}
puppet.customIntent.StopSync()
}
func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, since string) error {
if !puppet.customUser.IsConnected() {
puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
return nil
}
for roomID, events := range resp.Rooms.Join {
portal := puppet.bridge.GetPortalByMXID(roomID)
if portal == nil {
continue
}
for _, evt := range events.Ephemeral.Events {
err := evt.Content.ParseRaw(evt.Type)
if err != nil {
continue
}
switch evt.Type {
case event.EphemeralEventReceipt:
go puppet.handleReceiptEvent(portal, evt)
case event.EphemeralEventTyping:
go puppet.handleTypingEvent(portal, evt)
}
}
}
for _, evt := range resp.Presence.Events {
if evt.Sender != puppet.CustomMXID {
continue
}
err := evt.Content.ParseRaw(evt.Type)
if err != nil {
continue
}
go puppet.handlePresenceEvent(evt)
}
return nil
}
func (puppet *Puppet) handlePresenceEvent(event *event.Event) {
//presence := whatsapp.PresenceAvailable
//if event.Content.Raw["presence"].(string) != "online" {
// presence = whatsapp.PresenceUnavailable
// puppet.customUser.log.Debugln("Marking offline")
//} else {
// puppet.customUser.log.Debugln("Marking online")
//}
//_, err := puppet.customUser.Conn.Presence("", presence)
//if err != nil {
// puppet.customUser.log.Warnln("Failed to set presence:", err)
//}
}
func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *event.Event) {
//for eventID, receipts := range *event.Content.AsReceipt() {
// if _, ok := receipts.Read[puppet.CustomMXID]; !ok {
// continue
// }
// message := puppet.bridge.DB.Message.GetByMXID(eventID)
// if message == nil {
// continue
// }
// puppet.customUser.log.Infofln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
// _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
// if err != nil {
// puppet.customUser.log.Warnln("Error marking read:", err)
// }
//}
}
func (puppet *Puppet) handleTypingEvent(portal *Portal, evt *event.Event) {
//isTyping := false
//for _, userID := range evt.Content.AsTyping().UserIDs {
// if userID == puppet.CustomMXID {
// isTyping = true
// break
// }
//}
//if puppet.customTypingIn[evt.RoomID] != isTyping {
// puppet.customTypingIn[evt.RoomID] = isTyping
// presence := whatsapp.PresenceComposing
// if !isTyping {
// puppet.customUser.log.Infofln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
// presence = whatsapp.PresencePaused
// } else {
// puppet.customUser.log.Infofln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
// }
// _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
// if err != nil {
// puppet.customUser.log.Warnln("Error setting typing:", err)
// }
//}
}
func (puppet *Puppet) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) {
puppet.log.Warnln("Sync error:", err)
return 10 * time.Second, nil
}
func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
everything := []event.Type{{Type: "*"}}
return &mautrix.Filter{
Presence: mautrix.FilterPart{
Senders: []id.UserID{puppet.CustomMXID},
Types: []event.Type{event.EphemeralEventPresence},
},
AccountData: mautrix.FilterPart{NotTypes: everything},
Room: mautrix.RoomFilter{
Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
IncludeLeave: false,
AccountData: mautrix.FilterPart{NotTypes: everything},
State: mautrix.FilterPart{NotTypes: everything},
Timeline: mautrix.FilterPart{NotTypes: everything},
},
}
}
func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {}
func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
func (puppet *Puppet) SaveRoom(room *mautrix.Room) {}
func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" }
func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch }
func (puppet *Puppet) LoadRoom(roomID id.RoomID) *mautrix.Room { return nil }

102
database/cryptostore.go Normal file
View File

@ -0,0 +1,102 @@
// 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/>.
// +build cgo,!nocrypto
package database
import (
"database/sql"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/crypto"
"maunium.net/go/mautrix/id"
)
type SQLCryptoStore struct {
*crypto.SQLCryptoStore
UserID id.UserID
GhostIDFormat string
}
var _ crypto.Store = (*SQLCryptoStore)(nil)
func NewSQLCryptoStore(db *Database, userID id.UserID, ghostIDFormat string) *SQLCryptoStore {
return &SQLCryptoStore{
SQLCryptoStore: crypto.NewSQLCryptoStore(db.DB, db.dialect, "", "",
[]byte("maunium.net/go/mautrix-whatsapp"),
&cryptoLogger{db.log.Sub("CryptoStore")}),
UserID: userID,
GhostIDFormat: ghostIDFormat,
}
}
func (store *SQLCryptoStore) FindDeviceID() (deviceID id.DeviceID) {
err := store.DB.QueryRow("SELECT device_id FROM crypto_account WHERE account_id=$1", store.AccountID).Scan(&deviceID)
if err != nil && err != sql.ErrNoRows {
store.Log.Warn("Failed to scan device ID: %v", err)
}
return
}
func (store *SQLCryptoStore) GetRoomMembers(roomID id.RoomID) (members []id.UserID, err error) {
var rows *sql.Rows
rows, err = store.DB.Query(`
SELECT user_id FROM mx_user_profile
WHERE room_id=$1
AND (membership='join' OR membership='invite')
AND user_id<>$2
AND user_id NOT LIKE $3
`, roomID, store.UserID, store.GhostIDFormat)
if err != nil {
return
}
for rows.Next() {
var userID id.UserID
err := rows.Scan(&userID)
if err != nil {
store.Log.Warn("Failed to scan member in %s: %v", roomID, err)
} else {
members = append(members, userID)
}
}
return
}
// TODO merge this with the one in the parent package
type cryptoLogger struct {
int log.Logger
}
var levelTrace = log.Level{
Name: "Trace",
Severity: -10,
Color: -1,
}
func (c *cryptoLogger) Error(message string, args ...interface{}) {
c.int.Errorfln(message, args...)
}
func (c *cryptoLogger) Warn(message string, args ...interface{}) {
c.int.Warnfln(message, args...)
}
func (c *cryptoLogger) Debug(message string, args ...interface{}) {
c.int.Debugfln(message, args...)
}
func (c *cryptoLogger) Trace(message string, args ...interface{}) {
c.int.Logfln(levelTrace, message, args...)
}

81
database/database.go Normal file
View File

@ -0,0 +1,81 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package database
import (
"database/sql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
log "maunium.net/go/maulogger/v2"
"github.com/kelaresg/matrix-skype/database/upgrades"
)
type Database struct {
*sql.DB
log log.Logger
dialect string
User *UserQuery
Portal *PortalQuery
Puppet *PuppetQuery
Message *MessageQuery
}
func New(dbType string, uri string) (*Database, error) {
conn, err := sql.Open(dbType, uri)
if err != nil {
return nil, err
}
if dbType == "sqlite3" {
_, _ = conn.Exec("PRAGMA foreign_keys = ON")
}
db := &Database{
DB: conn,
log: log.Sub("Database"),
dialect: dbType,
}
db.User = &UserQuery{
db: db,
log: db.log.Sub("User"),
}
db.Portal = &PortalQuery{
db: db,
log: db.log.Sub("Portal"),
}
db.Puppet = &PuppetQuery{
db: db,
log: db.log.Sub("Puppet"),
}
db.Message = &MessageQuery{
db: db,
log: db.log.Sub("Message"),
}
return db, nil
}
func (db *Database) Init() error {
return upgrades.Run(db.log.Sub("Upgrade"), db.dialect, db.DB)
}
type Scannable interface {
Scan(...interface{}) error
}

145
database/message.go Normal file
View File

@ -0,0 +1,145 @@
package database
import (
"bytes"
"database/sql"
"encoding/json"
log "maunium.net/go/maulogger/v2"
"github.com/kelaresg/matrix-skype/types"
"maunium.net/go/mautrix/id"
)
type MessageQuery struct {
db *Database
log log.Logger
}
func (mq *MessageQuery) New() *Message {
return &Message{
db: mq.db,
log: mq.log,
}
}
func (mq *MessageQuery) GetAll(chat PortalKey) (messages []*Message) {
rows, err := mq.db.Query("SELECT id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content FROM message WHERE chat_jid=$1 AND chat_receiver=$2", chat.JID, chat.Receiver)
if err != nil || rows == nil {
return nil
}
defer rows.Close()
for rows.Next() {
messages = append(messages, mq.New().Scan(rows))
}
return
}
func (mq *MessageQuery) GetByJID(chat PortalKey, jid types.SkypeMessageID) *Message {
return mq.get("SELECT id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content " +
"FROM message WHERE chat_jid=$1 AND jid=$2", chat.JID, jid)
}
func (mq *MessageQuery) oldGetByJID(chat PortalKey, jid types.SkypeMessageID) *Message {
return mq.get("SELECT id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content " +
"FROM message WHERE chat_jid=$1 AND chat_receiver=$2 AND jid=$3", chat.JID, chat.Receiver, jid)
}
func (mq *MessageQuery) GetByMXID(mxid id.EventID) *Message {
return mq.get("SELECT id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content " +
"FROM message WHERE mxid=$1", mxid)
}
func (mq *MessageQuery) GetByID(id string) *Message {
return mq.get("SELECT id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content " +
"FROM message WHERE id=$1", id)
}
func (mq *MessageQuery) GetLastInChat(chat PortalKey) *Message {
msg := mq.get("SELECT id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content " +
"FROM message WHERE chat_jid=$1 AND chat_receiver=$2 ORDER BY timestamp DESC LIMIT 1", chat.JID, chat.Receiver)
if msg == nil || msg.Timestamp == 0 {
// Old db, we don't know what the last message is.
return nil
}
return msg
}
func (mq *MessageQuery) get(query string, args ...interface{}) *Message {
row := mq.db.QueryRow(query, args...)
if row == nil {
return nil
}
return mq.New().Scan(row)
}
type Message struct {
db *Database
log log.Logger
ID types.SkypeMessageID
Chat PortalKey
JID types.SkypeMessageID
MXID id.EventID
Sender types.SkypeID
Timestamp uint64
Content string
}
func (msg *Message) Scan(row Scannable) *Message {
var content []byte
err := row.Scan(&msg.ID, &msg.Chat.JID, &msg.Chat.Receiver, &msg.JID, &msg.MXID, &msg.Sender, &msg.Timestamp, &content)
if err != nil {
if err != sql.ErrNoRows {
msg.log.Errorln("Database scan failed:", err)
}
return nil
}
msg.decodeBinaryContent(content)
return msg
}
func (msg *Message) decodeBinaryContent(content []byte) {
//msg.Content = &skype.Resource{}
msg.Content = ""
reader := bytes.NewReader(content)
dec := json.NewDecoder(reader)
err := dec.Decode(&msg.Content)
if err != nil {
msg.log.Warnln("Failed to decode message content:", err)
}
}
func (msg *Message) encodeBinaryContent() []byte {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
err := enc.Encode(msg.Content)
if err != nil {
msg.log.Warnln("Failed to encode message content:", err)
}
return buf.Bytes()
}
func (msg *Message) Insert() {
_, err := msg.db.Exec("INSERT INTO message (id, chat_jid, chat_receiver, jid, mxid, sender, timestamp, content) " +
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
msg.ID, msg.Chat.JID, msg.Chat.Receiver, msg.JID, msg.MXID, msg.Sender, msg.Timestamp, msg.encodeBinaryContent())
if err != nil {
msg.log.Warnfln("Failed to insert %s@%s: %v", msg.Chat, msg.JID, err)
}
}
func (msg *Message) Delete() {
_, err := msg.db.Exec("DELETE FROM message WHERE chat_jid=$1 AND chat_receiver=$2 AND jid=$3", msg.Chat.JID, msg.Chat.Receiver, msg.JID)
if err != nil {
msg.log.Warnfln("Failed to delete %s@%s: %v", msg.Chat, msg.JID, err)
}
}
func (msg *Message) UpdateIDByJID(id string) {
_, err := msg.db.Exec("UPDATE message SET id=$1 WHERE chat_jid=$2 AND jid=$3", id, msg.Chat.JID, msg.JID)
if err != nil {
msg.log.Warnfln("Failed to UpdateIDByJID %s@%s: %v", msg.Chat.JID, msg.JID, err)
}
}

152
database/migrate.go Normal file
View File

@ -0,0 +1,152 @@
package database
import (
"fmt"
"math"
"strings"
)
func countRows(db *Database, table string) (int, error) {
countRow := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", table))
var count int
err := countRow.Scan(&count)
return count, err
}
const VariableCountLimit = 512
func migrateTable(old *Database, new *Database, table string, columns ...string) error {
columnNames := strings.Join(columns, ",")
fmt.Printf("Migrating %s: ", table)
rowCount, err := countRows(old, table)
if err != nil {
return err
}
fmt.Print("found ", rowCount, " rows of data, ")
rows, err := old.Query(fmt.Sprintf("SELECT %s FROM \"%s\"", columnNames, table))
if err != nil {
return err
}
serverColNames, err := rows.Columns()
if err != nil {
return err
}
colCount := len(serverColNames)
valueStringFormat := strings.Repeat("$%d, ", colCount)
valueStringFormat = fmt.Sprintf("(%s)", valueStringFormat[:len(valueStringFormat)-2])
cols := make([]interface{}, colCount)
colPtrs := make([]interface{}, colCount)
for i := 0; i < colCount; i++ {
colPtrs[i] = &cols[i]
}
batchSize := VariableCountLimit / colCount
values := make([]interface{}, batchSize*colCount)
valueStrings := make([]string, batchSize)
var inserted int64
batchCount := int(math.Ceil(float64(rowCount) / float64(batchSize)))
tx, err := new.Begin()
if err != nil {
return err
}
fmt.Printf("migrating in %d batches: ", batchCount)
for rowCount > 0 {
var i int
for ; rows.Next() && i < batchSize; i++ {
colPtrs := make([]interface{}, colCount)
valueStringArgs := make([]interface{}, colCount)
for j := 0; j < colCount; j++ {
pos := i*colCount + j
colPtrs[j] = &values[pos]
valueStringArgs[j] = pos + 1
}
valueStrings[i] = fmt.Sprintf(valueStringFormat, valueStringArgs...)
err = rows.Scan(colPtrs...)
if err != nil {
panic(err)
}
}
slicedValues := values
slicedValueStrings := valueStrings
if i < len(valueStrings) {
slicedValueStrings = slicedValueStrings[:i]
slicedValues = slicedValues[:i*colCount]
}
res, err := tx.Exec(fmt.Sprintf("INSERT INTO \"%s\" (%s) VALUES %s", table, columnNames, strings.Join(slicedValueStrings, ",")), slicedValues...)
if err != nil {
panic(err)
}
count, _ := res.RowsAffected()
inserted += count
rowCount -= batchSize
fmt.Print("#")
}
err = tx.Commit()
if err != nil {
return err
}
fmt.Println(" -- done with", inserted, "rows inserted")
return nil
}
func Migrate(old *Database, new *Database) {
err := migrateTable(old, new, "portal", "jid", "receiver", "mxid", "name", "topic", "avatar", "avatar_url", "encrypted")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "user", "mxid", "jid", "management_room", "endpoint_id", "skype_token", "registration_token", "registration_token_str", "location_host", "last_connection")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "puppet", "jid", "avatar", "displayname", "name_quality", "custom_mxid", "access_token", "next_batch", "avatar_url")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "user_portal", "user_jid", "portal_jid", "portal_receiver", "in_community")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "message", "chat_jid", "chat_receiver", "jid", "mxid", "sender", "content", "timestamp")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "mx_registrations", "user_id")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "mx_user_profile", "room_id", "user_id", "membership")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "mx_room_state", "room_id", "power_levels")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_account", "device_id", "shared", "sync_token", "account")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_message_index", "sender_key", "session_id", `"index"`, "event_id", "timestamp")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_tracked_user", "user_id")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_device", "user_id", "device_id", "identity_key", "signing_key", "trust", "deleted", "name")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_olm_session", "session_id", "sender_key", "session", "created_at", "last_used")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_megolm_inbound_session", "session_id", "sender_key", "signing_key", "room_id", "session", "forwarding_chains")
if err != nil {
panic(err)
}
err = migrateTable(old, new, "crypto_megolm_outbound_session", "room_id", "session_id", "session", "shared", "max_messages", "message_count", "max_age", "created_at", "last_used")
if err != nil {
panic(err)
}
}

176
database/portal.go Normal file
View File

@ -0,0 +1,176 @@
package database
import (
"database/sql"
skypeExt "github.com/kelaresg/matrix-skype/skype-ext"
"strings"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/id"
"github.com/kelaresg/matrix-skype/types"
)
type PortalKey struct {
JID types.SkypeID
Receiver types.SkypeID
}
func GroupPortalKey(jid types.SkypeID) PortalKey {
return PortalKey{
JID: jid,
Receiver: jid,
}
}
func NewPortalKey(jid, receiver types.SkypeID) PortalKey {
if strings.HasSuffix(jid, skypeExt.GroupSuffix) {
receiver = jid
}
jid = strings.Replace(jid, skypeExt.NewUserSuffix, "", 1)
return PortalKey{
JID: jid,
Receiver: receiver,
}
}
func (key PortalKey) String() string {
if key.Receiver == key.JID {
return key.JID
}
return key.JID + "-" + key.Receiver
}
type PortalQuery struct {
db *Database
log log.Logger
}
func (pq *PortalQuery) New() *Portal {
return &Portal{
db: pq.db,
log: pq.log,
}
}
func (pq *PortalQuery) GetAll() []*Portal {
return pq.getAll("SELECT * FROM portal")
}
func (pq *PortalQuery) GetByJID(key PortalKey) *Portal {
return pq.get("SELECT * FROM portal WHERE jid=$1 AND receiver=$2", key.JID, key.Receiver)
}
func (pq *PortalQuery) GetByMXID(mxid id.RoomID) *Portal {
return pq.get("SELECT * FROM portal WHERE mxid=$1", mxid)
}
func (pq *PortalQuery) GetAllByJID(jid types.SkypeID) []*Portal {
return pq.getAll("SELECT * FROM portal WHERE jid=$1", jid)
}
func (pq *PortalQuery) getAll(query string, args ...interface{}) (portals []*Portal) {
rows, err := pq.db.Query(query, args...)
if err != nil || rows == nil {
return nil
}
defer rows.Close()
for rows.Next() {
portals = append(portals, pq.New().Scan(rows))
}
return
}
func (pq *PortalQuery) get(query string, args ...interface{}) *Portal {
row := pq.db.QueryRow(query, args...)
if row == nil {
return nil
}
return pq.New().Scan(row)
}
type Portal struct {
db *Database
log log.Logger
Key PortalKey
MXID id.RoomID
Name string
Topic string
Avatar string
AvatarURL id.ContentURI
Encrypted bool
}
func (portal *Portal) Scan(row Scannable) *Portal {
var mxid, avatarURL sql.NullString
err := row.Scan(&portal.Key.JID, &portal.Key.Receiver, &mxid, &portal.Name, &portal.Topic, &portal.Avatar, &avatarURL, &portal.Encrypted)
if err != nil {
if err != sql.ErrNoRows {
portal.log.Errorln("Database scan failed:", err)
}
return nil
}
portal.MXID = id.RoomID(mxid.String)
portal.AvatarURL, _ = id.ParseContentURI(avatarURL.String)
return portal
}
func (portal *Portal) mxidPtr() *id.RoomID {
if len(portal.MXID) > 0 {
return &portal.MXID
}
return nil
}
func (portal *Portal) Insert() {
_, err := portal.db.Exec("INSERT INTO portal (jid, receiver, mxid, name, topic, avatar, avatar_url, encrypted) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
portal.Key.JID, portal.Key.Receiver, portal.mxidPtr(), portal.Name, portal.Topic, portal.Avatar, portal.AvatarURL.String(), portal.Encrypted)
if err != nil {
portal.log.Warnfln("Failed to insert %s: %v", portal.Key, err)
}
}
func (portal *Portal) Update() {
var mxid *id.RoomID
if len(portal.MXID) > 0 {
mxid = &portal.MXID
}
_, err := portal.db.Exec("UPDATE portal SET mxid=$1, name=$2, topic=$3, avatar=$4, avatar_url=$5, encrypted=$6 WHERE jid=$7 AND receiver=$8",
mxid, portal.Name, portal.Topic, portal.Avatar, portal.AvatarURL.String(), portal.Encrypted, portal.Key.JID, portal.Key.Receiver)
if err != nil {
portal.log.Warnfln("Failed to update %s: %v", portal.Key, err)
}
}
func (portal *Portal) Delete() {
_, err := portal.db.Exec("DELETE FROM portal WHERE jid=$1 AND receiver=$2", portal.Key.JID, portal.Key.Receiver)
if err != nil {
portal.log.Warnfln("Failed to delete %s: %v", portal.Key, err)
}
}
func (portal *Portal) GetUserIDs() []id.UserID {
rows, err := portal.db.Query(`SELECT "user".mxid FROM "user", user_portal
WHERE "user".jid=user_portal.user_jid
AND user_portal.portal_jid=$1
AND user_portal.portal_receiver=$2`,
portal.Key.JID, portal.Key.Receiver)
if err != nil {
portal.log.Debugln("Failed to get portal user ids:", err)
return nil
}
var userIDs []id.UserID
for rows.Next() {
var userID id.UserID
err = rows.Scan(&userID)
if err != nil {
portal.log.Warnln("Failed to scan row:", err)
continue
}
userIDs = append(userIDs, userID)
}
return userIDs
}

113
database/puppet.go Normal file
View File

@ -0,0 +1,113 @@
package database
import (
"database/sql"
log "maunium.net/go/maulogger/v2"
"github.com/kelaresg/matrix-skype/types"
"maunium.net/go/mautrix/id"
)
type PuppetQuery struct {
db *Database
log log.Logger
}
func (pq *PuppetQuery) New() *Puppet {
return &Puppet{
db: pq.db,
log: pq.log,
}
}
func (pq *PuppetQuery) GetAll() (puppets []*Puppet) {
rows, err := pq.db.Query("SELECT jid, avatar, avatar_url, displayname, name_quality, custom_mxid, access_token, next_batch FROM puppet")
if err != nil || rows == nil {
return nil
}
defer rows.Close()
for rows.Next() {
puppets = append(puppets, pq.New().Scan(rows))
}
return
}
func (pq *PuppetQuery) Get(jid types.SkypeID) *Puppet {
row := pq.db.QueryRow("SELECT jid, avatar, avatar_url, displayname, name_quality, custom_mxid, access_token, next_batch FROM puppet WHERE jid=$1", jid)
if row == nil {
return nil
}
return pq.New().Scan(row)
}
func (pq *PuppetQuery) GetByCustomMXID(mxid id.UserID) *Puppet {
row := pq.db.QueryRow("SELECT jid, avatar, avatar_url, displayname, name_quality, custom_mxid, access_token, next_batch FROM puppet WHERE custom_mxid=$1", mxid)
if row == nil {
return nil
}
return pq.New().Scan(row)
}
func (pq *PuppetQuery) GetAllWithCustomMXID() (puppets []*Puppet) {
rows, err := pq.db.Query("SELECT jid, avatar, avatar_url, displayname, name_quality, custom_mxid, access_token, next_batch FROM puppet WHERE custom_mxid<>''")
if err != nil || rows == nil {
return nil
}
defer rows.Close()
for rows.Next() {
puppets = append(puppets, pq.New().Scan(rows))
}
return
}
type Puppet struct {
db *Database
log log.Logger
JID types.SkypeID
Avatar string
AvatarURL id.ContentURI
Displayname string
NameQuality int8
CustomMXID id.UserID
AccessToken string
NextBatch string
}
func (puppet *Puppet) Scan(row Scannable) *Puppet {
var displayname, avatar, avatarURL, customMXID, accessToken, nextBatch sql.NullString
var quality sql.NullInt64
err := row.Scan(&puppet.JID, &avatar, &avatarURL, &displayname, &quality, &customMXID, &accessToken, &nextBatch)
if err != nil {
if err != sql.ErrNoRows {
puppet.log.Errorln("Database scan failed:", err)
}
return nil
}
puppet.Displayname = displayname.String
puppet.Avatar = avatar.String
puppet.AvatarURL, _ = id.ParseContentURI(avatarURL.String)
puppet.NameQuality = int8(quality.Int64)
puppet.CustomMXID = id.UserID(customMXID.String)
puppet.AccessToken = accessToken.String
puppet.NextBatch = nextBatch.String
return puppet
}
func (puppet *Puppet) Insert() {
_, err := puppet.db.Exec("INSERT INTO puppet (jid, avatar, avatar_url, displayname, name_quality, custom_mxid, access_token, next_batch) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
puppet.JID, puppet.Avatar, puppet.AvatarURL.String(), puppet.Displayname, puppet.NameQuality, puppet.CustomMXID, puppet.AccessToken, puppet.NextBatch)
if err != nil {
puppet.log.Warnfln("Failed to insert %s: %v", puppet.JID, err)
}
}
func (puppet *Puppet) Update() {
_, err := puppet.db.Exec("UPDATE puppet SET displayname=$1, name_quality=$2, avatar=$3, avatar_url=$4, custom_mxid=$5, access_token=$6, next_batch=$7 WHERE jid=$8",
puppet.Displayname, puppet.NameQuality, puppet.Avatar, puppet.AvatarURL.String(), puppet.CustomMXID, puppet.AccessToken, puppet.NextBatch, puppet.JID)
if err != nil {
puppet.log.Warnfln("Failed to update %s->%s: %v", puppet.JID, err)
}
}

286
database/statestore.go Normal file
View File

@ -0,0 +1,286 @@
package database
import (
"database/sql"
"encoding/json"
"fmt"
"sync"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
)
type SQLStateStore struct {
*appservice.TypingStateStore
db *Database
log log.Logger
Typing map[id.RoomID]map[id.UserID]int64
typingLock sync.RWMutex
}
var _ appservice.StateStore = (*SQLStateStore)(nil)
func NewSQLStateStore(db *Database) *SQLStateStore {
return &SQLStateStore{
TypingStateStore: appservice.NewTypingStateStore(),
db: db,
log: db.log.Sub("StateStore"),
}
}
func (store *SQLStateStore) IsRegistered(userID id.UserID) bool {
row := store.db.QueryRow("SELECT EXISTS(SELECT 1 FROM mx_registrations WHERE user_id=$1)", userID)
var isRegistered bool
err := row.Scan(&isRegistered)
if err != nil {
store.log.Warnfln("Failed to scan registration existence for %s: %v", userID, err)
}
return isRegistered
}
func (store *SQLStateStore) MarkRegistered(userID id.UserID) {
var err error
if store.db.dialect == "postgres" {
_, err = store.db.Exec("INSERT INTO mx_registrations (user_id) VALUES ($1) ON CONFLICT (user_id) DO NOTHING", userID)
} else if store.db.dialect == "sqlite3" {
_, err = store.db.Exec("INSERT OR REPLACE INTO mx_registrations (user_id) VALUES ($1)", userID)
} else {
err = fmt.Errorf("unsupported dialect %s", store.db.dialect)
}
if err != nil {
store.log.Warnfln("Failed to mark %s as registered: %v", userID, err)
}
}
func (store *SQLStateStore) GetRoomMembers(roomID id.RoomID) map[id.UserID]*event.MemberEventContent {
members := make(map[id.UserID]*event.MemberEventContent)
rows, err := store.db.Query("SELECT user_id, membership, displayname, avatar_url FROM mx_user_profile WHERE room_id=$1", roomID)
if err != nil {
return members
}
var userID id.UserID
var member event.MemberEventContent
for rows.Next() {
err := rows.Scan(&userID, &member.Membership, &member.Displayname, &member.AvatarURL)
if err != nil {
store.log.Warnfln("Failed to scan member in %s: %v", roomID, err)
} else {
members[userID] = &member
}
}
return members
}
func (store *SQLStateStore) GetMembership(roomID id.RoomID, userID id.UserID) event.Membership {
row := store.db.QueryRow("SELECT membership FROM mx_user_profile WHERE room_id=$1 AND user_id=$2", roomID, userID)
membership := event.MembershipLeave
err := row.Scan(&membership)
if err != nil && err != sql.ErrNoRows {
store.log.Warnfln("Failed to scan membership of %s in %s: %v", userID, roomID, err)
}
return membership
}
func (store *SQLStateStore) GetMember(roomID id.RoomID, userID id.UserID) *event.MemberEventContent {
member, ok := store.TryGetMember(roomID, userID)
if !ok {
member.Membership = event.MembershipLeave
}
return member
}
func (store *SQLStateStore) TryGetMember(roomID id.RoomID, userID id.UserID) (*event.MemberEventContent, bool) {
row := store.db.QueryRow("SELECT membership, displayname, avatar_url FROM mx_user_profile WHERE room_id=$1 AND user_id=$2", roomID, userID)
var member event.MemberEventContent
err := row.Scan(&member.Membership, &member.Displayname, &member.AvatarURL)
if err != nil && err != sql.ErrNoRows {
store.log.Warnfln("Failed to scan member info of %s in %s: %v", userID, roomID, err)
}
return &member, err == nil
}
func (store *SQLStateStore) FindSharedRooms(userID id.UserID) (rooms []id.RoomID) {
rows, err := store.db.Query(`
SELECT room_id FROM mx_user_profile
LEFT JOIN portal ON portal.mxid=mx_user_profile.room_id
WHERE user_id=$1 AND portal.encrypted=true
`, userID)
if err != nil {
store.log.Warnfln("Failed to query shared rooms with %s: %v", userID, err)
return
}
for rows.Next() {
var roomID id.RoomID
err := rows.Scan(&roomID)
if err != nil {
store.log.Warnfln("Failed to scan room ID: %v", err)
} else {
rooms = append(rooms, roomID)
}
}
return
}
func (store *SQLStateStore) IsInRoom(roomID id.RoomID, userID id.UserID) bool {
return store.IsMembership(roomID, userID, "join")
}
func (store *SQLStateStore) IsInvited(roomID id.RoomID, userID id.UserID) bool {
return store.IsMembership(roomID, userID, "join", "invite")
}
func (store *SQLStateStore) IsMembership(roomID id.RoomID, userID id.UserID, allowedMemberships ...event.Membership) bool {
membership := store.GetMembership(roomID, userID)
for _, allowedMembership := range allowedMemberships {
if allowedMembership == membership {
return true
}
}
return false
}
func (store *SQLStateStore) SetMembership(roomID id.RoomID, userID id.UserID, membership event.Membership) {
var err error
if store.db.dialect == "postgres" {
_, err = store.db.Exec(`INSERT INTO mx_user_profile (room_id, user_id, membership) VALUES ($1, $2, $3)
ON CONFLICT (room_id, user_id) DO UPDATE SET membership=$3`, roomID, userID, membership)
} else if store.db.dialect == "sqlite3" {
_, err = store.db.Exec("INSERT OR REPLACE INTO mx_user_profile (room_id, user_id, membership) VALUES ($1, $2, $3)", roomID, userID, membership)
} else {
err = fmt.Errorf("unsupported dialect %s", store.db.dialect)
}
if err != nil {
store.log.Warnfln("Failed to set membership of %s in %s to %s: %v", userID, roomID, membership, err)
}
}
func (store *SQLStateStore) SetMember(roomID id.RoomID, userID id.UserID, member *event.MemberEventContent) {
var err error
if store.db.dialect == "postgres" {
_, err = store.db.Exec(`INSERT INTO mx_user_profile (room_id, user_id, membership, displayname, avatar_url) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (room_id, user_id) DO UPDATE SET membership=$3`, roomID, userID, member.Membership, member.Displayname, member.AvatarURL)
} else if store.db.dialect == "sqlite3" {
_, err = store.db.Exec("INSERT OR REPLACE INTO mx_user_profile (room_id, user_id, membership, displayname, avatar_url) VALUES ($1, $2, $3, $4, $5)",
roomID, userID, member.Membership, member.Displayname, member.AvatarURL)
} else {
err = fmt.Errorf("unsupported dialect %s", store.db.dialect)
}
if err != nil {
store.log.Warnfln("Failed to set membership of %s in %s to %s: %v", userID, roomID, member, err)
}
}
func (store *SQLStateStore) SetPowerLevels(roomID id.RoomID, levels *event.PowerLevelsEventContent) {
levelsBytes, err := json.Marshal(levels)
if err != nil {
store.log.Errorfln("Failed to marshal power levels of %s: %v", roomID, err)
return
}
if store.db.dialect == "postgres" {
_, err = store.db.Exec(`INSERT INTO mx_room_state (room_id, power_levels) VALUES ($1, $2)
ON CONFLICT (room_id) DO UPDATE SET power_levels=$2`, roomID, levelsBytes)
} else if store.db.dialect == "sqlite3" {
_, err = store.db.Exec("INSERT OR REPLACE INTO mx_room_state (room_id, power_levels) VALUES ($1, $2)", roomID, levelsBytes)
} else {
err = fmt.Errorf("unsupported dialect %s", store.db.dialect)
}
if err != nil {
store.log.Warnfln("Failed to store power levels of %s: %v", roomID, err)
}
}
func (store *SQLStateStore) GetPowerLevels(roomID id.RoomID) (levels *event.PowerLevelsEventContent) {
row := store.db.QueryRow("SELECT power_levels FROM mx_room_state WHERE room_id=$1", roomID)
if row == nil {
return
}
var data []byte
err := row.Scan(&data)
if err != nil {
store.log.Errorln("Failed to scan power levels of %s: %v", roomID, err)
return
}
levels = &event.PowerLevelsEventContent{}
err = json.Unmarshal(data, levels)
if err != nil {
store.log.Errorln("Failed to parse power levels of %s: %v", roomID, err)
return nil
}
return
}
func (store *SQLStateStore) GetPowerLevel(roomID id.RoomID, userID id.UserID) int {
if store.db.dialect == "postgres" {
row := store.db.QueryRow(`SELECT
COALESCE((power_levels->'users'->$2)::int, (power_levels->'users_default')::int, 0)
FROM mx_room_state WHERE room_id=$1`, roomID, userID)
if row == nil {
// Power levels not in db
return 0
}
var powerLevel int
err := row.Scan(&powerLevel)
if err != nil {
store.log.Errorln("Failed to scan power level of %s in %s: %v", userID, roomID, err)
}
return powerLevel
}
return store.GetPowerLevels(roomID).GetUserLevel(userID)
}
func (store *SQLStateStore) GetPowerLevelRequirement(roomID id.RoomID, eventType event.Type) int {
if store.db.dialect == "postgres" {
defaultType := "events_default"
defaultValue := 0
if eventType.IsState() {
defaultType = "state_default"
defaultValue = 50
}
row := store.db.QueryRow(`SELECT
COALESCE((power_levels->'events'->$2)::int, (power_levels->'$3')::int, $4)
FROM mx_room_state WHERE room_id=$1`, roomID, eventType.Type, defaultType, defaultValue)
if row == nil {
// Power levels not in db
return defaultValue
}
var powerLevel int
err := row.Scan(&powerLevel)
if err != nil {
store.log.Errorln("Failed to scan power level for %s in %s: %v", eventType, roomID, err)
}
return powerLevel
}
return store.GetPowerLevels(roomID).GetEventLevel(eventType)
}
func (store *SQLStateStore) HasPowerLevel(roomID id.RoomID, userID id.UserID, eventType event.Type) bool {
if store.db.dialect == "postgres" {
defaultType := "events_default"
defaultValue := 0
if eventType.IsState() {
defaultType = "state_default"
defaultValue = 50
}
row := store.db.QueryRow(`SELECT
COALESCE((power_levels->'users'->$2)::int, (power_levels->'users_default')::int, 0)
>=
COALESCE((power_levels->'events'->$3)::int, (power_levels->'$4')::int, $5)
FROM mx_room_state WHERE room_id=$1`, roomID, userID, eventType.Type, defaultType, defaultValue)
if row == nil {
// Power levels not in db
return defaultValue == 0
}
var hasPower bool
err := row.Scan(&hasPower)
if err != nil {
store.log.Errorln("Failed to scan power level for %s in %s: %v", eventType, roomID, err)
}
return hasPower
}
return store.GetPowerLevel(roomID, userID) >= store.GetPowerLevelRequirement(roomID, eventType)
}

View File

@ -0,0 +1,67 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[0] = upgrade{"Initial schema", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`CREATE TABLE IF NOT EXISTS portal (
jid VARCHAR(255),
receiver VARCHAR(255),
mxid VARCHAR(255) UNIQUE,
name VARCHAR(255) NOT NULL,
topic VARCHAR(255) NOT NULL,
avatar VARCHAR(255) NOT NULL,
PRIMARY KEY (jid, receiver)
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE IF NOT EXISTS puppet (
jid VARCHAR(255) PRIMARY KEY,
avatar VARCHAR(255),
displayname VARCHAR(255),
name_quality SMALLINT
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE IF NOT EXISTS "user" (
mxid VARCHAR(255) PRIMARY KEY,
jid VARCHAR(255) UNIQUE,
management_room VARCHAR(255),
endpoint_id VARCHAR(255),
skype_token VARCHAR(255),
registration_token VARCHAR(255),
registration_token_str VARCHAR(255),
location_host VARCHAR(255)
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE IF NOT EXISTS message (
chat_jid VARCHAR(255),
chat_receiver VARCHAR(255),
jid VARCHAR(255),
mxid VARCHAR(255) NOT NULL UNIQUE,
sender VARCHAR(255) NOT NULL,
content bytea NOT NULL,
PRIMARY KEY (chat_jid, chat_receiver, jid),
FOREIGN KEY (chat_jid, chat_receiver) REFERENCES portal(jid, receiver) ON DELETE CASCADE
)`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,31 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[1] = upgrade{"Add ON DELETE CASCADE to message table", func(tx *sql.Tx, ctx context) error {
if ctx.dialect == SQLite {
// SQLite doesn't support constraint updates, but it isn't that careful with constraints anyway.
return nil
}
res, _ := ctx.db.Query(`SELECT EXISTS(SELECT constraint_name FROM information_schema.table_constraints
WHERE table_name='message' AND constraint_name='message_chat_jid_fkey')`)
var exists bool
_ = res.Scan(&exists)
if exists {
_, err := tx.Exec("ALTER TABLE message DROP CONSTRAINT IF EXISTS message_chat_jid_fkey")
if err != nil {
return err
}
_, err = tx.Exec(`ALTER TABLE message ADD CONSTRAINT message_chat_jid_fkey
FOREIGN KEY (chat_jid, chat_receiver) REFERENCES portal(jid, receiver)
ON DELETE CASCADE`)
if err != nil {
return err
}
}
return nil
}}
}

View File

@ -0,0 +1,15 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[2] = upgrade{"Add timestamp column to messages", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec("ALTER TABLE message ADD COLUMN timestamp BIGINT NOT NULL DEFAULT 0")
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,15 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[3] = upgrade{"Add last_connection column to users", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE "user" ADD COLUMN last_connection BIGINT NOT NULL DEFAULT 0`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,61 @@
package upgrades
import (
"database/sql"
"encoding/json"
"fmt"
)
func init() {
var keys = []string{"imageMessage", "contactMessage", "locationMessage", "extendedTextMessage", "documentMessage", "audioMessage", "videoMessage"}
upgrades[4] = upgrade{"Update message content to new protocol version. This may take a while.", func(tx *sql.Tx, ctx context) error {
rows, err := ctx.db.Query("SELECT mxid, content FROM message")
if err != nil {
return err
}
for rows.Next() {
var mxid string
var rawContent []byte
err = rows.Scan(&mxid, &rawContent)
if err != nil {
fmt.Println("Error scanning:", err)
continue
}
var content map[string]interface{}
err = json.Unmarshal(rawContent, &content)
if err != nil {
fmt.Printf("Error unmarshaling content of %s: %v\n", mxid, err)
continue
}
for _, key := range keys {
val, ok := content[key].(map[string]interface{})
if !ok {
continue
}
ci, ok := val["contextInfo"].(map[string]interface{})
if !ok {
continue
}
qm, ok := ci["quotedMessage"].([]interface{})
if !ok {
continue
}
ci["quotedMessage"] = qm[0]
goto save
}
continue
save:
rawContent, err = json.Marshal(&content)
if err != nil {
fmt.Printf("Error marshaling updated content of %s: %v\n", mxid, err)
}
_, err = tx.Exec("UPDATE message SET content=$1 WHERE mxid=$2", rawContent, mxid)
if err != nil {
fmt.Printf("Error updating row of %s: %v\n", mxid, err)
}
}
return nil
}}
}

View File

@ -0,0 +1,23 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[5] = upgrade{"Add columns to store custom puppet info", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE puppet ADD COLUMN custom_mxid VARCHAR(255)`)
if err != nil {
return err
}
_, err = tx.Exec(`ALTER TABLE puppet ADD COLUMN access_token VARCHAR(1023)`)
if err != nil {
return err
}
_, err = tx.Exec(`ALTER TABLE puppet ADD COLUMN next_batch VARCHAR(255)`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,19 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[6] = upgrade{"Add user-portal mapping table", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`CREATE TABLE user_portal (
user_jid VARCHAR(255),
portal_jid VARCHAR(255),
portal_receiver VARCHAR(255),
PRIMARY KEY (user_jid, portal_jid, portal_receiver),
FOREIGN KEY (user_jid) REFERENCES "user"(jid) ON DELETE CASCADE,
FOREIGN KEY (portal_jid, portal_receiver) REFERENCES portal(jid, receiver) ON DELETE CASCADE
)`)
return err
}}
}

View File

@ -0,0 +1,19 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[7] = upgrade{"Add columns to store avatar MXC URIs", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE puppet ADD COLUMN avatar_url VARCHAR(255)`)
if err != nil {
return err
}
_, err = tx.Exec(`ALTER TABLE portal ADD COLUMN avatar_url VARCHAR(255)`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,12 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[8] = upgrade{"Add columns to store portal in filtering community meta", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE user_portal ADD COLUMN in_community BOOLEAN NOT NULL DEFAULT FALSE`)
return err
}}
}

View File

@ -0,0 +1,141 @@
package upgrades
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"maunium.net/go/mautrix/event"
)
func init() {
migrateRegistrations := func(tx *sql.Tx, registrations map[string]bool) error {
if len(registrations) == 0 {
return nil
}
executeBatch := func(tx *sql.Tx, valueStrings []string, values ...interface{}) error {
valueString := strings.Join(valueStrings, ",")
_, err := tx.Exec("INSERT INTO mx_registrations (user_id) VALUES "+valueString, values...)
return err
}
batchSize := 100
values := make([]interface{}, 0, batchSize)
valueStrings := make([]string, 0, batchSize)
i := 1
for userID, registered := range registrations {
if i == batchSize {
err := executeBatch(tx, valueStrings, values...)
if err != nil {
return err
}
i = 1
values = make([]interface{}, 0, batchSize)
valueStrings = make([]string, 0, batchSize)
}
if registered {
values = append(values, userID)
valueStrings = append(valueStrings, fmt.Sprintf("($%d)", i))
i++
}
}
return executeBatch(tx, valueStrings, values...)
}
migrateMemberships := func(tx *sql.Tx, rooms map[string]map[string]event.Membership) error {
for roomID, members := range rooms {
if len(members) == 0 {
continue
}
var values []interface{}
var valueStrings []string
i := 1
for userID, membership := range members {
values = append(values, roomID, userID, membership)
valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d, $%d)", i, i+1, i+2))
i += 3
}
valueString := strings.Join(valueStrings, ",")
_, err := tx.Exec("INSERT INTO mx_user_profile (room_id, user_id, membership) VALUES "+valueString, values...)
if err != nil {
return err
}
}
return nil
}
migratePowerLevels := func(tx *sql.Tx, rooms map[string]*event.PowerLevelsEventContent) error {
if len(rooms) == 0 {
return nil
}
var values []interface{}
var valueStrings []string
i := 1
for roomID, powerLevels := range rooms {
powerLevelBytes, err := json.Marshal(powerLevels)
if err != nil {
return err
}
values = append(values, roomID, powerLevelBytes)
valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d)", i, i+1))
i += 2
}
valueString := strings.Join(valueStrings, ",")
_, err := tx.Exec("INSERT INTO mx_room_state (room_id, power_levels) VALUES "+valueString, values...)
return err
}
userProfileTable := `CREATE TABLE mx_user_profile (
room_id VARCHAR(255),
user_id VARCHAR(255),
membership VARCHAR(15) NOT NULL,
PRIMARY KEY (room_id, user_id)
)`
roomStateTable := `CREATE TABLE mx_room_state (
room_id VARCHAR(255) PRIMARY KEY,
power_levels TEXT
)`
registrationsTable := `CREATE TABLE mx_registrations (
user_id VARCHAR(255) PRIMARY KEY
)`
type TempStateStore struct {
Registrations map[string]bool `json:"registrations"`
Members map[string]map[string]event.Membership `json:"memberships"`
PowerLevels map[string]*event.PowerLevelsEventContent `json:"power_levels"`
}
upgrades[9] = upgrade{"Move state store to main DB", func(tx *sql.Tx, ctx context) error {
if ctx.dialect == Postgres {
roomStateTable = strings.Replace(roomStateTable, "TEXT", "JSONB", 1)
}
var store TempStateStore
if _, err := tx.Exec(userProfileTable); err != nil {
return err
} else if _, err = tx.Exec(roomStateTable); err != nil {
return err
} else if _, err = tx.Exec(registrationsTable); err != nil {
return err
} else if data, err := ioutil.ReadFile("mx-state.json"); err != nil {
ctx.log.Debugln("mx-state.json not found, not migrating state store")
} else if err = json.Unmarshal(data, &store); err != nil {
return err
} else if err = migrateRegistrations(tx, store.Registrations); err != nil {
return err
} else if err = migrateMemberships(tx, store.Members); err != nil {
return err
} else if err = migratePowerLevels(tx, store.PowerLevels); err != nil {
return err
} else if err = os.Rename("mx-state.json", "mx-state.json.bak"); err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,16 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[10] = upgrade{"Add columns to store full member info in state store", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE mx_user_profile ADD COLUMN displayname TEXT`)
if err != nil {
return err
}
_, err = tx.Exec(`ALTER TABLE mx_user_profile ADD COLUMN avatar_url VARCHAR(255)`)
return err
}}
}

View File

@ -0,0 +1,16 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[11] = upgrade{"Adjust the length of column topic in portal", func(tx *sql.Tx, ctx context) error {
if ctx.dialect == SQLite {
// SQLite doesn't support constraint updates, but it isn't that careful with constraints anyway.
return nil
}
_, err := tx.Exec(`ALTER TABLE portal ALTER COLUMN topic TYPE VARCHAR(512)`)
return err
}}
}

View File

@ -0,0 +1,12 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[12] = upgrade{"Add encryption status to portal table", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE portal ADD COLUMN encrypted BOOLEAN NOT NULL DEFAULT false`)
return err
}}
}

View File

@ -0,0 +1,73 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[13] = upgrade{"Add crypto store to database", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`CREATE TABLE crypto_account (
device_id VARCHAR(255) PRIMARY KEY,
shared BOOLEAN NOT NULL,
sync_token TEXT NOT NULL,
account bytea NOT NULL
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE crypto_message_index (
sender_key CHAR(43),
session_id CHAR(43),
"index" INTEGER,
event_id VARCHAR(255) NOT NULL,
timestamp BIGINT NOT NULL,
PRIMARY KEY (sender_key, session_id, "index")
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE crypto_tracked_user (
user_id VARCHAR(255) PRIMARY KEY
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE crypto_device (
user_id VARCHAR(255),
device_id VARCHAR(255),
identity_key CHAR(43) NOT NULL,
signing_key CHAR(43) NOT NULL,
trust SMALLINT NOT NULL,
deleted BOOLEAN NOT NULL,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id, device_id)
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE crypto_olm_session (
session_id CHAR(43) PRIMARY KEY,
sender_key CHAR(43) NOT NULL,
session bytea NOT NULL,
created_at timestamp NOT NULL,
last_used timestamp NOT NULL
)`)
if err != nil {
return err
}
_, err = tx.Exec(`CREATE TABLE crypto_megolm_inbound_session (
session_id CHAR(43) PRIMARY KEY,
sender_key CHAR(43) NOT NULL,
signing_key CHAR(43) NOT NULL,
room_id VARCHAR(255) NOT NULL,
session bytea NOT NULL,
forwarding_chains bytea NOT NULL
)`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,25 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[14] = upgrade{"Add outbound group sessions to database", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`CREATE TABLE crypto_megolm_outbound_session (
room_id VARCHAR(255) PRIMARY KEY,
session_id CHAR(43) NOT NULL UNIQUE,
session bytea NOT NULL,
shared BOOLEAN NOT NULL,
max_messages INTEGER NOT NULL,
message_count INTEGER NOT NULL,
max_age BIGINT NOT NULL,
created_at timestamp NOT NULL,
last_used timestamp NOT NULL
)`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,13 @@
package upgrades
import (
"database/sql"
"maunium.net/go/mautrix/crypto/sql_store_upgrade"
)
func init() {
upgrades[15] = upgrade{"Add account_id to crypto store", func(tx *sql.Tx, c context) error {
return sql_store_upgrade.Upgrades[1](tx, c.dialect.String())
}}
}

View File

@ -0,0 +1,13 @@
package upgrades
import (
"database/sql"
"maunium.net/go/mautrix/crypto/sql_store_upgrade"
)
func init() {
upgrades[16] = upgrade{"Add megolm withheld data to crypto store", func(tx *sql.Tx, c context) error {
return sql_store_upgrade.Upgrades[2](tx, c.dialect.String())
}}
}

View File

@ -0,0 +1,15 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[17] = upgrade{"Add id column to messages", func(tx *sql.Tx, ctx context) error {
_, err := tx.Exec(`ALTER TABLE message ADD COLUMN id CHAR(13) DEFAULT ''`)
if err != nil {
return err
}
return nil
}}
}

View File

@ -0,0 +1,13 @@
package upgrades
import (
"database/sql"
"maunium.net/go/mautrix/crypto/sql_store_upgrade"
)
func init() {
upgrades[18] = upgrade{"Add cross-signing keys to crypto store", func(tx *sql.Tx, c context) error {
return sql_store_upgrade.Upgrades[3](tx, c.dialect.String())
}}
}

View File

@ -0,0 +1,20 @@
package upgrades
import (
"database/sql"
)
func init() {
upgrades[19] = upgrade{"Update user fields varying.", func(tx *sql.Tx, c context) error {
if c.dialect == Postgres {
_, err := tx.Exec(`ALTER TABLE "user" ALTER COLUMN skype_token TYPE varchar(1500),
ALTER COLUMN registration_token TYPE varchar(1500),
ALTER COLUMN registration_token_str TYPE varchar(1500)`)
if err != nil {
return err
}
}
return nil
}}
}

View File

@ -0,0 +1,112 @@
package upgrades
import (
"database/sql"
"fmt"
"strings"
log "maunium.net/go/maulogger/v2"
)
type Dialect int
const (
Postgres Dialect = iota
SQLite
)
func (dialect Dialect) String() string {
switch dialect {
case Postgres:
return "postgres"
case SQLite:
return "sqlite3"
default:
return ""
}
}
type upgradeFunc func(*sql.Tx, context) error
type context struct {
dialect Dialect
db *sql.DB
log log.Logger
}
type upgrade struct {
message string
fn upgradeFunc
}
const NumberOfUpgrades = 20
var upgrades [NumberOfUpgrades]upgrade
var UnsupportedDatabaseVersion = fmt.Errorf("unsupported database version")
func GetVersion(db *sql.DB) (int, error) {
_, err := db.Exec("CREATE TABLE IF NOT EXISTS version (version INTEGER)")
if err != nil {
return -1, err
}
version := 0
row := db.QueryRow("SELECT version FROM version LIMIT 1")
if row != nil {
_ = row.Scan(&version)
}
return version, nil
}
func SetVersion(tx *sql.Tx, version int) error {
_, err := tx.Exec("DELETE FROM version")
if err != nil {
return err
}
_, err = tx.Exec("INSERT INTO version (version) VALUES ($1)", version)
return err
}
func Run(log log.Logger, dialectName string, db *sql.DB) error {
var dialect Dialect
switch strings.ToLower(dialectName) {
case "postgres":
dialect = Postgres
case "sqlite3":
dialect = SQLite
default:
return fmt.Errorf("unknown dialect %s", dialectName)
}
version, err := GetVersion(db)
if err != nil {
return err
}
if version > NumberOfUpgrades {
return UnsupportedDatabaseVersion
}
log.Infofln("Database currently on v%d, latest: v%d", version, NumberOfUpgrades)
for i, upgrade := range upgrades[version:] {
log.Infofln("Upgrading database to v%d: %s", version+i+1, upgrade.message)
tx, err := db.Begin()
if err != nil {
return err
}
err = upgrade.fn(tx, context{dialect, db, log})
if err != nil {
return err
}
err = SetVersion(tx, version+i+1)
if err != nil {
return err
}
err = tx.Commit()
if err != nil {
return err
}
}
return nil
}

241
database/user.go Normal file
View File

@ -0,0 +1,241 @@
package database
import (
"database/sql"
"fmt"
skype "github.com/kelaresg/go-skypeapi"
skypeExt "github.com/kelaresg/matrix-skype/skype-ext"
"strings"
"time"
log "maunium.net/go/maulogger/v2"
"github.com/kelaresg/matrix-skype/types"
"maunium.net/go/mautrix/id"
)
type UserQuery struct {
db *Database
log log.Logger
}
func (uq *UserQuery) New() *User {
return &User{
db: uq.db,
log: uq.log,
}
}
func (uq *UserQuery) GetAll() (users []*User) {
rows, err := uq.db.Query(`SELECT mxid, jid, management_room, last_connection, endpoint_id, skype_token, registration_token, registration_token_str, location_host FROM "user"`)
if err != nil || rows == nil {
return nil
}
defer rows.Close()
for rows.Next() {
users = append(users, uq.New().Scan(rows))
}
return
}
func (uq *UserQuery) GetByMXID(userID id.UserID) *User {
row := uq.db.QueryRow(`SELECT mxid, jid, management_room, last_connection, endpoint_id, skype_token, registration_token, registration_token_str, location_host FROM "user" WHERE mxid=$1`, userID)
if row == nil {
return nil
}
return uq.New().Scan(row)
}
func (uq *UserQuery) GetByJID(userID types.SkypeID) *User {
row := uq.db.QueryRow(`SELECT mxid, jid, management_room, last_connection, endpoint_id, skype_token, registration_token, registration_token_str, location_host FROM "user" WHERE jid=$1`, stripSuffix(userID))
if row == nil {
return nil
}
return uq.New().Scan(row)
}
type User struct {
db *Database
log log.Logger
MXID id.UserID
JID types.SkypeID
ManagementRoom id.RoomID
Session *skype.Session
LastConnection uint64
}
func (user *User) Scan(row Scannable) *User {
var jid, endpointId, skypeToken, registrationToken, registrationTokenStr, locationHost sql.NullString
err := row.Scan(&user.MXID, &jid, &user.ManagementRoom, &user.LastConnection, &endpointId, &skypeToken, &registrationToken, &registrationTokenStr, &locationHost)
if err != nil {
if err != sql.ErrNoRows {
user.log.Errorln("Database scan failed:", err)
}
return nil
}
if len(jid.String) > 0 && len(endpointId.String) > 0 {
user.JID = jid.String + skypeExt.NewUserSuffix
user.Session = &skype.Session{
EndpointId: endpointId.String,
SkypeToken: skypeToken.String,
RegistrationToken: registrationToken.String,
RegistrationTokenStr: registrationTokenStr.String,
LocationHost: locationHost.String,
}
} else {
user.Session = nil
}
return user
}
func stripSuffix(jid types.SkypeID) string {
if len(jid) == 0 {
return jid
}
index := strings.IndexRune(jid, '@')
if index < 0 {
return jid
}
return jid[:index]
}
func (user *User) jidPtr() *string {
if len(user.JID) > 0 {
str := stripSuffix(user.JID)
return &str
}
return nil
}
func (user *User) sessionUnptr() (sess skype.Session) {
if user.Session != nil {
sess = *user.Session
}
return
}
func (user *User) Insert() {
sess := user.sessionUnptr()
_, err := user.db.Exec(`INSERT INTO "user" (mxid, jid, management_room, last_connection, endpoint_id, skype_token, registration_token, registration_token_str, location_host) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
user.MXID, user.jidPtr(),
user.ManagementRoom, user.LastConnection,
sess.EndpointId, sess.SkypeToken, sess.RegistrationToken, sess.RegistrationTokenStr, sess.LocationHost)
if err != nil {
user.log.Warnfln("Failed to insert %s: %v", user.MXID, err)
}
}
func (user *User) UpdateLastConnection() {
user.LastConnection = uint64(time.Now().Unix())
_, err := user.db.Exec(`UPDATE "user" SET last_connection=$1 WHERE mxid=$2`,
user.LastConnection, user.MXID)
if err != nil {
user.log.Warnfln("Failed to update last connection ts: %v", err)
}
}
func (user *User) Update() {
sess := user.sessionUnptr()
_, err := user.db.Exec(`UPDATE "user" SET jid=$1, management_room=$2, last_connection=$3, endpoint_id=$4, skype_token=$5, registration_token=$6, registration_token_str=$7, location_host=$8 WHERE mxid=$9`,
user.jidPtr(), user.ManagementRoom, user.LastConnection,
sess.EndpointId, sess.SkypeToken, sess.RegistrationToken, sess.RegistrationTokenStr, sess.LocationHost,
user.MXID)
if err != nil {
user.log.Warnfln("Failed to update %s: %v", user.MXID, err)
}
}
type PortalKeyWithMeta struct {
PortalKey
InCommunity bool
}
func (user *User) SetPortalKeys(newKeys []PortalKeyWithMeta) error {
tx, err := user.db.Begin()
if err != nil {
return err
}
_, err = tx.Exec("DELETE FROM user_portal WHERE user_jid=$1", user.jidPtr())
if err != nil {
_ = tx.Rollback()
return err
}
valueStrings := make([]string, len(newKeys))
values := make([]interface{}, len(newKeys)*4)
for i, key := range newKeys {
pos := i * 4
valueStrings[i] = fmt.Sprintf("($%d, $%d, $%d, $%d)", pos+1, pos+2, pos+3, pos+4)
values[pos] = user.jidPtr()
values[pos+1] = key.JID
values[pos+2] = key.Receiver
values[pos+3] = key.InCommunity
}
query := fmt.Sprintf("INSERT INTO user_portal (user_jid, portal_jid, portal_receiver, in_community) VALUES %s",
strings.Join(valueStrings, ", "))
_, err = tx.Exec(query, values...)
if err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}
func (user *User) CreateUserPortal(newKey PortalKeyWithMeta) {
user.log.Debugfln("Creating new portal %s for %s", newKey.PortalKey.JID, newKey.PortalKey.Receiver)
_, err := user.db.Exec(`INSERT INTO user_portal (user_jid, portal_jid, portal_receiver, in_community) VALUES ($1, $2, $3, $4)`,
user.jidPtr(),
newKey.PortalKey.JID, newKey.PortalKey.Receiver,
newKey.InCommunity)
if err != nil {
user.log.Warnfln("Failed to insert %s: %v", user.MXID, err)
}
}
func (user *User) IsInPortal(key PortalKey) bool {
row := user.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM user_portal WHERE user_jid=$1 AND portal_jid=$2 AND portal_receiver=$3)`, user.jidPtr(), &key.JID, &key.Receiver)
var exists bool
_ = row.Scan(&exists)
return exists
}
func (user *User) GetPortalKeys() []PortalKey {
rows, err := user.db.Query(`SELECT portal_jid, portal_receiver FROM user_portal WHERE user_jid=$1`, user.jidPtr())
if err != nil {
user.log.Warnln("Failed to get user portal keys:", err)
return nil
}
var keys []PortalKey
for rows.Next() {
var key PortalKey
err = rows.Scan(&key.JID, &key.Receiver)
if err != nil {
user.log.Warnln("Failed to scan row:", err)
continue
}
keys = append(keys, key)
}
return keys
}
func (user *User) GetInCommunityMap() map[PortalKey]bool {
rows, err := user.db.Query(`SELECT portal_jid, portal_receiver, in_community FROM user_portal WHERE user_jid=$1`, user.jidPtr())
if err != nil {
user.log.Warnln("Failed to get user portal keys:", err)
return nil
}
keys := make(map[PortalKey]bool)
for rows.Next() {
var key PortalKey
var inCommunity bool
err = rows.Scan(&key.JID, &key.Receiver, &inCommunity)
if err != nil {
user.log.Warnln("Failed to scan row:", err)
continue
}
keys[key] = inCommunity
}
return keys
}

31
docker-run.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/sh
if [[ -z "$GID" ]]; then
GID="$UID"
fi
# Define functions.
function fixperms {
chown -R $UID:$GID /data /opt/matrix-skype
}
if [[ ! -f /data/config.yaml ]]; then
cp /opt/matrix-skype/example-config.yaml /data/config.yaml
echo "Didn't find a config file."
echo "Copied default config file to /data/config.yaml"
echo "Modify that config file to your liking."
echo "Start the container again after that to generate the registration file."
exit
fi
if [[ ! -f /data/registration.yaml ]]; then
/usr/bin/matrix-skype -g -c /data/config.yaml -r /data/registration.yaml
echo "Didn't find a registration file."
echo "Generated one for you."
echo "Copy that over to synapses app service directory."
exit
fi
cd /data
fixperms
exec su-exec $UID:$GID /usr/bin/matrix-skype

229
example-config.yaml Normal file
View File

@ -0,0 +1,229 @@
# Homeserver details.
homeserver:
# The address that this appservice can use to connect to the homeserver.
address: https://example.com
# The domain of the homeserver (for MXIDs, etc).
domain: example.com
# If you dont know what this is, no need to modify(for parse "mention user/reply message, etc")
server_name: matrix.to
# Application service host/registration related details.
# Changing these values requires regeneration of the registration.
appservice:
# The address that the homeserver can use to connect to this appservice.
address: http://localhost:29319
# The hostname and port where this appservice should listen.
hostname: 0.0.0.0
port: 29319
# Database config.
database:
# The database type. "sqlite3" and "postgres" are supported.
type: sqlite3
# The database URI.
# SQLite: File name is enough. https://github.com/mattn/go-sqlite3#connection-string
# Postgres: Connection string. For example, postgres://user:password@host/database?sslmode=disable
uri: matrix-skype.db
# Maximum number of connections. Mostly relevant for Postgres.
max_open_conns: 20
max_idle_conns: 2
# Settings for provisioning API
provisioning:
# Prefix for the provisioning API paths.
prefix: /_matrix/provision/v1
# Shared secret for authentication. If set to "disable", the provisioning API will be disabled.
shared_secret: disable
# The unique ID of this appservice.
id: skype
# Appservice bot details.
bot:
# Username of the appservice bot.
username: skypebridgebot
# Display name and avatar for bot. Set to "remove" to remove display name/avatar, leave empty
# to leave display name/avatar as-is.
displayname: Skype bridge bot
avatar: mxc://matrix.org/kGQUDQyPiwbRXPFkjoBrPyhC
# Authentication tokens for AS <-> HS communication. Autogenerated; do not modify.
as_token: "This value is generated when generating the registration"
hs_token: "This value is generated when generating the registration"
# Bridge config
bridge:
# Localpart template of MXIDs for Skype users.
# {{.}} is replaced with the phone number of the Skype user.
username_template: skype-{{.}}
# Displayname template for Skype users.
# {{.Notify}} - nickname set by the Skype user
# {{.Jid}} - phone number (international format)
# The following variables are also available, but will cause problems on multi-user instances:
# {{.Name}} - display name from contact list
# {{.Short}} - short display name from contact list
# To use multiple if's, you need to use: {{else if .Name}}, for example:
# "{{if .Notify}}{{.Notify}}{{else if .Name}}{{.Name}}{{else}}{{.Jid}}{{end}} (WA)"
displayname_template: "{{if .DisplayName}}{{.DisplayName}}{{else}}{{.PersonId}}{{end}} (Skype)"
# Localpart template for per-user room grouping community IDs.
# On startup, the bridge will try to create these communities, add all of the specific user's
# portals to the community, and invite the Matrix user to it.
# (Note that, by default, non-admins might not have your homeserver's permission to create
# communities.)
# {{.Localpart}} is the MXID localpart and {{.Server}} is the MXID server part of the user.
community_template: skype-{{.Localpart}}={{.Server}}
# Skype connection timeout in seconds.
connection_timeout: 20
# If Skype doesn't respond within connection_timeout, should the bridge try to fetch the message
# to see if it was actually bridged? Use this if you have problems with sends timing out but actually
# succeeding.
fetch_message_on_timeout: false
# Whether or not the bridge should send a read receipt from the bridge bot when a message has been
# sent to Skype. If fetch_message_on_timeout is enabled, a successful post-timeout fetch will
# trigger a read receipt too.
delivery_receipts: false
# Number of times to regenerate QR code when logging in.
# The regenerated QR code is sent as an edit and essentially multiplies the login timeout (20 seconds)
login_qr_regen_count: 2
# Maximum number of times to retry connecting on connection error.
max_connection_attempts: 3
# Number of seconds to wait between connection attempts.
# Negative numbers are exponential backoff: -connection_retry_delay + 1 + 2^attempts
connection_retry_delay: -1
# Whether or not the bridge should send a notice to the user's management room when it retries connecting.
# If false, it will only report when it stops retrying.
report_connection_retry: true
# Maximum number of seconds to wait for chats to be sent at startup.
# If this is too low and you have lots of chats, it could cause backfilling to fail.
chat_list_wait: 30
# Maximum number of seconds to wait to sync portals before force unlocking message processing.
# If this is too low and you have lots of chats, it could cause backfilling to fail.
portal_sync_wait: 600
# Whether or not to send call start/end notices to Matrix.
call_notices:
start: true
end: true
# Number of chats to sync for new users.
# Since some of the obtained conversations are not the conversations that the user needs to see,
# the actual number of conversations displayed on the matrix client will be slightly less than the set value
initial_chat_sync_count: 10
# Number of old messages to fill when creating new portal rooms.
initial_history_fill_count: 20
# Whether or not notifications should be turned off while filling initial history.
# Only applicable when using double puppeting.
initial_history_disable_notifications: false
# Maximum number of chats to sync when recovering from downtime.
# Set to -1 to sync all new chats during downtime.
recovery_chat_sync_limit: -1
# Whether or not to sync history when recovering from downtime.
recovery_history_backfill: true
# Maximum number of seconds since last message in chat to skip
# syncing the chat in any case. This setting will take priority
# over both recovery_chat_sync_limit and initial_chat_sync_count.
# Default is 3 days = 259200 seconds
sync_max_chat_age: 259200
# Whether or not to sync with custom puppets to receive EDUs that
# are not normally sent to appservices.
sync_with_custom_puppets: true
# Shared secret for https://github.com/devture/matrix-synapse-shared-secret-auth
#
# If set, custom puppets will be enabled automatically for local users
# instead of users having to find an access token and run `login-matrix`
# manually.
login_shared_secret: null
# Whether or not to invite own Skype user's Matrix puppet into private
# chat portals when backfilling if needed.
# This always uses the default puppet instead of custom puppets due to
# rate limits and timestamp massaging.
invite_own_puppet_for_backfilling: true
# Whether or not to explicitly set the avatar and room name for private
# chat portal rooms. This can be useful if the previous field works fine,
# but causes room avatar/name bugs.
private_chat_portal_meta: true
# Whether or not thumbnails from Skype should be sent.
# They're disabled by default due to very low resolution.
Skype_thumbnail: false
# Allow invite permission for user. User can invite any bots to room with Skype
# users (private chat and groups)
allow_user_invite: false
# The prefix for commands. Only required in non-management rooms.
command_prefix: "!wa"
# End-to-bridge encryption support options. This requires login_shared_secret to be configured
# in order to get a device for the bridge bot.
#
# Additionally, https://github.com/matrix-org/synapse/pull/5758 is required if using a normal
# application service.
encryption:
# Allow encryption, work in group chat rooms with e2ee enabled
allow: false
# Default to encryption, force-enable encryption in all portals the bridge creates
# This will cause the bridge bot to be in private chats for the encryption to work properly.
# It is recommended to also set private_chat_portal_meta to true when using this.
default: false
puppet_id:
# when set to true, the matrixid of the contact (puppet) from the bridge to the matrix will be encrypted into another string
default: false
# 8 characters
key: '12dsf323'
# Use the username_template prefix. (Warning: At present, username_template cannot be too complicated, otherwise this function may cause unknown errors)
username_template_prefix: 'skype-'
# Permissions for using the bridge.
# Permitted values:
# relaybot - Talk through the relaybot (if enabled), no access otherwise
# user - Access to use the bridge to chat with a Skype account.
# admin - User level and some additional administration tools
# Permitted keys:
# * - All Matrix users
# domain - All users on that homeserver
# mxid - Specific user
permissions:
"*": relaybot
"example.com": user
"@admin:example.com": admin
relaybot:
# Whether or not relaybot support is enabled.
enabled: false
# The management room for the bot. This is where all status notifications are posted and
# in this room, you can use `!wa <command>` instead of `!wa relaybot <command>`. Omitting
# the command prefix completely like in user management rooms is not possible.
management: !foo:example.com
# List of users to invite to all created rooms that include the relaybot.
invites: []
# The formats to use when sending messages to Skype via the relaybot.
message_formats:
m.text: "<b>{{ .Sender.Displayname }}</b>: {{ .Message }}"
m.notice: "<b>{{ .Sender.Displayname }}</b>: {{ .Message }}"
m.emote: "* <b>{{ .Sender.Displayname }}</b> {{ .Message }}"
m.file: "<b>{{ .Sender.Displayname }}</b> sent a file"
m.image: "<b>{{ .Sender.Displayname }}</b> sent an image"
m.audio: "<b>{{ .Sender.Displayname }}</b> sent an audio file"
m.video: "<b>{{ .Sender.Displayname }}</b> sent a video"
m.location: "<b>{{ .Sender.Displayname }}</b> sent a location"
# Logging config.
logging:
# The directory for log files. Will be created if not found.
directory: ./logs
# Available variables: .Date for the file date and .Index for different log files on the same day.
file_name_format: "{{.Date}}-{{.Index}}.log"
# Date format for file names in the Go time format: https://golang.org/pkg/time/#pkg-constants
file_date_format: 2006-01-02
# Log file permissions.
file_mode: 0600
# Timestamp format for log entries in the Go time format.
timestamp_format: Jan _2, 2006 15:04:05
# Minimum severity for log messages.
# Options: debug, info, warn, error, fatal
print_level: debug

221
formatting.go Normal file
View File

@ -0,0 +1,221 @@
package main
import (
"fmt"
skypeExt "github.com/kelaresg/matrix-skype/skype-ext"
"html"
"regexp"
"strings"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
"github.com/kelaresg/matrix-skype/types"
)
var italicRegex = regexp.MustCompile("([\\s>~*]|^)_(.+?)_([^a-zA-Z\\d]|$)")
var boldRegex = regexp.MustCompile("([\\s>_~]|^)\\*(.+?)\\*([^a-zA-Z\\d]|$)")
var strikethroughRegex = regexp.MustCompile("([\\s>_*]|^)~(.+?)~([^a-zA-Z\\d]|$)")
var codeBlockRegex = regexp.MustCompile("```(?:.|\n)+?```")
//var mentionRegex = regexp.MustCompile("@[0-9]+")
//var mentionRegex = regexp.MustCompile("@(.*)")
var mentionRegex = regexp.MustCompile("<at[^>]+\\bid=\"([^\"]+)\"(.*?)</at>*")
type Formatter struct {
bridge *Bridge
matrixHTMLParser *format.HTMLParser
waReplString map[*regexp.Regexp]string
waReplFunc map[*regexp.Regexp]func(string) string
waReplFuncText map[*regexp.Regexp]func(string) string
}
func NewFormatter(bridge *Bridge) *Formatter {
formatter := &Formatter{
bridge: bridge,
matrixHTMLParser: &format.HTMLParser{
TabsToSpaces: 4,
Newline: "\n",
PillConverter: func(mxid, eventID string, ctx format.Context) string {
if mxid[0] == '@' {
puppet := bridge.GetPuppetByMXID(id.UserID(mxid))
if puppet != nil {
return "@" + puppet.PhoneNumber()
}
}
return mxid
},
BoldConverter: func(text string, _ format.Context) string {
return fmt.Sprintf("*%s*", text)
},
ItalicConverter: func(text string, _ format.Context) string {
return fmt.Sprintf("_%s_", text)
},
StrikethroughConverter: func(text string, _ format.Context) string {
return fmt.Sprintf("~%s~", text)
},
MonospaceConverter: func(text string, _ format.Context) string {
return fmt.Sprintf("```%s```", text)
},
MonospaceBlockConverter: func(text, language string, _ format.Context) string {
return fmt.Sprintf("```%s```", text)
},
},
waReplString: map[*regexp.Regexp]string{
italicRegex: "$1<em>$2</em>$3",
boldRegex: "$1<strong>$2</strong>$3",
strikethroughRegex: "$1<del>$2</del>$3",
},
}
formatter.waReplFunc = map[*regexp.Regexp]func(string) string{
codeBlockRegex: func(str string) string {
str = str[3 : len(str)-3]
if strings.ContainsRune(str, '\n') {
return fmt.Sprintf("<pre><code>%s</code></pre>", str)
}
return fmt.Sprintf("<code>%s</code>", str)
},
}
formatter.waReplFuncText = map[*regexp.Regexp]func(string) string{
}
return formatter
}
func (formatter *Formatter) getMatrixInfoByJID(jid types.SkypeID) (mxid id.UserID, displayname string) {
if user := formatter.bridge.GetUserByJID(jid); user != nil {
mxid = user.MXID
displayname = string(user.MXID)
} else if puppet := formatter.bridge.GetPuppetByJID(jid); puppet != nil {
mxid = puppet.MXID
displayname = puppet.Displayname
}
return
}
func (formatter *Formatter) ParseSkype(content *event.MessageEventContent, RoomMXID id.RoomID) {
// parse '<a><a/>' tag
reg:= regexp.MustCompile(`(?U)(<a .*>(.*)</a>)`)
bodyMatch := reg.FindAllStringSubmatch(content.Body, -1)
for _, match := range bodyMatch {
content.Body = strings.ReplaceAll(content.Body, match[1], match[2])
}
output := content.Body
for regex, replacement := range formatter.waReplString {
output = regex.ReplaceAllString(output, replacement)
}
for regex, replacer := range formatter.waReplFunc {
output = regex.ReplaceAllStringFunc(output, replacer)
}
content.Body = html.UnescapeString(content.Body)
var backStr string
if output != content.Body {
output = strings.Replace(output, "\n", "<br/>", -1)
content.FormattedBody = output
content.Format = event.FormatHTML
var mxid id.UserID
// parse quote message(set reply)
content.Body = strings.ReplaceAll(content.Body, "\n", "")
quoteReg := regexp.MustCompile(`<quote[^>]+\bauthor="([^"]+)" authorname="([^"]+)" timestamp="([^"]+)" conversation="([^"]+)" messageid="([^"]+)".*>.*?</legacyquote>(.*?)<legacyquote>.*?</legacyquote></quote>(.*)`)
quoteMatches := quoteReg.FindAllStringSubmatch(content.Body, -1)
if len(quoteMatches) > 0 {
for _, match := range quoteMatches {
for index, a := range match {
fmt.Println("index: ", index)
fmt.Println("ParseSkype quoteMatches a:", a)
fmt.Println()
}
portal := formatter.bridge.GetPortalByMXID(RoomMXID)
if portal.Key.JID != match[4] {
content.FormattedBody = match[6]
content.Body = fmt.Sprintf("%s\n\n", match[6])
// this means that there are forwarding messages across groups
if strings.HasSuffix(match[4], skypeExt.GroupSuffix) || strings.HasSuffix(portal.Key.JID, skypeExt.GroupSuffix){
continue
}
}
msgMXID := ""
msg := formatter.bridge.DB.Message.GetByID(match[5])
if msg != nil {
msgMXID = string(msg.MXID)
}
mxid, _ = formatter.getMatrixInfoByJID("8:" + match[1] + skypeExt.NewUserSuffix)
href1 := fmt.Sprintf(`https://%s/#/room/%s/%s?via=%s`, formatter.bridge.Config.Homeserver.ServerName, RoomMXID, msgMXID, formatter.bridge.Config.Homeserver.Domain)
href2 := fmt.Sprintf(`https://%s/#/user/%s`, formatter.bridge.Config.Homeserver.ServerName, mxid)
newContent := fmt.Sprintf(`<mx-reply><blockquote><a href="%s">In reply to</a> <a href="%s">%s</a><br>%s</blockquote></mx-reply>`,
href1,
href2,
mxid,
match[6])
content.FormattedBody = newContent
content.Body = fmt.Sprintf("> <%s> %s\n\n", mxid, match[6])
inRelateTo := &event.RelatesTo{
Type: event.RelReply,
EventID: id.EventID(msgMXID),
}
content.SetRelatesTo(inRelateTo)
backStr = match[7]
}
}
}
// parse mention user message
r := regexp.MustCompile(`(?m)<at[^>]+\bid="([^"]+)">(.*?)</at>`)
var originStr string
var originBodyStr string
if len(backStr) == 0 {
originStr = content.Body
} else {
originStr = backStr
}
matches := r.FindAllStringSubmatch(originStr, -1)
if len(matches) > 0 {
for _, match := range matches {
mxid, displayname := formatter.getMatrixInfoByJID(match[1] + skypeExt.NewUserSuffix)
replaceStr := ""
if len(displayname) < 1 {
// TODO need to optimize
replaceStr = match[2] + ":"
} else {
replaceStr = fmt.Sprintf(`<a href="https://%s/#/%s">%s</a>:`, formatter.bridge.Config.Homeserver.ServerName, mxid, displayname)
}
// number := "@" + strings.Replace(match[1], skypeExt.NewUserSuffix, "", 1)
originStr = strings.ReplaceAll(originStr, match[0], replaceStr)
originBodyStr = strings.ReplaceAll(originStr, replaceStr, displayname + ":")
}
if len(backStr) == 0 {
content.Format = event.FormatHTML
content.Body = originBodyStr
content.FormattedBody = originStr
} else {
content.Body = content.Body + originBodyStr
content.FormattedBody = content.FormattedBody + originStr
}
} else {
content.Body = content.Body + backStr
content.FormattedBody = content.FormattedBody + backStr
}
//filter edit tag
e := regexp.MustCompile(`(<e_m a=".*></e_m>)`)
editMatches := e.FindAllStringSubmatch(content.Body, -1)
if len(editMatches) > 0 {
for _, match := range editMatches {
content.Body = strings.ReplaceAll(content.Body, match[0], "")
content.FormattedBody = strings.ReplaceAll(content.FormattedBody, match[0], "")
}
}
}
func (formatter *Formatter) ParseMatrix(html string) string {
ctx := make(format.Context)
return formatter.matrixHTMLParser.Parse(html, ctx)
}

96
formatting_test.go Normal file
View File

@ -0,0 +1,96 @@
package main
import (
"github.com/kelaresg/matrix-skype/database"
"github.com/kelaresg/matrix-skype/types"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"reflect"
"regexp"
"sync"
"testing"
)
func TestFormatter_ParseSkype(t *testing.T) {
type fields struct {
bridge *Bridge
matrixHTMLParser *format.HTMLParser
waReplString map[*regexp.Regexp]string
waReplFunc map[*regexp.Regexp]func(string) string
waReplFuncText map[*regexp.Regexp]func(string) string
}
type args struct {
content *event.MessageEventContent
}
type expect struct {
content *event.MessageEventContent
}
testUser := &User{
User: &database.User{
MXID: "mxtestid",
},
}
testBridge := &Bridge{
usersLock: *new(sync.Mutex),
usersByJID: map[types.SkypeID]*User{"test": testUser},
}
testFormatter := &Formatter{
bridge: testBridge,
}
tests := []struct {
name string
args args
expect expect
}{
{
"simple message",
args{
&event.MessageEventContent{
Body: "This is a very simple message.",
},
},
expect{
&event.MessageEventContent{
Body: "This is a very simple message.",
},
},
},
{
"simple punctuation test",
args{
&event.MessageEventContent{
Body: "It&apos;s the inclusion of &quot;simple&quot; punctuation that causes most of the problems.",
},
},
expect{
&event.MessageEventContent{
Body: "It's the inclusion of \"simple\" punctuation that causes most of the problems.",
Format: event.FormatHTML,
},
},
},
{
"full punctuation test",
args{
&event.MessageEventContent{
Body: "&amp;&lt;&gt;&quot;&#39", // use a few different encodings
Format: event.FormatHTML,
},
},
expect{
&event.MessageEventContent{
Body: "&<>\"'",
Format: event.FormatHTML,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
testFormatter.ParseSkype(tt.args.content, "")
if !reflect.DeepEqual(tt.args.content, tt.expect.content) {
t.Errorf("content = %v, wanted %v", tt.args.content, tt.expect.content)
}
})
}
}

20
go.mod Normal file
View File

@ -0,0 +1,20 @@
module github.com/kelaresg/matrix-skype
go 1.14
require (
github.com/chai2010/webp v1.1.0
github.com/gabriel-vasile/mimetype v1.1.2
github.com/gorilla/websocket v1.4.2
github.com/kelaresg/go-skypeapi v0.1.2-0.20210813144457-5bc29092a74e
github.com/lib/pq v1.9.0
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/pkg/errors v0.9.1
golang.org/x/image v0.0.0-20200618115811-c13761719519
gopkg.in/yaml.v2 v2.3.0
maunium.net/go/mauflag v1.0.0
maunium.net/go/maulogger/v2 v2.2.4
maunium.net/go/mautrix v0.8.0-rc.4
)
replace maunium.net/go/mautrix => github.com/pidongqianqian/mautrix-go v0.9.11-0.20210508035357-93e21d8c2bbe

397
go.sum Normal file
View File

@ -0,0 +1,397 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/goquery v1.5.1 h1:PSPBGne8NIUWw+/7vFBV+kG2J/5MOjbzc7154OaKCSE=
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/andybalholm/cascadia v1.1.0 h1:BuuO6sSfQNFRu1LppgbD25Hr2vLYW25JvxHs5zzsLTo=
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA=
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg=
github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts=
github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY=
github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc=
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/chai2010/webp v1.1.0 h1:4Ei0/BRroMF9FaXDG2e4OxwFcuW2vcXd+A6tyqTJUQQ=
github.com/chai2010/webp v1.1.0/go.mod h1:LP12PG5IFmLGHUU26tBiCBKnghxx3toZFwDjOYvd3Ow=
github.com/clbanning/mxj v1.8.4 h1:HuhwZtbyvyOw+3Z1AowPkU87JkJUSv751ELWaiTpj8I=
github.com/clbanning/mxj v1.8.4/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5PVGJng=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/gabriel-vasile/mimetype v1.1.2 h1:gaPnPcNor5aZSVCJVSGipcpbgMWiAAj9z182ocSGbHU=
github.com/gabriel-vasile/mimetype v1.1.2/go.mod h1:6CDPel/o/3/s4+bp6kIbsWATq8pmgOisOPG40CJa6To=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogf/gf v1.13.0 h1:URnD1CPVAuypmNAUveleraOA9CHRKHdvrn8D67uvKu0=
github.com/gogf/gf v1.13.0/go.mod h1:Ho7d+9F8dHe5LpEnIH+bky0aCtjwc8Gm82rUiCYnk/k=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0=
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gqcn/structs v1.1.1 h1:cyzGRwfmn3d1d54fwW3KUNyG9QxR0ldIeqwFGeBt638=
github.com/gqcn/structs v1.1.1/go.mod h1:/aBhTBSsKQ2Ec9pbnYdGphtdWXHFn4KrCL0fXM/Adok=
github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf h1:wIOAyJMMen0ELGiFzlmqxdcV1yGbkyHBAB6PolcNbLA=
github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kelaresg/go-skypeapi v0.1.2-0.20210813144457-5bc29092a74e h1:/C3k1dx0v2nVQ/AYvKvPJEJVba4K6rAJ+CRG38yhO0c=
github.com/kelaresg/go-skypeapi v0.1.2-0.20210813144457-5bc29092a74e/go.mod h1:2Mxwa2Flo+PKlVYEM4QBNgs408C/mUSBXRzAb6+B+Zg=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.9.0 h1:L8nSXQQzAYByakOFMTwpjRoHsMJklur4Gi59b6VivR8=
github.com/lib/pq v1.9.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.1 h1:b3iUnf1v+ppJiOfNX4yxxqfWKMQPZR5yoh8urCTFX88=
github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pidongqianqian/mautrix-go v0.9.11-0.20210508035357-93e21d8c2bbe h1:ZPK2QEV0zE5jUHl00AW0xl6kdCxtBaWxklcnMHtQGbs=
github.com/pidongqianqian/mautrix-go v0.9.11-0.20210508035357-93e21d8c2bbe/go.mod h1:7IzKfWvpQtN+W2Lzxc0rLvIxFM3ryKX6Ys3S/ZoWbg8=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM=
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tidwall/gjson v1.6.8 h1:CTmXMClGYPAmln7652e69B7OLXfTi5ABcPPwjIWUv7w=
github.com/tidwall/gjson v1.6.8/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI=
github.com/tidwall/match v1.0.3 h1:FQUVvBImDutD8wJLN6c5eMzWtjgONK9MwIBCOrUJKeE=
github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.0.2 h1:Z7S3cePv9Jwm1KwS0513MRaoUe3S01WPbLNV40pwWZU=
github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
github.com/tidwall/sjson v1.1.5 h1:wsUceI/XDyZk3J1FUvuuYlK62zJv2HO2Pzb8A5EWdUE=
github.com/tidwall/sjson v1.1.5/go.mod h1:VuJzsZnTowhSxWdOgsAnb886i4AjEyTkk7tNtsL7EYE=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20200618115811-c13761719519 h1:1e2ufUJNM3lCHEY5jIgac/7UTjd6cgJNdatjPdFWf34=
golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d h1:1aflnvSoWWLI2k/dMUAl5lvU1YO4Mb4hz0gh+1rjcxU=
golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
maunium.net/go/mauflag v1.0.0 h1:YiaRc0tEI3toYtJMRIfjP+jklH45uDHtT80nUamyD4M=
maunium.net/go/mauflag v1.0.0/go.mod h1:nLivPOpTpHnpzEh8jEdSL9UqO9+/KBJFmNRlwKfkPeA=
maunium.net/go/maulogger/v2 v2.2.4 h1:oV2GDeM4fx1uRysdpDC0FcrPg+thFicSd9XzPcYMbVY=
maunium.net/go/maulogger/v2 v2.2.4/go.mod h1:TYWy7wKwz/tIXTpsx8G3mZseIRiC5DoMxSZazOHy68A=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=

402
main.go Normal file
View File

@ -0,0 +1,402 @@
package main
import (
"fmt"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
flag "maunium.net/go/mauflag"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"github.com/kelaresg/matrix-skype/config"
"github.com/kelaresg/matrix-skype/database"
"github.com/kelaresg/matrix-skype/database/upgrades"
"github.com/kelaresg/matrix-skype/types"
)
var (
// These are static
Name = "matrix-skype"
URL = "unknown"
// This is changed when making a release
Version = "0.1.1"
SkypeVersion = ""
// These are filled at build time with the -X linker flag
Tag = "unknown"
Commit = "unknown"
BuildTime = "unknown"
)
func init() {
if len(Tag) > 0 && Tag[0] == 'v' {
Tag = Tag[1:]
}
if Tag != Version && !strings.HasSuffix(Version, "+dev") {
Version += "+dev"
}
SkypeVersion = strings.FieldsFunc(Version, func(r rune) bool { return r == '-' || r == '+' })[0]
}
var configPath = flag.MakeFull("c", "config", "The path to your config file.", "config.yaml").String()
//var baseConfigPath = flag.MakeFull("b", "base-config", "The path to the example config file.", "example-config.yaml").String()
var registrationPath = flag.MakeFull("r", "registration", "The path where to save the appservice registration.", "registration.yaml").String()
var generateRegistration = flag.MakeFull("g", "generate-registration", "Generate registration and quit.", "false").Bool()
var version = flag.MakeFull("v", "version", "View bridge version and quit.", "false").Bool()
var ignoreUnsupportedDatabase = flag.Make().LongKey("ignore-unsupported-database").Usage("Run even if database is too new").Default("false").Bool()
var migrateFrom = flag.Make().LongKey("migrate-db").Usage("Source database type and URI to migrate from.").Bool()
var wantHelp, _ = flag.MakeHelpFlag()
func (bridge *Bridge) GenerateRegistration() {
reg, err := bridge.Config.NewRegistration()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to generate registration:", err)
os.Exit(20)
}
err = reg.Save(*registrationPath)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to save registration:", err)
os.Exit(21)
}
err = bridge.Config.Save(*configPath)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to save config:", err)
os.Exit(22)
}
fmt.Println("Registration generated. Add the path to the registration to your Synapse config, restart it, then start the bridge.")
os.Exit(0)
}
func (bridge *Bridge) MigrateDatabase() {
oldDB, err := database.New(flag.Arg(0), flag.Arg(1))
if err != nil {
fmt.Println("Failed to open old database:", err)
os.Exit(30)
}
err = oldDB.Init()
if err != nil {
fmt.Println("Failed to upgrade old database:", err)
os.Exit(31)
}
newDB, err := database.New(bridge.Config.AppService.Database.Type, bridge.Config.AppService.Database.URI)
if err != nil {
bridge.Log.Fatalln("Failed to open new database:", err)
os.Exit(32)
}
err = newDB.Init()
if err != nil {
fmt.Println("Failed to upgrade new database:", err)
os.Exit(33)
}
database.Migrate(oldDB, newDB)
}
type Bridge struct {
AS *appservice.AppService
EventProcessor *appservice.EventProcessor
MatrixHandler *MatrixHandler
Config *config.Config
DB *database.Database
Log log.Logger
StateStore *database.SQLStateStore
Provisioning *ProvisioningAPI
Bot *appservice.IntentAPI
Formatter *Formatter
Relaybot *User
Crypto Crypto
usersByMXID map[id.UserID]*User
usersByJID map[types.SkypeID]*User
usersLock sync.Mutex
managementRooms map[id.RoomID]*User
managementRoomsLock sync.Mutex
portalsByMXID map[id.RoomID]*Portal
portalsByJID map[database.PortalKey]*Portal
portalsLock sync.Mutex
puppets map[types.SkypeID]*Puppet
puppetsByCustomMXID map[id.UserID]*Puppet
puppetsLock sync.Mutex
}
type Crypto interface {
HandleMemberEvent(*event.Event)
Decrypt(*event.Event) (*event.Event, error)
Encrypt(id.RoomID, event.Type, event.Content) (*event.EncryptedEventContent, error)
Init() error
Start()
Stop()
}
func NewBridge() *Bridge {
bridge := &Bridge{
usersByMXID: make(map[id.UserID]*User),
usersByJID: make(map[types.SkypeID]*User),
managementRooms: make(map[id.RoomID]*User),
portalsByMXID: make(map[id.RoomID]*Portal),
portalsByJID: make(map[database.PortalKey]*Portal),
puppets: make(map[types.SkypeID]*Puppet),
puppetsByCustomMXID: make(map[id.UserID]*Puppet),
}
var err error
bridge.Config, err = config.Load(*configPath)
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to load config:", err)
os.Exit(10)
}
return bridge
}
func (bridge *Bridge) ensureConnection() {
for {
resp, err := bridge.Bot.Whoami()
if err != nil {
if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.RespError != nil && httpErr.RespError.ErrCode == "M_UNKNOWN_ACCESS_TOKEN" {
bridge.Log.Fatalln("Access token invalid. Is the registration installed in your homeserver correctly?")
os.Exit(16)
}
bridge.Log.Errorfln("Failed to connect to homeserver: %v. Retrying in 10 seconds...", err)
time.Sleep(10 * time.Second)
} else if resp.UserID != bridge.Bot.UserID {
bridge.Log.Fatalln("Unexpected user ID in whoami call: got %s, expected %s", resp.UserID, bridge.Bot.UserID)
os.Exit(17)
} else {
break
}
}
}
func (bridge *Bridge) Init() {
var err error
bridge.AS, err = bridge.Config.MakeAppService()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to initialize AppService:", err)
os.Exit(11)
}
_, _ = bridge.AS.Init()
bridge.Bot = bridge.AS.BotIntent()
bridge.Log = log.Create()
bridge.Config.Logging.Configure(bridge.Log)
log.DefaultLogger = bridge.Log.(*log.BasicLogger)
if len(bridge.Config.Logging.FileNameFormat) > 0 {
err = log.OpenFile()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "Failed to open log file:", err)
os.Exit(12)
}
}
bridge.AS.Log = log.Sub("Matrix")
bridge.Log.Debugln("Initializing database")
bridge.DB, err = database.New(bridge.Config.AppService.Database.Type, bridge.Config.AppService.Database.URI)
if err != nil && (err != upgrades.UnsupportedDatabaseVersion || !*ignoreUnsupportedDatabase) {
bridge.Log.Fatalln("Failed to initialize database:", err)
os.Exit(14)
}
if len(bridge.Config.AppService.StateStore) > 0 && bridge.Config.AppService.StateStore != "./mx-state.json" {
version, err := upgrades.GetVersion(bridge.DB.DB)
if version < 0 && err == nil {
bridge.Log.Fatalln("Non-standard state store path. Please move the state store to ./mx-state.json " +
"and update the config. The state store will be migrated into the db on the next launch.")
os.Exit(18)
}
}
bridge.Log.Debugln("Initializing state store")
bridge.StateStore = database.NewSQLStateStore(bridge.DB)
bridge.AS.StateStore = bridge.StateStore
bridge.DB.SetMaxOpenConns(bridge.Config.AppService.Database.MaxOpenConns)
bridge.DB.SetMaxIdleConns(bridge.Config.AppService.Database.MaxIdleConns)
ss := bridge.Config.AppService.Provisioning.SharedSecret
if len(ss) > 0 && ss != "disable" {
bridge.Provisioning = &ProvisioningAPI{bridge: bridge}
}
bridge.Log.Debugln("Initializing Matrix event processor")
bridge.EventProcessor = appservice.NewEventProcessor(bridge.AS)
bridge.Log.Debugln("Initializing Matrix event handler")
bridge.MatrixHandler = NewMatrixHandler(bridge)
bridge.Formatter = NewFormatter(bridge)
bridge.Crypto = NewCryptoHelper(bridge)
}
func (bridge *Bridge) Start() {
err := bridge.DB.Init()
if err != nil {
bridge.Log.Fatalln("Failed to initialize database:", err)
os.Exit(15)
}
bridge.Log.Debugln("Checking connection to homeserver")
bridge.ensureConnection()
if bridge.Crypto != nil {
err := bridge.Crypto.Init()
if err != nil {
bridge.Log.Fatalln("Error initializing end-to-bridge encryption:", err)
os.Exit(19)
}
}
if bridge.Provisioning != nil {
bridge.Log.Debugln("Initializing provisioning API")
bridge.Provisioning.Init()
}
bridge.LoadRelaybot()
//bridge.Log.Debugln("Checking connection to homeserver")
//bridge.ensureConnection()
bridge.Log.Debugln("Starting application service HTTP server")
go bridge.AS.Start()
bridge.Log.Debugln("Starting event processor")
go bridge.EventProcessor.Start()
go bridge.UpdateBotProfile()
if bridge.Crypto != nil {
go bridge.Crypto.Start()
}
go bridge.StartUsers()
}
func (bridge *Bridge) LoadRelaybot() {
if !bridge.Config.Bridge.Relaybot.Enabled {
return
}
bridge.Relaybot = bridge.GetUserByMXID("relaybot")
if bridge.Relaybot.HasSession() {
bridge.Log.Debugln("Relaybot is enabled")
} else {
bridge.Log.Debugln("Relaybot is enabled, but not logged in")
}
bridge.Relaybot.ManagementRoom = bridge.Config.Bridge.Relaybot.ManagementRoom
bridge.Relaybot.IsRelaybot = true
bridge.Relaybot.Connect(false)
}
func (bridge *Bridge) UpdateBotProfile() {
bridge.Log.Debugln("Updating bot profile")
botConfig := bridge.Config.AppService.Bot
var err error
var mxc id.ContentURI
if botConfig.Avatar == "remove" {
err = bridge.Bot.SetAvatarURL(mxc)
} else if len(botConfig.Avatar) > 0 {
mxc, err = id.ParseContentURI(botConfig.Avatar)
if err == nil {
err = bridge.Bot.SetAvatarURL(mxc)
}
}
if err != nil {
bridge.Log.Warnln("Failed to update bot avatar:", err)
}
if botConfig.Displayname == "remove" {
err = bridge.Bot.SetDisplayName("")
} else if len(botConfig.Avatar) > 0 {
err = bridge.Bot.SetDisplayName(botConfig.Displayname)
}
if err != nil {
bridge.Log.Warnln("Failed to update bot displayname:", err)
}
}
func (bridge *Bridge) StartUsers() {
bridge.Log.Debugln("Starting users")
for _, user := range bridge.GetAllUsers() {
go user.Connect(false)
}
bridge.Log.Debugln("Starting custom puppets")
for _, loopuppet := range bridge.GetAllPuppetsWithCustomMXID() {
go func(puppet *Puppet) {
puppet.log.Debugln("Starting custom puppet", puppet.CustomMXID)
err := puppet.StartCustomMXID()
if err != nil {
puppet.log.Errorln("Failed to start custom puppet:", err)
}
}(loopuppet)
}
}
func (bridge *Bridge) Stop() {
if bridge.Crypto != nil {
bridge.Crypto.Stop()
}
bridge.AS.Stop()
bridge.EventProcessor.Stop()
for _, user := range bridge.usersByJID {
if user.Conn == nil {
continue
}
//bridge.Log.Debugln("Disconnecting", user.MXID)
//sess, err := user.Conn.Disconnect()
//if err != nil {
// bridge.Log.Errorfln("Error while disconnecting %s: %v", user.MXID, err)
//} else if len(sess.Wid) > 0 {
// user.SetSession(&sess)
//}
}
}
func (bridge *Bridge) Main() {
if *generateRegistration {
bridge.GenerateRegistration()
return
} else if *migrateFrom {
bridge.MigrateDatabase()
return
}
bridge.Init()
bridge.Log.Infoln("Bridge initialization complete, starting...")
bridge.Start()
bridge.Log.Infoln("Bridge started!")
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
bridge.Log.Infoln("Interrupt received, stopping...")
bridge.Stop()
bridge.Log.Infoln("Bridge stopped.")
os.Exit(0)
}
func main() {
flag.SetHelpTitles(
"matrix-skype - A Matrix-Skype puppeting bridge.",
"matrix-skype [-h] [-c <path>] [-r <path>] [-g] [--migrate-db <source type> <source uri>]")
err := flag.Parse()
if err != nil {
fmt.Fprintln(os.Stderr, err)
flag.PrintHelp()
os.Exit(1)
} else if *wantHelp {
flag.PrintHelp()
os.Exit(0)
} else if *version {
if Tag == Version {
fmt.Printf("%s %s (%s)\n", Name, Tag, BuildTime)
} else if len(Commit) > 8 {
fmt.Printf("%s %s.%s (%s)\n", Name, Version, Commit[:8], BuildTime)
} else {
fmt.Printf("%s %s.unknown\n", Name, Version)
}
return
}
NewBridge().Main()
}

455
matrix.go Normal file
View File

@ -0,0 +1,455 @@
package main
import (
"fmt"
skype "github.com/kelaresg/go-skypeapi"
"github.com/kelaresg/matrix-skype/database"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/patch"
"strconv"
"strings"
"time"
"maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
)
type MatrixHandler struct {
bridge *Bridge
as *appservice.AppService
log maulogger.Logger
cmd *CommandHandler
}
func NewMatrixHandler(bridge *Bridge) *MatrixHandler {
handler := &MatrixHandler{
bridge: bridge,
as: bridge.AS,
log: bridge.Log.Sub("Matrix"),
cmd: NewCommandHandler(bridge),
}
bridge.EventProcessor.On(event.EventMessage, handler.HandleMessage)
bridge.EventProcessor.On(event.EventEncrypted, handler.HandleEncrypted)
bridge.EventProcessor.On(event.EventSticker, handler.HandleMessage)
bridge.EventProcessor.On(event.EventRedaction, handler.HandleRedaction)
bridge.EventProcessor.On(event.StateMember, handler.HandleMembership)
bridge.EventProcessor.On(event.StateRoomName, handler.HandleRoomMetadata)
bridge.EventProcessor.On(event.StateRoomAvatar, handler.HandleRoomMetadata)
bridge.EventProcessor.On(event.StateTopic, handler.HandleRoomMetadata)
bridge.EventProcessor.On(event.StateEncryption, handler.HandleEncryption)
return handler
}
func (mx *MatrixHandler) HandleEncryption(evt *event.Event) {
if evt.Content.AsEncryption().Algorithm != id.AlgorithmMegolmV1 {
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if portal != nil && !portal.Encrypted {
mx.log.Debugfln("%s enabled encryption in %s", evt.Sender, evt.RoomID)
portal.Encrypted = true
portal.Update()
}
}
func (mx *MatrixHandler) joinAndCheckMembers(evt *event.Event, intent *appservice.IntentAPI) *mautrix.RespJoinedMembers {
resp, err := intent.JoinRoomByID(evt.RoomID)
if err != nil {
mx.log.Debugfln("JoinRoomByID err, retry in 5 seconds", err)
time.Sleep(5 * time.Second)
resp, err = intent.JoinRoomByID(evt.RoomID)
if err != nil {
mx.log.Debugfln("JoinRoomByID err, retry again in 5 seconds", err)
time.Sleep(5 * time.Second)
resp, err = intent.JoinRoomByID(evt.RoomID)
if err != nil {
mx.log.Debugfln("Failed to join room %s as %s with invite from %s: %v", evt.RoomID, intent.UserID, evt.Sender, err)
return nil
}
}
}
members, err := intent.JoinedMembers(resp.RoomID)
if err != nil {
mx.log.Debugfln("Failed to get members in room %s after accepting invite from %s as %s: %v", resp.RoomID, evt.Sender, intent.UserID, err)
_, _ = intent.LeaveRoom(resp.RoomID)
return nil
}
if len(members.Joined) < 2 {
mx.log.Debugln("Leaving empty room", resp.RoomID, "after accepting invite from", evt.Sender, "as", intent.UserID)
_, _ = intent.LeaveRoom(resp.RoomID)
return nil
}
return members
}
func (mx *MatrixHandler) HandleBotInvite(evt *event.Event) {
intent := mx.as.BotIntent()
user := mx.bridge.GetUserByMXID(evt.Sender)
if user == nil {
return
}
members := mx.joinAndCheckMembers(evt, intent)
if members == nil {
return
}
if !user.Whitelisted {
_, _ = intent.SendNotice(evt.RoomID, "You are not whitelisted to use this bridge.\n"+
"If you're the owner of this bridge, see the bridge.permissions section in your config file.")
_, _ = intent.LeaveRoom(evt.RoomID)
return
}
if evt.RoomID == mx.bridge.Config.Bridge.Relaybot.ManagementRoom {
_, _ = intent.SendNotice(evt.RoomID, "This is the relaybot management room. Send `!wa help` to get a list of commands.")
mx.log.Debugln("Joined relaybot management room", evt.RoomID, "after invite from", evt.Sender)
return
}
hasPuppets := false
for mxid, _ := range members.Joined {
if mxid == intent.UserID || mxid == evt.Sender {
continue
} else if _, ok := mx.bridge.ParsePuppetMXID(mxid); ok {
hasPuppets = true
continue
}
mx.log.Debugln("Leaving multi-user room", evt.RoomID, "after accepting invite from", evt.Sender)
_, _ = intent.SendNotice(evt.RoomID, "This bridge is user-specific, please don't invite me into rooms with other users.")
_, _ = intent.LeaveRoom(evt.RoomID)
return
}
if !hasPuppets && (len(user.ManagementRoom) == 0 || evt.Content.AsMember().IsDirect) {
user.SetManagementRoom(evt.RoomID)
_, _ = intent.SendNotice(user.ManagementRoom, "This room has been registered as your bridge management/status room. Send `help` to get a list of commands.")
mx.log.Debugln(evt.RoomID, "registered as a management room with", evt.Sender)
}
}
func (mx *MatrixHandler) handlePrivatePortal(roomID id.RoomID, inviter *User, puppet *Puppet, key database.PortalKey) {
portal := mx.bridge.GetPortalByJID(key)
if len(portal.MXID) == 0 {
mx.createPrivatePortalFromInvite(roomID, inviter, puppet, portal)
return
}
err := portal.MainIntent().EnsureInvited(portal.MXID, inviter.MXID)
if err != nil {
mx.log.Warnfln("Failed to invite %s to existing private chat portal %s with %s: %v. Redirecting portal to new room...", inviter.MXID, portal.MXID, puppet.JID, err)
mx.createPrivatePortalFromInvite(roomID, inviter, puppet, portal)
return
}
intent := puppet.DefaultIntent()
_, _ = intent.SendNotice(roomID, fmt.Sprintf("You already have a private chat portal with me at %s", roomID))
mx.log.Debugln("Leaving private chat room", roomID, "as", puppet.MXID, "after accepting invite from", inviter.MXID, "as we already have chat with the user")
_, _ = intent.LeaveRoom(roomID)
}
func (mx *MatrixHandler) createPrivatePortalFromInvite(roomID id.RoomID, inviter *User, puppet *Puppet, portal *Portal) {
portal.MXID = roomID
portal.Topic = "Skype private chat"
_, _ = portal.MainIntent().SetRoomTopic(portal.MXID, portal.Topic)
if portal.bridge.Config.Bridge.PrivateChatPortalMeta {
portal.Name = puppet.Displayname
portal.AvatarURL = puppet.AvatarURL
portal.Avatar = puppet.Avatar
_, _ = portal.MainIntent().SetRoomName(portal.MXID, portal.Name)
_, _ = portal.MainIntent().SetRoomAvatar(portal.MXID, portal.AvatarURL)
} else {
portal.Name = ""
}
portal.log.Infoln("Created private chat portal in %s after invite from", roomID, inviter.MXID)
intent := puppet.DefaultIntent()
if mx.bridge.Config.Bridge.Encryption.Default {
_, err := intent.InviteUser(roomID, &mautrix.ReqInviteUser{UserID: mx.bridge.Bot.UserID})
if err != nil {
portal.log.Warnln("Failed to invite bridge bot to enable e2be:", err)
}
err = mx.bridge.Bot.EnsureJoined(roomID)
if err != nil {
portal.log.Warnln("Failed to join as bridge bot to enable e2be:", err)
}
_, err = intent.SendStateEvent(roomID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
if err != nil {
portal.log.Warnln("Failed to enable e2be:", err)
}
mx.as.StateStore.SetMembership(roomID, inviter.MXID, event.MembershipJoin)
mx.as.StateStore.SetMembership(roomID, puppet.MXID, event.MembershipJoin)
mx.as.StateStore.SetMembership(roomID, mx.bridge.Bot.UserID, event.MembershipJoin)
portal.Encrypted = true
}
portal.Update()
portal.UpdateBridgeInfo()
_, _ = intent.SendNotice(roomID, "Private chat portal created")
err := portal.FillInitialHistory(inviter)
if err != nil {
portal.log.Errorln("Failed to fill history:", err)
}
inviter.addPortalToCommunity(portal)
inviter.addPuppetToCommunity(puppet)
}
func (mx *MatrixHandler) HandlePuppetInvite(evt *event.Event, inviter *User, puppet *Puppet) {
intent := puppet.DefaultIntent()
members := mx.joinAndCheckMembers(evt, intent)
if members == nil {
return
}
var hasBridgeBot, hasOtherUsers bool
for mxid, _ := range members.Joined {
fmt.Println()
fmt.Println()
fmt.Println("HandlePuppetInvite mxid", mxid)
fmt.Println("HandlePuppetInvite intent.UserID", intent.UserID)
fmt.Println("HandlePuppetInvite patch.Parse(intent.UserID)", id.UserID(patch.Parse(string(intent.UserID))))
fmt.Println("HandlePuppetInvite inviter.MXID", inviter.MXID)
fmt.Println()
fmt.Println()
if mxid == id.UserID(patch.Parse(string(intent.UserID))) || mxid == inviter.MXID {
continue
} else if mxid == mx.bridge.Bot.UserID {
hasBridgeBot = true
} else {
hasOtherUsers = true
}
}
if !hasBridgeBot && !hasOtherUsers {
key := database.NewPortalKey(puppet.JID, inviter.JID)
mx.handlePrivatePortal(evt.RoomID, inviter, puppet, key)
} else if !hasBridgeBot {
mx.log.Debugln("Leaving multi-user room", evt.RoomID, "as", puppet.MXID, "after accepting invite from", evt.Sender)
_, _ = intent.SendNotice(evt.RoomID, "Please invite the bridge bot first if you want to bridge to a skype group.")
_, _ = intent.LeaveRoom(evt.RoomID)
} else {
_, _ = intent.SendNotice(evt.RoomID, "This puppet will remain inactive until this room is bridged to a Skype group.")
}
}
func (mx *MatrixHandler) HandleMembership(evt *event.Event) {
fmt.Println("HandleMembership0 evt.Sender:", evt.Sender)
fmt.Println("HandleMembership0 evt.GetStateKey:", evt.GetStateKey())
if _, isPuppet := mx.bridge.ParsePuppetMXID(evt.Sender); evt.Sender == mx.bridge.Bot.UserID || isPuppet {
return
}
if mx.bridge.Crypto != nil {
mx.bridge.Crypto.HandleMemberEvent(evt)
}
content := evt.Content.AsMember()
if content.Membership == event.MembershipInvite && id.UserID(evt.GetStateKey()) == mx.as.BotMXID() {
mx.HandleBotInvite(evt)
return
}
user := mx.bridge.GetUserByMXID(evt.Sender)
if user == nil || user.Conn == nil || user.Conn.LoginInfo == nil || !user.Whitelisted || !user.IsConnected() {
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if portal == nil {
puppet := mx.bridge.GetPuppetByMXID(id.UserID(evt.GetStateKey()))
if content.Membership == event.MembershipInvite && puppet != nil {
mx.HandlePuppetInvite(evt, user, puppet)
}
return
}
isSelf := id.UserID(evt.GetStateKey()) == evt.Sender
fmt.Println("HandleMembership isSelf:", isSelf)
fmt.Println("HandleMembership id.UserID(evt.GetStateKey()):", id.UserID(evt.GetStateKey()))
fmt.Println("HandleMembership evt.Sender:", evt.Sender)
if content.Membership == event.MembershipLeave {
if id.UserID(evt.GetStateKey()) == evt.Sender {
if evt.Unsigned.PrevContent != nil {
_ = evt.Unsigned.PrevContent.ParseRaw(evt.Type)
prevContent, ok := evt.Unsigned.PrevContent.Parsed.(*event.MemberEventContent)
if ok {
if portal.IsPrivateChat() || prevContent.Membership == "join" {
portal.HandleMatrixLeave(user)
}
}
}
} else {
fmt.Println()
fmt.Println()
fmt.Println("HandleMembership evt.RoomID", evt.RoomID)
fmt.Println("HandleMembership id.UserID(evt.GetStateKey())", id.UserID(evt.GetStateKey()))
fmt.Println("HandleMembership event.MembershipLeave", event.MembershipLeave)
fmt.Println("HandleMembership user.", event.MembershipLeave)
fmt.Println()
//mx.as.StateStore.SetMembership(evt.RoomID, id.UserID(evt.GetStateKey()), event.MembershipLeave)
portal.HandleMatrixKick(user, evt)
}
} else if content.Membership == event.MembershipInvite && !isSelf {
portal.HandleMatrixInvite(user, evt)
}
}
func (mx *MatrixHandler) HandleRoomMetadata(evt *event.Event) {
user := mx.bridge.GetUserByMXID(evt.Sender)
if user == nil || !user.Whitelisted || !user.IsConnected() {
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if user.Conn == nil || user.Conn.LoginInfo == nil || portal == nil || portal.IsPrivateChat() {
return
}
//var resp <-chan string
var resp string
var err error
switch content := evt.Content.Parsed.(type) {
case *event.RoomNameEventContent:
resp, err = user.Conn.SetConversationThreads(portal.Key.JID, map[string]string{
"topic": content.Name,
})
case *event.TopicEventContent:
//resp, err = user.Conn.SetConversationThreads(portal.Key.JID, map[string]string{
// "topic": content.Topic,
//})
return
case *event.RoomAvatarEventContent:
data, err := portal.MainIntent().DownloadBytes(content.URL)
if err != nil {
portal.log.Errorfln("Failed to download media in %v", err)
return
}
_, fileId, _, err := user.Conn.UploadFile(portal.Key.JID, &skype.SendMessage{
Jid: portal.Key.JID,
ClientMessageId: "",
Type: "avatar/group",
SendMediaMessage: &skype.SendMediaMessage{
FileName: "avatar",
RawData: data,
FileSize: strconv.Itoa(len(data)), // strconv.FormatUint(fileSize, 10),
Duration: 0,
},
})
if err != nil {
mx.log.Errorln(err)
return
}
resp, err = user.Conn.SetConversationThreads(portal.Key.JID, map[string]string{
"picture": fmt.Sprintf("URL@https://api.asm.skype.com/v1/objects/%s", fileId),
})
}
if err != nil {
mx.log.Errorln(err)
} else {
//out := <-resp
mx.log.Infoln(resp)
}
}
func (mx *MatrixHandler) shouldIgnoreEvent(evt *event.Event) bool {
if _, isPuppet := mx.bridge.ParsePuppetMXID(evt.Sender); evt.Sender == mx.bridge.Bot.UserID || isPuppet {
fmt.Println()
fmt.Printf("shouldIgnoreEvent: isPuppet%+v", isPuppet)
fmt.Println()
fmt.Printf("shouldIgnoreEvent: isPuppet%+v", evt.Sender)
fmt.Println()
return true
}
isCustomPuppet, ok := evt.Content.Raw["net.maunium.skype.puppet"].(bool)
if ok && isCustomPuppet && mx.bridge.GetPuppetByCustomMXID(evt.Sender) != nil {
return true
}
user := mx.bridge.GetUserByMXID(evt.Sender)
fmt.Println()
fmt.Printf("shouldIgnoreEvent: user%+v", *user)
fmt.Println()
if !user.RelaybotWhitelisted {
fmt.Println("user.RelaybotWhitelisted true", user.RelaybotWhitelisted)
return true
}
fmt.Println("shouldIgnoreEvent: false")
return false
}
func (mx *MatrixHandler) HandleEncrypted(evt *event.Event) {
if mx.shouldIgnoreEvent(evt) || mx.bridge.Crypto == nil {
fmt.Println("HandleEncrypted return 1")
return
}
decrypted, err := mx.bridge.Crypto.Decrypt(evt)
if err != nil {
mx.log.Warnfln("Failed to decrypt %s: %v", evt.ID, err)
return
}
mx.bridge.EventProcessor.Dispatch(decrypted)
}
func (mx *MatrixHandler) HandleMessage(evt *event.Event) {
if mx.shouldIgnoreEvent(evt) {
return
}
user := mx.bridge.GetUserByMXID(evt.Sender)
content := evt.Content.AsMessage()
if user.Whitelisted && content.MsgType == event.MsgText {
commandPrefix := mx.bridge.Config.Bridge.CommandPrefix
hasCommandPrefix := strings.HasPrefix(content.Body, commandPrefix)
if hasCommandPrefix {
content.Body = strings.TrimLeft(content.Body[len(commandPrefix):], " ")
}
if hasCommandPrefix || evt.RoomID == user.ManagementRoom {
mx.cmd.Handle(evt.RoomID, user, content.Body)
return
}
}
fmt.Println()
fmt.Printf("HandleMessage evt.RoomID1: %+v", evt.RoomID)
fmt.Println()
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
fmt.Println()
fmt.Printf("HandleMessage portal: %+v", portal)
fmt.Println()
if user.Conn != nil && portal != nil && (user.Whitelisted || portal.HasRelaybot()) {
portal.HandleMatrixMessage(user, evt)
}
}
func (mx *MatrixHandler) HandleRedaction(evt *event.Event) {
if _, isPuppet := mx.bridge.ParsePuppetMXID(evt.Sender); evt.Sender == mx.bridge.Bot.UserID || isPuppet {
return
}
user := mx.bridge.GetUserByMXID(evt.Sender)
if !user.Whitelisted {
return
}
if !user.HasSession() {
return
} else if !user.IsConnected() {
msg := format.RenderMarkdown(fmt.Sprintf("[%[1]s](https://matrix.to/#/%[1]s): \u26a0 "+
"You are not connected to skype, so your redaction was not bridged. "+
"Use `%[2]s reconnect` to reconnect.", user.MXID, mx.bridge.Config.Bridge.CommandPrefix), true, false)
msg.MsgType = event.MsgNotice
_, _ = mx.bridge.Bot.SendMessageEvent(evt.RoomID, event.EventMessage, msg)
return
}
portal := mx.bridge.GetPortalByMXID(evt.RoomID)
if user.Conn != nil && user.Conn.LoginInfo != nil && portal != nil {
portal.HandleMatrixRedaction(user, evt)
}
}

22
no-cgo.go Normal file
View File

@ -0,0 +1,22 @@
// +build !cgo
package main
import (
"image"
"io"
"golang.org/x/image/webp"
)
func NewCryptoHelper(bridge *Bridge) Crypto {
if !bridge.Config.Bridge.Encryption.Allow {
bridge.Log.Warnln("Bridge built without end-to-bridge encryption, but encryption is enabled in config")
}
bridge.Log.Debugln("Bridge built without end-to-bridge encryption")
return nil
}
func decodeWebp(r io.Reader) (image.Image, error) {
return webp.Decode(r)
}

2476
portal.go Normal file

File diff suppressed because it is too large Load Diff

345
provisioning.go Normal file
View File

@ -0,0 +1,345 @@
package main
import (
"context"
"encoding/json"
"github.com/gorilla/websocket"
log "maunium.net/go/maulogger/v2"
"net/http"
"maunium.net/go/mautrix/id"
)
type ProvisioningAPI struct {
bridge *Bridge
log log.Logger
}
func (prov *ProvisioningAPI) Init() {
prov.log = prov.bridge.Log.Sub("Provisioning")
prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
r.Use(prov.AuthMiddleware)
r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
r.HandleFunc("/login", prov.Login)
r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
r.HandleFunc("/delete_connection", prov.DeleteConnection).Methods(http.MethodPost)
r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
}
func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
auth = auth[len("Bearer "):]
if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
jsonResponse(w, http.StatusForbidden, map[string]interface{}{
"error": "Invalid auth token",
"errcode": "M_FORBIDDEN",
})
return
}
userID := r.URL.Query().Get("user_id")
user := prov.bridge.GetUserByMXID(id.UserID(userID))
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "user", user)))
})
}
type Error struct {
Success bool `json:"success"`
Error string `json:"error"`
ErrCode string `json:"errcode"`
}
type Response struct {
Success bool `json:"success"`
Status string `json:"status"`
}
func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user.Session == nil && user.Conn == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "Nothing to purge: no session information stored and no active connection.",
ErrCode: "no session",
})
return
}
user.SetSession(nil)
if user.Conn != nil {
//_, _ = user.Conn.Disconnect()
user.Conn.RemoveHandlers()
user.Conn = nil
}
jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
}
func (prov *ProvisioningAPI) DeleteConnection(w http.ResponseWriter, r *http.Request) {
//user := r.Context().Value("user").(*User)
//if user.Conn == nil {
// jsonResponse(w, http.StatusNotFound, Error{
// Error: "You don't have a WhatsApp connection.",
// ErrCode: "not connected",
// })
// return
//}
//sess, err := user.Conn.Disconnect()
//if err == nil && len(sess.Wid) > 0 {
// user.SetSession(&sess)
//}
//user.Conn.RemoveHandlers()
//user.Conn = nil
//jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp and connection deleted"})
}
func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
//user := r.Context().Value("user").(*User)
//if user.Conn == nil {
// jsonResponse(w, http.StatusNotFound, Error{
// Error: "You don't have a WhatsApp connection.",
// ErrCode: "no connection",
// })
// return
//}
//sess, err := user.Conn.Disconnect()
//if err == whatsapp.ErrNotConnected {
// jsonResponse(w, http.StatusNotFound, Error{
// Error: "You were not connected",
// ErrCode: "not connected",
// })
// return
//} else if err != nil {
// user.log.Warnln("Error while disconnecting:", err)
// jsonResponse(w, http.StatusInternalServerError, Error{
// Error: fmt.Sprintf("Unknown error while disconnecting: %v", err),
// ErrCode: err.Error(),
// })
// return
//} else if len(sess.Wid) > 0 {
// user.SetSession(&sess)
//}
//jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
}
func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
//user := r.Context().Value("user").(*User)
//if user.Conn == nil {
// if user.Session == nil {
// jsonResponse(w, http.StatusForbidden, Error{
// Error: "No existing connection and no session. Please log in first.",
// ErrCode: "no session",
// })
// } else {
// user.Connect(false)
// jsonResponse(w, http.StatusOK, Response{true, "Created connection to WhatsApp."})
// }
// return
//}
//
//wasConnected := true
//sess, err := user.Conn.Disconnect()
//if err == whatsapp.ErrNotConnected {
// wasConnected = false
//} else if err != nil {
// user.log.Warnln("Error while disconnecting:", err)
//} else if len(sess.Wid) > 0 {
// user.SetSession(&sess)
//}
//
//err = user.Conn.Restore()
//if err == whatsapp.ErrInvalidSession {
// if user.Session != nil {
// user.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
// var sess whatsapp.Session
// sess, err = user.Conn.RestoreWithSession(*user.Session)
// if err == nil {
// user.SetSession(&sess)
// }
// } else {
// jsonResponse(w, http.StatusForbidden, Error{
// Error: "You're not logged in",
// ErrCode: "not logged in",
// })
// return
// }
//} else if err == whatsapp.ErrLoginInProgress {
// jsonResponse(w, http.StatusConflict, Error{
// Error: "A login or reconnection is already in progress.",
// ErrCode: "login in progress",
// })
// return
//} else if err == whatsapp.ErrAlreadyLoggedIn {
// jsonResponse(w, http.StatusConflict, Error{
// Error: "You were already connected.",
// ErrCode: err.Error(),
// })
// return
//}
//if err != nil {
// user.log.Warnln("Error while reconnecting:", err)
// if err.Error() == "restore session connection timed out" {
// jsonResponse(w, http.StatusForbidden, Error{
// Error: "Reconnection timed out. Is WhatsApp on your phone reachable?",
// ErrCode: err.Error(),
// })
// } else {
// jsonResponse(w, http.StatusForbidden, Error{
// Error: fmt.Sprintf("Unknown error while reconnecting: %v", err),
// ErrCode: err.Error(),
// })
// }
// user.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
// sess, err := user.Conn.Disconnect()
// if err != nil {
// user.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
// } else if len(sess.Wid) > 0 {
// user.SetSession(&sess)
// }
// return
//}
//user.ConnectionErrors = 0
//user.PostLogin()
//
//var msg string
//if wasConnected {
// msg = "Reconnected successfully."
//} else {
// msg = "Connected successfully."
//}
//
//jsonResponse(w, http.StatusOK, Response{true, msg})
}
func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
//user := r.Context().Value("user").(*User)
//wa := map[string]interface{}{
// "has_session": user.Session != nil,
// "management_room": user.ManagementRoom,
// "jid": user.JID,
// "conn": nil,
// "ping": nil,
//}
//if user.Conn != nil {
// wa["conn"] = map[string]interface{}{
// "is_connected": user.Conn.IsConnected(),
// "is_logged_in": user.Conn.IsLoggedIn(),
// "is_login_in_progress": user.Conn.IsLoginInProgress(),
// }
// ok, err := user.Conn.AdminTest()
// wa["ping"] = map[string]interface{}{
// "ok": ok,
// "err": err,
// }
//}
//resp := map[string]interface{}{
// "mxid": user.MXID,
// "admin": user.Admin,
// "whitelisted": user.Whitelisted,
// "relaybot_whitelisted": user.RelaybotWhitelisted,
// "whatsapp": wa,
//}
//jsonResponse(w, http.StatusOK, resp)
}
func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(response)
}
func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
//user := r.Context().Value("user").(*User)
//if user.Session == nil {
// jsonResponse(w, http.StatusNotFound, Error{
// Error: "You're not logged in",
// ErrCode: "not logged in",
// })
// return
//}
//
//err := user.Conn.Logout()
//if err != nil {
// user.log.Warnln("Error while logging out:", err)
// jsonResponse(w, http.StatusInternalServerError, Error{
// Error: fmt.Sprintf("Unknown error while logging out: %v", err),
// ErrCode: err.Error(),
// })
// return
//}
//_, err = user.Conn.Disconnect()
//if err != nil {
// user.log.Warnln("Error while disconnecting after logout:", err)
//}
//user.Conn.RemoveHandlers()
//user.Conn = nil
//user.removeFromJIDMap()
//// TODO this causes a foreign key violation, which should be fixed
////ce.User.JID = ""
//user.SetSession(nil)
//jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
}
var upgrader = websocket.Upgrader{}
func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
//userID := r.URL.Query().Get("user_id")
//user := prov.bridge.GetUserByMXID(id.UserID(userID))
//
//c, err := upgrader.Upgrade(w, r, nil)
//if err != nil {
// prov.log.Errorfln("Failed to upgrade connection to websocket:", err)
// return
//}
//defer c.Close()
//
//if !user.Connect(true) {
// user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
// _ = c.WriteJSON(Error{
// Error: "Failed to connect to WhatsApp",
// ErrCode: "connection error",
// })
// return
//}
//
//qrChan := make(chan string, 3)
//go func() {
// for code := range qrChan {
// if code == "stop" {
// return
// }
// _ = c.WriteJSON(map[string]interface{}{
// "code": code,
// })
// }
//}()
//session, err := user.Conn.LoginWithRetry(qrChan, user.bridge.Config.Bridge.LoginQRRegenCount)
//qrChan <- "stop"
//if err != nil {
// var msg string
// if err == whatsapp.ErrAlreadyLoggedIn {
// msg = "You're already logged in"
// } else if err == whatsapp.ErrLoginInProgress {
// msg = "You have a login in progress already."
// } else if err == whatsapp.ErrLoginTimedOut {
// msg = "QR code scan timed out. Please try again."
// } else {
// user.log.Warnln("Failed to log in:", err)
// msg = fmt.Sprintf("Unknown error while logging in: %v", err)
// }
// _ = c.WriteJSON(Error{
// Error: msg,
// ErrCode: err.Error(),
// })
// return
//}
//user.ConnectionErrors = 0
//user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
//user.addToJIDMap()
//user.SetSession(&session)
//_ = c.WriteJSON(map[string]interface{}{
// "success": true,
// "jid": user.JID,
//})
//user.PostLogin()
}

327
puppet.go Normal file
View File

@ -0,0 +1,327 @@
package main
import (
"fmt"
skype "github.com/kelaresg/go-skypeapi"
skypeExt "github.com/kelaresg/matrix-skype/skype-ext"
"net/http"
"regexp"
"strings"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/id"
"github.com/kelaresg/matrix-skype/database"
"github.com/kelaresg/matrix-skype/types"
//"github.com/kelaresg/matrix-skype/whatsapp-ext"
)
func (bridge *Bridge) ParsePuppetMXID(mxid id.UserID) (types.SkypeID, bool) {
userIDRegex, err := regexp.Compile(fmt.Sprintf("^@%s:%s$",
bridge.Config.Bridge.FormatUsername("(.*)"),
bridge.Config.Homeserver.Domain))
if err != nil {
bridge.Log.Warnln("Failed to compile puppet user ID regex:", err)
return "", false
}
match := userIDRegex.FindStringSubmatch(string(mxid))
if match == nil || len(match) != 2 {
return "", false
}
realId := match[1]
cond1 := "8-live-"
cond2 := "8-"
if strings.HasPrefix(realId, cond1) {
realId = strings.Replace(realId, cond1, "8:live:", 1)
} else if strings.HasPrefix(realId, cond2){
realId = strings.Replace(realId, cond2, "8:", 1)
}
jid := types.SkypeID(realId + skypeExt.NewUserSuffix)
return jid, true
}
func (bridge *Bridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
jid, ok := bridge.ParsePuppetMXID(mxid)
if !ok {
return nil
}
return bridge.GetPuppetByJID(jid)
}
func (bridge *Bridge) GetPuppetByJID(jid types.SkypeID) *Puppet {
jid = strings.Trim(jid, " ")
if len(jid) < 1 {
return nil
}
if strings.Index(jid, skypeExt.NewUserSuffix) < 0 {
jid = jid + skypeExt.NewUserSuffix
}
bridge.puppetsLock.Lock()
defer bridge.puppetsLock.Unlock()
puppet, ok := bridge.puppets[jid]
if !ok {
bridge.Log.Debugln("GetPuppetByJID(NewPuppet):", jid)
dbPuppet := bridge.DB.Puppet.Get(jid)
if dbPuppet == nil {
dbPuppet = bridge.DB.Puppet.New()
dbPuppet.JID = jid
dbPuppet.Insert()
}
puppet = bridge.NewPuppet(dbPuppet)
bridge.puppets[puppet.JID] = puppet
if len(puppet.CustomMXID) > 0 {
bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
}
}
return puppet
}
func (bridge *Bridge) GetPuppetByCustomMXID(mxid id.UserID) *Puppet {
bridge.puppetsLock.Lock()
defer bridge.puppetsLock.Unlock()
puppet, ok := bridge.puppetsByCustomMXID[mxid]
if !ok {
dbPuppet := bridge.DB.Puppet.GetByCustomMXID(mxid)
if dbPuppet == nil {
return nil
}
bridge.Log.Debugln("GetPuppetByCustomMXID(NewPuppet):", dbPuppet.JID)
puppet = bridge.NewPuppet(dbPuppet)
bridge.puppets[puppet.JID] = puppet
bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
}
return puppet
}
func (bridge *Bridge) GetAllPuppetsWithCustomMXID() []*Puppet {
return bridge.dbPuppetsToPuppets(bridge.DB.Puppet.GetAllWithCustomMXID())
}
func (bridge *Bridge) GetAllPuppets() []*Puppet {
return bridge.dbPuppetsToPuppets(bridge.DB.Puppet.GetAll())
}
func (bridge *Bridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
bridge.puppetsLock.Lock()
defer bridge.puppetsLock.Unlock()
output := make([]*Puppet, len(dbPuppets))
for index, dbPuppet := range dbPuppets {
if dbPuppet == nil {
continue
}
puppet, ok := bridge.puppets[dbPuppet.JID]
if !ok {
bridge.Log.Debugln("dbPuppetsToPuppets(NewPuppet):", dbPuppet.JID)
puppet = bridge.NewPuppet(dbPuppet)
bridge.puppets[dbPuppet.JID] = puppet
if len(dbPuppet.CustomMXID) > 0 {
bridge.puppetsByCustomMXID[dbPuppet.CustomMXID] = puppet
}
}
output[index] = puppet
}
return output
}
func (bridge *Bridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
return &Puppet{
Puppet: dbPuppet,
bridge: bridge,
log: bridge.Log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.JID)),
MXID: id.NewUserID(
bridge.Config.Bridge.FormatUsername(
strings.Replace(
strings.Replace(dbPuppet.JID, skypeExt.NewUserSuffix, "", 1),
":",
"-",
-1,
),
),
bridge.Config.Homeserver.Domain),
}
}
type Puppet struct {
*database.Puppet
bridge *Bridge
log log.Logger
typingIn id.RoomID
typingAt int64
MXID id.UserID
customIntent *appservice.IntentAPI
customTypingIn map[id.RoomID]bool
customUser *User
}
func (puppet *Puppet) PhoneNumber() string {
return strings.Replace(puppet.JID, skypeExt.NewUserSuffix, "", 1)
}
func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
fmt.Println()
fmt.Printf("puppent IntentFor: %+v", puppet)
fmt.Println()
if (!portal.IsPrivateChat() && puppet.customIntent == nil) ||
(portal.backfilling && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling) ||
portal.Key.JID + skypeExt.NewUserSuffix == puppet.JID {
fmt.Println()
fmt.Println("puppent IntentFor0:", portal.Key.JID, puppet.JID)
fmt.Println("puppent IntentFor0:", portal.Key.JID, puppet.JID)
fmt.Println()
return puppet.DefaultIntent()
}
fmt.Println()
fmt.Printf("puppent IntentFor2: %+v", puppet.customIntent)
fmt.Println()
if portal.IsPrivateChat() && puppet.customIntent == nil{
return puppet.DefaultIntent()
}
return puppet.customIntent
}
func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
return puppet.customIntent
}
func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
fmt.Println()
fmt.Println("DefaultIntent puppet.MXID: ", puppet.MXID)
fmt.Println()
return puppet.bridge.AS.Intent(puppet.MXID)
}
func (puppet *Puppet) UpdateAvatar(source *User, avatar *skypeExt.ProfilePicInfo) bool {
if avatar == nil {
return false
//var err error
//avatar, err = source.Conn.GetProfilePicThumb(puppet.JID)
//if err != nil {
// puppet.log.Warnln("Failed to get avatar:", err)
// return false
//}
}
if avatar.Status != 0 {
return false
}
if avatar.Tag == puppet.Avatar {
return false
}
if len(avatar.URL) == 0 {
err := puppet.DefaultIntent().SetAvatarURL(id.ContentURI{})
if err != nil {
puppet.log.Warnln("Failed to remove avatar:", err)
}
puppet.AvatarURL = id.ContentURI{}
puppet.Avatar = avatar.Tag
go puppet.updatePortalAvatar()
return true
}
data, err := avatar.DownloadBytes()
if err != nil {
puppet.log.Warnln("Failed to download avatar:", err)
return false
}
mime := http.DetectContentType(data)
resp, err := puppet.DefaultIntent().UploadBytes(data, mime)
if err != nil {
puppet.log.Warnln("Failed to upload avatar:", err)
return false
}
puppet.AvatarURL = resp.ContentURI
err = puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
if err != nil {
puppet.log.Warnln("Failed to set avatar:", err)
}
puppet.Avatar = avatar.Tag
go puppet.updatePortalAvatar()
return true
}
func (puppet *Puppet) UpdateName(source *User, contact skype.Contact) bool {
newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(contact)
if puppet.Displayname != newName && quality >= puppet.NameQuality {
err := puppet.DefaultIntent().SetDisplayName(newName)
if err == nil {
puppet.Displayname = newName
puppet.NameQuality = quality
go puppet.updatePortalName()
puppet.Update()
} else {
puppet.log.Warnln("Failed to set display name:", err)
}
return true
}
return false
}
func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
if puppet.bridge.Config.Bridge.PrivateChatPortalMeta {
jid := strings.Replace(puppet.JID, skypeExt.NewUserSuffix, "", 1)
for _, portal := range puppet.bridge.GetAllPortalsByJID(jid) {
meta(portal)
}
}
}
func (puppet *Puppet) updatePortalAvatar() {
puppet.updatePortalMeta(func(portal *Portal) {
if len(portal.MXID) > 0 {
_, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
if err != nil {
portal.log.Warnln("Failed to set avatar:", err)
}
}
portal.AvatarURL = puppet.AvatarURL
portal.Avatar = puppet.Avatar
portal.Update()
})
}
func (puppet *Puppet) updatePortalName() {
puppet.updatePortalMeta(func(portal *Portal) {
if len(portal.MXID) > 0 {
_, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
if err != nil {
portal.log.Warnln("Failed to set name:", err)
}
}
portal.Name = puppet.Displayname
portal.Update()
})
}
func (puppet *Puppet) Sync(source *User, contact skype.Contact) {
err := puppet.DefaultIntent().EnsureRegistered()
if err != nil {
puppet.log.Errorln("Failed to ensure registered:", err)
}
//if contact.Jid == source.JID {
// contact.Notify = source.Conn.Info.Pushname
//}
avatar := &skypeExt.ProfilePicInfo{
URL: contact.Profile.AvatarUrl,
Tag: contact.Profile.AvatarUrl,
Status: 0,
}
update := false
update = puppet.UpdateName(source, contact) || update
update = puppet.UpdateAvatar(source, avatar) || update
if update {
puppet.Update()
}
}

181
skype-ext/chat.go Normal file
View File

@ -0,0 +1,181 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package skypeExt
import (
"encoding/json"
skype "github.com/kelaresg/go-skypeapi"
"strings"
)
type ChatUpdateCommand string
const (
ChatUpdateCommandAction ChatUpdateCommand = "action"
)
type ChatUpdate struct {
JID string `json:"id"`
Command ChatUpdateCommand `json:"cmd"`
Data ChatUpdateData `json:"data"`
}
type ChatActionType string
const (
ChatActionNameChange ChatActionType = "subject"
ChatActionAddTopic ChatActionType = "desc_add"
ChatActionRemoveTopic ChatActionType = "desc_remove"
ChatActionRestrict ChatActionType = "restrict"
ChatActionAnnounce ChatActionType = "announce"
ChatActionPromote ChatActionType = "promote"
ChatActionDemote ChatActionType = "demote"
ChatActionRemove ChatActionType = "remove"
ChatActionAdd ChatActionType = "add"
ChatActionIntroduce ChatActionType = "introduce"
ChatActionCreate ChatActionType = "create"
ChatActionThread ChatActionType = "Thread"
)
const (
ChatTopicUpdate ChatActionType = "ThreadActivity/TopicUpdate"
ChatPictureUpdate ChatActionType = "ThreadActivity/PictureUpdate"
ChatMemberAdd ChatActionType = "ThreadActivity/AddMember"
ChatMemberDelete ChatActionType = "ThreadActivity/DeleteMember"
)
type ChatUpdateData struct {
Action ChatActionType
SenderJID string
NameChange struct {
Name string `json:"subject"`
SetAt int64 `json:"s_t"`
SetBy string `json:"s_o"`
}
AddTopic struct {
Topic string `json:"desc"`
ID string `json:"descId"`
SetAt int64 `json:"descTime"`
}
RemoveTopic struct {
ID string `json:"descId"`
}
Restrict bool
Announce bool
PermissionChange struct {
JIDs []string `json:"participants"`
}
MemberAction struct {
JIDs []string `json:"participants"`
}
Create struct {
Creation int64 `json:"creation"`
Name string `json:"subject"`
SetAt int64 `json:"s_t"`
SetBy string `json:"s_o"`
Admins []string `json:"admins"`
SuperAdmins []string `json:"superadmins"`
Regulars []string `json:"regulars"`
}
}
func (cud *ChatUpdateData) UnmarshalJSON(data []byte) error {
var arr []json.RawMessage
err := json.Unmarshal(data, &arr)
if err != nil {
return err
} else if len(arr) < 3 {
return nil
}
err = json.Unmarshal(arr[0], &cud.Action)
if err != nil {
return err
}
err = json.Unmarshal(arr[1], &cud.SenderJID)
if err != nil {
return err
}
cud.SenderJID = strings.Replace(cud.SenderJID, OldUserSuffix, NewUserSuffix, 1)
var unmarshalTo interface{}
switch cud.Action {
case ChatActionNameChange:
unmarshalTo = &cud.NameChange
case ChatActionAddTopic:
unmarshalTo = &cud.AddTopic
case ChatActionRemoveTopic:
unmarshalTo = &cud.RemoveTopic
case ChatActionRestrict:
unmarshalTo = &cud.Restrict
case ChatActionAnnounce:
unmarshalTo = &cud.Announce
case ChatActionPromote, ChatActionDemote:
unmarshalTo = &cud.PermissionChange
case ChatActionAdd, ChatActionRemove:
unmarshalTo = &cud.MemberAction
case ChatActionCreate:
unmarshalTo = &cud.Create
default:
return nil
}
err = json.Unmarshal(arr[2], unmarshalTo)
if err != nil {
return err
}
cud.NameChange.SetBy = strings.Replace(cud.NameChange.SetBy, OldUserSuffix, NewUserSuffix, 1)
for index, jid := range cud.PermissionChange.JIDs {
cud.PermissionChange.JIDs[index] = strings.Replace(jid, OldUserSuffix, NewUserSuffix, 1)
}
return nil
}
type ChatUpdateHandler interface {
skype.Handler
HandleChatUpdate(ChatUpdate)
}
func (ext *ExtendedConn) handleMessageChatUpdate(message []byte) {
var event ChatUpdate
err := json.Unmarshal(message, &event)
if err != nil {
ext.jsonParseError(err)
return
}
event.JID = strings.Replace(event.JID, OldUserSuffix, NewUserSuffix, 1)
for _, handler := range ext.handlers {
chatUpdateHandler, ok := handler.(ChatUpdateHandler)
if !ok {
continue
}
if ext.shouldCallSynchronously(chatUpdateHandler) {
chatUpdateHandler.HandleChatUpdate(event)
} else {
go chatUpdateHandler.HandleChatUpdate(event)
}
}
}

68
skype-ext/cmd.go Normal file
View File

@ -0,0 +1,68 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package skypeExt
import (
"encoding/json"
skype "github.com/kelaresg/go-skypeapi"
"strings"
)
type CommandType string
const (
CommandPicture CommandType = "picture"
CommandDisconnect CommandType = "disconnect"
)
type Command struct {
Type CommandType `json:"type"`
JID string `json:"jid"`
*ProfilePicInfo
Kind string `json:"kind"`
Raw json.RawMessage `json:"-"`
}
type CommandHandler interface {
skype.Handler
HandleCommand(Command)
}
func (ext *ExtendedConn) handleMessageCommand(message []byte) {
var event Command
err := json.Unmarshal(message, &event)
if err != nil {
ext.jsonParseError(err)
return
}
event.Raw = message
event.JID = strings.Replace(event.JID, OldUserSuffix, NewUserSuffix, 1)
for _, handler := range ext.handlers {
commandHandler, ok := handler.(CommandHandler)
if !ok {
continue
}
if ext.shouldCallSynchronously(commandHandler) {
commandHandler.HandleCommand(event)
} else {
go commandHandler.HandleCommand(event)
}
}
}

104
skype-ext/jsonmessage.go Normal file
View File

@ -0,0 +1,104 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package skypeExt
import (
"encoding/json"
"github.com/kelaresg/go-skypeapi"
)
type JSONMessage []json.RawMessage
type JSONMessageType string
const (
MessageMsgInfo JSONMessageType = "MsgInfo"
MessageMsg JSONMessageType = "Msg"
MessagePresence JSONMessageType = "Presence"
MessageStream JSONMessageType = "Stream"
MessageConn JSONMessageType = "Conn"
MessageProps JSONMessageType = "Props"
MessageCmd JSONMessageType = "Cmd"
MessageChat JSONMessageType = "Chat"
MessageCall JSONMessageType = "Call"
)
func (ext *ExtendedConn) HandleError(error) {}
type UnhandledJSONMessageHandler interface {
skype.Handler
HandleUnhandledJSONMessage(string)
}
type JSONParseErrorHandler interface {
skype.Handler
HandleJSONParseError(error)
}
func (ext *ExtendedConn) jsonParseError(err error) {
for _, handler := range ext.handlers {
errorHandler, ok := handler.(JSONParseErrorHandler)
if !ok {
continue
}
errorHandler.HandleJSONParseError(err)
}
}
func (ext *ExtendedConn) HandleJsonMessage(message string) {
msg := JSONMessage{}
err := json.Unmarshal([]byte(message), &msg)
if err != nil || len(msg) < 2 {
ext.jsonParseError(err)
return
}
var msgType JSONMessageType
json.Unmarshal(msg[0], &msgType)
switch msgType {
//case MessagePresence:
// ext.handleMessagePresence(msg[1])
//case MessageStream:
// ext.handleMessageStream(msg[1:])
//case MessageConn:
// ext.handleMessageConn(msg[1])
//case MessageProps:
// ext.handleMessageProps(msg[1])
//case MessageMsgInfo, MessageMsg:
// ext.handleMessageMsgInfo(msgType, msg[1])
//case MessageCmd:
// ext.handleMessageCommand(msg[1])
//case MessageChat:
// ext.handleMessageChatUpdate(msg[1])
//case MessageCall:
// ext.handleMessageCall(msg[1])
default:
for _, handler := range ext.handlers {
ujmHandler, ok := handler.(UnhandledJSONMessageHandler)
if !ok {
continue
}
if ext.shouldCallSynchronously(ujmHandler) {
ujmHandler.HandleUnhandledJSONMessage(message)
} else {
go ujmHandler.HandleUnhandledJSONMessage(message)
}
}
}
}

9
skype-ext/presence.go Normal file
View File

@ -0,0 +1,9 @@
package skypeExt
import skype "github.com/kelaresg/go-skypeapi"
type Presence struct {
Id string
Availability string
Status skype.Presence
}

299
skype-ext/skype.go Normal file
View File

@ -0,0 +1,299 @@
// matrix-skype - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2019 Tulir Asokan
//
// 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/>.
package skypeExt
import (
"encoding/json"
"fmt"
"github.com/kelaresg/go-skypeapi"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)
const (
OldUserSuffix = ""
NewUserSuffix = "@s.skype.net"
GroupSuffix = "@thread.skype"
)
type ExtendedConn struct {
*skype.Conn
handlers []skype.Handler
}
func ExtendConn(conn *skype.Conn) *ExtendedConn {
ext := &ExtendedConn{
Conn: conn,
}
ext.Conn.AddHandler(ext)
return ext
}
func (ext *ExtendedConn) AddHandler(handler skype.Handler) {
ext.Conn.AddHandler(handler)
ext.handlers = append(ext.handlers, handler)
}
func (ext *ExtendedConn) RemoveHandler(handler skype.Handler) bool {
ext.Conn.RemoveHandler(handler)
for i, v := range ext.handlers {
if v == handler {
ext.handlers = append(ext.handlers[:i], ext.handlers[i+1:]...)
return true
}
}
return false
}
func (ext *ExtendedConn) RemoveHandlers() {
ext.Conn.RemoveHandlers()
ext.handlers = make([]skype.Handler, 0)
}
func (ext *ExtendedConn) shouldCallSynchronously(handler skype.Handler) bool {
//sh, ok := handler.(skype.SyncHandler)
//return ok && sh.ShouldCallSynchronously()
return true
}
func (ext *ExtendedConn) ShouldCallSynchronously() bool {
return true
}
type GroupInfo struct {
JID string `json:"jid"`
OwnerJID string `json:"owner"`
Name string `json:"subject"`
NameSetTime int64 `json:"subjectTime"`
NameSetBy string `json:"subjectOwner"`
Topic string `json:"desc"`
TopicID string `json:"descId"`
TopicSetAt int64 `json:"descTime"`
TopicSetBy string `json:"descOwner"`
GroupCreated int64 `json:"creation"`
Status int16 `json:"status"`
Participants []struct {
JID string `json:"id"`
IsAdmin bool `json:"isAdmin"`
IsSuperAdmin bool `json:"isSuperAdmin"`
} `json:"participants"`
}
func (ext *ExtendedConn) GetGroupMetaData(jid string) (*GroupInfo, error) {
data, err := ext.Conn.GetConversation(jid)
if err != nil {
return nil, fmt.Errorf("failed to get group metadata: %v", err)
}
//content := <-data
//info := data
membersStr := data.ThreadProperties.Members
var members []string
if len(membersStr) < 1 {
resp, _ := ext.Conn.GetConsumptionHorizons(jid)
for _, con := range resp.ConsumptionHorizons {
members = append(members, con.Id)
}
} else {
err = json.Unmarshal([]byte(membersStr), &members)
}
info := &GroupInfo{}
fmt.Println()
fmt.Println("GetGroupMetaData: ", members)
fmt.Println()
for _, participant := range members {
type a struct {
JID string `json:"id"`
IsAdmin bool `json:"isAdmin"`
IsSuperAdmin bool `json:"isSuperAdmin"`
}
isSuperAdmin := false
if "8:" + ext.Conn.UserProfile.Username == participant {
isSuperAdmin = true
}
info.Participants = append(info.Participants, a{
participant + NewUserSuffix,
false,
isSuperAdmin,
})
personId := participant + NewUserSuffix
if _, ok := ext.Conn.Store.Contacts[personId]; !ok {
participantArr := strings.Split(participant, "8:")
if participantArr[1] != "" {
ext.Conn.NameSearch(participantArr[1])
}
}
}
info.Topic = data.ThreadProperties.Topic
info.Name = data.ThreadProperties.Topic
fmt.Println()
fmt.Println("GetGroupMetaData:3 ")
fmt.Println()
//info.NameSetBy = info.NameSetBy + NewUserSuffix
//info.TopicSetBy = info.TopicSetBy + NewUserSuffix
return info, nil
}
type ProfilePicInfo struct {
URL string `json:"eurl"`
Tag string `json:"tag"`
Status int16 `json:"status"`
Authorization string `json:"authorization"`
}
func (ppi *ProfilePicInfo) Download() (io.ReadCloser, error) {
if ppi.Authorization != "" {
client := &http.Client{
Timeout: 20 * time.Second,
}
headers := map[string]string{
"X-Client-Version": "0/0.0.0.0",
"Authorization": ppi.Authorization, // "skype_token " + Conn.LoginInfo.SkypeToken,
}
req, err := http.NewRequest("GET", ppi.URL, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp.Body, nil
}else {
resp, err := http.Get(ppi.URL)
if err != nil {
return nil, err
}
return resp.Body, nil
}
}
func (ppi *ProfilePicInfo) DownloadBytes() ([]byte, error) {
body, err := ppi.Download()
if err != nil {
return nil, err
}
defer body.Close()
data, err := ioutil.ReadAll(body)
return data, err
}
func (ext *ExtendedConn) GetProfilePicThumb(jid string) (*ProfilePicInfo, error) {
//data, err := ext.Conn.GetProfilePicThumb(jid)
//if err != nil {
// return nil, fmt.Errorf("failed to get avatar: %v", err)
//}
//content := <-data
//info := &ProfilePicInfo{}
//err = json.Unmarshal([]byte(content), info)
//if err != nil {
// return info, fmt.Errorf("failed to unmarshal avatar info: %v", err)
//}
//return info, nil
return nil, nil
}
func (ext *ExtendedConn) HandleGroupInvite(groupJid string, numbers[]string) (err error) {
var parts []string
parts = append(parts, numbers...)
members := skype.Members{}
members = skype.Members{}
for _, memberId := range numbers {
members.Members = append(members.Members, skype.Member{
Id: memberId,
Role: "Admin",
})
}
err = ext.Conn.AddMember(members, groupJid)
if err != nil {
fmt.Printf("%s Handle Invite err", err)
}
return
}
func (ext *ExtendedConn) HandleGroupJoin(code string) (err error, codeinfo skype.JoinToConInfo) {
err, codeinfo = ext.Conn.JoinConByCode(code)
member := skype.Member{
Id: "8:"+ext.UserProfile.Username,
Role: "Admin",
}
Members := skype.Members{}
Members.Members = append(Members.Members, member)
//cli.AddMember(cli.LoginInfo.LocationHost, cli.LoginInfo.SkypeToken, cli.LoginInfo.RegistrationTokenStr, Members, rsp.Resource)
err = ext.AddMember(Members, codeinfo.Resource)
member2 := skype.Member{
Id: "8:"+ext.UserProfile.Username,
Role: "User",
}
mewMembers := skype.Members{}
mewMembers.Members = append(mewMembers.Members, member2)
err = ext.AddMember( mewMembers, codeinfo.Resource)
return
}
func (ext *ExtendedConn) HandleGroupShare(groupJid string) (err error, link string) {
res, err := ext.Conn.GetConJoinUrl(groupJid)
if err != nil {
return err, ""
}
link = res.Url
return
}
func (ext *ExtendedConn) HandleGroupKick(groupJid string, numbers[]string) (err error) {
for _, number := range numbers{
if err == nil {
err = ext.Conn.RemoveMember(groupJid, number)
} else {
_ = ext.Conn.RemoveMember(groupJid, number)
}
}
return
}
func (ext *ExtendedConn) HandleGroupCreate(numbers skype.Members) (err error) {
return ext.Conn.CreateConversationGroup(numbers)
}
func (ext *ExtendedConn) HandleGroupLeave(groupJid string) (err error) {
fmt.Println("groyp id", groupJid)
fmt.Println("ext.UserProfile.Username", ext.UserProfile.Username)
err = ext.Conn.RemoveMember(groupJid, "8:"+ext.UserProfile.Username)
if err != nil {
fmt.Printf("%s HandleGroupLeave err", err)
}
return
}

7
types/types.go Normal file
View File

@ -0,0 +1,7 @@
package types
// SkypeID is a skype useID.
type SkypeID = string
// SkypeMessageID is the internal Client Message ID of a skype message.
type SkypeMessageID = string

1144
user.go Normal file

File diff suppressed because it is too large Load Diff

14
webp.go Normal file
View File

@ -0,0 +1,14 @@
// +build cgo
package main
import (
"image"
"io"
"github.com/chai2010/webp"
)
func decodeWebp(r io.Reader) (image.Image, error) {
return webp.Decode(r)
}