init
@@ -0,0 +1 @@
|
||||
/target
|
||||
@@ -0,0 +1,41 @@
|
||||
[package]
|
||||
name = "movim"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
aes-gcm = "0.11.1"
|
||||
anyhow = "1.0.104"
|
||||
axum = { version = "0.8", features = ["multipart", "ws"] }
|
||||
axum-extra = { version = "0.12.6", features = ["cookie"] }
|
||||
base64 = "0.23.1"
|
||||
base64ct = "1.8.3"
|
||||
chrono = { version = "0.4.45", features = ["serde", "unstable-locales"] }
|
||||
chrono-tz = "0.10.4"
|
||||
futures = "0.3.34"
|
||||
futures-util = "0.3.34"
|
||||
hex = "0.4.3"
|
||||
html-escape = "0.3.0"
|
||||
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] }
|
||||
indexmap = "2.14.2"
|
||||
minidom = "0.19"
|
||||
minijinja = { version = "2", features = ["loader", "json"] }
|
||||
percent-encoding = "2.3.2"
|
||||
rand = "0.9"
|
||||
regex = "1.13.1"
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "stream", "json"] }
|
||||
sasl = "0.5"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = { version = "1.0.154", features = ["preserve_order"] }
|
||||
sha1 = "0.11.0"
|
||||
sha2 = "0.11.1"
|
||||
sqlx = { version = "0.9", features = ["runtime-tokio", "sqlite", "chrono"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-xmpp = { version = "6", features = ["insecure-tcp"] }
|
||||
tower-http = { version = "0.7", features = ["fs"] }
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
uuid = { version = "1.29.0", features = ["v4"] }
|
||||
web-push-native = { version = "0.5", features = ["vapid"] }
|
||||
xmpp-parsers = "0.23"
|
||||
xso = "0.4"
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Movim (Rust edition)
|
||||
|
||||
A rewrite of the [Movim](https://movim.eu) XMPP web client backend in Rust, keeping
|
||||
Movim's frontend (CSS/JS/theme, in `frontend/`). The PHP daemon, widgets and
|
||||
templates were replaced by a single Rust server (tokio, axum, tokio-xmpp, sqlx/SQLite,
|
||||
minijinja). Scope: a Conversations-like chat client.
|
||||
|
||||
## Features
|
||||
1:1 chat, group chats (MUC, bookmarks, invitations, moderation, configuration),
|
||||
MAM history, carbons, receipts and chat markers, typing states, corrections,
|
||||
retractions, reactions, replies, link previews (OpenGraph cards, picture links
|
||||
shown inline), HTTP file upload, avatars and vCards, OMEMO (in-browser
|
||||
libsignal), 1:1 audio/video calls (Jingle + JMI), group audio/video calls in
|
||||
group chats (Muji, XEP-0272: a mesh of Jingle sessions), blocking, contact
|
||||
requests, search, account registration (XEP-0077), settings, Web Push,
|
||||
last seen (XEP-0319 idle), Client State Indication when no tab is open, and
|
||||
automatic XMPP reconnection (backoff up to 60s, rooms rejoined).
|
||||
|
||||
## Run
|
||||
cargo build --release
|
||||
MOVIM_BIND=0.0.0.0:8080 MOVIM_DOMAIN=example.org ./target/release/movim
|
||||
|
||||
Put it behind a TLS reverse proxy (WebSocket on `/ws/`, same host).
|
||||
|
||||
Link previews are fetched by the server (only public addresses, every redirect
|
||||
checked) and cached for 30 days. Group calls are a mesh: every participant
|
||||
sends its streams to every other one, fine for a handful of people. They need a
|
||||
non-anonymous room (the default for group chats created by Movim).
|
||||
|
||||
Environment: `MOVIM_BIND`, `MOVIM_ROOT`, `MOVIM_DATA_DIR`, `MOVIM_DATABASE_URL`,
|
||||
`MOVIM_DOMAIN`, `MOVIM_XMPP_WHITELIST`, `MOVIM_MAX_SESSIONS`,
|
||||
`MOVIM_DISABLE_REGISTRATION`, `MOVIM_LOCALE`, `MOVIM_SESSION_TIMEOUT_HOURS`,
|
||||
dev only: `MOVIM_XMPP_PLAINTEXT=host:port`, `MOVIM_ALLOW_PRIVATE_URLS=1`,
|
||||
`MOVIM_DEBUG_XMPP=1`.
|
||||
|
||||
## Tests
|
||||
`cargo test` runs the unit tests. `tests/e2e/` holds end-to-end scripts that
|
||||
drive the server (and the real frontend in headless Chromium) against a local
|
||||
Prosody; see `tests/e2e/README.md`.
|
||||
|
||||
## Frontend patches (vs upstream Movim)
|
||||
- `widgets/Notif/notif.js`: guard missing service worker registration.
|
||||
- `widgets/ChatOmemo/chatomemo_storage.js`: blind trust before verification
|
||||
(upstream trust check crashes: `libsignal.util` is undefined).
|
||||
- `scripts/movim_jingles.js`: the signaling of each call session runs through a
|
||||
promise queue (a content-add could arrive before the remote description was
|
||||
applied, early ICE candidates were dropped).
|
||||
|
||||
## Not implemented
|
||||
Movim social features (blogs, communities, stories), SFU conference calls
|
||||
(Movim's own extension; Muji group calls work), sticker packs/GIFs, ad-hoc
|
||||
commands, XEP-0198 stream resumption. Web Push has only been tested without a real HTTPS push
|
||||
service; Dictaphone/Snap/Draw go through the upload path but are untested.
|
||||
|
||||
License: AGPL-3.0 (same as Movim).
|
||||
@@ -0,0 +1 @@
|
||||
vr45gJQnaUJcShMOibGW9Z91mS0R-934uLz4pt7ZyJ0
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"ach": "Acholi",
|
||||
"ady": "ady",
|
||||
"af": "Afrikaans",
|
||||
"am": "Amharic",
|
||||
"ar": "عربي",
|
||||
"be": "Беларускі",
|
||||
"bg": "български",
|
||||
"bn": "Bengali; Bangla",
|
||||
"br": "brezhoneg",
|
||||
"ca": "Català",
|
||||
"cs": "čeština",
|
||||
"da": "Dansk",
|
||||
"de": "Deutsch",
|
||||
"el": "ελληνικά",
|
||||
"en": "English",
|
||||
"en_ca": "English",
|
||||
"en_sg": "English",
|
||||
"eo": "Esperanto",
|
||||
"es": "Español",
|
||||
"eu": "Euskara",
|
||||
"fa": "فارسى",
|
||||
"fi": "Suomi",
|
||||
"fr": "Français",
|
||||
"ga": "Irish",
|
||||
"gl": "Galego",
|
||||
"he": "עברית",
|
||||
"hr": "Hrvatski",
|
||||
"hu": "Magyar",
|
||||
"id": "Indonesia",
|
||||
"io": "Ido",
|
||||
"is": "íslenska",
|
||||
"it": "Italiano",
|
||||
"ja": "日本語",
|
||||
"jbo": "Lojban",
|
||||
"kk": "कोंकणी",
|
||||
"ko": "한국어",
|
||||
"lb": "Lëtzebuergesch",
|
||||
"lt": "Lietuvių",
|
||||
"lv": "Latviešu",
|
||||
"my": "Burmese",
|
||||
"nb": "Norsk bokmål",
|
||||
"ne": "Nepali",
|
||||
"nl": "Nederlands",
|
||||
"oc": "Òc",
|
||||
"pl": "Polski",
|
||||
"pt": "Português",
|
||||
"pt_br": "Português do Brasil",
|
||||
"ro": "Română",
|
||||
"ru": "русский",
|
||||
"sk": "Slovenčina",
|
||||
"sl": "Slovenščina",
|
||||
"sq": "Shqip",
|
||||
"sv": "Svenska",
|
||||
"sw": "Kiswahili",
|
||||
"tr": "Türkçe",
|
||||
"ug": "Uighur",
|
||||
"uk": "українська",
|
||||
"ur": "ٱردو",
|
||||
"ur_pk": "ٱردو",
|
||||
"vi": "Tiếng Việt",
|
||||
"zh": "中文",
|
||||
"zh_tw": "台灣中文"
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
; Strings added by the Rust edition of Movim
|
||||
[room]
|
||||
kick = Kick from the room
|
||||
ban = Ban from the room
|
||||
invite_sent = Invitation sent
|
||||
|
||||
[affiliation]
|
||||
no = None
|
||||
|
||||
[status]
|
||||
status = Status
|
||||
|
||||
[upload]
|
||||
not_available = No file upload service is available on your server
|
||||
|
||||
[omemo]
|
||||
not_supported = This contact does not support encryption
|
||||
|
||||
[clients]
|
||||
this_device = This device
|
||||
|
||||
[omemo]
|
||||
this_device = This device
|
||||
@@ -0,0 +1,295 @@
|
||||
[global]
|
||||
no_js = Movim requires Javascript to be enabled to work properly.
|
||||
description = Movim is a kickass distributed social networking platform that protects your privacy and comes with a set of awesome features.
|
||||
loading = Loading…
|
||||
or = Or
|
||||
change_pod = Switch to another pod
|
||||
main_menu = Main menu
|
||||
bottom_menu = Bottom menu
|
||||
skip_main = Skip to main content
|
||||
|
||||
[page]
|
||||
about = About
|
||||
account = Account
|
||||
account_creation = Account Creation
|
||||
administration = Administration
|
||||
avatar = Profile Picture
|
||||
blog = Blog
|
||||
chats = Messages
|
||||
communities = Communities
|
||||
configuration = Configuration
|
||||
contacts = Contacts
|
||||
explore = Explore
|
||||
feed = Feed
|
||||
gallery = Gallery
|
||||
help = Help
|
||||
home = Home
|
||||
login = Login
|
||||
news = News
|
||||
not_found = Not Found
|
||||
post = Post
|
||||
posts = Posts
|
||||
profile = Profile
|
||||
publish = Publish
|
||||
room = Group Chat
|
||||
share = Share
|
||||
space = Space
|
||||
tag = Tag
|
||||
visio = Visio-conference
|
||||
|
||||
[error]
|
||||
error = Error: %s
|
||||
cannot_load_file = "Cannot load file '%s'"
|
||||
widget_load_error = "Requested widget '%s' doesn’t exist."
|
||||
widget_call_error = "Requested event '%s' not registered."
|
||||
whoops = "Whoops!"
|
||||
websocket = Movim cannot talk with the server, please try again later
|
||||
websocket_connect = Reconnection to the server…
|
||||
oops = Oops!
|
||||
|
||||
[button]
|
||||
accept = Accept
|
||||
add = Add
|
||||
audio_call = Audio Call
|
||||
bool_no = No
|
||||
bool_yes = Yes
|
||||
call = Call
|
||||
cancel = Cancel
|
||||
chat = Chat
|
||||
clear = Clear
|
||||
close = Close
|
||||
connecting = Connecting
|
||||
copy_link = Copy Link
|
||||
create = Create
|
||||
delete = Delete
|
||||
destroy = Destroy
|
||||
discover = Discover
|
||||
edit = Edit
|
||||
enable = Enable
|
||||
invite = Invite
|
||||
join = Join
|
||||
leave = Leave
|
||||
like = Like
|
||||
more = More
|
||||
new = New conversation
|
||||
next = Next
|
||||
not_now = Not Now
|
||||
open = Open
|
||||
preview = Preview
|
||||
previous = Previous
|
||||
quote = Quote
|
||||
refresh = Refresh
|
||||
refuse = Refuse
|
||||
register = Register
|
||||
remove = Remove
|
||||
reply = Reply
|
||||
reset = Reset
|
||||
return = Return
|
||||
save = Save
|
||||
search = Search
|
||||
send_to = Send to
|
||||
share = Share
|
||||
sign_up = Sign Up
|
||||
submit = Submit
|
||||
submitting = Submitting
|
||||
unregister = Unregister
|
||||
update = Update
|
||||
updating = Updating
|
||||
upload = Upload
|
||||
validate = Validate
|
||||
video_call = Video Call
|
||||
|
||||
[input]
|
||||
username = Username
|
||||
password = Password
|
||||
optional = Optional
|
||||
muc_pubsub_node = Associated Community
|
||||
open_me_using = "Open me using"
|
||||
|
||||
[day]
|
||||
title = Day
|
||||
monday = Monday
|
||||
tuesday = Tuesday
|
||||
wednesday = Wednesday
|
||||
thursday = Thursday
|
||||
friday = Friday
|
||||
saturday = Saturday
|
||||
sunday = Sunday
|
||||
|
||||
[client]
|
||||
bot = Bot
|
||||
console = Console
|
||||
desktop = Desktop
|
||||
phone = Phone
|
||||
web = Web
|
||||
registered = Registered
|
||||
gateway = Gateway
|
||||
im = Server
|
||||
|
||||
[presence]
|
||||
online = Online
|
||||
away = Away
|
||||
dnd = Do Not Disturb
|
||||
xa = Extended Away
|
||||
offline = Offline
|
||||
error = Error
|
||||
|
||||
[mood]
|
||||
afraid = afraid
|
||||
amazed = amazed
|
||||
amorous = amorous
|
||||
angry = angry
|
||||
annoyed = annoyed
|
||||
anxious = anxious
|
||||
aroused = aroused
|
||||
ashamed = ashamed
|
||||
bored = bored
|
||||
brave = brave
|
||||
calm = calm
|
||||
cautious = cautious
|
||||
cold = cold
|
||||
confident = confident
|
||||
confused = confused
|
||||
contemplative = contemplative
|
||||
contented = contented
|
||||
cranky = cranky
|
||||
crazy = crazy
|
||||
creative = creative
|
||||
curious = curious
|
||||
dejected = dejected
|
||||
depressed = depressed
|
||||
disappointed = disappointed
|
||||
disgusted = disgusted
|
||||
dismayed = dismayed
|
||||
distracted = distracted
|
||||
embarrassed = embarrassed
|
||||
envious = envious
|
||||
excited = excited
|
||||
flirtatious = flirtatious
|
||||
frustrated = frustrated
|
||||
grateful = grateful
|
||||
grieving = grieving
|
||||
grumpy = grumpy
|
||||
guilty = guilty
|
||||
happy = happy
|
||||
hopeful = hopeful
|
||||
hot = hot
|
||||
humbled = humbled
|
||||
humiliated = humiliated
|
||||
hungry = hungry
|
||||
hurt = hurt
|
||||
impressed = impressed
|
||||
in_awe = in awe
|
||||
in_love = in love
|
||||
indignant = indignant
|
||||
interested = interested
|
||||
intoxicated = intoxicated
|
||||
invincible = invincible
|
||||
jealous = jealous
|
||||
lonely = lonely
|
||||
lost = lost
|
||||
lucky = lucky
|
||||
mean = mean
|
||||
moody = moody
|
||||
nervous = nervous
|
||||
neutral = neutral
|
||||
offended = offended
|
||||
outraged = outraged
|
||||
playful = playful
|
||||
proud = proud
|
||||
relaxed = relaxed
|
||||
relieved = relieved
|
||||
remorseful = remorseful
|
||||
restless = restless
|
||||
sad = sad
|
||||
sarcastic = sarcastic
|
||||
satisfied = satisfied
|
||||
serious = serious
|
||||
shocked = shocked
|
||||
shy = shy
|
||||
sick = sick
|
||||
sleepy = sleepy
|
||||
spontaneous = spontaneous
|
||||
stressed = stressed
|
||||
strong = strong
|
||||
surprised = surprised
|
||||
thankful = thankful
|
||||
thirsty = thirsty
|
||||
tired = tired
|
||||
undefined = undefined
|
||||
weak = weak
|
||||
worried = worried
|
||||
|
||||
[month]
|
||||
title = Month
|
||||
january = January
|
||||
february = February
|
||||
march = March
|
||||
april = April
|
||||
may = May
|
||||
june = June
|
||||
july = July
|
||||
august = August
|
||||
september = September
|
||||
october = October
|
||||
november = November
|
||||
december = December
|
||||
|
||||
[year]
|
||||
title = Year
|
||||
|
||||
[date]
|
||||
today = Today
|
||||
tomorrow = Tomorrow
|
||||
yesterday = Yesterday
|
||||
ago = %d days ago
|
||||
day = day
|
||||
|
||||
[post]
|
||||
title = Title
|
||||
place = Place
|
||||
by = by
|
||||
geolocalisation = Geolocalisation
|
||||
email = email
|
||||
empty = No content
|
||||
no_comments = No comments yet
|
||||
older = Get older posts
|
||||
new_items = %s new items
|
||||
comment_error = Comment publication error
|
||||
comments_get = Get the comments
|
||||
comment_add = Add a comment
|
||||
share = Share with
|
||||
share_everyone = Everyone
|
||||
delete = Delete this post
|
||||
updated = Updated
|
||||
content_not_found = Content not found
|
||||
default_title = Contact publication
|
||||
comments = Comments
|
||||
original_deleted = Original post deleted
|
||||
|
||||
[filesize]
|
||||
byte = B
|
||||
kilobyte = KB
|
||||
megabyte = MB
|
||||
gigabyte = GB
|
||||
terabyte = TB
|
||||
|
||||
[affiliation]
|
||||
owner = Owner
|
||||
admin = Admin
|
||||
publisher = Publisher
|
||||
publish-only = Publish only
|
||||
member = Member
|
||||
outcast = Outcast
|
||||
no_aff = No affiliation
|
||||
owner_changed = User granted as owner
|
||||
admin_changed = User granted as admin
|
||||
member_changed = User granted as member
|
||||
outcast_changed = User banned
|
||||
none_changed = Affiliation removed for the user
|
||||
|
||||
[api]
|
||||
error = The API is not reachable, try again later
|
||||
|
||||
[field]
|
||||
type_here = Type here
|
||||
@@ -0,0 +1,110 @@
|
||||
var version = 10;
|
||||
var cacheKey = 'movim_' + version;
|
||||
|
||||
const channel = new BroadcastChannel('messages');
|
||||
|
||||
self.addEventListener('install', (e) => {
|
||||
self.skipWaiting();
|
||||
|
||||
// Workaround for https://issues.chromium.org/issues/466790291
|
||||
e.addRoutes({
|
||||
condition: {
|
||||
urlPattern: new URLPattern({})
|
||||
},
|
||||
source: "fetch-event"
|
||||
});
|
||||
|
||||
e.waitUntil(
|
||||
caches.open(cacheKey).then((cache) => cache.addAll([
|
||||
'/scripts/libsignal_protocol.min.js',
|
||||
'/scripts/thumbhash.js',
|
||||
'/scripts/movim_emojis_list.js',
|
||||
'/theme/audio/call.opus',
|
||||
'/theme/audio/message.message',
|
||||
'/theme/audio/user_joined.opus',
|
||||
'/theme/audio/user_left.message',
|
||||
'/theme/fonts/MaterialSymbols/MaterialSymbols-Outlined.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fCRc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fABc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fCBc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fBxc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fCxc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fChc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmSU5fBBc4.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu72xKOzY.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu5mxKOzY.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu7mxKOzY.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu4WxKOzY.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu7WxKOzY.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu7GxKOzY.woff2',
|
||||
'/theme/fonts/Roboto/KFOmCnqEu92Fr1Mu4mxK.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fCRc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fABc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fCBc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fBxc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fCxc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fChc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmEU9fBBc4.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfCRc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfABc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfCBc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfBxc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfCxc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfChc4EsA.woff2',
|
||||
'/theme/fonts/Roboto/KFOlCnqEu92Fr1MmWUlfBBc4.woff2',
|
||||
]))
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', function (e) {
|
||||
e.waitUntil(caches.keys().then(keys => {
|
||||
return Promise.all(keys
|
||||
.filter(key => key != cacheKey)
|
||||
.map(key => caches.delete(key))
|
||||
);
|
||||
}).then(function () {
|
||||
return self.clients.claim();
|
||||
}));
|
||||
});
|
||||
|
||||
self.addEventListener('push', function (e) {
|
||||
var json = e.data.json();
|
||||
var options = {
|
||||
body: json.body,
|
||||
icon: json.picture,
|
||||
badge: '/theme/img/app/badge.png',
|
||||
vibrate: [100, 50, 100],
|
||||
data: json.data,
|
||||
actions: json.actions,
|
||||
timestamp: json.timestamp * 1000,
|
||||
tag: json.tag,
|
||||
};
|
||||
e.waitUntil(
|
||||
self.registration.showNotification(json.title, options)
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', function (e) {
|
||||
e.waitUntil(
|
||||
clients
|
||||
.matchAll({
|
||||
type: "window",
|
||||
})
|
||||
.then((clientList) => {
|
||||
for (const client of clientList) {
|
||||
if ("focus" in client) return client.focus();
|
||||
}
|
||||
if (clients.openWindow) return clients.openWindow(e.notification.data.url);
|
||||
}),
|
||||
);
|
||||
|
||||
channel.postMessage({ type: e.action, data: e.notification.data });
|
||||
|
||||
e.notification.close();
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (e) => {
|
||||
e.respondWith(
|
||||
caches.match(e.request).then((response) => response || fetch(e.request)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
[libsignal_protocol.js]
|
||||
indent_size = unset
|
||||
indent_style = unset
|
||||
insert_final_newline = unset
|
||||
@@ -0,0 +1,52 @@
|
||||
var MovimAvatar = {
|
||||
file : function(files, formname, width = 384, height = 384) {
|
||||
var f = files[0];
|
||||
if (!f.type.match(/image.*/)) {
|
||||
console.log("Not a picture !");
|
||||
MovimAvatar.clear(formname);
|
||||
} else {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(f);
|
||||
|
||||
reader.onload = function (ev) {
|
||||
MovimUtils.getOrientation(f, function(orientation) {
|
||||
MovimAvatar.preview(ev.target.result, orientation, formname, width, height);
|
||||
});
|
||||
};
|
||||
};
|
||||
},
|
||||
clear : function(formname) {
|
||||
document.querySelector('form[name=' + formname + '] img').src = '';
|
||||
document.querySelector('form[name=' + formname + '] input[name="photobin"]').value = '';
|
||||
},
|
||||
preview : function(src, orientation, formname, setWidth, setHeight) {
|
||||
var image = new Image();
|
||||
image.src = src;
|
||||
|
||||
image.onload = function() {
|
||||
var canvas = document.createElement('canvas');
|
||||
width = canvas.width = setWidth;
|
||||
height = canvas.height = setHeight;
|
||||
ctx = canvas.getContext("2d");
|
||||
|
||||
MovimUtils.applyOrientation(ctx, orientation, width, height)
|
||||
MovimUtils.drawImageProp(ctx, image);
|
||||
|
||||
var base64 = canvas.toDataURL('image/jpeg', 0.80);
|
||||
|
||||
var preview = document.querySelector('form[name=' + formname + '] img');
|
||||
|
||||
var list = document.querySelector('form[name=' + formname + '] ul');
|
||||
if (list) list.classList.add('hide');
|
||||
|
||||
var input = document.querySelector('form[name=' + formname + '] input[name="photobin"]');
|
||||
|
||||
if (preview.className == 'error') preview.className = '';
|
||||
|
||||
preview.src = base64;
|
||||
|
||||
var bin = base64.split(",");
|
||||
input.value = bin[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Register a service worker for the Progressive Web App
|
||||
*/
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker
|
||||
.register(SW_URI)
|
||||
.then(e => navigator.serviceWorker.ready)
|
||||
.then((r) => {
|
||||
console.log('Service Worker Registered');
|
||||
});
|
||||
|
||||
let refreshing = false;
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
if (refreshing) return;
|
||||
refreshing = true;
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
const channel = new BroadcastChannel('messages');
|
||||
channel.addEventListener('message', event => {
|
||||
Notif.snackbarClear();
|
||||
window.focus();
|
||||
|
||||
switch (event.data.type) {
|
||||
case 'call':
|
||||
break;
|
||||
case 'call_reject':
|
||||
VisioUtils.cancelLobby(event.data.data.fullJid, event.data.data.callId);
|
||||
break;
|
||||
case 'space_chat':
|
||||
MovimUtils.reload(event.data.data.server, event.data.data.node, event.data.data.room);
|
||||
break;
|
||||
case 'chat':
|
||||
Search.chat(event.data.data.jid, event.data.data.muc);
|
||||
break;
|
||||
default:
|
||||
if (event.data.data.url) {
|
||||
MovimUtils.reload(event.data.data.url);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MovimEvents.registerWindow('loaded', 'movimbase', () => {
|
||||
const pwaButton = document.querySelector('#pwa');
|
||||
|
||||
if (pwaButton) {
|
||||
window.addEventListener('beforeinstallprompt', (e) => {
|
||||
e.preventDefault();
|
||||
deferredPrompt = e;
|
||||
pwaButton.style.display = 'initial';
|
||||
|
||||
pwaButton.addEventListener('click', () => {
|
||||
deferredPrompt.prompt();
|
||||
|
||||
deferredPrompt.userChoice.then((choiceResult) => {
|
||||
if (choiceResult.outcome === 'accepted') {
|
||||
console.log('Movim App installed');
|
||||
}
|
||||
|
||||
deferredPrompt = null;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
const KEY_ALGO = {
|
||||
'name': 'AES-GCM',
|
||||
'length': 128
|
||||
};
|
||||
const NUM_PREKEYS = 50;
|
||||
const SIGNED_PREKEY_ID = 1;
|
||||
const AESGCM_REGEX = /^aesgcm:\/\/([^#]+\/([^\/]+\.([a-z0-9]+)))#([a-z0-9]+)/i;
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Movim Events
|
||||
*/
|
||||
|
||||
var MovimEvents = {
|
||||
eventsBody: {},
|
||||
eventsWindow: {},
|
||||
isFocused: false,
|
||||
isTouch: false,
|
||||
|
||||
/**
|
||||
* @brief Register an event on the body
|
||||
* @param string event
|
||||
* @param string key
|
||||
* @param function action
|
||||
*/
|
||||
registerBody: function (event, key, action) {
|
||||
if (MovimEvents.eventsBody[event] == undefined) {
|
||||
MovimEvents.eventsBody[event] = {};
|
||||
}
|
||||
|
||||
MovimEvents.eventsBody[event][key] = action;
|
||||
},
|
||||
|
||||
/**
|
||||
* @brief Register an event on the window
|
||||
* @param string event
|
||||
* @param string key
|
||||
* @param function action
|
||||
*/
|
||||
registerWindow: function (event, key, action) {
|
||||
if (MovimEvents.eventsWindow[event] == undefined) {
|
||||
MovimEvents.eventsWindow[event] = {};
|
||||
}
|
||||
|
||||
MovimEvents.eventsWindow[event][key] = action;
|
||||
},
|
||||
|
||||
triggerBody: function (event, e) {
|
||||
if (MovimEvents.eventsBody[event] != undefined) {
|
||||
for (const value of Object.values(MovimEvents.eventsBody[event])) {
|
||||
value(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
triggerWindow: function (event, e) {
|
||||
if (MovimEvents.eventsWindow[event] != undefined) {
|
||||
for (const value of Object.values(MovimEvents.eventsWindow[event])) {
|
||||
value(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
focusEvent: function (e) {
|
||||
if (MovimEvents.isFocused) return;
|
||||
|
||||
MovimEvents.isFocused = true;
|
||||
MovimEvents.triggerWindow('focus', e);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', (e) => {
|
||||
// Window
|
||||
window.addEventListener('load', (e) => MovimEvents.triggerWindow('loaded', e), false);
|
||||
window.addEventListener('keydown', (e) => MovimEvents.triggerWindow('keydown', e), false);
|
||||
window.addEventListener('paste', (e) => MovimEvents.triggerWindow('paste', e), false);
|
||||
window.addEventListener('resize', (e) => MovimEvents.triggerWindow('resize', e), false);
|
||||
window.addEventListener('online', (e) => MovimEvents.triggerWindow('online', e), false);
|
||||
window.addEventListener('offline', (e) => MovimEvents.triggerWindow('offline', e), false);
|
||||
window.addEventListener('popstate', (e) => MovimEvents.triggerWindow('popstate', e), false);
|
||||
window.addEventListener('touchstart', (e) => MovimEvents.triggerWindow('touchstart', e), false);
|
||||
window.addEventListener('touchstart', function () { MovimEvents.isTouch = true; }, { once: true });
|
||||
|
||||
/**
|
||||
* The focus event doesn't seems to be triggered all the time ¯\_(ツ)_/¯
|
||||
*/
|
||||
window.addEventListener('blur', (e) => {
|
||||
MovimEvents.isFocused = false;
|
||||
MovimEvents.triggerWindow('blur', e);
|
||||
}, false);
|
||||
window.addEventListener('focusin', (e) => MovimEvents.focusEvent(e), false);
|
||||
window.addEventListener('mouseover', (e) => MovimEvents.focusEvent(e), false);
|
||||
|
||||
// Body
|
||||
document.body.addEventListener('click', (e) => MovimEvents.triggerBody('click', e), false);
|
||||
document.body.addEventListener('keydown', (e) => MovimEvents.triggerBody('keydown', e), false);
|
||||
document.body.addEventListener('touchstart', (e) => MovimEvents.triggerBody('touchstart', e), false);
|
||||
document.body.addEventListener('touchend', (e) => MovimEvents.triggerBody('touchend', e), false);
|
||||
document.body.addEventListener('touchmove', (e) => MovimEvents.triggerBody('touchmove', e), false);
|
||||
document.body.addEventListener('dragover', (e) => MovimEvents.triggerBody('dragover', e), false);
|
||||
document.body.addEventListener('drop', (e) => MovimEvents.triggerBody('drop', e), false);
|
||||
document.body.addEventListener('dragleave', (e) => MovimEvents.triggerBody('dragleave', e), false);
|
||||
}, false);
|
||||
@@ -0,0 +1,75 @@
|
||||
var MovimFavicon = {
|
||||
originalUrl: null,
|
||||
originalIcon: null,
|
||||
sizes: '128x128',
|
||||
|
||||
counter: function (counterTab1, counterTab2) {
|
||||
let counter = counterTab1 + counterTab2;
|
||||
|
||||
link = document.querySelector('link[sizes="' + MovimFavicon.sizes + '"]');
|
||||
|
||||
canvas = document.createElement("canvas");
|
||||
ctx = canvas.getContext('2d');
|
||||
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
|
||||
ctx.drawImage(MovimFavicon.originalIcon, 0, 0, 32, 32);
|
||||
|
||||
if (counter > 0) {
|
||||
large = counter > 9;
|
||||
if (counter > 99) {
|
||||
counter = '+';
|
||||
large = false;
|
||||
}
|
||||
|
||||
ctx.textAlign = 'center';
|
||||
ctx.font = 'bold 18px Roboto';
|
||||
|
||||
radius = 5;
|
||||
x = large ? 4 : 12;
|
||||
y = 12;
|
||||
w = large ? 28 : 20;
|
||||
h = 20;
|
||||
|
||||
var r = x + w;
|
||||
var b = y + h;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue(counterTab2 > 0
|
||||
? '--p-red'
|
||||
: '--movim-accent'
|
||||
);
|
||||
ctx.moveTo(x + radius, y);
|
||||
ctx.lineTo(r - radius, y);
|
||||
ctx.quadraticCurveTo(r, y, r, y + radius);
|
||||
ctx.lineTo(r, y + h - radius);
|
||||
ctx.quadraticCurveTo(r, b, r - radius, b);
|
||||
ctx.lineTo(x + radius, b);
|
||||
ctx.quadraticCurveTo(x, b, x, b - radius);
|
||||
ctx.lineTo(x, y + radius);
|
||||
ctx.quadraticCurveTo(x, y, x + radius, y);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "#fff";
|
||||
counterTextX = large ? 18 : 22;
|
||||
ctx.fillText(counter, counterTextX, 28, w);
|
||||
}
|
||||
|
||||
MovimFavicon.set(canvas.toDataURL());
|
||||
},
|
||||
|
||||
set: function (url) {
|
||||
link = document.querySelector('link[sizes="' + MovimFavicon.sizes + '"]');
|
||||
link.href = url;
|
||||
},
|
||||
|
||||
init: function () {
|
||||
link = document.querySelector('link[sizes="' + MovimFavicon.sizes + '"]');
|
||||
MovimFavicon.originalUrl = link.href;
|
||||
MovimFavicon.originalIcon = new Image();
|
||||
MovimFavicon.originalIcon.src = MovimFavicon.originalUrl;
|
||||
}
|
||||
}
|
||||
|
||||
MovimFavicon.init();
|
||||
@@ -0,0 +1,61 @@
|
||||
class MovimJingleSessionAudioWorklet extends AudioWorkletProcessor {
|
||||
static BUFFER_SIZE = 128 * 128;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.isMuteStep = 0;
|
||||
this.remoteMaxLevel = 0;
|
||||
this.buffer = new Float32Array(MovimJingleSessionAudioWorklet.BUFFER_SIZE);
|
||||
this.offset = 0;
|
||||
}
|
||||
|
||||
process(inputList, _outputList, _parameters) {
|
||||
const input = inputList[0][0];
|
||||
|
||||
if (input != undefined) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
this.buffer[i + this.offset] = input[i];
|
||||
}
|
||||
|
||||
this.offset += input.length;
|
||||
|
||||
if (this.offset >= this.buffer.length - 1) {
|
||||
this.flush();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
flush() {
|
||||
this.offset = 0;
|
||||
|
||||
var instant = 0.0;
|
||||
var sum = 0.0;
|
||||
|
||||
for (var i = 0; i < this.buffer.length; ++i) {
|
||||
sum += this.buffer[i] * this.buffer[i];
|
||||
}
|
||||
|
||||
instant = Math.sqrt(sum / this.buffer.length);
|
||||
this.remoteMaxLevel = Math.max(this.remoteMaxLevel, instant);
|
||||
|
||||
var base = (instant / this.remoteMaxLevel);
|
||||
var level = (base > 0.05) ? base ** .3 : 0;
|
||||
|
||||
// Fallback in case we don't have the proper signalisation
|
||||
if (level == 0) {
|
||||
this.isMuteStep++;
|
||||
} else {
|
||||
this.isMuteStep = 0;
|
||||
}
|
||||
|
||||
this.port.postMessage({
|
||||
"isMuteStep": this.isMuteStep,
|
||||
"level": level.toFixed(2),
|
||||
"published": Date.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('jinglesession-audioworklet', MovimJingleSessionAudioWorklet);
|
||||
@@ -0,0 +1,935 @@
|
||||
var MovimJingleSession = function (jid, fullJid, id, name, avatarUrl) {
|
||||
this.id = id ?? crypto.randomUUID();
|
||||
this.jid = jid;
|
||||
this.fullJid = fullJid;
|
||||
this.tracksTypes = {};
|
||||
this.tracksScreen = {};
|
||||
this.name = name;
|
||||
this.avatarUrl = avatarUrl;
|
||||
this.audioLevel = 0;
|
||||
this.lastPostMessage = 0;
|
||||
|
||||
this.audioSharingSender = null;
|
||||
this.screenSharingSender = null;
|
||||
|
||||
this.pc = new RTCPeerConnection({
|
||||
iceServers: MovimVisio.services,
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceCandidatePoolSize: 10
|
||||
});
|
||||
|
||||
this.screenSharingPc = null; // RTCPc specific for the SFU
|
||||
|
||||
this.adaptToNetworkCondition = setInterval(() => {
|
||||
VisioUtils.adaptToNetworkCondition(this.pc);
|
||||
}, 5000);
|
||||
|
||||
this.participant = document.createElement('div');
|
||||
this.participant.dataset.jid = this.jid;
|
||||
this.participant.classList.add('participant');
|
||||
|
||||
document.querySelector('#participants').appendChild(this.participant);
|
||||
|
||||
this.participant.classList.add('audio_off');
|
||||
this.participant.classList.add('screen_off');
|
||||
this.participant.classList.add('video_off');
|
||||
|
||||
this.remoteScreenVideo = document.createElement('video');
|
||||
this.remoteScreenVideo.classList.add('screen');
|
||||
this.remoteScreenVideo.autoplay = true;
|
||||
this.remoteScreenVideo.disablePictureInPicture = true;
|
||||
this.remoteScreenVideo.poster = BASE_URI + 'theme/img/empty.png';
|
||||
this.participant.appendChild(this.remoteScreenVideo);
|
||||
|
||||
this.remoteVideo = document.createElement('video');
|
||||
this.remoteVideo.autoplay = true;
|
||||
this.remoteVideo.disablePictureInPicture = true;
|
||||
this.remoteVideo.poster = BASE_URI + 'theme/img/empty.png';
|
||||
this.remoteVideo.muted = true;
|
||||
this.participant.appendChild(this.remoteVideo);
|
||||
|
||||
this.remoteAudio = document.createElement('audio');
|
||||
this.remoteAudio.autoplay = true;
|
||||
this.participant.appendChild(this.remoteAudio);
|
||||
|
||||
this.remoteScreenAudio = document.createElement('audio');
|
||||
this.remoteScreenAudio.classList.add('screen');
|
||||
this.remoteScreenAudio.autoplay = true;
|
||||
this.participant.appendChild(this.remoteScreenAudio);
|
||||
|
||||
this.callStatus = document.createElement('div')
|
||||
this.callStatus.classList.add('status');
|
||||
this.participant.appendChild(this.callStatus);
|
||||
|
||||
this.audioOffStatus = document.createElement('span');
|
||||
this.audioOffStatus.classList.add('audio_off');
|
||||
this.callStatus.appendChild(this.audioOffStatus);
|
||||
|
||||
this.videoOffStatus = document.createElement('span');
|
||||
this.videoOffStatus.classList.add('video_off');
|
||||
this.callStatus.appendChild(this.videoOffStatus);
|
||||
|
||||
this.screenStatus = document.createElement('span');
|
||||
this.screenStatus.classList.add('screen');
|
||||
this.callStatus.appendChild(this.screenStatus);
|
||||
|
||||
// Pin button
|
||||
this.pin = document.createElement('span');
|
||||
this.pin.classList.add('pin');
|
||||
this.participant.appendChild(this.pin);
|
||||
|
||||
this.pin.addEventListener('click', e => {
|
||||
VisioUtils.toggleMode(true);
|
||||
|
||||
if (MovimJingles.pinned == this.jid) {
|
||||
MovimJingles.pinned = null;
|
||||
Visio_ajaxHttpUnpin();
|
||||
} else {
|
||||
MovimJingles.pinned = this.jid;
|
||||
|
||||
if (this.name) {
|
||||
Visio_ajaxHttpPin(this.name);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingles.checkActiveSpeaker();
|
||||
})
|
||||
|
||||
this.screenQualityInterval = setInterval(() => {
|
||||
this.callStatus.classList.remove('screen_hd', 'screen_fhd');
|
||||
if (!this.participant.classList.contains('screen_off')) {
|
||||
if (this.remoteScreenVideo.videoWidth >= 1920) {
|
||||
this.callStatus.classList.add('screen_fhd');
|
||||
} else if (this.remoteScreenVideo.videoWidth >= 1280) {
|
||||
this.callStatus.classList.add('screen_hd');
|
||||
}
|
||||
}
|
||||
}, 3000);
|
||||
|
||||
if (this.name) {
|
||||
this.callStatus.dataset.name = this.name;
|
||||
}
|
||||
|
||||
if (this.avatarUrl) {
|
||||
let background = document.createElement('img');
|
||||
background.classList.add('avatar');
|
||||
background.src = this.avatarUrl;
|
||||
this.participant.prepend(background);
|
||||
}
|
||||
|
||||
this.pc.ontrack = event => {
|
||||
var srcObject = null;
|
||||
|
||||
if (event.streams && event.streams[0]) {
|
||||
srcObject = event.streams[0];
|
||||
} else {
|
||||
srcObject = new MediaStream();
|
||||
srcObject.addTrack(event.track);
|
||||
}
|
||||
|
||||
if (event.track.kind == 'audio') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenAudio.srcObject = srcObject;
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'audio_screen';
|
||||
} else {
|
||||
this.remoteAudio.srcObject = srcObject;
|
||||
this.participant.classList.remove('audio_off');
|
||||
this.handleRemoteAudio();
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'audio';
|
||||
}
|
||||
} else if (event.track.kind === 'video') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenVideo.srcObject = srcObject;
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'video_screen';
|
||||
this.remoteScreenVideo.oncanplay = event => {
|
||||
this.participant.classList.remove('screen_off');
|
||||
}
|
||||
} else {
|
||||
this.remoteVideo.srcObject = srcObject;
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'video';
|
||||
this.participant.classList.remove('video_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.pc.onnegotiationneeded = event => {
|
||||
if (this.pc.localDescription) {
|
||||
this.oldLocalDescription = this.pc.localDescription.sdp;
|
||||
|
||||
this.pc.getTransceivers().forEach(transceiver => {
|
||||
if (transceiver.sender.track && transceiver.sender.track.kind === 'video') {
|
||||
VisioUtils.setVideoCodecPreferences(transceiver);
|
||||
}
|
||||
});
|
||||
|
||||
this.pc.createOffer()
|
||||
.then(offer => {
|
||||
offer.sdp = this.maybeInjectScreenCategory(offer.sdp);
|
||||
return this.pc.setLocalDescription(offer)
|
||||
}).then(() => this.updateContent())
|
||||
.catch(err => MovimUtils.logError(err));
|
||||
}
|
||||
};
|
||||
|
||||
this.pc.onicecandidate = event => {
|
||||
let candidate = event.candidate;
|
||||
if (candidate && candidate.candidate && candidate.candidate.length > 0) {
|
||||
Visio_ajaxCandidate(this.fullJid, this.id, event.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Add all the existing tracks
|
||||
*/
|
||||
|
||||
if (MovimVisio.sfu == null) {
|
||||
MovimVisio.localStream.getTracks().forEach(track => {
|
||||
this.pc.addTrack(track, MovimVisio.localStream);
|
||||
});
|
||||
|
||||
if (MovimVisio.screenSharing.srcObject) {
|
||||
this.enableScreenSharing();
|
||||
}
|
||||
}
|
||||
|
||||
Notif.userJoinedCall();
|
||||
MovimJingles.checkActiveSpeaker();
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.handleRemoteAudio = async function () {
|
||||
this.remoteAudioContext = new AudioContext();
|
||||
|
||||
try {
|
||||
var remoteMicrophone = this.remoteAudioContext.createMediaStreamSource(
|
||||
this.remoteAudio.srcObject
|
||||
);
|
||||
|
||||
await this.remoteAudioContext.audioWorklet.addModule(BASE_URI + 'scripts/movim_jingle_session_audio_worklet.js');
|
||||
const audioWorkletNode = new AudioWorkletNode(this.remoteAudioContext, 'jinglesession-audioworklet');
|
||||
remoteMicrophone.connect(audioWorkletNode);
|
||||
|
||||
audioWorkletNode.port.onmessage = (e) => {
|
||||
this.processRemoteAudioMessage(e.data);
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
MovimUtils.logError(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In some clients, such as Dino, the buffer is stopped when the microphone is muted
|
||||
* we detect that there and send a clear message properly
|
||||
*/
|
||||
MovimJingleSession.prototype.clearRemoteAudioMessage = function () {
|
||||
const second = 1000;
|
||||
const secondAgo = Date.now() - second;
|
||||
|
||||
if (this.lastPostMessage < secondAgo) {
|
||||
this.processRemoteAudioMessage({
|
||||
"isMuteStep": 5,
|
||||
"level": 0,
|
||||
"published": Date.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.processRemoteAudioMessage = function (message) {
|
||||
if (message.isMuteStep >= 5) {
|
||||
this.participant.classList.add('audio_off');
|
||||
} else {
|
||||
this.participant.classList.remove('audio_off');
|
||||
}
|
||||
|
||||
this.lastPostMessage = message.published;
|
||||
this.audioLevel = message.level;
|
||||
this.participant.style.setProperty('--level', message.level);
|
||||
|
||||
if (message.level > 0) {
|
||||
clearTimeout(this.clearRemoteAudioMessageId);
|
||||
this.clearRemoteAudioMessageId = setTimeout(this.clearRemoteAudioMessage.bind(this), 2000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* movim-rs: the signaling messages can arrive faster than the asynchronous
|
||||
* WebRTC calls complete (a content-add right after a session-accept, candidates
|
||||
* before the remote description), run them one after the other.
|
||||
*/
|
||||
MovimJingleSession.prototype.enqueue = function (task) {
|
||||
this.queue = (this.queue || Promise.resolve())
|
||||
.then(() => this.pc ? task() : null)
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onCandidate = function (candidate, mid, mlineindex) {
|
||||
this.enqueue(() => this._onCandidate(candidate, mid, mlineindex));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onContentAdd = function (sdp, mids) {
|
||||
this.enqueue(() => this._onContentAdd(sdp, mids));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onContentModify = function (sdp, mid) {
|
||||
this.enqueue(() => this._onContentModify(sdp, mid));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onContentRemove = function (sdp, mids) {
|
||||
this.enqueue(() => this._onContentRemove(sdp, mids));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onAcceptSDP = function (sdp) {
|
||||
this.enqueue(() => this._onAcceptSDP(sdp));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onInitiateSDP = function (sdp) {
|
||||
this.enqueue(() => this._onInitiateSDP(sdp));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.terminate = function (reason, muji) {
|
||||
if (MovimVisio.sfu == null) {
|
||||
Visio_ajaxTerminate(this.fullJid, this.id, reason, muji);
|
||||
}
|
||||
this.close();
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.close = function () {
|
||||
clearInterval(this.adaptToNetworkCondition);
|
||||
clearInterval(this.screenQualityInterval);
|
||||
|
||||
Notif.userLeftCall();
|
||||
|
||||
if (this.pc) {
|
||||
this.pc.close();
|
||||
this.pc = null;
|
||||
}
|
||||
|
||||
if (this.remoteAudioContext) {
|
||||
this.remoteAudioContext.close();
|
||||
this.remoteAudioContext = null;
|
||||
}
|
||||
|
||||
let participant = document.querySelector('.participant[data-jid="' + this.jid + '"]');
|
||||
if (participant) participant.remove();
|
||||
|
||||
let remoteVideoStream = this.remoteVideo.srcObject;
|
||||
if (remoteVideoStream) {
|
||||
remoteVideoStream.getTracks().forEach(track => track.stop());
|
||||
remoteVideoStream = null;
|
||||
}
|
||||
|
||||
let remoteAudioStream = this.remoteAudio.srcObject;
|
||||
if (remoteAudioStream) {
|
||||
remoteAudioStream.getTracks().forEach(track => track.stop());
|
||||
remoteAudioStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onCandidate = function (candidate, mid, mlineindex) {
|
||||
const iceCandidate = new RTCIceCandidate({
|
||||
// filter the a=candidate lines
|
||||
'candidate': candidate.split(/\n/).filter(line => {
|
||||
return line.startsWith('a=candidate');
|
||||
}).join('').substring(2),
|
||||
'sdpMid': mid,
|
||||
'sdpMLineIndex': mlineindex
|
||||
});
|
||||
|
||||
// When we share our own screen have some candidates from the SFU for our PC
|
||||
if (this.jid == MovimVisio.sfu && MovimVisio.screenshareSFUPc) {
|
||||
MovimVisio.screenshareSFUPc.addIceCandidate(iceCandidate).catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
if (this.screenSharingPc) {
|
||||
// In this case we send the candidate to both pcs, and let it sort it out ¯\_(ツ)_/¯
|
||||
this.screenSharingPc.addIceCandidate(iceCandidate).catch(error => MovimUtils.logError(error));
|
||||
} else if (this.pc && this.pc.remoteDescription) {
|
||||
return this.pc.addIceCandidate(iceCandidate).catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onContentAdd = function (sdp, mids) {
|
||||
remoteDescription = this.pc.remoteDescription.sdp;
|
||||
remoteDescription += sdp.match('m=[^]*');
|
||||
remoteDescription = remoteDescription.replace(/^a=group.*/m, sdp.match(/a=group.*/)[0]);
|
||||
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': remoteDescription + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => Visio_ajaxContentAccept(this.fullJid, this.id, this.pc.localDescription.sdp))
|
||||
.catch(MovimUtils.logError);
|
||||
})
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onContentModify = function (sdp, mid) {
|
||||
// TODO, implement mid
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => Visio_ajaxContentAccept(this.fullJid, this.id, this.pc.localDescription.sdp))
|
||||
.catch(MovimUtils.logError);
|
||||
})
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onContentRemove = function (sdp, mids) {
|
||||
remoteDescription = this.pc.remoteDescription.sdp;
|
||||
mids.forEach(mid => delete this.tracksScreen[mid]);
|
||||
|
||||
let parts = remoteDescription.split('m=');
|
||||
let filtered = [];
|
||||
|
||||
parts.forEach(part => {
|
||||
let mid = part.match(/a=mid:(.*)/);
|
||||
if (!mid || !mids.includes(mid[1])) {
|
||||
filtered.push(part)
|
||||
}
|
||||
});
|
||||
|
||||
remoteDescription = filtered.join('m=');
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => Visio_ajaxContentAccept(this.fullJid, this.id, this.pc.localDescription.sdp))
|
||||
.catch(MovimUtils.logError);
|
||||
})
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.sessionInitiate = function (fullJid, id, mujiRoom) {
|
||||
this.id = id;
|
||||
this.fullJid = fullJid;
|
||||
|
||||
this.pc.getTransceivers().forEach(transceiver => {
|
||||
if (transceiver.sender.track.kind === 'video') {
|
||||
VisioUtils.setVideoCodecPreferences(transceiver)
|
||||
}
|
||||
});
|
||||
|
||||
this.pc.createOffer()
|
||||
.then(offer => this.pc.setLocalDescription(offer))
|
||||
.then(() => Visio_ajaxSessionInitiate(this.fullJid, this.pc.localDescription, id, mujiRoom));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.updateContent = function () {
|
||||
let oldMedias = this.oldLocalDescription.match(MovimVisio.bundleRegex)[2].split(' ');
|
||||
let newMedias = this.pc.localDescription.sdp.match(MovimVisio.bundleRegex)[2].split(' ');
|
||||
|
||||
let createdMedias = newMedias.filter((e) => !oldMedias.includes(e));
|
||||
let destroyedMedias = oldMedias.filter((e) => !newMedias.includes(e));
|
||||
|
||||
let changed = false;
|
||||
let localDescription = this.maybeInjectScreenCategory(this.pc.localDescription.sdp);
|
||||
|
||||
if (createdMedias.length > 0) {
|
||||
changed = true;
|
||||
console.log('CONTENT ADD ?' + this.fullJid + ' ' + this.jid);
|
||||
Visio_ajaxContentAdd(this.fullJid, localDescription, this.id, createdMedias);
|
||||
}
|
||||
|
||||
if (destroyedMedias.length > 0) {
|
||||
changed = true;
|
||||
Visio_ajaxContentRemove(this.fullJid, this.oldLocalDescription, this.id, destroyedMedias);
|
||||
}
|
||||
|
||||
// Nothing added, nothing removed, lets update everything...
|
||||
if (changed == false) {
|
||||
Visio_ajaxContentModify(this.fullJid, localDescription, this.id);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onAcceptSDP = function (sdp) {
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'answer' })
|
||||
.catch(error => {
|
||||
let visio = document.querySelector('#visio');
|
||||
Visio_ajaxGoodbye(visio.dataset.jid, this.id, 'incompatible-parameters');
|
||||
|
||||
MovimUtils.logError(error);
|
||||
});
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onInitiateSDP = function (sdp) {
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => {
|
||||
if (MovimVisio.sfu != null) {
|
||||
Visio_ajaxContentAccept(
|
||||
this.fullJid,
|
||||
this.id,
|
||||
this.maybeInjectScreenCategory(this.pc.localDescription.sdp),
|
||||
this.jid
|
||||
);
|
||||
} else {
|
||||
Visio_ajaxSessionAccept(
|
||||
this.fullJid,
|
||||
this.id,
|
||||
this.maybeInjectScreenCategory(this.pc.localDescription.sdp)
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(MovimUtils.logError);
|
||||
}).catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
/**
|
||||
* With the SFU we can't have the screen as a new content, so we have to build a completely
|
||||
* new RTPPc
|
||||
*/
|
||||
MovimJingleSession.prototype.onSFUScreenSharingPropose = function (sdp) {
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
this.screenSharingPc = new RTCPeerConnection({
|
||||
iceServers: MovimVisio.services,
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceCandidatePoolSize: 10
|
||||
});
|
||||
|
||||
this.screenSharingPc.ontrack = event => {
|
||||
var srcObject = null;
|
||||
|
||||
if (event.streams && event.streams[0]) {
|
||||
srcObject = event.streams[0];
|
||||
} else {
|
||||
srcObject = new MediaStream();
|
||||
srcObject.addTrack(event.track);
|
||||
}
|
||||
|
||||
if (event.track.kind == 'audio') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenAudio.srcObject = srcObject;
|
||||
this.tracksTypes['sfu_screen_mid' + event.transceiver.mid] = 'audio_screen';
|
||||
}
|
||||
} else if (event.track.kind === 'video') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenVideo.srcObject = srcObject;
|
||||
this.tracksTypes['sfu_screen_mid' + event.transceiver.mid] = 'video_screen';
|
||||
this.remoteScreenVideo.oncanplay = event => {
|
||||
this.participant.classList.remove('screen_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.screenSharingPc.onicecandidate = event => {
|
||||
let candidate = event.candidate;
|
||||
if (candidate && candidate.candidate && candidate.candidate.length > 0) {
|
||||
Visio_ajaxCandidate(this.fullJid, this.id, event.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
this.screenSharingPc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(this.screenSharingPc.createAnswer()
|
||||
.then(answer => this.screenSharingPc.setLocalDescription(answer))
|
||||
.then(() => {
|
||||
Visio_ajaxContentAccept(
|
||||
this.fullJid,
|
||||
this.id,
|
||||
this.maybeInjectScreenCategory(this.screenSharingPc.localDescription.sdp),
|
||||
this.jid
|
||||
)
|
||||
})
|
||||
.catch(MovimUtils.logError));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onSFUScreenSharingTerminate = function () {
|
||||
if (this.screenSharingPc) {
|
||||
this.screenSharingPc.close();
|
||||
this.screenSharingPc = null;
|
||||
}
|
||||
|
||||
this.participant.classList.add('screen_off');
|
||||
|
||||
Object.keys(MovimJingles.sessions[this.jid].tracksTypes).forEach(
|
||||
key => {
|
||||
if (key.startsWith('sfu_screen_mid')) {
|
||||
delete MovimJingles.sessions[this.jid].tracksTypes[key]
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.enableScreenSharing = function () {
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => {
|
||||
if (track.kind == 'video') {
|
||||
if (this.screenSharingSender) {
|
||||
this.screenSharingSender.replaceTrack(track).then(() => {
|
||||
this.unmute(track);
|
||||
});
|
||||
} else {
|
||||
this.screenSharingSender = this.pc.addTrack(track);
|
||||
}
|
||||
} else {
|
||||
if (this.audioSharingSender) {
|
||||
this.audioSharingSender.replaceTrack(track).then(() => {
|
||||
this.unmute(track);
|
||||
});
|
||||
} else {
|
||||
this.audioSharingSender = this.pc.addTrack(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.disableScreenSharing = function () {
|
||||
if (this.pc && MovimVisio.screenSharing.srcObject) {
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => this.mute(track));
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.resolveTransceiver = function (track) {
|
||||
const transceiver = this.pc.getTransceivers().find(transceiver => transceiver.sender.track && transceiver.sender.track.id == track.id);
|
||||
return transceiver ?? null;
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.mute = function (track) {
|
||||
const transceiver = this.resolveTransceiver(track);
|
||||
if (transceiver) {
|
||||
Visio_ajaxMute(this.fullJid, this.id, 'mid' + transceiver.mid);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.unmute = function (track) {
|
||||
const transceiver = this.resolveTransceiver(track);
|
||||
if (transceiver) {
|
||||
Visio_ajaxUnmute(this.fullJid, this.id, 'mid' + transceiver.mid);
|
||||
} else if (track.kind == 'video') {
|
||||
this.pc.addTrack(track);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onMute = function (name) {
|
||||
if (this.tracksTypes[name]) {
|
||||
if (this.tracksTypes[name] == 'audio') {
|
||||
this.participant.classList.add('audio_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video') {
|
||||
this.participant.classList.add('video_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video_screen') {
|
||||
this.participant.classList.add('screen_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onUnmute = function (name) {
|
||||
if (this.tracksTypes[name]) {
|
||||
if (this.tracksTypes[name] == 'audio') {
|
||||
this.participant.classList.remove('audio_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video') {
|
||||
this.participant.classList.remove('video_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video_screen') {
|
||||
this.participant.classList.remove('screen_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.insertDtmf = function (s) {
|
||||
var rtc = this.pc.getSenders().find(rtc => rtc.track && rtc.track.kind == 'audio');
|
||||
|
||||
if (!rtc || !rtc.dtmf.canInsertDTMF) return;
|
||||
|
||||
rtc.dtmf.insertDTMF(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect RFC4796 content attribute
|
||||
*/
|
||||
MovimJingleSession.prototype.maybeDetectTracksScreen = function (sdp) {
|
||||
sdp.split('m=').forEach(media => {
|
||||
let content = media.match(/a=content:(.*)/);
|
||||
if (content && content.includes('slides')) {
|
||||
let mid = media.match(/a=mid:(.*)/);
|
||||
this.tracksScreen[mid[1]] = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject RFC4796 content attribute to respect XEP-0507: Jingle Content Category
|
||||
*/
|
||||
MovimJingleSession.prototype.maybeInjectScreenCategory = function (sdp) {
|
||||
if (this.audioSharingSender?.track || this.screenSharingSender?.track) {
|
||||
let ids = [];
|
||||
if (this.audioSharingSender) ids.push(this.audioSharingSender.track.id);
|
||||
if (this.screenSharingSender) ids.push(this.screenSharingSender.track.id);
|
||||
|
||||
sdp = sdp.split('m=').map(media => {
|
||||
let mid = media.match(MovimVisio.midRegex);
|
||||
if (mid != null) {
|
||||
const transceiver = this.pc.getTransceivers().find(transceiver => transceiver.mid == mid[1]);
|
||||
if (transceiver) {
|
||||
if (ids.includes(transceiver.sender.track.id)) {
|
||||
return media + 'a=content:slides' + "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return media;
|
||||
}).join('m=');
|
||||
}
|
||||
|
||||
return sdp;
|
||||
}
|
||||
|
||||
var MovimJingles = {
|
||||
sessions: {},
|
||||
pinned: null,
|
||||
|
||||
startCalls: function (mujiRoom) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.onProceed(jid, MovimJingles.sessions[jid].fullJid, MovimJingles.sessions[jid].id, mujiRoom);
|
||||
}
|
||||
},
|
||||
|
||||
initSession: function (jid, fullJid, id, name, avatarUrl) {
|
||||
if (Object.keys(MovimJingles.sessions).includes(jid)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!MovimVisio.localStream) {
|
||||
throw Error('localStream is not ready');
|
||||
};
|
||||
|
||||
MovimJingles.sessions[jid] = new MovimJingleSession(jid, fullJid, id, name, avatarUrl);
|
||||
return MovimJingles.sessions[jid].id;
|
||||
},
|
||||
|
||||
checkActiveSpeaker: function () {
|
||||
let maxLevel = 0;
|
||||
let maxJid = null;
|
||||
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
if (maxLevel < MovimJingles.sessions[jid].audioLevel) {
|
||||
maxLevel = MovimJingles.sessions[jid].audioLevel;
|
||||
maxJid = jid;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].participant.classList.remove('active', 'pinned');
|
||||
}
|
||||
|
||||
// Pinned has priority
|
||||
if (MovimJingles.pinned && MovimJingles.sessions[MovimJingles.pinned]) {
|
||||
MovimJingles.sessions[MovimJingles.pinned].participant.classList.add('active', 'pinned');
|
||||
return;
|
||||
}
|
||||
|
||||
if (maxJid != null) {
|
||||
MovimJingles.sessions[maxJid].participant.classList.add('active');
|
||||
} else if (Object.values(MovimJingles.sessions).length > 0) {
|
||||
Object.values(MovimJingles.sessions)[MovimVisio.sfu != null ? 1 : 0]?.participant.classList.add('active');
|
||||
}
|
||||
},
|
||||
|
||||
onManageTrack: function (stream, enable) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].onManageTrack(stream, enable);
|
||||
}
|
||||
},
|
||||
|
||||
enableScreenSharing: function () {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].enableScreenSharing();
|
||||
}
|
||||
},
|
||||
|
||||
disableScreenSharing: function () {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].disableScreenSharing();
|
||||
}
|
||||
},
|
||||
|
||||
enableAudio: function (enable = true) {
|
||||
MovimVisio.localStream.getTracks().filter(track => track.kind == 'audio').forEach(track => {
|
||||
track.enabled = enable;
|
||||
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
if (enable) {
|
||||
MovimJingles.sessions[jid].unmute(track);
|
||||
} else {
|
||||
MovimJingles.sessions[jid].mute(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
enableVideo: function (enable = true) {
|
||||
MovimVisio.mujiPublish();
|
||||
|
||||
MovimVisio.localStream.getTracks().filter(track => track.kind == 'video').forEach(track => {
|
||||
track.enabled = enable;
|
||||
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
if (enable) {
|
||||
MovimJingles.sessions[jid].unmute(track);
|
||||
} else {
|
||||
MovimJingles.sessions[jid].mute(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
insertDtmf: function (s) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].insertDtmf(s);
|
||||
}
|
||||
},
|
||||
|
||||
onCandidate: function (jid, candidate, mid, mlineindex, sid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Candidate from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
if (sid && sid === MovimVisio.screenshareSid) {
|
||||
MovimVisio.onScreenshareCandidate(candidate, mid, mlineindex);
|
||||
return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onCandidate(candidate, mid, mlineindex);
|
||||
},
|
||||
|
||||
onInitiateSDP: function (jid, sdp, sid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Initiate SDP from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
// Put the real sid
|
||||
MovimJingles.sessions[jid].id = sid;
|
||||
MovimJingles.sessions[jid].onInitiateSDP(sdp);
|
||||
},
|
||||
|
||||
onAcceptSDP: function (jid, sdp, sid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Accept SDP from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
if (sid && sid === MovimVisio.screenshareSid) {
|
||||
MovimVisio.onScreenshareAcceptSDP(sdp);
|
||||
return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onAcceptSDP(sdp);
|
||||
},
|
||||
|
||||
onProceed: function (jid, fullJid, id, mujiRoom) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Proceed from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].sessionInitiate(fullJid, id, mujiRoom);
|
||||
},
|
||||
|
||||
onMute: function (jid, name) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Mute from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onMute(name);
|
||||
},
|
||||
|
||||
onUnmute: function (jid, name) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Unmute from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onUnmute(name);
|
||||
},
|
||||
|
||||
onContentAdd: function (jid, sdp, mid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Content add from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onContentAdd(sdp, mid);
|
||||
},
|
||||
|
||||
onContentModify: function (jid, sdp, mid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Content modify from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onContentModify(sdp, mid);
|
||||
},
|
||||
|
||||
onContentRemove: function (jid, sdp, mid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Content remove from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onContentRemove(sdp, mid);
|
||||
},
|
||||
|
||||
onSFUScreenSharingPropose: function (jid, sdp) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('SFU screen sharing propose from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onSFUScreenSharingPropose(sdp);
|
||||
},
|
||||
|
||||
onSFUScreenSharingTerminate: function (jid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('SFU screen sharing terminate from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onSFUScreenSharingTerminate();
|
||||
},
|
||||
|
||||
terminate: function (jid, reason) {
|
||||
if (MovimJingles.sessions[jid] == undefined) return;
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
MovimJingles.sessions[jid].terminate(reason, (visio.dataset.muji == 'true'));
|
||||
delete MovimJingles.sessions[jid];
|
||||
},
|
||||
|
||||
onTerminate: function (jid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) return;
|
||||
|
||||
MovimJingles.sessions[jid].close();
|
||||
delete MovimJingles.sessions[jid];
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
|
||||
// No sessions left
|
||||
if (Object.keys(MovimJingles.sessions).length == 0) {
|
||||
if (visio.dataset.muji == 'false') {
|
||||
Visio_ajaxClear();
|
||||
} else {
|
||||
let state = document.querySelector('p.state');
|
||||
if (state) {
|
||||
state.innerText = MovimVisio.states.no_participants_left;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
terminateAll: function (reason) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.terminate(jid, reason);
|
||||
}
|
||||
|
||||
MovimJingles.pinned = null;
|
||||
Visio_ajaxClear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Short functions
|
||||
*/
|
||||
function MWSa(widget, func, params) {
|
||||
return MovimRPC.fetch(widget, func, params, false);
|
||||
}
|
||||
|
||||
function MWSad(widget, func, params) {
|
||||
return MovimRPC.fetch(widget, func, params, true);
|
||||
}
|
||||
|
||||
var MovimRPC = {
|
||||
fetchWithTimeout: async function (resource, options = {}) {
|
||||
const { timeout = 5000 } = options;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
const id = setTimeout(() => controller.abort(), timeout);
|
||||
const response = await fetch(resource, {
|
||||
...options,
|
||||
signal: controller.signal
|
||||
});
|
||||
clearTimeout(id);
|
||||
|
||||
return response;
|
||||
},
|
||||
|
||||
fetch: function (widget, func, params, daemon) {
|
||||
var body = {
|
||||
'c': MovimUtils.urlParts().page,
|
||||
'w': widget,
|
||||
'f': func
|
||||
};
|
||||
|
||||
if (params) body.p = params;
|
||||
|
||||
var url = BASE_URI;
|
||||
let request = MovimRPC.fetchWithTimeout(url += daemon ? 'ajaxd' : 'ajax', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(
|
||||
{ 'func': 'message', 'b': body }
|
||||
)
|
||||
});
|
||||
|
||||
if (!daemon) {
|
||||
request.then(response => {
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
} else if (response.status == 403) {
|
||||
MovimUtils.disconnect();
|
||||
}
|
||||
}).then(data => {
|
||||
for (funcall of data) {
|
||||
MovimRPC.handle(funcall);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return request;
|
||||
},
|
||||
|
||||
handle: function (funcall) {
|
||||
if (funcall.func != null && (typeof window[funcall.func] == 'function')) {
|
||||
try {
|
||||
window[funcall.func].apply(null, funcall.p);
|
||||
} catch (err) {
|
||||
console.log("Error caught: "
|
||||
+ err.toString()
|
||||
+ " - "
|
||||
+ funcall.func
|
||||
+ ":"
|
||||
+ JSON.stringify(funcall.p)
|
||||
);
|
||||
}
|
||||
} else if (funcall.func != null) {
|
||||
var funcs = funcall.func.split('.');
|
||||
var called = funcs[0];
|
||||
if (typeof window[called] == 'object'
|
||||
&& typeof window[funcs[0]][funcs[1]] != 'undefined') {
|
||||
window[funcs[0]][funcs[1]].apply(null, funcall.p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Movim Javascript Template functions
|
||||
|
||||
* Look at the comments for help.
|
||||
*/
|
||||
|
||||
var MovimTpl = {
|
||||
startX: 0,
|
||||
startY: 0,
|
||||
translateX: 0,
|
||||
menuDragged: false,
|
||||
currentPage: '',
|
||||
currentAnchor: '',
|
||||
popAnchorKey: null,
|
||||
popAnchorAction: null,
|
||||
|
||||
loadingPage: function () {
|
||||
document.body.classList.add('loading');
|
||||
document.body.classList.remove('finished');
|
||||
},
|
||||
finishedPage: function () {
|
||||
document.body.classList.add('finished');
|
||||
|
||||
setTimeout(e => {
|
||||
document.body.classList.remove('loading', 'finished');
|
||||
}, 1000);
|
||||
},
|
||||
|
||||
append: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('beforeend', html);
|
||||
}
|
||||
},
|
||||
appendAfter: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('afterend', html);
|
||||
}
|
||||
},
|
||||
pushAnchorState: function (key, action) {
|
||||
if (MovimTpl.popAnchorAction && key != MovimTpl.popAnchorKey) {
|
||||
MovimTpl.popAnchorAction();
|
||||
}
|
||||
|
||||
window.history.pushState(null, null, '#' + key);
|
||||
MovimTpl.popAnchorKey = key;
|
||||
MovimTpl.popAnchorAction = action;
|
||||
},
|
||||
clearAnchorState: function () {
|
||||
if (MovimTpl.popAnchorAction) {
|
||||
MovimTpl.popAnchorAction();
|
||||
}
|
||||
|
||||
MovimTpl.popAnchorKey = null;
|
||||
MovimTpl.popAnchorAction = null;
|
||||
window.history.replaceState(null, null, ' ');
|
||||
},
|
||||
fill: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.innerHTML = html;
|
||||
}
|
||||
},
|
||||
showPanel: function () {
|
||||
MovimUtils.addClass('main', 'enabled');
|
||||
MovimUtils.addClass('ul#bottomnavigation', 'hidden');
|
||||
},
|
||||
hidePanel: function () {
|
||||
MovimUtils.removeClass('main', 'enabled');
|
||||
MovimUtils.removeClass('ul#bottomnavigation', 'hidden');
|
||||
},
|
||||
prepend: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('afterbegin', html);
|
||||
}
|
||||
},
|
||||
prependBefore: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('beforebegin', html);
|
||||
}
|
||||
},
|
||||
remove: function (selector) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.remove();
|
||||
}
|
||||
},
|
||||
replace: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
var div = document.createElement('div');
|
||||
div.innerHTML = html;
|
||||
var element = div.firstChild;
|
||||
replacedNode = target.parentNode.replaceChild(element, target);
|
||||
}
|
||||
},
|
||||
showContextMenu: function () {
|
||||
var contextMenu = document.querySelector('ul.context_menu');
|
||||
contextMenu.classList.add('shown');
|
||||
},
|
||||
hideContextMenu: function (e) {
|
||||
var contextMenu = document.querySelector('ul.context_menu');
|
||||
if (contextMenu == null) return;
|
||||
|
||||
if (!document.querySelector('.show_context_menu')?.contains(e.target)) {
|
||||
contextMenu.classList.remove('shown');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
MovimEvents.registerBody('click', 'movimtpl', (e) => MovimTpl.hideContextMenu(e));
|
||||
|
||||
MovimEvents.registerWindow('loaded', 'movimtpl', () => {
|
||||
MovimTpl.currentPage = window.location.pathname;
|
||||
});
|
||||
|
||||
MovimEvents.registerWindow('popstate', 'movimtpl', (e) => {
|
||||
if (Dialog.filled()) {
|
||||
Dialog.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if (MovimTpl.popAnchorKey || e.target.location.hash != '') {
|
||||
MovimTpl.clearAnchorState();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.target.location.pathname == MovimTpl.currentPage) return;
|
||||
|
||||
MovimUtils.reload(e.target.location.href, true);
|
||||
|
||||
MovimTpl.currentPage = e.target.location.pathname;
|
||||
MovimTpl.currentAnchor = window.location.hash.substring(1);
|
||||
});
|
||||
@@ -0,0 +1,484 @@
|
||||
/**
|
||||
* Movim Utils
|
||||
*
|
||||
* This file include some useful functions used quite everywhere in Movim
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Set object in localStorage
|
||||
* @param key string
|
||||
* @param value the object
|
||||
*/
|
||||
Storage.prototype.setObject = function (key, value) {
|
||||
this.setItem(key, JSON.stringify(value));
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Get object in localStorage
|
||||
* @param key
|
||||
*/
|
||||
Storage.prototype.getObject = function (key) {
|
||||
return JSON.parse(this.getItem(key));
|
||||
};
|
||||
|
||||
var MovimUtils = {
|
||||
cleanupId: function (string) {
|
||||
return 'id-' + string.replace(/([^a-z0-9]+)/gi, '-').toLowerCase();
|
||||
},
|
||||
hash(string) {
|
||||
let hash = 0;
|
||||
|
||||
if (string.length === 0) return hash;
|
||||
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
const char = string.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
|
||||
return hash;
|
||||
},
|
||||
isMobile: function () {
|
||||
return window.matchMedia('(max-width: 1024px)').matches;
|
||||
},
|
||||
disconnect: function () {
|
||||
window.location.replace(ERROR_URI);
|
||||
},
|
||||
|
||||
clearAllActivesRooms: function () {
|
||||
document.querySelectorAll('ul.list.rooms li:not(.subheader)')
|
||||
.forEach(item => item.classList.remove('active'));
|
||||
},
|
||||
setActiveRoom: function (jid) {
|
||||
if (typeof Chats != 'undefined') Chats.clearAllActives();
|
||||
MovimUtils.clearAllActivesRooms();
|
||||
MovimUtils.addClass('ul.list.rooms li[data-jid="' + jid + '"]', 'active');
|
||||
},
|
||||
|
||||
formSetDirty: function (formname) {
|
||||
var form = document.forms[formname];
|
||||
|
||||
if (!form) {
|
||||
return false;
|
||||
}
|
||||
|
||||
form.dataset.dirty = true;
|
||||
},
|
||||
|
||||
formToJson: function (formname) {
|
||||
var form = document.forms[formname];
|
||||
|
||||
if (!form) {
|
||||
return;
|
||||
}
|
||||
|
||||
var json = {};
|
||||
|
||||
json['isDirty'] = Boolean(form.dataset.dirty);
|
||||
|
||||
for (var i = 0; i < form.elements.length; i++) {
|
||||
json_att = {};
|
||||
|
||||
for (var j = 0; j < form.elements[i].attributes.length; j++) {
|
||||
if (form.elements[i].attributes[j].name != 'value') {
|
||||
json_att[form.elements[i].attributes[j].name] = form.elements[i].attributes[j].value;
|
||||
}
|
||||
}
|
||||
|
||||
if (form.elements[i].name.length != 0) {
|
||||
if (form.elements[i].type == 'checkbox') {
|
||||
json[form.elements[i].name] = {
|
||||
'value': form.elements[i].checked,
|
||||
'attributes': json_att
|
||||
};
|
||||
} else if (form.elements[i].type == 'radio' && form.elements[i].checked) {
|
||||
json[form.elements[i].name] = {
|
||||
'value': form.elements[i].value,
|
||||
'attributes': json_att
|
||||
};
|
||||
} else if (form.elements[i].type != 'radio') {
|
||||
json[form.elements[i].name] = {
|
||||
'value': form.elements[i].value,
|
||||
'attributes': json_att
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return json;
|
||||
},
|
||||
cleanTime: function (seconds) {
|
||||
var currentMinute = parseInt(seconds / 60) % 60,
|
||||
currentSecondsLong = seconds % 60,
|
||||
currentSeconds = currentSecondsLong.toFixed(),
|
||||
currentTime = (currentMinute < 10 ? "0" + currentMinute : currentMinute)
|
||||
+ ":" + (currentSeconds < 10 ? "0" + currentSeconds : currentSeconds);
|
||||
|
||||
return currentTime;
|
||||
},
|
||||
setTitle: function (title) {
|
||||
document.title = title;
|
||||
},
|
||||
pushState: function (url) {
|
||||
window.history.pushState(null, '', url);
|
||||
},
|
||||
pushSoftState: function (url) {
|
||||
if (window.location != url) {
|
||||
window.history.pushState({ soft: true }, '', url);
|
||||
MovimTpl.currentPage = window.location.pathname;
|
||||
}
|
||||
},
|
||||
redirect: function (url) {
|
||||
window.location.href = url;
|
||||
},
|
||||
openInNew: function (url) {
|
||||
window.open(url, '_blank');
|
||||
},
|
||||
reload: function (uri, noHistory) {
|
||||
requestUri = new URL(uri.replace(/^\/\//, 'https://'));
|
||||
requestUri.searchParams.append('soft', 'true');
|
||||
|
||||
MovimTpl.loadingPage();
|
||||
|
||||
MovimRPC.fetchWithTimeout(requestUri.toString(), {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}).then(reponse => {
|
||||
reponse.text().then(value => {
|
||||
let page = JSON.parse(value);
|
||||
|
||||
const oldWidgetCss = Array.from(
|
||||
document.head.querySelectorAll('link[rel=stylesheet].widget')
|
||||
);
|
||||
|
||||
const cssPromises = page.widgetsCSS.map(url => new Promise((resolve) => {
|
||||
const css = document.createElement('link');
|
||||
css.setAttribute('rel', 'stylesheet');
|
||||
css.href = url;
|
||||
css.classList.add('widget');
|
||||
css.onload = resolve;
|
||||
css.onerror = resolve;
|
||||
document.head.appendChild(css);
|
||||
}));
|
||||
|
||||
Promise.all(cssPromises).then(() => {
|
||||
MovimTpl.finishedPage();
|
||||
|
||||
if (noHistory !== true) {
|
||||
MovimUtils.pushSoftState(uri);
|
||||
}
|
||||
|
||||
if (typeof MovimWebsocket !== 'undefined') {
|
||||
MovimWebsocket.clear();
|
||||
}
|
||||
|
||||
oldWidgetCss.forEach(e => e.remove());
|
||||
document.head.querySelectorAll('script[type=\'text/javascript\'].widget').forEach(e => e.remove());
|
||||
document.head.querySelectorAll('script[type=\'text/javascript\'].inline').forEach(e => e.remove());
|
||||
document.querySelectorAll('#endcommon ~ *').forEach(e => e.remove());
|
||||
|
||||
document.body.insertAdjacentHTML('beforeend', page.content);
|
||||
document.title = page.title;
|
||||
|
||||
const promises = page.widgetsScripts.map(script => new Promise((resolve) => {
|
||||
const js = document.createElement('script');
|
||||
js.src = script;
|
||||
js.setAttribute('type', 'text/javascript');
|
||||
js.onload = resolve;
|
||||
js.onerror = resolve;
|
||||
js.classList.add('widget');
|
||||
document.head.appendChild(js);
|
||||
}));
|
||||
|
||||
const inlineJs = document.createElement('script');
|
||||
inlineJs.classList.add('inline');
|
||||
inlineJs.innerHTML = page.inlineScripts;
|
||||
document.head.appendChild(inlineJs);
|
||||
|
||||
Promise.all(promises).then(() => {
|
||||
MovimEvents.triggerWindow('loaded', null);
|
||||
});
|
||||
});
|
||||
});
|
||||
}).catch(error => {
|
||||
document.body.classList.add('finished');
|
||||
});
|
||||
},
|
||||
reloadThis: function () {
|
||||
window.location.reload();
|
||||
},
|
||||
addClass: function (element, classname) {
|
||||
let el = document.querySelector(element);
|
||||
if (el) el.classList.add(classname);
|
||||
},
|
||||
removeClass: function (element, classname) {
|
||||
let el = document.querySelector(element);
|
||||
if (el) el.classList.remove(classname);
|
||||
},
|
||||
setDataItem: function (element, key, value) {
|
||||
let el = document.querySelector(element);
|
||||
if (el) {
|
||||
if (value) {
|
||||
el.dataset[key] = value;
|
||||
} else {
|
||||
delete el.dataset[key];
|
||||
}
|
||||
}
|
||||
},
|
||||
decodeHTMLEntities(text) {
|
||||
var textarea = document.createElement('textarea');
|
||||
textarea.innerHTML = text;
|
||||
return textarea.value;
|
||||
},
|
||||
copyToClipboard: function (text) {
|
||||
navigator.clipboard.writeText(text).catch(err => MovimUtils.logError(err));
|
||||
},
|
||||
htmlEscape: function (string) {
|
||||
return string
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
},
|
||||
enhanceArticlesContent: function () {
|
||||
document.querySelectorAll('article section > div video')
|
||||
.forEach(item => item.setAttribute('controls', 'controls'));
|
||||
|
||||
document.querySelectorAll('article section > div a:not(.innertag)')
|
||||
.forEach(link => link.setAttribute('target', '_blank'));
|
||||
|
||||
document.querySelectorAll('article section > div img')
|
||||
.forEach(img => {
|
||||
if (img.parentNode.localName != 'a') {
|
||||
var div = document.createElement('div');
|
||||
if (!img.parentNode.classList.contains('previewable')) {
|
||||
img.parentNode.insertBefore(div, img);
|
||||
div.classList.add('previewable');
|
||||
img.classList.add('active');
|
||||
img.addEventListener('click', () => Preview_ajaxHttpShow(img.src))
|
||||
|
||||
div.appendChild(img);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
urlParts: function () {
|
||||
var str = window.location.pathname.split('/');
|
||||
var page = str[1];
|
||||
|
||||
str.shift();
|
||||
str.shift();
|
||||
|
||||
str = str.map(param => decodeURIComponent(param));
|
||||
|
||||
return { 'page': page, 'params': str, 'hash': window.location.hash.substring(1) };
|
||||
},
|
||||
humanFileSize: function (bytes, si) {
|
||||
var thresh = si ? 1000 : 1024;
|
||||
if (Math.abs(bytes) < thresh) {
|
||||
return bytes + ' B';
|
||||
}
|
||||
var units = si
|
||||
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
||||
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
|
||||
var u = -1;
|
||||
do {
|
||||
bytes /= thresh;
|
||||
++u;
|
||||
} while (Math.abs(bytes) >= thresh && u < units.length - 1);
|
||||
return bytes.toFixed(1) + ' ' + units[u];
|
||||
},
|
||||
getOrientation: function (file, callback) {
|
||||
var testImageURL =
|
||||
'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' +
|
||||
'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' +
|
||||
'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' +
|
||||
'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' +
|
||||
'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' +
|
||||
'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' +
|
||||
'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' +
|
||||
'H/9k='
|
||||
|
||||
var img = document.createElement('img');
|
||||
img.onload = function () {
|
||||
// Check if the browser supports automatic image orientation:
|
||||
let orientation = img.width === 2 && img.height === 3;
|
||||
|
||||
if (orientation) {
|
||||
return callback(-1);
|
||||
} else {
|
||||
var reader = new FileReader();
|
||||
|
||||
reader.onload = function (e) {
|
||||
var view = new DataView(e.target.result);
|
||||
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
|
||||
var length = view.byteLength, offset = 2;
|
||||
|
||||
while (offset < length) {
|
||||
var marker = view.getUint16(offset, false);
|
||||
offset += 2;
|
||||
if (marker == 0xFFE1) {
|
||||
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
|
||||
|
||||
var little = view.getUint16(offset += 6, false) == 0x4949;
|
||||
offset += view.getUint32(offset + 4, little);
|
||||
|
||||
var tags = view.getUint16(offset, little);
|
||||
offset += 2;
|
||||
|
||||
for (var i = 0; i < tags; i++)
|
||||
if (view.getUint16(offset + (i * 12), little) == 0x0112)
|
||||
|
||||
return callback(view.getUint16(offset + (i * 12) + 8, little));
|
||||
}
|
||||
else if ((marker & 0xFF00) != 0xFF00) break;
|
||||
else offset += view.getUint16(offset, false);
|
||||
}
|
||||
|
||||
return callback(-1);
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
}
|
||||
}
|
||||
img.src = testImageURL
|
||||
},
|
||||
applyOrientation: function (ctx, orientation, width, height) {
|
||||
switch (orientation) {
|
||||
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
|
||||
case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
|
||||
case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
|
||||
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
|
||||
case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
|
||||
case 7: ctx.transform(0, -1, -1, 0, height, width); break;
|
||||
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
|
||||
default: ctx.transform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
},
|
||||
drawImageProp: function (ctx, img, x, y, w, h, offsetX, offsetY) {
|
||||
if (arguments.length === 2) {
|
||||
x = y = 0;
|
||||
w = ctx.canvas.width;
|
||||
h = ctx.canvas.height;
|
||||
}
|
||||
|
||||
// default offset is center
|
||||
offsetX = typeof offsetX === "number" ? offsetX : 0.5;
|
||||
offsetY = typeof offsetY === "number" ? offsetY : 0.5;
|
||||
|
||||
// keep bounds [0.0, 1.0]
|
||||
if (offsetX < 0) offsetX = 0;
|
||||
if (offsetY < 0) offsetY = 0;
|
||||
if (offsetX > 1) offsetX = 1;
|
||||
if (offsetY > 1) offsetY = 1;
|
||||
|
||||
var iw = img.width,
|
||||
ih = img.height,
|
||||
r = Math.min(w / iw, h / ih),
|
||||
nw = iw * r, // new prop. width
|
||||
nh = ih * r, // new prop. height
|
||||
cx, cy, cw, ch, ar = 1;
|
||||
|
||||
// decide which gap to fill
|
||||
if (nw < w) ar = w / nw;
|
||||
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // updated
|
||||
nw *= ar;
|
||||
nh *= ar;
|
||||
|
||||
// calc source rectangle
|
||||
cw = iw / (nw / w);
|
||||
ch = ih / (nh / h);
|
||||
|
||||
cx = (iw - cw) * offsetX;
|
||||
cy = (ih - ch) * offsetY;
|
||||
|
||||
// make sure source rectangle is valid
|
||||
if (cx < 0) cx = 0;
|
||||
if (cy < 0) cy = 0;
|
||||
if (cw > iw) cw = iw;
|
||||
if (ch > ih) ch = ih;
|
||||
|
||||
// fill image in dest. rectangle
|
||||
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
|
||||
},
|
||||
imageToHex: function (img) {
|
||||
const context = document.createElement("canvas").getContext("2d");
|
||||
context.drawImage(img, 0, 0, 1, 1);
|
||||
const i = context.getImageData(0, 0, 1, 1).data;
|
||||
return "#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1);
|
||||
},
|
||||
getEventLocation: function (e) {
|
||||
if (e.touches && e.touches.length == 1) {
|
||||
return { x: e.touches[0].clientX, y: e.touches[0].clientY }
|
||||
}
|
||||
else if (e.clientX && e.clientY) {
|
||||
return { x: e.clientX, y: e.clientY }
|
||||
}
|
||||
},
|
||||
base64ToBinary: function (base64) {
|
||||
return new Uint8Array(atob(base64).split('').map(x => x.charCodeAt(0)));
|
||||
},
|
||||
arrayBufferToBase64: function (ab) {
|
||||
return btoa((new Uint8Array(ab)).reduce((data, byte) => data + String.fromCharCode(byte), ''));
|
||||
},
|
||||
base64ToArrayBuffer: function (base64) {
|
||||
var binary_string = window.atob(base64);
|
||||
var len = binary_string.length;
|
||||
var bytes = new Uint8Array(len);
|
||||
for (var i = 0; i < len; i++) {
|
||||
bytes[i] = binary_string.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
},
|
||||
stringToArrayBuffer: function (string) {
|
||||
const bytes = new TextEncoder("utf-8").encode(string);
|
||||
return bytes.buffer;
|
||||
},
|
||||
arrayBufferToString: function (ab) {
|
||||
return new TextDecoder().decode(ab);
|
||||
},
|
||||
hexToArrayBuffer: function (hex) {
|
||||
const typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
|
||||
return typedArray.buffer;
|
||||
},
|
||||
appendArrayBuffer: function (buffer1, buffer2) {
|
||||
const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
|
||||
tmp.set(new Uint8Array(buffer1), 0);
|
||||
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
|
||||
return tmp.buffer;
|
||||
},
|
||||
range: function (start, end) {
|
||||
return Array.from({ length: end - start + 1 }, (_, i) => i)
|
||||
},
|
||||
linkify: function (inputText) {
|
||||
const replacePattern1 = /(^|[ ])(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])($|[ ])/gim;
|
||||
const replacePattern2 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
|
||||
|
||||
let replacedText = inputText.replace(replacePattern1, '<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>');
|
||||
replacedText = replacedText.replace(replacePattern2, '<a href="mailto:$1">$1</a>');
|
||||
|
||||
return replacedText;
|
||||
},
|
||||
logError: function (error) {
|
||||
console.log(error.name + ': ' + error.message);
|
||||
console.error(error);
|
||||
},
|
||||
};
|
||||
|
||||
/*
|
||||
* Set the li onclick event to the link and stop propagation, for accessinility purposes
|
||||
*/
|
||||
function listIconClick(event) {
|
||||
event.stopPropagation();
|
||||
let li = event.target.closest('li');
|
||||
if (li && li.onclick) {
|
||||
li.click();
|
||||
return;
|
||||
}
|
||||
|
||||
let span = event.target.closest('span.icon');
|
||||
if (span) span.click();
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
var MovimVisio = {
|
||||
id: null,
|
||||
|
||||
calling: false,
|
||||
|
||||
pc: null,
|
||||
|
||||
screenshareSid: null,
|
||||
screenshareSFUPc: null,
|
||||
|
||||
states: null,
|
||||
services: [],
|
||||
|
||||
localStream: null,
|
||||
localVideo: null,
|
||||
localAudio: null,
|
||||
screenSharing: null,
|
||||
|
||||
observer: null,
|
||||
|
||||
activeSpeakerIntervalId: null,
|
||||
|
||||
bundleRegex: 'a=group:(\\S+) (.+)',
|
||||
midRegex: 'a=mid:(.+)',
|
||||
|
||||
mouseMovement: null,
|
||||
mouseMovementTimeout: 5000,
|
||||
|
||||
startedAtTimer: null,
|
||||
|
||||
sfu: null,
|
||||
|
||||
load: function () {
|
||||
MovimVisio.localVideo = document.getElementById('local_video');
|
||||
|
||||
// Disable the video toggle by default
|
||||
MovimVisio.localVideo.classList.add('video_off');
|
||||
|
||||
MovimVisio.localVideo.addEventListener('loadeddata', () => {
|
||||
MovimVisio.localVideo.play()
|
||||
});
|
||||
|
||||
MovimVisio.screenSharing = document.getElementById('screen_sharing_video');
|
||||
MovimVisio.localAudio = document.getElementById('local_audio');
|
||||
},
|
||||
|
||||
init: function (fullJid, jid, id, withVideo, isMuji, sfuConference, contactName, contactAvatarUrl) {
|
||||
MovimVisio.id = id;
|
||||
|
||||
// Set a lock for the current browser (in case there's several others opened)
|
||||
localStorage.setItem('callId', id);
|
||||
localStorage.setItem('callJid', jid);
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
delete visio.dataset.type;
|
||||
visio.dataset.jid = jid;
|
||||
visio.dataset.muji = isMuji ? 'true' : 'false';
|
||||
|
||||
if (typeof sfuConference == 'string') {
|
||||
visio.dataset.muji = 'true'; // To use the Muji layout... without using Muji
|
||||
visio.dataset.sfu = 'true';
|
||||
visio.dataset.jid = sfuConference;
|
||||
|
||||
Visio_ajaxHttpPrepareInfo(sfuConference, true);
|
||||
MovimVisio.activeSpeakerIntervalId = setInterval(MovimJingles.checkActiveSpeaker, 1000);
|
||||
} else {
|
||||
Visio_ajaxHttpPrepareInfo(jid, isMuji);
|
||||
}
|
||||
|
||||
if (isMuji == true) {
|
||||
MovimVisio.mujiPublish(true);
|
||||
MovimVisio.activeSpeakerIntervalId = setInterval(MovimJingles.checkActiveSpeaker, 1000);
|
||||
} else {
|
||||
MovimJingles.initSession(jid, fullJid, id, contactName, contactAvatarUrl);
|
||||
|
||||
if (MovimVisio.id) {
|
||||
// Called
|
||||
Visio_ajaxProceed(fullJid, MovimVisio.id);
|
||||
} else {
|
||||
// Calling
|
||||
MovimVisio.id = crypto.randomUUID();
|
||||
localStorage.setItem('callId', MovimVisio.id);
|
||||
Visio_ajaxPropose(fullJid, MovimVisio.id, withVideo, (typeof sfuConference == 'string'));
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof sfuConference == 'string') {
|
||||
MovimVisio.sfu = jid;
|
||||
|
||||
let sfuParticipant = visio.querySelector('div.participant[data-jid="' + jid + '"]');
|
||||
if (sfuParticipant) {
|
||||
// Ugly but works for now
|
||||
sfuParticipant.remove();
|
||||
}
|
||||
|
||||
Visio_ajaxUpgradeCurrentCallToSFU(jid, sfuConference);
|
||||
}
|
||||
|
||||
visio.classList.add('movements');
|
||||
|
||||
Notif.setCallStatus(MovimVisio.states.in_call);
|
||||
|
||||
visio.addEventListener('mousemove', e => {
|
||||
clearTimeout(MovimVisio.mouseMovement);
|
||||
visio.classList.add('movements');
|
||||
|
||||
MovimVisio.mouseMovement = setTimeout(() => {
|
||||
visio.classList.remove('movements');
|
||||
}, MovimVisio.mouseMovementTimeout);
|
||||
})
|
||||
|
||||
if (typeof navigator.mediaDevices.getDisplayMedia == 'undefined') {
|
||||
document.querySelector('#screen_sharing').classList.add('hide');
|
||||
}
|
||||
|
||||
if (MovimVisio.startedAtTimer) {
|
||||
clearInterval(MovimVisio.startedAtTimer);
|
||||
}
|
||||
|
||||
setInterval(VisioUtils.updateStartedAtCounters, 1000);
|
||||
|
||||
Dialog_ajaxClear();
|
||||
Notif.snackbarClear();
|
||||
},
|
||||
|
||||
startScreenshareSFU: function () {
|
||||
if (!MovimVisio.screenSharing.srcObject) return;
|
||||
|
||||
const pc = new RTCPeerConnection({
|
||||
iceServers: MovimVisio.services,
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceCandidatePoolSize: 10
|
||||
});
|
||||
|
||||
MovimVisio.screenshareSid = crypto.randomUUID();
|
||||
MovimVisio.screenshareSFUPc = pc;
|
||||
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => {
|
||||
pc.addTrack(track, MovimVisio.screenSharing.srcObject);
|
||||
});
|
||||
|
||||
pc.onicecandidate = event => {
|
||||
if (event.candidate && event.candidate.candidate) {
|
||||
Visio_ajaxCandidate(MovimVisio.sfu, MovimVisio.screenshareSid, event.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
pc.createOffer()
|
||||
.then(offer => pc.setLocalDescription(offer))
|
||||
.then(() => Visio_ajaxSessionInitiate(MovimVisio.sfu, pc.localDescription, MovimVisio.screenshareSid, null))
|
||||
.catch(err => MovimUtils.logError(err));
|
||||
},
|
||||
|
||||
stopScreenshareSFU: function () {
|
||||
if (!MovimVisio.screenshareSFUPc) return;
|
||||
|
||||
Visio_ajaxTerminate(MovimVisio.sfu, MovimVisio.screenshareSid, 'success', false);
|
||||
|
||||
MovimVisio.screenshareSFUPc.close();
|
||||
MovimVisio.screenshareSFUPc = null;
|
||||
MovimVisio.screenshareSid = null;
|
||||
},
|
||||
|
||||
onScreenshareAcceptSDP: function (sdp) {
|
||||
if (!MovimVisio.screenshareSFUPc) return;
|
||||
|
||||
MovimVisio.screenshareSFUPc
|
||||
.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'answer' })
|
||||
.catch(err => MovimUtils.logError(err));
|
||||
},
|
||||
|
||||
onScreenshareCandidate: function (candidate, mid, mlineindex) {
|
||||
if (!MovimVisio.screenshareSFUPc) return;
|
||||
|
||||
MovimVisio.screenshareSFUPc.addIceCandidate(new RTCIceCandidate({
|
||||
'candidate': candidate.split(/\n/).filter(line => line.startsWith('a=candidate')).join('').substring(2),
|
||||
'sdpMid': mid,
|
||||
'sdpMLineIndex': mlineindex
|
||||
})).catch(error => MovimUtils.logError(error));
|
||||
},
|
||||
|
||||
mujiPublish: function (init) {
|
||||
let pc = new RTCPeerConnection({ 'iceServers': MovimVisio.services });
|
||||
|
||||
/**
|
||||
* Ugly heuristic because it is not possible to match the SDP mids with the tranceiver sender track ids...
|
||||
*/
|
||||
let id = 0;
|
||||
|
||||
MovimVisio.localStream.getTracks().forEach(track => {
|
||||
pc.addTrack(track, MovimVisio.localStream);
|
||||
id++;
|
||||
});
|
||||
|
||||
let screenIds = [];
|
||||
|
||||
if (MovimVisio.screenSharing.srcObject) {
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => {
|
||||
pc.addTrack(track);
|
||||
screenIds.push(id);
|
||||
id++;
|
||||
});
|
||||
}
|
||||
|
||||
pc.createOffer().then(function (offer) {
|
||||
if (MovimVisio.screenSharing.srcObject) {
|
||||
// XEP-0507: Jingle Content Category
|
||||
newMedias = offer.sdp.split('m=').map(media => {
|
||||
let mid = media.match(MovimVisio.midRegex);
|
||||
if (mid != null) {
|
||||
if (screenIds.includes(parseInt(mid[1]))) {
|
||||
return media + 'a=content:slides' + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return media;
|
||||
});
|
||||
|
||||
localDescription = newMedias.join('m=');
|
||||
offer.sdp = localDescription;
|
||||
}
|
||||
|
||||
Visio_ajaxMujiPublish(MovimVisio.id, offer, init);
|
||||
pc.close();
|
||||
});
|
||||
},
|
||||
|
||||
setStates: function (states) {
|
||||
MovimVisio.states = states;
|
||||
},
|
||||
|
||||
setServices: function (services) {
|
||||
MovimVisio.services = services;
|
||||
},
|
||||
|
||||
getUserMedia: function (withVideo) {
|
||||
MovimVisio.load();
|
||||
|
||||
let lobby = document.querySelector('#visio_lobby');
|
||||
|
||||
if (lobby) {
|
||||
VisioUtils.disableLobbyCallButton();
|
||||
}
|
||||
|
||||
MovimTpl.loadingPage();
|
||||
|
||||
return navigator.mediaDevices.getUserMedia(VisioUtils.getConstraints(withVideo)).then(stream => {
|
||||
MovimTpl.finishedPage();
|
||||
|
||||
MovimVisio.localStream = stream;
|
||||
|
||||
if (lobby) {
|
||||
lobby.classList.add('configure');
|
||||
} else if (MovimVisio.localAudio.srcObject == null) {
|
||||
Visio_ajaxClear();
|
||||
return;
|
||||
}
|
||||
|
||||
stream.getTracks().forEach(track => {
|
||||
if (lobby) {
|
||||
VisioUtils.enableLobbyCallButton();
|
||||
}
|
||||
|
||||
if (track.kind == 'audio' && MovimVisio.localAudio && MovimVisio.localAudio.srcObject == null /* In case we're just adding the video */) {
|
||||
MovimVisio.localAudio.srcObject = stream;
|
||||
} else if (withVideo && track.kind === 'video') {
|
||||
MovimVisio.localVideo.srcObject = stream;
|
||||
|
||||
// Toggle the video on
|
||||
MovimVisio.localVideo.classList.remove('video_off');
|
||||
document.querySelector('#toggle_video i').innerText = 'videocam';
|
||||
|
||||
if (lobby) {
|
||||
let cameraPreview = lobby.querySelector('video#camera_preview');
|
||||
cameraPreview.addEventListener('loadeddata', () => cameraPreview.play());
|
||||
cameraPreview.srcObject = stream;
|
||||
cameraPreview.disablePictureInPicture = true;
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
VisioUtils.handleAudio();
|
||||
|
||||
if (lobby) {
|
||||
navigator.mediaDevices.enumerateDevices().then(devices => MovimVisio.gotDevices(withVideo, devices));
|
||||
}
|
||||
}, (e) => {
|
||||
MovimTpl.finishedPage();
|
||||
});
|
||||
},
|
||||
|
||||
gotDevices: function (withVideo, devicesInfo) {
|
||||
microphoneFound = false;
|
||||
cameraFound = false;
|
||||
|
||||
let microphoneSelect = document.querySelector('select[name=default_microphone]');
|
||||
microphoneSelect.onchange = (e) => {
|
||||
localStorage.defaultMicrophone = e.target.value;
|
||||
MovimVisio.getUserMedia(withVideo);
|
||||
};
|
||||
microphoneSelect.innerText = '';
|
||||
|
||||
VisioUtils.handleAudio();
|
||||
|
||||
let cameraSelect = document.querySelector('select[name=default_camera]');
|
||||
|
||||
if (cameraSelect) {
|
||||
cameraSelect.addEventListener('change', e => {
|
||||
localStorage.defaultCamera = e.target.value;
|
||||
|
||||
let cameraPreview = document.querySelector('video#camera_preview');
|
||||
|
||||
if (cameraPreview.srcObject) {
|
||||
cameraPreview.srcObject.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
|
||||
cameraPreview.srcObject = null;
|
||||
|
||||
MovimVisio.getUserMedia(withVideo);
|
||||
});
|
||||
cameraSelect.innerText = '';
|
||||
}
|
||||
|
||||
for (const deviceInfo of devicesInfo) {
|
||||
if (deviceInfo.kind === 'audioinput') {
|
||||
const option = document.createElement('option');
|
||||
option.value = deviceInfo.deviceId;
|
||||
option.text = deviceInfo.label || `Microphone ${microphoneSelect.length + 1}`;
|
||||
|
||||
if (deviceInfo.deviceId == localStorage.defaultMicrophone) {
|
||||
option.selected = true;
|
||||
microphoneFound = true;
|
||||
}
|
||||
|
||||
microphoneSelect.appendChild(option);
|
||||
}
|
||||
|
||||
if (withVideo && deviceInfo.kind === 'videoinput') {
|
||||
const option = document.createElement('option');
|
||||
option.value = deviceInfo.deviceId;
|
||||
option.text = deviceInfo.label || `Camera ${microphoneSelect.length + 1}`;
|
||||
|
||||
if (deviceInfo.deviceId == localStorage.defaultCamera) {
|
||||
option.selected = true;
|
||||
cameraFound = true;
|
||||
}
|
||||
|
||||
// Sometimes we can have two devices with the same id
|
||||
if (!cameraSelect.querySelector('option[value="' + deviceInfo.deviceId + '"]')) {
|
||||
cameraSelect.appendChild(option);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (microphoneFound == false) {
|
||||
localStorage.defaultMicrophone = microphoneSelect.value;
|
||||
}
|
||||
|
||||
if (withVideo && cameraFound == false) {
|
||||
localStorage.defaultCamera = cameraSelect.value;
|
||||
}
|
||||
},
|
||||
|
||||
clear: function () {
|
||||
MovimTpl.finishedPage();
|
||||
|
||||
MovimVisio.id = null;
|
||||
MovimVisio.sfu = null;
|
||||
|
||||
Notif.setCallStatus(null);
|
||||
|
||||
clearInterval(MovimVisio.activeSpeakerIntervalId);
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
//delete visio.dataset.type;
|
||||
delete visio.dataset.jid;
|
||||
delete visio.dataset.muji;
|
||||
delete visio.dataset.sfu;
|
||||
|
||||
if (document.fullscreenElement) {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
|
||||
VisioUtils.stopAudio();
|
||||
|
||||
if (MovimVisio.localAudio) {
|
||||
let stream = MovimVisio.localAudio.srcObject;
|
||||
|
||||
if (stream) {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
stream = null;
|
||||
}
|
||||
|
||||
MovimVisio.localAudio.srcObject = null;
|
||||
}
|
||||
|
||||
if (MovimVisio.localVideo) {
|
||||
let stream = MovimVisio.localVideo.srcObject;
|
||||
|
||||
if (stream) {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
stream = null;
|
||||
}
|
||||
|
||||
MovimVisio.localVideo.srcObject = null;
|
||||
}
|
||||
|
||||
if (MovimVisio.localStream) {
|
||||
MovimVisio.localStream.getTracks().forEach(function (track) {
|
||||
track.stop();
|
||||
});
|
||||
MovimVisio.localStream = null;
|
||||
}
|
||||
|
||||
VisioUtils.disableScreenSharing();
|
||||
|
||||
MovimVisio.localAudio = null;
|
||||
MovimVisio.localVideo = null;
|
||||
MovimVisio.screenSharing = null;
|
||||
},
|
||||
|
||||
moveToChat: function (jid) {
|
||||
if (MovimVisio.observer != null) {
|
||||
MovimVisio.observer.disconnect();
|
||||
}
|
||||
|
||||
// SFU case
|
||||
if (MovimVisio.sfu != null) {
|
||||
let visio = document.querySelector('#visio');
|
||||
jid = visio.dataset.jid;
|
||||
}
|
||||
|
||||
var parts = MovimUtils.urlParts();
|
||||
|
||||
if ((parts.page == 'chat' && parts.params[0] == jid)
|
||||
|| (parts.page == 'space' && parts.params[2] == jid)) {
|
||||
const visio = document.getElementById('visio');
|
||||
const body = document.body;
|
||||
|
||||
document.querySelector('#chat_widget header').after(visio);
|
||||
Chat.scrollRestore();
|
||||
|
||||
const callback = (mutationList, observer) => {
|
||||
if (!document.getElementById('visio')) {
|
||||
document.getElementById('endcommon').before(visio);
|
||||
}
|
||||
};
|
||||
|
||||
MovimVisio.observer = new MutationObserver(callback);
|
||||
MovimVisio.observer.observe(body, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
callStop: function (id, jid) {
|
||||
localStorage.removeItem('callId');
|
||||
localStorage.removeItem('callJid');
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof Visio_ajaxHttpGetStates == 'function') {
|
||||
Visio_ajaxHttpGetStates();
|
||||
}
|
||||
|
||||
if (typeof MovimWebsocket != 'undefined') {
|
||||
MovimWebsocket.attach(() => {
|
||||
if (MovimVisio.services.length == 0 && typeof Visio_ajaxResolveServices == 'function') {
|
||||
Visio_ajaxResolveServices();
|
||||
Visio_ajaxCheckStatus(localStorage.getItem('callId'), localStorage.getItem('callJid'));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* Movim Websocket
|
||||
*
|
||||
* This file define the websocket behaviour and handle its connection
|
||||
*/
|
||||
|
||||
WebSocket.prototype.unregister = function () {
|
||||
this.send(JSON.stringify({ 'func': 'unregister' }));
|
||||
};
|
||||
|
||||
WebSocket.prototype.register = function (host) {
|
||||
this.send(JSON.stringify({ 'func': 'register', 'host': host }));
|
||||
};
|
||||
|
||||
/**
|
||||
* Short functions
|
||||
*/
|
||||
function MWSs(widget, func, params) {
|
||||
MovimWebsocket.send(widget, func, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Definition of the MovimWebsocket object
|
||||
* @param string error
|
||||
*/
|
||||
|
||||
var MovimWebsocket = {
|
||||
connection: null,
|
||||
initiated: [], // Launched when the socket is connecting or reconnecting
|
||||
attached: [], // Launched when the socket is connected to the daemon
|
||||
started: [], // Launched when the linker is started
|
||||
registered: [], // Launched when the linker is connected to XMPP
|
||||
reconnectTimeout: null,
|
||||
attempts: 1,
|
||||
pong: false,
|
||||
closed: false,
|
||||
statusBar: null,
|
||||
|
||||
launchAttached: function () {
|
||||
// We hide the Websocket error
|
||||
MovimWebsocket.statusBar.classList.add('hide');
|
||||
|
||||
for (var i = 0; i < MovimWebsocket.attached.length; i++) {
|
||||
MovimWebsocket.attached[i]();
|
||||
}
|
||||
},
|
||||
|
||||
launchRegistered: function () {
|
||||
for (var i = 0; i < MovimWebsocket.registered.length; i++) {
|
||||
MovimWebsocket.registered[i]();
|
||||
}
|
||||
},
|
||||
|
||||
launchStarted: function () {
|
||||
for (var i = 0; i < MovimWebsocket.started.length; i++) {
|
||||
MovimWebsocket.started[i]();
|
||||
}
|
||||
},
|
||||
|
||||
launchInitiated: function () {
|
||||
for (var i = 0; i < MovimWebsocket.initiated.length; i++) {
|
||||
MovimWebsocket.initiated[i]();
|
||||
}
|
||||
},
|
||||
|
||||
resolvePushEndpoint: async function () {
|
||||
if (!('serviceWorker' in navigator)) return null;
|
||||
|
||||
const registration = await navigator.serviceWorker.getRegistration(SW_URI);
|
||||
if (!registration || !registration.pushManager) return null;
|
||||
|
||||
const pushSubscription = await registration.pushManager.getSubscription();
|
||||
if (!pushSubscription) return null;
|
||||
|
||||
return pushSubscription.endpoint;
|
||||
},
|
||||
|
||||
init: async function () {
|
||||
var uri = 'ws:' + BASE_URI + 'ws/';
|
||||
|
||||
if (window.location.protocol === "https:") {
|
||||
var uri = 'wss:' + BASE_URI + 'ws/';
|
||||
}
|
||||
|
||||
if (this.connection !== null) {
|
||||
this.connection.onclose = null;
|
||||
this.connection.close();
|
||||
}
|
||||
|
||||
const pushEndpoint = await this.resolvePushEndpoint();
|
||||
|
||||
if (pushEndpoint) {
|
||||
uri += '?push=' + encodeURIComponent(pushEndpoint);
|
||||
}
|
||||
|
||||
this.connection = new WebSocket(uri);
|
||||
|
||||
this.connection.onopen = function (e) {
|
||||
console.log("Connection established!");
|
||||
|
||||
MovimWebsocket.attempts = 1;
|
||||
clearTimeout(MovimWebsocket.reconnectTimeout);
|
||||
|
||||
MovimWebsocket.launchAttached();
|
||||
};
|
||||
|
||||
this.connection.onmessage = function (e) {
|
||||
var obj = JSON.parse(e.data);
|
||||
|
||||
if (obj != null) {
|
||||
if (obj.func == 'registered') {
|
||||
MovimWebsocket.launchRegistered();
|
||||
}
|
||||
|
||||
if (obj.func == 'started') {
|
||||
// If the linker was started but we're not on the login page
|
||||
if (!['login', 'account', 'register', 'tag', 'about', 'community'].includes(MovimUtils.urlParts().page)) {
|
||||
MovimUtils.disconnect();
|
||||
} else {
|
||||
MovimWebsocket.launchStarted();
|
||||
}
|
||||
}
|
||||
|
||||
if (obj.func == 'disconnected') {
|
||||
MovimUtils.disconnect();
|
||||
}
|
||||
|
||||
if (obj.func == 'pong') {
|
||||
MovimWebsocket.pong = true;
|
||||
}
|
||||
|
||||
MovimRPC.handle(obj);
|
||||
}
|
||||
};
|
||||
|
||||
this.connection.onclose = function (e) {
|
||||
console.log("Connection closed by the server or session closed");
|
||||
|
||||
if (e.code == 1008) {
|
||||
// The server closed the connection and asked to keep it this way
|
||||
this.closed = true;
|
||||
MovimWebsocket.statusBar.classList.remove('hide', 'connect');
|
||||
MovimWebsocket.connection.close();
|
||||
} else if (e.code == 1006) {
|
||||
MovimWebsocket.reconnect();
|
||||
} else if (e.code == 1000) {
|
||||
MovimUtils.disconnect();
|
||||
}
|
||||
};
|
||||
|
||||
this.connection.onerror = function (e) {
|
||||
console.log("Connection error!");
|
||||
|
||||
// We show the Websocket error
|
||||
MovimWebsocket.statusBar.classList.remove('hide', 'connect');
|
||||
MovimWebsocket.reconnect();
|
||||
|
||||
// We prevent the onclose launch
|
||||
this.onclose = null;
|
||||
};
|
||||
},
|
||||
|
||||
send: function (widget, func, params) {
|
||||
if (this.connection && this.connection.readyState == 1) {
|
||||
var body = {
|
||||
'w': widget,
|
||||
'f': func
|
||||
};
|
||||
|
||||
if (params) body.p = params;
|
||||
this.connection.send(JSON.stringify(
|
||||
{ 'func': 'message', 'b': body }
|
||||
));
|
||||
}
|
||||
},
|
||||
|
||||
attach: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.attached.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
register: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.registered.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
start: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.started.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
initiate: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.initiated.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
clearAttached: function () {
|
||||
this.attached = [];
|
||||
},
|
||||
|
||||
clearInitiated: function () {
|
||||
this.initiated = [];
|
||||
},
|
||||
|
||||
clear: function () {
|
||||
this.clearAttached();
|
||||
this.clearInitiated();
|
||||
},
|
||||
|
||||
unregister: function () {
|
||||
this.connection.unregister();
|
||||
},
|
||||
|
||||
reconnect: function () {
|
||||
var interval = MovimWebsocket.generateInterval();
|
||||
console.log("Try to reconnect");
|
||||
|
||||
MovimWebsocket.reconnectTimeout = setTimeout(function () {
|
||||
// We've tried to reconnect so increment the attempts by 1
|
||||
MovimWebsocket.attempts++;
|
||||
|
||||
// Show the reconnect state
|
||||
MovimWebsocket.statusBar.classList.remove('hide');
|
||||
MovimWebsocket.statusBar.classList.add('connect');
|
||||
|
||||
// Connection has closed so try to reconnect every x seconds.
|
||||
MovimWebsocket.init();
|
||||
}, interval);
|
||||
},
|
||||
|
||||
generateInterval: function () {
|
||||
var maxInterval = (Math.pow(2, MovimWebsocket.attempts) - 1) * 1000;
|
||||
|
||||
if (maxInterval > 10 * 1000) {
|
||||
maxInterval = 10 * 1000; // If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
|
||||
}
|
||||
|
||||
// generate the interval to a random number between 0 and the maxInterval determined from above
|
||||
return Math.random() * maxInterval;
|
||||
}
|
||||
}
|
||||
|
||||
MovimEvents.registerWindow('offline', 'movimwebsocket', () => {
|
||||
console.log('offline');
|
||||
MovimWebsocket.connection.onerror();
|
||||
});
|
||||
|
||||
MovimEvents.registerWindow('online', 'movimwebsocket', () => {
|
||||
MovimWebsocket.statusBar.classList.remove('hide');
|
||||
MovimWebsocket.statusBar.classList.add('connect');
|
||||
|
||||
MovimWebsocket.launchInitiated();
|
||||
MovimWebsocket.init();
|
||||
});
|
||||
|
||||
window.onbeforeunload = function () {
|
||||
if (MovimWebsocket.connection !== null) {
|
||||
MovimWebsocket.connection.onclose = function () { }; // disable onclose handler first
|
||||
MovimWebsocket.connection.close()
|
||||
}
|
||||
};
|
||||
|
||||
// If the Websocket was closed after some inactivity, we try to reconnect
|
||||
MovimEvents.registerWindow('focus', 'movimwebsocket', () => {
|
||||
if (MovimWebsocket.connection !== null
|
||||
&& MovimWebsocket.connection.readyState > 1) {
|
||||
|
||||
// Show the reconnect state
|
||||
MovimWebsocket.statusBar.classList.remove('hide');
|
||||
MovimWebsocket.statusBar.classList.add('connect');
|
||||
|
||||
MovimWebsocket.init();
|
||||
}
|
||||
});
|
||||
|
||||
MovimEvents.registerWindow('loaded', 'movimwebsocket', () => {
|
||||
MovimWebsocket.statusBar = document.getElementById('status_websocket');
|
||||
MovimWebsocket.launchInitiated();
|
||||
MovimWebsocket.init();
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Encodes an RGBA image to a ThumbHash. RGB should not be premultiplied by A.
|
||||
*
|
||||
* @param w The width of the input image. Must be ≤100px.
|
||||
* @param h The height of the input image. Must be ≤100px.
|
||||
* @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
|
||||
* @returns The ThumbHash as a Uint8Array.
|
||||
*/
|
||||
function rgbaToThumbHash(w, h, rgba) {
|
||||
// Encoding an image larger than 100x100 is slow with no benefit
|
||||
if (w > 100 || h > 100) throw new Error(`${w}x${h} doesn't fit in 100x100`)
|
||||
let { PI, round, max, cos, abs } = Math
|
||||
|
||||
// Determine the average color
|
||||
let avg_r = 0, avg_g = 0, avg_b = 0, avg_a = 0
|
||||
for (let i = 0, j = 0; i < w * h; i++, j += 4) {
|
||||
let alpha = rgba[j + 3] / 255
|
||||
avg_r += alpha / 255 * rgba[j]
|
||||
avg_g += alpha / 255 * rgba[j + 1]
|
||||
avg_b += alpha / 255 * rgba[j + 2]
|
||||
avg_a += alpha
|
||||
}
|
||||
if (avg_a) {
|
||||
avg_r /= avg_a
|
||||
avg_g /= avg_a
|
||||
avg_b /= avg_a
|
||||
}
|
||||
|
||||
let hasAlpha = avg_a < w * h
|
||||
let l_limit = hasAlpha ? 5 : 7 // Use fewer luminance bits if there's alpha
|
||||
let lx = max(1, round(l_limit * w / max(w, h)))
|
||||
let ly = max(1, round(l_limit * h / max(w, h)))
|
||||
let l = [] // luminance
|
||||
let p = [] // yellow - blue
|
||||
let q = [] // red - green
|
||||
let a = [] // alpha
|
||||
|
||||
// Convert the image from RGBA to LPQA (composite atop the average color)
|
||||
for (let i = 0, j = 0; i < w * h; i++, j += 4) {
|
||||
let alpha = rgba[j + 3] / 255
|
||||
let r = avg_r * (1 - alpha) + alpha / 255 * rgba[j]
|
||||
let g = avg_g * (1 - alpha) + alpha / 255 * rgba[j + 1]
|
||||
let b = avg_b * (1 - alpha) + alpha / 255 * rgba[j + 2]
|
||||
l[i] = (r + g + b) / 3
|
||||
p[i] = (r + g) / 2 - b
|
||||
q[i] = r - g
|
||||
a[i] = alpha
|
||||
}
|
||||
|
||||
// Encode using the DCT into DC (constant) and normalized AC (varying) terms
|
||||
let encodeChannel = (channel, nx, ny) => {
|
||||
let dc = 0, ac = [], scale = 0, fx = []
|
||||
for (let cy = 0; cy < ny; cy++) {
|
||||
for (let cx = 0; cx * ny < nx * (ny - cy); cx++) {
|
||||
let f = 0
|
||||
for (let x = 0; x < w; x++)
|
||||
fx[x] = cos(PI / w * cx * (x + 0.5))
|
||||
for (let y = 0; y < h; y++)
|
||||
for (let x = 0, fy = cos(PI / h * cy * (y + 0.5)); x < w; x++)
|
||||
f += channel[x + y * w] * fx[x] * fy
|
||||
f /= w * h
|
||||
if (cx || cy) {
|
||||
ac.push(f)
|
||||
scale = max(scale, abs(f))
|
||||
} else {
|
||||
dc = f
|
||||
}
|
||||
}
|
||||
}
|
||||
if (scale)
|
||||
for (let i = 0; i < ac.length; i++)
|
||||
ac[i] = 0.5 + 0.5 / scale * ac[i]
|
||||
return [dc, ac, scale]
|
||||
}
|
||||
let [l_dc, l_ac, l_scale] = encodeChannel(l, max(3, lx), max(3, ly))
|
||||
let [p_dc, p_ac, p_scale] = encodeChannel(p, 3, 3)
|
||||
let [q_dc, q_ac, q_scale] = encodeChannel(q, 3, 3)
|
||||
let [a_dc, a_ac, a_scale] = hasAlpha ? encodeChannel(a, 5, 5) : []
|
||||
|
||||
// Write the constants
|
||||
let isLandscape = w > h
|
||||
let header24 = round(63 * l_dc) | (round(31.5 + 31.5 * p_dc) << 6) | (round(31.5 + 31.5 * q_dc) << 12) | (round(31 * l_scale) << 18) | (hasAlpha << 23)
|
||||
let header16 = (isLandscape ? ly : lx) | (round(63 * p_scale) << 3) | (round(63 * q_scale) << 9) | (isLandscape << 15)
|
||||
let hash = [header24 & 255, (header24 >> 8) & 255, header24 >> 16, header16 & 255, header16 >> 8]
|
||||
let ac_start = hasAlpha ? 6 : 5
|
||||
let ac_index = 0
|
||||
if (hasAlpha) hash.push(round(15 * a_dc) | (round(15 * a_scale) << 4))
|
||||
|
||||
// Write the varying factors
|
||||
for (let ac of hasAlpha ? [l_ac, p_ac, q_ac, a_ac] : [l_ac, p_ac, q_ac])
|
||||
for (let f of ac)
|
||||
hash[ac_start + (ac_index >> 1)] |= round(15 * f) << ((ac_index++ & 1) << 2)
|
||||
return new Uint8Array(hash)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a ThumbHash to an RGBA image. RGB is not be premultiplied by A.
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns The width, height, and pixels of the rendered placeholder image.
|
||||
*/
|
||||
function thumbHashToRGBA(hash) {
|
||||
let { PI, min, max, cos, round } = Math
|
||||
|
||||
// Read the constants
|
||||
let header24 = hash[0] | (hash[1] << 8) | (hash[2] << 16)
|
||||
let header16 = hash[3] | (hash[4] << 8)
|
||||
let l_dc = (header24 & 63) / 63
|
||||
let p_dc = ((header24 >> 6) & 63) / 31.5 - 1
|
||||
let q_dc = ((header24 >> 12) & 63) / 31.5 - 1
|
||||
let l_scale = ((header24 >> 18) & 31) / 31
|
||||
let hasAlpha = header24 >> 23
|
||||
let p_scale = ((header16 >> 3) & 63) / 63
|
||||
let q_scale = ((header16 >> 9) & 63) / 63
|
||||
let isLandscape = header16 >> 15
|
||||
let lx = max(3, isLandscape ? hasAlpha ? 5 : 7 : header16 & 7)
|
||||
let ly = max(3, isLandscape ? header16 & 7 : hasAlpha ? 5 : 7)
|
||||
let a_dc = hasAlpha ? (hash[5] & 15) / 15 : 1
|
||||
let a_scale = (hash[5] >> 4) / 15
|
||||
|
||||
// Read the varying factors (boost saturation by 1.25x to compensate for quantization)
|
||||
let ac_start = hasAlpha ? 6 : 5
|
||||
let ac_index = 0
|
||||
let decodeChannel = (nx, ny, scale) => {
|
||||
let ac = []
|
||||
for (let cy = 0; cy < ny; cy++)
|
||||
for (let cx = cy ? 0 : 1; cx * ny < nx * (ny - cy); cx++)
|
||||
ac.push((((hash[ac_start + (ac_index >> 1)] >> ((ac_index++ & 1) << 2)) & 15) / 7.5 - 1) * scale)
|
||||
return ac
|
||||
}
|
||||
let l_ac = decodeChannel(lx, ly, l_scale)
|
||||
let p_ac = decodeChannel(3, 3, p_scale * 1.25)
|
||||
let q_ac = decodeChannel(3, 3, q_scale * 1.25)
|
||||
let a_ac = hasAlpha && decodeChannel(5, 5, a_scale)
|
||||
|
||||
// Decode using the DCT into RGB
|
||||
let ratio = thumbHashToApproximateAspectRatio(hash)
|
||||
let w = round(ratio > 1 ? 32 : 32 * ratio)
|
||||
let h = round(ratio > 1 ? 32 / ratio : 32)
|
||||
let rgba = new Uint8Array(w * h * 4), fx = [], fy = []
|
||||
for (let y = 0, i = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++, i += 4) {
|
||||
let l = l_dc, p = p_dc, q = q_dc, a = a_dc
|
||||
|
||||
// Precompute the coefficients
|
||||
for (let cx = 0, n = max(lx, hasAlpha ? 5 : 3); cx < n; cx++)
|
||||
fx[cx] = cos(PI / w * (x + 0.5) * cx)
|
||||
for (let cy = 0, n = max(ly, hasAlpha ? 5 : 3); cy < n; cy++)
|
||||
fy[cy] = cos(PI / h * (y + 0.5) * cy)
|
||||
|
||||
// Decode L
|
||||
for (let cy = 0, j = 0; cy < ly; cy++)
|
||||
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx * ly < lx * (ly - cy); cx++, j++)
|
||||
l += l_ac[j] * fx[cx] * fy2
|
||||
|
||||
// Decode P and Q
|
||||
for (let cy = 0, j = 0; cy < 3; cy++) {
|
||||
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 3 - cy; cx++, j++) {
|
||||
let f = fx[cx] * fy2
|
||||
p += p_ac[j] * f
|
||||
q += q_ac[j] * f
|
||||
}
|
||||
}
|
||||
|
||||
// Decode A
|
||||
if (hasAlpha)
|
||||
for (let cy = 0, j = 0; cy < 5; cy++)
|
||||
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 5 - cy; cx++, j++)
|
||||
a += a_ac[j] * fx[cx] * fy2
|
||||
|
||||
// Convert to RGB
|
||||
let b = l - 2 / 3 * p
|
||||
let r = (3 * l - b + q) / 2
|
||||
let g = r - q
|
||||
rgba[i] = max(0, 255 * min(1, r))
|
||||
rgba[i + 1] = max(0, 255 * min(1, g))
|
||||
rgba[i + 2] = max(0, 255 * min(1, b))
|
||||
rgba[i + 3] = max(0, 255 * min(1, a))
|
||||
}
|
||||
}
|
||||
return { w, h, rgba }
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the average color from a ThumbHash. RGB is not be premultiplied by A.
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns The RGBA values for the average color. Each value ranges from 0 to 1.
|
||||
*/
|
||||
function thumbHashToAverageRGBA(hash) {
|
||||
let { min, max } = Math
|
||||
let header = hash[0] | (hash[1] << 8) | (hash[2] << 16)
|
||||
let l = (header & 63) / 63
|
||||
let p = ((header >> 6) & 63) / 31.5 - 1
|
||||
let q = ((header >> 12) & 63) / 31.5 - 1
|
||||
let hasAlpha = header >> 23
|
||||
let a = hasAlpha ? (hash[5] & 15) / 15 : 1
|
||||
let b = l - 2 / 3 * p
|
||||
let r = (3 * l - b + q) / 2
|
||||
let g = r - q
|
||||
return {
|
||||
r: max(0, min(1, r)),
|
||||
g: max(0, min(1, g)),
|
||||
b: max(0, min(1, b)),
|
||||
a
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the approximate aspect ratio of the original image.
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns The approximate aspect ratio (i.e. width / height).
|
||||
*/
|
||||
function thumbHashToApproximateAspectRatio(hash) {
|
||||
let header = hash[3]
|
||||
let hasAlpha = hash[2] & 0x80
|
||||
let isLandscape = hash[4] & 0x80
|
||||
let lx = isLandscape ? hasAlpha ? 5 : 7 : header & 7
|
||||
let ly = isLandscape ? header & 7 : hasAlpha ? 5 : 7
|
||||
return lx / ly
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes an RGBA image to a PNG data URL. RGB should not be premultiplied by
|
||||
* A. This is optimized for speed and simplicity and does not optimize for size
|
||||
* at all. This doesn't do any compression (all values are stored uncompressed).
|
||||
*
|
||||
* @param w The width of the input image. Must be ≤100px.
|
||||
* @param h The height of the input image. Must be ≤100px.
|
||||
* @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
|
||||
* @returns A data URL containing a PNG for the input image.
|
||||
*/
|
||||
function rgbaToDataURL(w, h, rgba) {
|
||||
let row = w * 4 + 1
|
||||
let idat = 6 + h * (5 + row)
|
||||
let bytes = [
|
||||
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0,
|
||||
w >> 8, w & 255, 0, 0, h >> 8, h & 255, 8, 6, 0, 0, 0, 0, 0, 0, 0,
|
||||
idat >>> 24, (idat >> 16) & 255, (idat >> 8) & 255, idat & 255,
|
||||
73, 68, 65, 84, 120, 1
|
||||
]
|
||||
let table = [
|
||||
0, 498536548, 997073096, 651767980, 1994146192, 1802195444, 1303535960,
|
||||
1342533948, -306674912, -267414716, -690576408, -882789492, -1687895376,
|
||||
-2032938284, -1609899400, -1111625188
|
||||
]
|
||||
let a = 1, b = 0
|
||||
for (let y = 0, i = 0, end = row - 1; y < h; y++, end += row - 1) {
|
||||
bytes.push(y + 1 < h ? 0 : 1, row & 255, row >> 8, ~row & 255, (row >> 8) ^ 255, 0)
|
||||
for (b = (b + a) % 65521; i < end; i++) {
|
||||
let u = rgba[i] & 255
|
||||
bytes.push(u)
|
||||
a = (a + u) % 65521
|
||||
b = (b + a) % 65521
|
||||
}
|
||||
}
|
||||
bytes.push(
|
||||
b >> 8, b & 255, a >> 8, a & 255, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130
|
||||
)
|
||||
for (let [start, end] of [[12, 29], [37, 41 + idat]]) {
|
||||
let c = ~0
|
||||
for (let i = start; i < end; i++) {
|
||||
c ^= bytes[i]
|
||||
c = (c >>> 4) ^ table[c & 15]
|
||||
c = (c >>> 4) ^ table[c & 15]
|
||||
}
|
||||
c = ~c
|
||||
bytes[end++] = c >>> 24
|
||||
bytes[end++] = (c >> 16) & 255
|
||||
bytes[end++] = (c >> 8) & 255
|
||||
bytes[end++] = c & 255
|
||||
}
|
||||
return 'data:image/png;base64,' + btoa(String.fromCharCode(...bytes))
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a ThumbHash to a PNG data URL. This is a convenience function that
|
||||
* just calls "thumbHashToRGBA" followed by "rgbaToDataURL".
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns A data URL containing a PNG for the rendered ThumbHash.
|
||||
*/
|
||||
function thumbHashToDataURL(hash) {
|
||||
let image = thumbHashToRGBA(hash)
|
||||
return rgbaToDataURL(image.w, image.h, image.rgba)
|
||||
}
|
||||
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 71 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 18 KiB |