aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--.helix/languages.toml3
-rw-r--r--Cargo.toml36
-rw-r--r--LICENSE661
-rw-r--r--README.md3
-rw-r--r--filamento/.cargo/config.toml19
-rw-r--r--filamento/.gitignore2
-rw-r--r--filamento/Cargo.toml76
-rw-r--r--filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0bin0 -> 8623 bytes
-rw-r--r--filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377bin0 -> 6364 bytes
-rw-r--r--filamento/files/britney_starbies.jpgbin0 -> 11674 bytes
-rw-r--r--filamento/migrations/1.sql (renamed from filamento/migrations/20240113011930_luz.sql)34
-rw-r--r--filamento/src/chat.rs64
-rw-r--r--filamento/src/db.rs2419
-rw-r--r--filamento/src/error.rs105
-rw-r--r--filamento/src/files.rs25
-rw-r--r--filamento/src/files/opfs.rs128
-rw-r--r--filamento/src/lib.rs43
-rw-r--r--filamento/src/logic/local_only.rs14
-rw-r--r--filamento/src/logic/offline.rs18
-rw-r--r--filamento/src/logic/online.rs17
-rw-r--r--filamento/src/logic/process_stanza.rs23
-rw-r--r--filamento/src/presence.rs30
-rw-r--r--filamento/src/roster.rs86
-rw-r--r--filamento/src/user.rs4
-rw-r--r--jid/Cargo.toml4
-rw-r--r--jid/src/lib.rs68
-rw-r--r--lampada/Cargo.toml31
-rw-r--r--lampada/src/error.rs6
-rw-r--r--lampada/src/lib.rs14
-rw-r--r--luz/Cargo.toml64
-rw-r--r--luz/src/client/ws.rs3
-rw-r--r--luz/src/connection/ws.rs97
-rw-r--r--luz/src/error.rs24
-rw-r--r--luz/src/jabber_stream.rs12
-rw-r--r--luz/src/jabber_stream/bound_stream.rs2
-rw-r--r--luz/src/jabber_stream/tcp.rs2
-rw-r--r--luz/src/jabber_stream/ws.rs7
-rw-r--r--stanza/Cargo.toml9
-rw-r--r--stanza/src/bind.rs21
-rw-r--r--stanza/src/client/error.rs7
-rw-r--r--stanza/src/client/iq.rs13
-rw-r--r--stanza/src/client/message.rs21
-rw-r--r--stanza/src/client/mod.rs12
-rw-r--r--stanza/src/client/presence.rs21
-rw-r--r--stanza/src/lib.rs2
-rw-r--r--stanza/src/rfc_7395.rs5
-rw-r--r--stanza/src/roster.rs17
-rw-r--r--stanza/src/sasl.rs29
-rw-r--r--stanza/src/stanza_error.rs13
-rw-r--r--stanza/src/starttls.rs19
-rw-r--r--stanza/src/stream.rs7
-rw-r--r--stanza/src/stream_error.rs13
-rw-r--r--stanza/src/xep_0004.rs45
-rw-r--r--stanza/src/xep_0030/info.rs17
-rw-r--r--stanza/src/xep_0030/items.rs13
-rw-r--r--stanza/src/xep_0059.rs37
-rw-r--r--stanza/src/xep_0060/errors.rs9
-rw-r--r--stanza/src/xep_0060/event.rs61
-rw-r--r--stanza/src/xep_0060/owner.rs45
-rw-r--r--stanza/src/xep_0060/pubsub.rs81
-rw-r--r--stanza/src/xep_0084/data.rs9
-rw-r--r--stanza/src/xep_0084/metadata.rs17
-rw-r--r--stanza/src/xep_0115.rs9
-rw-r--r--stanza/src/xep_0131.rs13
-rw-r--r--stanza/src/xep_0156.rs230
-rw-r--r--stanza/src/xep_0172.rs9
-rw-r--r--stanza/src/xep_0199.rs9
-rw-r--r--stanza/src/xep_0203.rs9
-rw-r--r--stanza/src/xep_0300.rs13
-rw-r--r--stanza/src/xep_0390.rs9
70 files changed, 3521 insertions, 1467 deletions
diff --git a/.helix/languages.toml b/.helix/languages.toml
index 8e3e532..7662fff 100644
--- a/.helix/languages.toml
+++ b/.helix/languages.toml
@@ -5,4 +5,5 @@ environment = { "DATABASE_URL" = "sqlite://filamento/filamento.db" }
# check.overrideCommand="cargo check --message-format=json -p luz",
# check.workspace = false,
# cargo.target = "wasm32-unknown-unknown",
-config = { cargo.features = ["stanza/rfc_6121", "stanza/xep_0203", "stanza/rfc_7395", "stanza/xep_0030", "stanza/xep_0060", "stanza/xep_0172", "stanza/xep_0390", "stanza/xep_0128", "stanza/xep_0115", "stanza/xep_0084", "sqlx/sqlite", "sqlx/runtime-tokio", "sqlx/uuid", "sqlx/chrono", "jid/sqlx", "uuid/v4", "tokio/full", "rsasl/provider_base64", "rsasl/plain", "rsasl/config_builder", "rsasl/scram-sha-1"] }
+config = { cargo.target = "wasm32-unknown-unknown", cargo.features = ["jid/rusqlite", "stanza/rfc_6121", "stanza/xep_0203", "stanza/rfc_7395", "stanza/xep_0030", "stanza/xep_0060", "stanza/xep_0172", "stanza/xep_0390", "stanza/xep_0128", "stanza/xep_0115", "stanza/xep_0084", "uuid/v4", "tokio/full", "rsasl/provider_base64", "rsasl/plain", "rsasl/config_builder", "rsasl/scram-sha-1", "stanza/xep_0156"] }
+# "sqlx/sqlite", "sqlx/runtime-tokio", "sqlx/uuid", "sqlx/chrono", "jid/sqlx",
diff --git a/Cargo.toml b/Cargo.toml
index b3cefa7..3a729d2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,11 +1,37 @@
[workspace]
resolver = "2"
-members = [
- "luz",
- "lampada",
- "stanza", "jid", "filamento",
-]
+members = ["luz", "lampada", "stanza", "jid", "filamento"]
[workspace.dependencies]
+jid = { path = "jid" }
+stanza = { path = "stanza" }
+luz = { path = "luz" }
+lampada = { path = "lampada" }
tokio = { version = "1.42.0" }
+peanuts = { version = "0.1.0", git = "https://bunny.garden/peanuts" }
+thiserror = "2.0.11"
+chrono = { version = "0.4.40" }
+serde = { version = "1.0.219" }
+tracing = { version = "0.1.40" }
+uuid = { version = "1.13.1" }
+futures = { version = "0.3.30" }
+
+# WASM dependencies
+
+tokio_with_wasm = "0.8.2"
+web-sys = "0.3"
+js-sys = "0.3"
+wasm-bindgen = "0.2"
+wasm-bindgen-futures = "0.4.50"
+
+# dev-dependencies
+
+tracing-wasm = "0.2.1"
+wasm-bindgen-test = "0.3.0"
+test-log = "0.2"
+env_logger = "*"
+tracing-subscriber = "0.3"
+
+[patch.crates-io]
+tokio_with_wasm = { path = "../tokio-with-wasm/tokio_with_wasm" }
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/README.md b/README.md
index 99fe16c..29c5242 100644
--- a/README.md
+++ b/README.md
@@ -101,13 +101,12 @@
- [ ] xep-0393: message styling
- [ ] message routing NG
-#### will prioritise new spec instead of:
-
- [ ] muc
- [ ] xep-0045: muc
- [ ] xep-0249: direct muc invitations
- [ ] xep-0410: muc self-ping
- [ ] xep-0402: pep native bookmarks
+ - [ ] xep-0421: occupant identifiers for semi-anonymous mucs
- [ ] vcard legacy
- [ ] xep-0292: vcard4
- [ ] xep-0398: user avatar compat
diff --git a/filamento/.cargo/config.toml b/filamento/.cargo/config.toml
new file mode 100644
index 0000000..319101a
--- /dev/null
+++ b/filamento/.cargo/config.toml
@@ -0,0 +1,19 @@
+[build]
+rustflags = [
+ # LLD (shipped with the Rust toolchain) is used as the default linker
+ # "-C", "link-arg=-Tlink.x",
+
+ # if you run into problems with LLD switch to the GNU linker by commenting out
+ # this line
+ # "-C", "linker=arm-none-eabi-ld",
+
+ # if you need to link to pre-compiled C libraries provided by a C toolchain
+ # use GCC as the linker by commenting out both lines above and then
+ # uncommenting the three lines below
+ "-C",
+ "target-feature=+atomics,+bulk-memory,+mutable-globals",
+]
+
+[unstable]
+build-std = ["std", "panic_abort"]
+
diff --git a/filamento/.gitignore b/filamento/.gitignore
index 1ba9f2a..52acf71 100644
--- a/filamento/.gitignore
+++ b/filamento/.gitignore
@@ -1,3 +1,3 @@
filamento.db
-files/
+./files/
.sqlx/
diff --git a/filamento/Cargo.toml b/filamento/Cargo.toml
index 66cbc31..7d7af0c 100644
--- a/filamento/Cargo.toml
+++ b/filamento/Cargo.toml
@@ -3,38 +3,80 @@ name = "filamento"
version = "0.1.0"
edition = "2024"
+[features]
+serde = [
+ "dep:serde",
+ "jid/serde",
+ "uuid/serde",
+ "chrono/serde",
+ "lampada/serde",
+]
+opfs = ["dep:web-sys"]
+reactive_stores = ["dep:reactive_stores"]
+
[dependencies]
-futures = "0.3.31"
-lampada = { version = "0.1.0", path = "../lampada" }
-tokio = { workspace = true }
-thiserror = "2.0.11"
-stanza = { version = "0.1.0", path = "../stanza", features = ["rfc_6121", "xep_0203", "xep_0030", "xep_0060", "xep_0172", "xep_0390", "xep_0128", "xep_0115", "xep_0084"] }
+futures = { workspace = true }
+lampada = { workspace = true }
+thiserror = { workspace = true }
+stanza = { workspace = true, features = [
+ "rfc_6121",
+ "xep_0203",
+ "xep_0030",
+ "xep_0060",
+ "xep_0172",
+ "xep_0390",
+ "xep_0128",
+ "xep_0115",
+ "xep_0084",
+] }
# TODO: re-export jid?
-jid = { version = "0.1.0", path = "../jid" }
-uuid = { version = "1.13.1", features = ["v4"] }
-rusqlite = { git = "https://github.com/Spxg/rusqlite.git" }
-tracing = "0.1.41"
-chrono = "0.4.40"
+jid = { workspace = true, features = ["rusqlite"] }
+uuid = { workspace = true, features = ["v4"] }
+rusqlite = { git = "https://github.com/Spxg/rusqlite.git", branch = "wasm-demo", features = [
+ "uuid",
+ "chrono",
+] }
+tracing = { workspace = true }
+chrono = { workspace = true }
+serde = { workspace = true, features = ["derive"], optional = true }
sha2 = "0.10.8"
sha3 = "0.10.8"
base64 = "0.22.1"
sha1 = "0.10.6"
image = "0.25.6"
hex = "0.4.3"
+reactive_stores = { version = "0.2.2", optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
-tokio = { workspace = true, features = ["sync", "time", "rt", "fs"] }
+tokio = { workspace = true, features = ["sync", "time", "rt", "fs", "io-std"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
tokio = { workspace = true, features = ["sync", "time", "rt"] }
-tokio_with_wasm = { version = "0.8.2", features = ["sync", "time", "rt"] }
+web-sys = { workspace = true, features = [
+ "FileSystemDirectoryHandle",
+ "FileSystemWritableFileStream",
+ "FileSystemGetDirectoryOptions",
+ "FileSystemFileHandle",
+ "StorageManager",
+ "File",
+ "Url",
+ "Window",
+ "Navigator",
+], optional = true }
+wasm-bindgen = { workspace = true }
+wasm-bindgen-futures = { workspace = true }
+rusqlite = { git = "https://github.com/Spxg/rusqlite.git", branch = "wasm-demo", features = [
+ "uuid",
+ "chrono",
+ "precompiled-wasm",
+] }
+tokio_with_wasm = { workspace = true, features = ["sync", "time", "rt"] }
[dev-dependencies]
-tracing-subscriber = "0.3.19"
-peanuts = { version = "0.1.0", git = "https://bunny.garden/peanuts" }
-tracing-wasm = "0.2.1"
-tokio_with_wasm = { version = "0.8.2", features = ["sync", "time", "rt"] }
-wasm-bindgen-test = "0.3.0"
+tracing-subscriber = { workspace = true }
+peanuts = { workspace = true }
+tracing-wasm = { workspace = true }
+wasm-bindgen-test = { workspace = true }
[[example]]
name = "example"
diff --git a/filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0 b/filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0
new file mode 100644
index 0000000..0b27b91
--- /dev/null
+++ b/filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0
Binary files differ
diff --git a/filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377 b/filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377
new file mode 100644
index 0000000..4284eb6
--- /dev/null
+++ b/filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377
Binary files differ
diff --git a/filamento/files/britney_starbies.jpg b/filamento/files/britney_starbies.jpg
new file mode 100644
index 0000000..2e81677
--- /dev/null
+++ b/filamento/files/britney_starbies.jpg
Binary files differ
diff --git a/filamento/migrations/20240113011930_luz.sql b/filamento/migrations/1.sql
index c2f35dd..502c5a9 100644
--- a/filamento/migrations/20240113011930_luz.sql
+++ b/filamento/migrations/1.sql
@@ -2,7 +2,7 @@ PRAGMA foreign_keys = on;
-- a user jid will never change, only a chat user will change
-- TODO: avatar, nick, etc.
-create table users(
+create table if not exists users(
-- TODO: enforce bare jid
jid text primary key not null,
nick text,
@@ -29,7 +29,7 @@ create table users(
-- primary key(activated timestamp, id, jid)
-- );
-create table resources(
+create table if not exists resources(
bare_jid text not null,
resource text not null,
foreign key(bare_jid) references users(jid),
@@ -37,14 +37,14 @@ create table resources(
);
-- enum for subscription state
-create table subscription(
+create table if not exists subscription(
state text primary key not null
);
-insert into subscription ( state ) values ('none'), ('pending-out'), ('pending-in'), ('pending-in-pending-out'), ('only-out'), ('only-in'), ('out-pending-in'), ('in-pending-out'), ('buddy');
+insert into subscription ( state ) values ('none'), ('pending-out'), ('pending-in'), ('pending-in-pending-out'), ('only-out'), ('only-in'), ('out-pending-in'), ('in-pending-out'), ('buddy') on conflict do nothing;
-- a roster contains users, with client-set nickname
-CREATE TABLE roster(
+CREATE TABLE if not exists roster(
user_jid text primary key not null,
name TEXT,
subscription text not null,
@@ -52,11 +52,11 @@ CREATE TABLE roster(
foreign key(user_jid) references users(jid)
);
-create table groups(
+create table if not exists groups(
group_name text primary key not null
);
-create table groups_roster(
+create table if not exists groups_roster(
group_name text not null,
contact_jid text not null,
foreign key(group_name) references groups(group_name),
@@ -67,7 +67,7 @@ create table groups_roster(
-- chat includes reference to user jid chat is with
-- specifically for dms, groups should be different
-- can send chat message to user (creating a new chat if not already exists)
-create table chats (
+create table if not exists chats (
id text primary key not null,
have_chatted bool not null,
correspondent text not null unique,
@@ -75,14 +75,14 @@ create table chats (
);
-- enum for subscription state
-create table delivery(
+create table if not exists delivery(
state text primary key not null
);
-insert into delivery ( state ) values ('sending'), ('written'), ('sent'), ('delivered'), ('read'), ('failed'), ('queued');
+insert into delivery ( state ) values ('sending'), ('written'), ('sent'), ('delivered'), ('read'), ('failed'), ('queued') on conflict do nothing;
-- messages include reference to chat they are in, and who sent them.
-create table messages (
+create table if not exists messages (
id text primary key not null,
body text,
-- delivery is nullable as only messages sent by the user are markable
@@ -116,26 +116,26 @@ create table messages (
);
-- enum for subscription state
-create table show (
+create table if not exists show (
state text primary key not null
);
-insert into show ( state ) values ('away'), ('chat'), ('do-not-disturb'), ('extended-away');
+insert into show ( state ) values ('away'), ('chat'), ('do-not-disturb'), ('extended-away') on conflict do nothing;
-create table cached_status (
+create table if not exists cached_status (
id integer primary key not null,
show text,
message text,
foreign key(show) references show(state)
);
-insert into cached_status (id) values (0);
+insert into cached_status (id) values (0) on conflict do nothing;
-create table capability_hash_nodes (
+create table if not exists capability_hash_nodes (
node text primary key not null,
timestamp text,
-- TODO: normalization
capabilities text not null
);
-insert into capability_hash_nodes ( node, capabilities ) values ('https://bunny.garden/filamento#mSavc/SLnHm8zazs5RlcbD/iXoc=', 'aHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvY2Fwcx9odHRwOi8vamFiYmVyLm9yZy9wcm90b2NvbC9kaXNjbyNpbmZvH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL2Rpc2NvI2l0ZW1zH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL25pY2sfaHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvbmljaytub3RpZnkfHGNsaWVudB9wYx8fZmlsYW1lbnRvIDAuMS4wHx4cHA==');
+insert into capability_hash_nodes ( node, capabilities ) values ('https://bunny.garden/filamento#mSavc/SLnHm8zazs5RlcbD/iXoc=', 'aHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvY2Fwcx9odHRwOi8vamFiYmVyLm9yZy9wcm90b2NvbC9kaXNjbyNpbmZvH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL2Rpc2NvI2l0ZW1zH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL25pY2sfaHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvbmljaytub3RpZnkfHGNsaWVudB9wYx8fZmlsYW1lbnRvIDAuMS4wHx4cHA==') on conflict do nothing;
diff --git a/filamento/src/chat.rs b/filamento/src/chat.rs
index 557b42b..5f58866 100644
--- a/filamento/src/chat.rs
+++ b/filamento/src/chat.rs
@@ -1,8 +1,16 @@
+use std::fmt::{Display, Write};
+
use chrono::{DateTime, Utc};
use jid::JID;
+use rusqlite::{
+ ToSql,
+ types::{FromSql, ToSqlOutput, Value},
+};
use uuid::Uuid;
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
+#[cfg_attr(feature = "reactive_stores", derive(reactive_stores::Store))]
pub struct Message {
pub id: Uuid,
// does not contain full user information
@@ -16,7 +24,8 @@ pub struct Message {
pub body: Body,
}
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum Delivery {
Sending,
Written,
@@ -27,19 +36,66 @@ pub enum Delivery {
Queued,
}
+impl Display for Delivery {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Delivery::Sending => f.write_str("sending"),
+ Delivery::Written => f.write_str("written"),
+ Delivery::Sent => f.write_str("sent"),
+ Delivery::Delivered => f.write_str("delivered"),
+ Delivery::Read => f.write_str("read"),
+ Delivery::Failed => f.write_str("failed"),
+ Delivery::Queued => f.write_str("queued"),
+ }
+ }
+}
+
+impl ToSql for Delivery {
+ fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
+ Ok(match self {
+ Delivery::Sending => ToSqlOutput::Owned(Value::Text("sending".to_string())),
+ Delivery::Written => ToSqlOutput::Owned(Value::Text("written".to_string())),
+ Delivery::Sent => ToSqlOutput::Owned(Value::Text("sent".to_string())),
+ Delivery::Delivered => ToSqlOutput::Owned(Value::Text("delivered".to_string())),
+ Delivery::Read => ToSqlOutput::Owned(Value::Text("read".to_string())),
+ Delivery::Failed => ToSqlOutput::Owned(Value::Text("failed".to_string())),
+ Delivery::Queued => ToSqlOutput::Owned(Value::Text("queued".to_string())),
+ })
+ }
+}
+
+impl FromSql for Delivery {
+ fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
+ Ok(match value.as_str()? {
+ "sending" => Self::Sending,
+ "written" => Self::Written,
+ "sent" => Self::Sent,
+ "delivered" => Self::Delivered,
+ "read" => Self::Read,
+ "failed" => Self::Failed,
+ "queued" => Self::Queued,
+ // TODO: don't have these lol
+ value => panic!("unexpected subscription `{value}`"),
+ })
+ }
+}
+
// TODO: user migrations
// pub enum Migrated {
// Jabber(User),
// Outside,
// }
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Body {
// TODO: rich text, other contents, threads
pub body: String,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
+#[cfg_attr(feature = "reactive_stores", derive(reactive_stores::Store))]
pub struct Chat {
pub correspondent: JID,
pub have_chatted: bool,
diff --git a/filamento/src/db.rs b/filamento/src/db.rs
index 467030d..1b5afe6 100644
--- a/filamento/src/db.rs
+++ b/filamento/src/db.rs
@@ -1,7 +1,15 @@
-use std::{collections::HashSet, path::Path};
+use core::fmt::Display;
+use std::{collections::HashSet, ops::Deref, path::Path, sync::Arc};
use chrono::{DateTime, Utc};
use jid::JID;
+use rusqlite::{Connection, OptionalExtension};
+use tokio::sync::{Mutex, MutexGuard};
+use tokio::sync::{mpsc, oneshot};
+use tokio::task::{spawn, spawn_blocking};
+#[cfg(target_arch = "wasm32")]
+use tokio_with_wasm::alias as tokio;
+use tracing::debug;
use uuid::Uuid;
use crate::{
@@ -12,75 +20,193 @@ use crate::{
user::User,
};
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub struct Db {
- // db: SqlitePool,
+ sender: mpsc::UnboundedSender<DbCommand>,
+}
+
+impl Deref for Db {
+ type Target = mpsc::UnboundedSender<DbCommand>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.sender
+ }
+}
+
+#[derive(Debug)]
+pub struct DbActor {
+ receiver: mpsc::UnboundedReceiver<DbCommand>,
+ db: Connection,
+}
+
+macro_rules! impl_db_sends {
+ ($($command:ident => $name:ident($($arg:ident: $arg_t:ty),*) -> $ret:ty);*) => {
+ $(
+ pub(crate) async fn $name(&self, $($arg: $arg_t),*) -> Result<$ret, Error> {
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::$command { $($arg,)* result };
+ let _ = self.sender.send(command);
+ let result = recv.await?;
+ result
+ }
+ )*
+ }
}
-// TODO: turn into trait
impl Db {
#[cfg(not(target_arch = "wasm32"))]
pub async fn create_connect_and_migrate(
- path: impl AsRef<Path>,
+ path: impl AsRef<Path> + Send,
) -> Result<Self, DatabaseOpenError> {
- if let Some(dir) = path.as_ref().parent() {
- if dir.is_dir() {
- } else {
- tokio::fs::create_dir_all(dir).await?;
+ let (sender, receiver) = mpsc::channel(20);
+ let (result_send, result_recv) = oneshot::channel();
+ spawn_blocking(move || {
+ let result = DbActor::new(path, receiver).await;
+ match result {
+ Ok(a) => {
+ result_send.send(Ok(()));
+ a.run()
+ }
+ Err(e) => {
+ result_send.send(Err(e));
+ }
}
- let _file = tokio::fs::OpenOptions::new()
- .append(true)
- .create(true)
- .open(path.as_ref())
- .await?;
+ });
+ match result_recv.await {
+ Ok(r) => match r {
+ Ok(o) => Ok(Self { sender }),
+ Err(e) => return Err(e),
+ },
+ Err(e) => return Err(e.into()),
+ }
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub async fn create_connect_and_migrate_memory() -> Result<Self, DatabaseOpenError> {
+ let (sender, receiver) = mpsc::channel(20);
+ let (result_send, result_recv) = oneshot::channel();
+ spawn_blocking(move || {
+ let result = DbActor::new_memory(receiver).await;
+ match result {
+ Ok(a) => {
+ result_send.send(Ok(()));
+ // TODO: async run when not wasm
+ a.run()
+ }
+ Err(e) => {
+ result_send.send(Err(e));
+ }
+ }
+ });
+ match result_recv.await {
+ Ok(r) => match r {
+ Ok(o) => Ok(Self { sender }),
+ Err(e) => return Err(e),
+ },
+ Err(e) => return Err(e.into()),
}
- let url = format!(
- "sqlite://{}",
- path.as_ref()
- .to_str()
- .ok_or(DatabaseOpenError::InvalidPath)?
- );
- // let db = SqlitePool::connect(&url).await?;
- // migrate!().run(&db).await?;
- // Ok(Self { db })
- Ok(Self {})
}
+ /// `file_name` should be a file not in a directory
#[cfg(target_arch = "wasm32")]
pub async fn create_connect_and_migrate(
- path: impl AsRef<Path>,
+ file_name: impl AsRef<str> + Send + 'static,
) -> Result<Self, DatabaseOpenError> {
- // let url = "mem.db";
- // let db = SqlitePool::connect(&url).await?;
- // // migrate!().run(&db).await?;
- Ok(Self {})
+ use tokio_with_wasm::spawn_local;
+
+ let (sender, receiver) = mpsc::unbounded_channel();
+ let (result_send, result_recv) = oneshot::channel();
+ spawn_blocking(move || {
+ spawn_local(async move {
+ debug!("installing opfs in spawn");
+ rusqlite::ffi::install_opfs_sahpool(
+ Some(&rusqlite::ffi::OpfsSAHPoolCfg::default()),
+ false,
+ )
+ .await
+ .unwrap();
+ debug!("opfs installed");
+ let file_name = format!("file:{}?vfs=opfs-sahpool", file_name.as_ref());
+ let result = DbActor::new(file_name, receiver);
+ match result {
+ Ok(a) => {
+ result_send.send(Ok(()));
+ a.run().await
+ }
+ Err(e) => {
+ result_send.send(Err(e));
+ }
+ }
+ });
+ });
+ match result_recv.await {
+ Ok(r) => match r {
+ Ok(o) => Ok(Self { sender }),
+ Err(e) => return Err(e),
+ },
+ Err(e) => return Err(e.into()),
+ }
}
- // pub(crate) fn new(db: SqlitePool) -> Self {
- // // Self { db }
- // Self {}
- // }
+ #[cfg(target_arch = "wasm32")]
+ pub async fn create_connect_and_migrate_memory() -> Result<Self, DatabaseOpenError> {
+ let (sender, receiver) = mpsc::unbounded_channel();
+ let (result_send, result_recv) = oneshot::channel();
+ spawn_blocking(move || {
+ let result = DbActor::new_memory(receiver);
+ match result {
+ Ok(a) => {
+ result_send.send(Ok(()));
+ tokio_with_wasm::spawn_local(async { a.run().await });
+ // a.run()
+ }
+ Err(e) => {
+ result_send.send(Err(e));
+ }
+ }
+ });
+ match result_recv.await {
+ Ok(r) => match r {
+ Ok(o) => Ok(Self { sender }),
+ Err(e) => return Err(e),
+ },
+ Err(e) => return Err(e.into()),
+ }
+ }
pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::CreateUser { user, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
+ // TODO: this is not a 'read' user
pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> {
- Ok(User {
- jid: user,
- nick: None,
- avatar: None,
- })
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadUser { user, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// returns whether or not the nickname was updated
pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> {
- Ok(true)
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::DeleteUserNick { jid, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// returns whether or not the nickname was updated
pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> {
- Ok(true)
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpsertUserNick { jid, nick, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
@@ -88,7 +214,11 @@ impl Db {
&self,
jid: JID,
) -> Result<(bool, Option<String>), Error> {
- Ok((true, None))
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::DeleteUserAvatar { jid, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
@@ -97,11 +227,24 @@ impl Db {
jid: JID,
avatar: String,
) -> Result<(bool, Option<String>), Error> {
- Ok((true, None))
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpsertUserAvatar {
+ jid,
+ avatar,
+ result,
+ };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
+ // TODO: use references everywhere
pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpdateUser { user, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
// TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them.
@@ -109,64 +252,112 @@ impl Db {
/// does not create the underlying user, if underlying user does not exist, create_user() must be called separately
pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::CreateContact { contact, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> {
- Ok(Contact {
- user_jid: contact,
- subscription: crate::roster::Subscription::None,
- name: None,
- groups: HashSet::new(),
- })
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadContact { contact, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
- pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> {
- Ok(None)
+ pub(crate) async fn read_contact_opt(&self, contact: JID) -> Result<Option<Contact>, Error> {
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadContactOpt { contact, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// does not update the underlying user, to update user, update_user() must be called separately
pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpdateContact { contact, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpsertContact { contact, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::DeleteContact { contact, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReplaceCachedRoster { roster, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> {
- Ok(Vec::new())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadCachedRoster { result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn read_cached_roster_with_users(
&self,
) -> Result<Vec<(Contact, User)>, Error> {
- Ok(Vec::new())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadCachedRosterWithUsers { result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::CreateChat { chat, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
// TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster.
pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> {
- Ok(Chat {
- correspondent: chat,
- have_chatted: false,
- })
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadChat { chat, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
+ }
+
+ pub(crate) async fn read_chat_and_user(&self, chat: JID) -> Result<(Chat, User), Error> {
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadChatAndUser { chat, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::MarkChatAsChatted { chat, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
pub(crate) async fn update_chat_correspondent(
@@ -174,27 +365,44 @@ impl Db {
old_chat: Chat,
new_correspondent: JID,
) -> Result<Chat, Error> {
- Ok(Chat {
- correspondent: new_correspondent,
- have_chatted: false,
- })
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpdateChatCorrespondent {
+ old_chat,
+ new_correspondent,
+ result,
+ };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
// pub(crate) async fn update_chat
pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::DeleteChat { chat, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// TODO: sorting and filtering (for now there is no sorting)
pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> {
- Ok(Vec::new())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadChats { result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// chats ordered by date of last message
// greatest-n-per-group
pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> {
- Ok(Vec::new())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadChatsOrdered { result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// chats ordered by date of last message
@@ -202,7 +410,11 @@ impl Db {
pub(crate) async fn read_chats_ordered_with_latest_messages(
&self,
) -> Result<Vec<(Chat, Message)>, Error> {
- Ok(Vec::new())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadChatsOrderedWithLatestMessages { result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// chats ordered by date of last message
@@ -210,51 +422,79 @@ impl Db {
pub(crate) async fn read_chats_ordered_with_latest_messages_and_users(
&self,
) -> Result<Vec<((Chat, User), (Message, User))>, Error> {
- Ok(Vec::new())
- }
-
- async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> {
- Ok(Uuid::new_v4())
- }
-
- async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> {
- Ok(None)
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::ReadChatsOrderedWithLatestMessagesAndUsers { result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
/// if the chat doesn't already exist, it must be created by calling create_chat() before running this function.
+ #[tracing::instrument]
pub(crate) async fn create_message(
&self,
message: Message,
chat: JID,
from: JID,
) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::CreateMessage {
+ message,
+ chat,
+ from,
+ result,
+ };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
- pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> {
- Ok(false)
+ pub(crate) async fn upsert_chat_and_user(&self, chat: JID) -> Result<bool, Error> {
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpsertChatAndUser { chat, result };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
- /// MUST upsert chat beforehand
- pub(crate) async fn create_message_with_self_resource(
+ /// create direct message from incoming. MUST upsert chat and user
+ #[tracing::instrument]
+ pub(crate) async fn create_message_with_user_resource(
&self,
message: Message,
+ // TODO: enforce two kinds of jid. bare and full
+ // must be bare jid
chat: JID,
// full jid
from: JID,
) -> Result<(), Error> {
- Ok(())
+ tracing::info!("MSGDEBUG create_message_with_user_resource exists");
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::CreateMessageWithUserResource {
+ message,
+ chat,
+ from,
+ result,
+ };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
- /// create direct message from incoming. MUST upsert chat and user
- pub(crate) async fn create_message_with_user_resource(
+ pub(crate) async fn update_message_delivery(
&self,
- message: Message,
- chat: JID,
- // full jid
- from: JID,
+ message: Uuid,
+ delivery: Delivery,
) -> Result<(), Error> {
- Ok(())
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpdateMessageDelivery {
+ message,
+ delivery,
+ result,
+ };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
// pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> {
@@ -269,909 +509,1208 @@ impl Db {
// TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {}
- pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> {
- Ok(())
- }
+ impl_db_sends!(
+ ReadCapabilities => read_capabilities(node: String) -> String;
+ DeleteCachedStatus => delete_cached_status() -> ();
+ UpsertCachedStatus => upsert_cached_status(status: Online) -> ();
+ ReadCachedStatus => read_cached_status() -> Online;
+ ReadMessageHistoryWithUsers => read_message_history_with_users(chat: JID) -> Vec<(Message, User)>;
+ // TODO: paging
+ ReadMessageHistory => read_message_history(chat: JID) -> Vec<Message>;
+ ReadMessage => read_message(message: Uuid) -> Message;
+ DeleteMessage => delete_message(message: Uuid) -> ()
+ );
- // TODO: paging
- pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> {
- Ok(Vec::new())
+ pub(crate) async fn upsert_capabilities(
+ &self,
+ node: String,
+ capabilities: String,
+ ) -> Result<(), Error> {
+ let (result, recv) = oneshot::channel();
+ let command = DbCommand::UpsertCapabilities {
+ node,
+ capabilities,
+ result,
+ };
+ self.sender.send(command);
+ let result = recv.await?;
+ result
}
+}
- pub(crate) async fn read_message_history_with_users(
- &self,
+// TODO: i should really just make an actor macro
+#[derive(Debug)]
+pub enum DbCommand {
+ CreateUser {
+ user: User,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadUser {
+ user: JID,
+ result: oneshot::Sender<Result<User, Error>>,
+ },
+ DeleteUserNick {
+ jid: JID,
+ result: oneshot::Sender<Result<bool, Error>>,
+ },
+ UpsertUserNick {
+ jid: JID,
+ nick: String,
+ result: oneshot::Sender<Result<bool, Error>>,
+ },
+ DeleteUserAvatar {
+ jid: JID,
+ result: oneshot::Sender<Result<(bool, Option<String>), Error>>,
+ },
+ UpsertUserAvatar {
+ jid: JID,
+ avatar: String,
+ result: oneshot::Sender<Result<(bool, Option<String>), Error>>,
+ },
+ UpdateUser {
+ user: User,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ CreateContact {
+ contact: Contact,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadContact {
+ contact: JID,
+ result: oneshot::Sender<Result<Contact, Error>>,
+ },
+ ReadContactOpt {
+ contact: JID,
+ result: oneshot::Sender<Result<Option<Contact>, Error>>,
+ },
+ UpdateContact {
+ contact: Contact,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ UpsertContact {
+ contact: Contact,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ DeleteContact {
+ contact: JID,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReplaceCachedRoster {
+ roster: Vec<Contact>,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadCachedRoster {
+ result: oneshot::Sender<Result<Vec<Contact>, Error>>,
+ },
+ ReadCachedRosterWithUsers {
+ result: oneshot::Sender<Result<Vec<(Contact, User)>, Error>>,
+ },
+ CreateChat {
+ chat: Chat,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadChat {
chat: JID,
- ) -> Result<Vec<(Message, User)>, Error> {
- Ok(Vec::new())
+ result: oneshot::Sender<Result<Chat, Error>>,
+ },
+ ReadChatAndUser {
+ chat: JID,
+ result: oneshot::Sender<Result<(Chat, User), Error>>,
+ },
+ MarkChatAsChatted {
+ chat: JID,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ UpdateChatCorrespondent {
+ old_chat: Chat,
+ new_correspondent: JID,
+ result: oneshot::Sender<Result<Chat, Error>>,
+ },
+ DeleteChat {
+ chat: JID,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadChats {
+ result: oneshot::Sender<Result<Vec<Chat>, Error>>,
+ },
+ ReadChatsOrdered {
+ result: oneshot::Sender<Result<Vec<Chat>, Error>>,
+ },
+ ReadChatsOrderedWithLatestMessages {
+ result: oneshot::Sender<Result<Vec<(Chat, Message)>, Error>>,
+ },
+ ReadChatsOrderedWithLatestMessagesAndUsers {
+ result: oneshot::Sender<Result<Vec<((Chat, User), (Message, User))>, Error>>,
+ },
+ // ReadChatID {
+
+ // result: oneshot::Sender<Result<, Error>>,
+ // },
+ // ReadChatIDOpt {
+ // chat: JID,
+ // result: oneshot::Sender<Result<Option<Uuid>, Error>>,
+ // },
+ CreateMessage {
+ message: Message,
+ chat: JID,
+ from: JID,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ UpsertChatAndUser {
+ chat: JID,
+ result: oneshot::Sender<Result<bool, Error>>,
+ },
+ CreateMessageWithUserResource {
+ message: Message,
+ chat: JID,
+ from: JID,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ UpdateMessageDelivery {
+ message: Uuid,
+ delivery: Delivery,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ DeleteMessage {
+ message: Uuid,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadMessage {
+ message: Uuid,
+ result: oneshot::Sender<Result<Message, Error>>,
+ },
+ ReadMessageHistory {
+ chat: JID,
+ result: oneshot::Sender<Result<Vec<Message>, Error>>,
+ },
+ ReadMessageHistoryWithUsers {
+ chat: JID,
+ result: oneshot::Sender<Result<Vec<(Message, User)>, Error>>,
+ },
+ ReadCachedStatus {
+ result: oneshot::Sender<Result<Online, Error>>,
+ },
+ UpsertCachedStatus {
+ status: Online,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ DeleteCachedStatus {
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+ ReadCapabilities {
+ node: String,
+ result: oneshot::Sender<Result<String, Error>>,
+ },
+ UpsertCapabilities {
+ node: String,
+ capabilities: String,
+ result: oneshot::Sender<Result<(), Error>>,
+ },
+}
+
+impl Display for DbCommand {
+ #[rustfmt::skip]
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ DbCommand::CreateUser { user, result } => "CreateUser",
+ DbCommand::ReadUser { user, result } => "ReadUser",
+ DbCommand::DeleteUserNick { jid, result } => "DeleteUserNick",
+ DbCommand::UpsertUserNick { jid, nick, result } => "UpsertUserNick",
+ DbCommand::DeleteUserAvatar { jid, result } => "DeleteUserAvatar",
+ DbCommand::UpsertUserAvatar { jid, avatar, result } => "UpsertUserAvatar",
+ DbCommand::UpdateUser { user, result } => "UpdateUser",
+ DbCommand::CreateContact { contact, result } => "CreateContact",
+ DbCommand::ReadContact { contact, result } => "ReadContact",
+ DbCommand::ReadContactOpt { contact, result } => "ReadContactOpt",
+ DbCommand::UpdateContact { contact, result } => "UpdateContact",
+ DbCommand::UpsertContact { contact, result } => "UpsertContact",
+ DbCommand::DeleteContact { contact, result } => "DeleteContact",
+ DbCommand::ReplaceCachedRoster { roster, result } => "ReplaceCachedRoster",
+ DbCommand::ReadCachedRoster { result } => "ReadCachedRoster",
+ DbCommand::ReadCachedRosterWithUsers { result } => "ReadCachedRosterWithUsers",
+ DbCommand::CreateChat { chat, result } => "CreateChat",
+ DbCommand::ReadChat { chat, result } => "ReadChat",
+ DbCommand::MarkChatAsChatted { chat, result } => "MarkChatAsChatted",
+ DbCommand::UpdateChatCorrespondent { old_chat, new_correspondent, result } => "UpdateChatCorrespondent",
+ DbCommand::DeleteChat { chat, result } => "DeleteChat",
+ DbCommand::ReadChats { result } => "ReadChats",
+ DbCommand::ReadChatsOrdered { result } => "ReadChatsOrdered",
+ DbCommand::ReadChatsOrderedWithLatestMessages { result } => "ReadChatsOrderedWithLatestMessages",
+ DbCommand::ReadChatsOrderedWithLatestMessagesAndUsers { result } => "ReadChatsOrderedWithLatestMessagesAndUsers",
+ DbCommand::CreateMessage { message, chat, from, result } => "CreateMessage",
+ DbCommand::UpsertChatAndUser { chat, result } => "UpsertChatAndUser",
+ DbCommand::CreateMessageWithUserResource { message, chat, from, result } => "CreateMessageWithUserResource",
+ DbCommand::UpdateMessageDelivery { message, delivery, result } => "UpdateMessageDelivery",
+ DbCommand::DeleteMessage { message, result } => "DeleteMessage",
+ DbCommand::ReadMessage { message, result } => "ReadMessage",
+ DbCommand::ReadMessageHistory { chat, result } => "ReadMessageHistory",
+ DbCommand::ReadMessageHistoryWithUsers { chat, result } => "ReadMessageHistoryWithUsers",
+ DbCommand::ReadCachedStatus { result } => "ReadCachedStatus",
+ DbCommand::UpsertCachedStatus { status, result } => "UpsertCachedStatus",
+ DbCommand::DeleteCachedStatus { result } => "DeleteCachedStatus",
+ DbCommand::ReadCapabilities { node, result } => "ReadCapabilities",
+ DbCommand::UpsertCapabilities { node, capabilities, result } => "UpsertCapabilities",
+ DbCommand::ReadChatAndUser { chat, result } => "ReadChatAndUser",
+ })
}
+}
- pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> {
- Ok(Online::default())
+impl DbActor {
+ /// must be run in blocking spawn
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn new(path: impl AsRef<Path>, receiver: mpsc::Receiver<DbCommand>) -> Self {
+ if let Some(dir) = path.as_ref().parent() {
+ if dir.is_dir() {
+ } else {
+ tokio::fs::create_dir_all(dir).await?;
+ }
+ let _file = tokio::fs::OpenOptions::new()
+ .append(true)
+ .create(true)
+ .open(path.as_ref())
+ .await?;
+ }
+ let url = format!(
+ "{}",
+ path.as_ref()
+ .to_str()
+ .ok_or(DatabaseOpenError::InvalidPath)?
+ );
+ // let db = SqlitePool::connect(&url).await?;
+ // migrate!().run(&db).await?;
+ // Ok(Self { db })
+ let db = Connection::open(url)?;
+ db.execute_batch(include_str!("../migrations/1.sql"))?;
+ Ok(Self { db, receiver })
}
- pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> {
- Ok(())
+ /// must be run in blocking spawn
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn new_memory(receiver: mpsc::Receiver<DbCommand>) -> Self {
+ let db = Connection::open_in_memory()?;
+ db.execute_batch(include_str!("../migrations/1.sql"))?;
+ Ok(Self { db, receiver })
}
- pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> {
- Ok(())
+ /// must be run in blocking spawn
+ #[cfg(target_arch = "wasm32")]
+ pub fn new_memory(
+ receiver: mpsc::UnboundedReceiver<DbCommand>,
+ ) -> Result<Self, DatabaseOpenError> {
+ let db = Connection::open("mem.db")?;
+ db.execute_batch(include_str!("../migrations/1.sql"))?;
+ Ok(Self { db, receiver })
}
- pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> {
- Ok("aHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvY2Fwcx9odHRwOi8vamFiYmVyLm9yZy9wcm90b2NvbC9kaXNjbyNpbmZvH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL2Rpc2NvI2l0ZW1zH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL25pY2sfaHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvbmljaytub3RpZnkfHGNsaWVudB9wYx8fZmlsYW1lbnRvIDAuMS4wHx4cHA==".to_string())
+ /// must be run in blocking spawn
+ #[cfg(target_arch = "wasm32")]
+ pub fn new(
+ file_name: impl AsRef<Path>,
+ receiver: mpsc::UnboundedReceiver<DbCommand>,
+ ) -> Result<Self, DatabaseOpenError> {
+ let db = Connection::open(file_name)?;
+ db.execute_batch(include_str!("../migrations/1.sql"))?;
+ Ok(Self { db, receiver })
}
- pub(crate) async fn upsert_capabilities(
- &self,
- node: &str,
- capabilities: &str,
- ) -> Result<(), Error> {
+ pub(crate) async fn run(mut self) {
+ while let Some(cmd) = self.receiver.recv().await {
+ let cmd_name = cmd.to_string();
+ tracing::warn!("command recv: {cmd_name}");
+ match cmd {
+ DbCommand::CreateUser { user, result } => {
+ result.send(self.create_user(user));
+ }
+ DbCommand::ReadUser { user, result } => {
+ result.send(self.read_user(user));
+ }
+ DbCommand::DeleteUserNick { jid, result } => {
+ result.send(self.delete_user_nick(jid));
+ }
+ DbCommand::UpsertUserNick { jid, nick, result } => {
+ result.send(self.upsert_user_nick(jid, nick));
+ }
+ DbCommand::DeleteUserAvatar { jid, result } => {
+ result.send(self.delete_user_avatar(jid));
+ }
+ DbCommand::UpsertUserAvatar {
+ jid,
+ avatar,
+ result,
+ } => {
+ result.send(self.upsert_user_avatar(jid, avatar));
+ }
+ DbCommand::UpdateUser { user, result } => {
+ result.send(self.update_user(user));
+ }
+ DbCommand::CreateContact { contact, result } => {
+ result.send(self.create_contact(contact));
+ }
+ DbCommand::ReadContact { contact, result } => {
+ result.send(self.read_contact(contact));
+ }
+ DbCommand::ReadContactOpt { contact, result } => {
+ result.send(self.read_contact_opt(&contact));
+ }
+ DbCommand::UpdateContact { contact, result } => {
+ result.send(self.update_contact(contact));
+ }
+ DbCommand::UpsertContact { contact, result } => {
+ result.send(self.upsert_contact(contact));
+ }
+ DbCommand::DeleteContact { contact, result } => {
+ result.send(self.delete_contact(contact));
+ }
+ DbCommand::ReplaceCachedRoster { roster, result } => {
+ result.send(self.replace_cached_roster(roster));
+ }
+ DbCommand::ReadCachedRoster { result } => {
+ result.send(self.read_cached_roster());
+ }
+ DbCommand::ReadCachedRosterWithUsers { result } => {
+ result.send(self.read_cached_roster_with_users());
+ }
+ DbCommand::CreateChat { chat, result } => {
+ result.send(self.create_chat(chat));
+ }
+ DbCommand::ReadChat { chat, result } => {
+ result.send(self.read_chat(chat));
+ }
+ DbCommand::ReadChatAndUser { chat, result } => {
+ result.send(self.read_chat_and_user(chat));
+ }
+ DbCommand::MarkChatAsChatted { chat, result } => {
+ result.send(self.mark_chat_as_chatted(chat));
+ }
+ DbCommand::UpdateChatCorrespondent {
+ old_chat,
+ new_correspondent,
+ result,
+ } => {
+ result.send(self.update_chat_correspondent(old_chat, new_correspondent));
+ }
+ DbCommand::DeleteChat { chat, result } => {
+ result.send(self.delete_chat(chat));
+ }
+ DbCommand::ReadChats { result } => {
+ result.send(self.read_chats());
+ }
+ DbCommand::ReadChatsOrdered { result } => {
+ result.send(self.read_chats_ordered());
+ }
+ DbCommand::ReadChatsOrderedWithLatestMessages { result } => {
+ result.send(self.read_chats_ordered_with_latest_messages());
+ }
+ DbCommand::ReadChatsOrderedWithLatestMessagesAndUsers { result } => {
+ result.send(self.read_chats_ordered_with_latest_messages_and_users());
+ }
+ DbCommand::CreateMessage {
+ message,
+ chat,
+ from,
+ result,
+ } => {
+ result.send(self.create_message(message, chat, from));
+ }
+ DbCommand::UpsertChatAndUser { chat, result } => {
+ result.send(self.upsert_chat_and_user(&chat));
+ }
+ DbCommand::CreateMessageWithUserResource {
+ message,
+ chat,
+ from,
+ result,
+ } => {
+ result.send(self.create_message_with_user_resource(message, chat, from));
+ }
+ DbCommand::UpdateMessageDelivery {
+ message,
+ delivery,
+ result,
+ } => {
+ result.send(self.update_message_delivery(message, delivery));
+ }
+ DbCommand::DeleteMessage { message, result } => {
+ result.send(self.delete_message(message));
+ }
+ DbCommand::ReadMessage { message, result } => {
+ result.send(self.read_message(message));
+ }
+ DbCommand::ReadMessageHistory { chat, result } => {
+ result.send(self.read_message_history(chat));
+ }
+ DbCommand::ReadMessageHistoryWithUsers { chat, result } => {
+ result.send(self.read_message_history_with_users(chat));
+ }
+ DbCommand::ReadCachedStatus { result } => {
+ result.send(self.read_cached_status());
+ }
+ DbCommand::UpsertCachedStatus { status, result } => {
+ result.send(self.upsert_cached_status(status));
+ }
+ DbCommand::DeleteCachedStatus { result } => {
+ result.send(self.delete_cached_status());
+ }
+ DbCommand::ReadCapabilities { node, result } => {
+ result.send(self.read_capabilities(node));
+ }
+ DbCommand::UpsertCapabilities {
+ node,
+ capabilities,
+ result,
+ } => {
+ result.send(self.upsert_capabilities(node, capabilities));
+ }
+ }
+ tracing::warn!("command finished: {cmd_name}");
+ }
+ tracing::error!("command: db actor exited");
+ }
+
+ pub(crate) fn create_user(&self, user: User) -> Result<(), Error> {
+ {
+ self.db.execute(
+ "insert into users ( jid, nick, avatar ) values ( ?1, ?2, ?3 )",
+ (user.jid, user.nick, user.avatar),
+ )?;
+ }
Ok(())
}
- // pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> {
- // sqlx::query!(
- // "insert into users ( jid, nick ) values ( ?, ? )",
- // user.jid,
- // user.nick,
- // )
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ // TODO: this is not a 'read' user
+ pub(crate) fn read_user(&self, user: JID) -> Result<User, Error> {
+ let db = &self.db;
+ let user_opt = db
+ .query_row(
+ "select jid, nick, avatar from users where jid = ?1",
+ [&user],
+ |row| {
+ Ok(User {
+ jid: row.get(0)?,
+ nick: row.get(1)?,
+ avatar: row.get(2)?,
+ })
+ },
+ )
+ .optional()?;
+ match user_opt {
+ Some(user) => Ok(user),
+ None => {
+ db.execute("insert into users ( jid ) values ( ?1 )", [&user])?;
+ Ok(User {
+ jid: user,
+ nick: None,
+ avatar: None,
+ })
+ }
+ }
+ }
- // pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> {
- // sqlx::query!(
- // "insert into users ( jid ) values ( ? ) on conflict do nothing",
- // user
- // )
- // .execute(&self.db)
- // .await?;
- // let user: User = sqlx::query_as("select * from users where jid = ?")
- // .bind(user)
- // .fetch_one(&self.db)
- // .await?;
- // Ok(user)
- // }
+ /// returns whether or not the nickname was updated
+ pub(crate) fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> {
+ let rows_affected;
+ {
+ rows_affected = self.db.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, None::<String>, None::<String>, None::<String>))?;
+ }
+ if rows_affected > 0 {
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
- // /// returns whether or not the nickname was updated
- // pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> {
- // if sqlx::query!(
- // "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?",
- // jid,
- // None::<String>,
- // None::<String>,
- // None::<String>,
- // )
- // .execute(&self.db)
- // .await?
- // .rows_affected()
- // > 0
- // {
- // Ok(true)
- // } else {
- // Ok(false)
- // }
- // }
+ /// returns whether or not the nickname was updated
+ pub(crate) fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> {
+ let rows_affected;
+ {
+ rows_affected = self.db.execute("insert into users (jid, nick) values (?1, ?2) on conflict do update set nick = ?3 where nick is not ?4", (jid, &nick, &nick, &nick))?;
+ }
+ if rows_affected > 0 {
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
- // /// returns whether or not the nickname was updated
- // pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> {
- // let rows_affected = sqlx::query!(
- // "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ? where nick is not ?",
- // jid,
- // nick,
- // nick,
- // nick
- // )
- // .execute(&self.db)
- // .await?
- // .rows_affected();
- // tracing::debug!("rows affected: {}", rows_affected);
- // if rows_affected > 0 {
- // Ok(true)
- // } else {
- // Ok(false)
- // }
- // }
+ /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
+ pub(crate) fn delete_user_avatar(&self, jid: JID) -> Result<(bool, Option<String>), Error> {
+ let (old_avatar, rows_affected): (Option<String>, _);
+ {
+ let db = &self.db;
+ old_avatar = db
+ .query_row("select avatar from users where jid = ?1", [&jid], |row| {
+ Ok(row.get(0)?)
+ })
+ .optional()?;
+ rows_affected = db.execute("insert into users (jid, avatar) values (?1, ?2) on conflict do update set avatar = ?3 where avatar is not ?4", (jid, None::<String>, None::<String>, None::<String>))?;
+ }
+ if rows_affected > 0 {
+ Ok((true, old_avatar))
+ } else {
+ Ok((false, old_avatar))
+ }
+ }
- // /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
- // pub(crate) async fn delete_user_avatar(
- // &self,
- // jid: JID,
- // ) -> Result<(bool, Option<String>), Error> {
- // #[derive(sqlx::FromRow)]
- // struct AvatarRow {
- // avatar: Option<String>,
- // }
- // let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?")
- // .bind(jid.clone())
- // .fetch_optional(&self.db)
- // .await?
- // .map(|row: AvatarRow| row.avatar)
- // .unwrap_or(None);
- // if sqlx::query!(
- // "insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?",
- // jid,
- // None::<String>,
- // None::<String>,
- // None::<String>,
- // )
- // .execute(&self.db)
- // .await?
- // .rows_affected()
- // > 0
- // {
- // Ok((true, old_avatar))
- // } else {
- // Ok((false, old_avatar))
- // }
- // }
+ /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
+ pub(crate) fn upsert_user_avatar(
+ &self,
+ jid: JID,
+ avatar: String,
+ ) -> Result<(bool, Option<String>), Error> {
+ let (old_avatar, rows_affected): (Option<String>, _);
+ {
+ let db = &self.db;
+ old_avatar = db
+ .query_row("select avatar from users where jid = ?1", [&jid], |row| {
+ let avatar: Option<String> = row.get(0)?;
+ Ok(avatar)
+ })
+ .optional()?
+ .unwrap_or_default();
+ rows_affected = db.execute("insert into users (jid, avatar) values (?1, ?2) on conflict do update set avatar = ?3 where avatar is not ?4", (jid, &avatar, &avatar, &avatar))?;
+ }
+ if rows_affected > 0 {
+ Ok((true, old_avatar))
+ } else {
+ Ok((false, old_avatar))
+ }
+ }
- // /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar
- // pub(crate) async fn upsert_user_avatar(
- // &self,
- // jid: JID,
- // avatar: String,
- // ) -> Result<(bool, Option<String>), Error> {
- // #[derive(sqlx::FromRow)]
- // struct AvatarRow {
- // avatar: Option<String>,
- // }
- // let old_avatar: Option<String> = sqlx::query_as("select avatar from users where jid = ?")
- // .bind(jid.clone())
- // .fetch_optional(&self.db)
- // .await?
- // .map(|row: AvatarRow| row.avatar)
- // .unwrap_or(None);
- // if sqlx::query!(
- // "insert into users (jid, avatar) values (?, ?) on conflict do update set avatar = ? where avatar is not ?",
- // jid,
- // avatar,
- // avatar,
- // avatar,
- // )
- // .execute(&self.db)
- // .await?
- // .rows_affected()
- // > 0
- // {
- // Ok((true, old_avatar))
- // } else {
- // Ok((false, old_avatar))
- // }
- // }
+ // TODO: use references everywhere
+ pub(crate) fn update_user(&self, user: User) -> Result<(), Error> {
+ self.db.execute(
+ "update users set nick = ?1, avatar = ?2 where user_jid = ?1",
+ (&user.nick, &user.avatar, &user.jid),
+ )?;
+ Ok(())
+ }
- // pub(crate) async fn update_user(&self, user: User) -> Result<(), Error> {
- // sqlx::query!(
- // "update users set nick = ? where jid = ?",
- // user.nick,
- // user.jid
- // )
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them.
+ // pub(crate) fn delete_user(&self, user: JID) -> Result<(), Error> {}
- // // TODO: should this be allowed? messages need to reference users. should probably only allow delete if every other thing referencing it has been deleted, or if you make clear to the user deleting a user will delete all messages associated with them.
- // // pub(crate) async fn delete_user(&self, user: JID) -> Result<(), Error> {}
-
- // /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately
- // pub(crate) async fn create_contact(&self, contact: Contact) -> Result<(), Error> {
- // sqlx::query!(
- // "insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? )",
- // contact.user_jid,
- // contact.name,
- // contact.subscription
- // )
- // .execute(&self.db)
- // .await?;
- // // TODO: abstract this out in to add_to_group() function ?
- // for group in contact.groups {
- // sqlx::query!(
- // "insert into groups (group_name) values (?) on conflict do nothing",
- // group
- // )
- // .execute(&self.db)
- // .await?;
- // sqlx::query!(
- // "insert into groups_roster (group_name, contact_jid) values (?, ?)",
- // group,
- // contact.user_jid
- // )
- // .execute(&self.db)
- // .await?;
- // }
- // Ok(())
- // }
+ /// does not create the underlying user, if underlying user does not exist, create_user() must be called separately
+ pub(crate) fn create_contact(&self, contact: Contact) -> Result<(), Error> {
+ let db = &self.db;
+ db.execute(
+ "insert into roster ( user_jid, name, subscription ) values ( ?1, ?2, ?3 )",
+ (&contact.user_jid, &contact.name, contact.subscription),
+ )?;
+ for group in contact.groups {
+ db.execute(
+ "insert into groups (group_name) values (?1) on conflict do nothing",
+ [&group],
+ )?;
+ db.execute(
+ "insert into groups_roster (group_name, contact_jid) values (?1, ?2)",
+ (group, &contact.user_jid),
+ )?;
+ }
+ Ok(())
+ }
- // pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> {
- // let mut contact: Contact = sqlx::query_as("select * from roster where user_jid = ?")
- // .bind(contact)
- // .fetch_one(&self.db)
- // .await?;
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // group_name: String,
- // }
- // let groups: Vec<Row> =
- // sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
- // .bind(&contact.user_jid)
- // .fetch_all(&self.db)
- // .await?;
- // contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
- // Ok(contact)
- // }
+ pub(crate) fn read_contact(&self, contact: JID) -> Result<Contact, Error> {
+ let db = &self.db;
+ let mut contact_item = db.query_row(
+ "select user_jid, name, subscription from roster where user_jid = ?1",
+ [&contact],
+ |row| {
+ Ok(Contact {
+ user_jid: row.get(0)?,
+ name: row.get(1)?,
+ subscription: row.get(2)?,
+ groups: HashSet::new(),
+ })
+ },
+ )?;
+ let groups: Result<HashSet<String>, _> = db
+ .prepare("select group_name from groups_roster where contact_jid = ?1")?
+ .query_map([&contact], |row| Ok(row.get(0)?))?
+ .collect();
+ contact_item.groups = groups?;
+ Ok(contact_item)
+ }
- // pub(crate) async fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> {
- // let contact: Option<Contact> =
- // sqlx::query_as("select * from roster join users on jid = user_jid where jid = ?")
- // .bind(contact)
- // .fetch_optional(&self.db)
- // .await?;
- // if let Some(mut contact) = contact {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // group_name: String,
- // }
- // let groups: Vec<Row> =
- // sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
- // .bind(&contact.user_jid)
- // .fetch_all(&self.db)
- // .await?;
- // contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
- // Ok(Some(contact))
- // } else {
- // Ok(None)
- // }
- // }
+ pub(crate) fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> {
+ let db = &self.db;
+ let contact_item = db
+ .query_row(
+ "select user_jid, name, subscription from roster where user_jid = ?1",
+ [&contact],
+ |row| {
+ Ok(Contact {
+ user_jid: row.get(0)?,
+ name: row.get(1)?,
+ subscription: row.get(2)?,
+ groups: HashSet::new(),
+ })
+ },
+ )
+ .optional()?;
+ if let Some(mut contact_item) = contact_item {
+ let groups: Result<HashSet<String>, _> = db
+ .prepare("select group_name from groups_roster where contact_jid = ?1")?
+ .query_map([&contact], |row| Ok(row.get(0)?))?
+ .collect();
+ contact_item.groups = groups?;
+ Ok(Some(contact_item))
+ } else {
+ Ok(None)
+ }
+ }
- // /// does not update the underlying user, to update user, update_user() must be called separately
- // pub(crate) async fn update_contact(&self, contact: Contact) -> Result<(), Error> {
- // sqlx::query!(
- // "update roster set name = ?, subscription = ? where user_jid = ?",
- // contact.name,
- // contact.subscription,
- // contact.user_jid
- // )
- // .execute(&self.db)
- // .await?;
- // sqlx::query!(
- // "delete from groups_roster where contact_jid = ?",
- // contact.user_jid
- // )
- // .execute(&self.db)
- // .await?;
- // // TODO: delete orphaned groups from groups table
- // for group in contact.groups {
- // sqlx::query!(
- // "insert into groups (group_name) values (?) on conflict do nothing",
- // group
- // )
- // .execute(&self.db)
- // .await?;
- // sqlx::query!(
- // "insert into groups_roster (group_name, contact_jid) values (?, ?)",
- // group,
- // contact.user_jid
- // )
- // .execute(&self.db)
- // .await?;
- // }
- // Ok(())
- // }
+ /// does not update the underlying user, to update user, update_user() must be called separately
+ pub(crate) fn update_contact(&self, contact: Contact) -> Result<(), Error> {
+ let db = &self.db;
+ db.execute(
+ "update roster set name = ?1, subscription = ?2 where user_jid = ?3",
+ (&contact.name, &contact.subscription, &contact.user_jid),
+ )?;
+ db.execute(
+ "delete from groups_roster where contact_jid = ?1",
+ [&contact.user_jid],
+ )?;
+ for group in contact.groups {
+ db.execute(
+ "insert into groups (group_name) values (?1) on conflict do nothing",
+ [&group],
+ )?;
+ db.execute(
+ "insert into groups_roster (group_name, contact_jid), values (?1, ?2)",
+ (&group, &contact.user_jid),
+ )?;
+ }
+ // TODO: delete orphaned groups from groups table, users etc.
+ Ok(())
+ }
- // pub(crate) async fn upsert_contact(&self, contact: Contact) -> Result<(), Error> {
- // sqlx::query!(
- // "insert into users ( jid ) values ( ? ) on conflict do nothing",
- // contact.user_jid,
- // )
- // .execute(&self.db)
- // .await?;
- // sqlx::query!(
- // "insert into roster ( user_jid, name, subscription ) values ( ?, ?, ? ) on conflict do update set name = ?, subscription = ?",
- // contact.user_jid,
- // contact.name,
- // contact.subscription,
- // contact.name,
- // contact.subscription
- // )
- // .execute(&self.db)
- // .await?;
- // sqlx::query!(
- // "delete from groups_roster where contact_jid = ?",
- // contact.user_jid
- // )
- // .execute(&self.db)
- // .await?;
- // // TODO: delete orphaned groups from groups table
- // for group in contact.groups {
- // sqlx::query!(
- // "insert into groups (group_name) values (?) on conflict do nothing",
- // group
- // )
- // .execute(&self.db)
- // .await?;
- // sqlx::query!(
- // "insert into groups_roster (group_name, contact_jid) values (?, ?)",
- // group,
- // contact.user_jid
- // )
- // .execute(&self.db)
- // .await?;
- // }
- // Ok(())
- // }
+ pub(crate) fn upsert_contact(&self, contact: Contact) -> Result<(), Error> {
+ let db = &self.db;
+ db.execute(
+ "insert into users (jid) values (?1) on conflict do nothing",
+ [&contact.user_jid],
+ )?;
+ db.execute(
+ "insert into roster ( user_jid, name, subscription ) values ( ?1, ?2, ?3 ) on conflict do update set name = ?4, subscription = ?5",
+ (&contact.user_jid, &contact.name, &contact.subscription, &contact.name, &contact.subscription),
+ )?;
+ db.execute(
+ "delete from groups_roster where contact_jid = ?1",
+ [&contact.user_jid],
+ )?;
+ for group in contact.groups {
+ db.execute(
+ "insert into groups (group_name) values (?1) on conflict do nothing",
+ [&group],
+ )?;
+ db.execute(
+ "insert into groups_roster (group_name, contact_jid) values (?1, ?2)",
+ (group, &contact.user_jid),
+ )?;
+ }
+ Ok(())
+ }
- // pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> {
- // sqlx::query!("delete from roster where user_jid = ?", contact)
- // .execute(&self.db)
- // .await?;
- // // TODO: delete orphaned groups from groups table
- // Ok(())
- // }
+ pub(crate) fn delete_contact(&self, contact: JID) -> Result<(), Error> {
+ self.db
+ .execute("delete from roster where user_jid = ?1", [&contact])?;
+ Ok(())
+ }
- // pub(crate) async fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> {
- // sqlx::query!("delete from roster").execute(&self.db).await?;
- // for contact in roster {
- // self.upsert_contact(contact).await?;
- // }
- // Ok(())
- // }
+ pub(crate) fn replace_cached_roster(&self, roster: Vec<Contact>) -> Result<(), Error> {
+ {
+ self.db.execute("delete from roster", [])?;
+ }
+ for contact in roster {
+ self.upsert_contact(contact)?;
+ }
+ Ok(())
+ }
- // pub(crate) async fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> {
- // let mut roster: Vec<Contact> = sqlx::query_as("select * from roster")
- // .fetch_all(&self.db)
- // .await?;
- // for contact in &mut roster {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // group_name: String,
- // }
- // let groups: Vec<Row> =
- // sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
- // .bind(&contact.user_jid)
- // .fetch_all(&self.db)
- // .await?;
- // contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
- // }
- // Ok(roster)
- // }
+ pub(crate) fn read_cached_roster(&self) -> Result<Vec<Contact>, Error> {
+ let db = &self.db;
+ let mut roster: Vec<_> = db
+ .prepare("select user_jid, name, subscription from roster")?
+ .query_map([], |row| {
+ Ok(Contact {
+ user_jid: row.get(0)?,
+ name: row.get(1)?,
+ subscription: row.get(2)?,
+ groups: HashSet::new(),
+ })
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ for contact in &mut roster {
+ let groups: Result<HashSet<String>, _> = db
+ .prepare("select group_name from groups_roster where contact_jid = ?1")?
+ .query_map([&contact.user_jid], |row| Ok(row.get(0)?))?
+ .collect();
+ contact.groups = groups?;
+ }
+ Ok(roster)
+ }
- // pub(crate) async fn read_cached_roster_with_users(
- // &self,
- // ) -> Result<Vec<(Contact, User)>, Error> {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // #[sqlx(flatten)]
- // contact: Contact,
- // #[sqlx(flatten)]
- // user: User,
- // }
- // let mut roster: Vec<Row> =
- // sqlx::query_as("select * from roster join users on jid = user_jid")
- // .fetch_all(&self.db)
- // .await?;
- // for row in &mut roster {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // group_name: String,
- // }
- // let groups: Vec<Row> =
- // sqlx::query_as("select group_name from groups_roster where contact_jid = ?")
- // .bind(&row.contact.user_jid)
- // .fetch_all(&self.db)
- // .await?;
- // row.contact.groups = HashSet::from_iter(groups.into_iter().map(|row| row.group_name));
- // }
- // let roster = roster
- // .into_iter()
- // .map(|row| (row.contact, row.user))
- // .collect();
- // Ok(roster)
- // }
+ pub(crate) fn read_cached_roster_with_users(&self) -> Result<Vec<(Contact, User)>, Error> {
+ let db = &self.db;
+ let mut roster: Vec<(Contact, User)> = db.prepare("select user_jid, name, subscription, jid, nick, avatar from roster join users on jid = user_jid")?.query_map([], |row| {
+ Ok((
+ Contact {
+ user_jid: row.get(0)?,
+ name: row.get(1)?,
+ subscription: row.get(2)?,
+ groups: HashSet::new(),
+ },
+ User {
+ jid: row.get(3)?,
+ nick: row.get(4)?,
+ avatar: row.get(5)?,
+ }
+ ))
+ })?.collect::<Result<Vec<_>, _>>()?;
+ for (contact, _) in &mut roster {
+ let groups: Result<HashSet<String>, _> = db
+ .prepare("select group_name from groups_roster where contact_jid = ?1")?
+ .query_map([&contact.user_jid], |row| Ok(row.get(0)?))?
+ .collect();
+ contact.groups = groups?;
+ }
+ Ok(roster)
+ }
- // pub(crate) async fn create_chat(&self, chat: Chat) -> Result<(), Error> {
- // let id = Uuid::new_v4();
- // let jid = chat.correspondent();
- // sqlx::query!(
- // "insert into chats (id, correspondent, have_chatted) values (?, ?, ?)",
- // id,
- // jid,
- // chat.have_chatted,
- // )
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ pub(crate) fn create_chat(&self, chat: Chat) -> Result<(), Error> {
+ let id = Uuid::new_v4();
+ let jid = chat.correspondent();
+ self.db.execute(
+ "insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3)",
+ (id, jid, chat.have_chatted),
+ )?;
+ Ok(())
+ }
- // // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster.
+ // TODO: what happens if a correspondent changes from a user to a contact? maybe just have correspondent be a user, then have the client make the user show up as a contact in ui if they are in the loaded roster.
- // pub(crate) async fn read_chat(&self, chat: JID) -> Result<Chat, Error> {
- // // check if the chat correponding with the jid exists
- // let chat: Chat = sqlx::query_as("select correspondent from chats where correspondent = ?")
- // .bind(chat)
- // .fetch_one(&self.db)
- // .await?;
- // Ok(chat)
- // }
+ /// should be a bare jid
+ /// TODO: this is NOT a read
+ pub(crate) fn read_chat(&self, chat: JID) -> Result<Chat, Error> {
+ let chat_opt = self.db.query_row(
+ "select correspondent, have_chatted from chats where correspondent = ?1",
+ [&chat],
+ |row| {
+ Ok(Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ })
+ },
+ ).optional()?;
+ match chat_opt {
+ Some(chat) => return Ok(chat),
+ None => {
+ let chat = Chat {
+ correspondent: chat,
+ have_chatted: false,
+ };
+ self.create_chat(chat.clone())?;
+ Ok(chat)
+ }
+ }
+ }
- // pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> {
- // let jid = chat.as_bare();
- // sqlx::query!(
- // "update chats set have_chatted = true where correspondent = ?",
- // jid
- // )
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ pub(crate) fn read_chat_and_user(&self, chat: JID) -> Result<(Chat, User), Error> {
+ let user = self.read_user(chat.clone())?;
+ let chat_opt = self.db.query_row(
+ "select correspondent, have_chatted, jid, nick, avatar from chats join users on correspondent = jid where correspondent = ?1",
+ [&chat],
+ |row| {
+ Ok((
+ Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ },
+ User {
+ jid: row.get(2)?,
+ nick: row.get(3)?,
+ avatar: row.get(4)?,
+ }
+ ))
+ },
+ ).optional()?;
+ match chat_opt {
+ Some(chat) => return Ok(chat),
+ None => {
+ let chat = Chat {
+ correspondent: chat,
+ have_chatted: false,
+ };
+ self.create_chat(chat.clone())?;
+ Ok((chat, user))
+ }
+ }
+ }
- // pub(crate) async fn update_chat_correspondent(
- // &self,
- // old_chat: Chat,
- // new_correspondent: JID,
- // ) -> Result<Chat, Error> {
- // // TODO: update other chat data if it differs (for now there is only correspondent so doesn't matter)
- // let new_jid = &new_correspondent;
- // let old_jid = old_chat.correspondent();
- // sqlx::query!(
- // "update chats set correspondent = ? where correspondent = ?",
- // new_jid,
- // old_jid,
- // )
- // .execute(&self.db)
- // .await?;
- // let chat = self.read_chat(new_correspondent).await?;
- // Ok(chat)
- // }
+ pub(crate) fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> {
+ self.db.execute(
+ "update chats set have_chatted = true where correspondent = ?1",
+ [chat],
+ )?;
+ Ok(())
+ }
- // // pub(crate) async fn update_chat
+ pub(crate) fn update_chat_correspondent(
+ &self,
+ old_chat: Chat,
+ new_correspondent: JID,
+ ) -> Result<Chat, Error> {
+ let new_jid = &new_correspondent;
+ let old_jid = old_chat.correspondent();
+ let chat = self.db.query_row(
+ "update chats set correspondent = ?1 where correspondent = ?2 returning correspondent, have_chatted",
+ [new_jid, old_jid],
+ |row| Ok(Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ })
+ )?;
+ Ok(chat)
+ }
- // pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> {
- // sqlx::query!("delete from chats where correspondent = ?", chat)
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ // pub(crate) fn update_chat
- // /// TODO: sorting and filtering (for now there is no sorting)
- // pub(crate) async fn read_chats(&self) -> Result<Vec<Chat>, Error> {
- // let chats: Vec<Chat> = sqlx::query_as("select * from chats")
- // .fetch_all(&self.db)
- // .await?;
- // Ok(chats)
- // }
+ pub(crate) fn delete_chat(&self, chat: JID) -> Result<(), Error> {
+ self.db
+ .execute("delete from chats where correspondent = ?1", [chat])?;
+ Ok(())
+ }
- // /// chats ordered by date of last message
- // // greatest-n-per-group
- // pub(crate) async fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> {
- // let chats = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")
- // .fetch_all(&self.db)
- // .await?;
- // Ok(chats)
- // }
+ /// TODO: sorting and filtering (for now there is no sorting)
+ pub(crate) fn read_chats(&self) -> Result<Vec<Chat>, Error> {
+ let chats = self
+ .db
+ .prepare("select correspondent, have_chatted from chats")?
+ .query_map([], |row| {
+ Ok(Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ })
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(chats)
+ }
- // /// chats ordered by date of last message
- // // greatest-n-per-group
- // pub(crate) async fn read_chats_ordered_with_latest_messages(
- // &self,
- // ) -> Result<Vec<(Chat, Message)>, Error> {
- // #[derive(sqlx::FromRow)]
- // pub struct RowChat {
- // chat_correspondent: JID,
- // chat_have_chatted: bool,
- // }
- // impl From<RowChat> for Chat {
- // fn from(value: RowChat) -> Self {
- // Self {
- // correspondent: value.chat_correspondent,
- // have_chatted: value.chat_have_chatted,
- // }
- // }
- // }
- // #[derive(sqlx::FromRow)]
- // pub struct RowMessage {
- // message_id: Uuid,
- // message_body: String,
- // message_delivery: Option<Delivery>,
- // message_timestamp: DateTime<Utc>,
- // message_from_jid: JID,
- // }
- // impl From<RowMessage> for Message {
- // fn from(value: RowMessage) -> Self {
- // Self {
- // id: value.message_id,
- // from: value.message_from_jid,
- // delivery: value.message_delivery,
- // timestamp: value.message_timestamp,
- // body: Body {
- // body: value.message_body,
- // },
- // }
- // }
- // }
-
- // #[derive(sqlx::FromRow)]
- // pub struct ChatWithMessageRow {
- // #[sqlx(flatten)]
- // pub chat: RowChat,
- // #[sqlx(flatten)]
- // pub message: RowMessage,
- // }
-
- // pub struct ChatWithMessage {
- // chat: Chat,
- // message: Message,
- // }
-
- // impl From<ChatWithMessageRow> for ChatWithMessage {
- // fn from(value: ChatWithMessageRow) -> Self {
- // Self {
- // chat: value.chat.into(),
- // message: value.message.into(),
- // }
- // }
- // }
-
- // // TODO: sometimes chats have no messages.
- // let chats: Vec<ChatWithMessageRow> = sqlx::query_as("select c.*, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")
- // .fetch_all(&self.db)
- // .await?;
-
- // let chats = chats
- // .into_iter()
- // .map(|chat_with_message_row| {
- // let chat_with_message: ChatWithMessage = chat_with_message_row.into();
- // (chat_with_message.chat, chat_with_message.message)
- // })
- // .collect();
-
- // Ok(chats)
- // }
+ /// chats ordered by date of last message
+ // greatest-n-per-group
+ pub(crate) fn read_chats_ordered(&self) -> Result<Vec<Chat>, Error> {
+ let chats = self
+ .db
+ .prepare("select c.correspondent, c.have_chatted, m.* from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")?
+ .query_map([], |row| {
+ Ok(Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ })
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(chats)
+ }
- // /// chats ordered by date of last message
- // // greatest-n-per-group
- // pub(crate) async fn read_chats_ordered_with_latest_messages_and_users(
- // &self,
- // ) -> Result<Vec<((Chat, User), (Message, User))>, Error> {
- // #[derive(sqlx::FromRow)]
- // pub struct RowChat {
- // chat_correspondent: JID,
- // chat_have_chatted: bool,
- // }
- // impl From<RowChat> for Chat {
- // fn from(value: RowChat) -> Self {
- // Self {
- // correspondent: value.chat_correspondent,
- // have_chatted: value.chat_have_chatted,
- // }
- // }
- // }
- // #[derive(sqlx::FromRow)]
- // pub struct RowMessage {
- // message_id: Uuid,
- // message_body: String,
- // message_delivery: Option<Delivery>,
- // message_timestamp: DateTime<Utc>,
- // message_from_jid: JID,
- // }
- // impl From<RowMessage> for Message {
- // fn from(value: RowMessage) -> Self {
- // Self {
- // id: value.message_id,
- // from: value.message_from_jid,
- // delivery: value.message_delivery,
- // timestamp: value.message_timestamp,
- // body: Body {
- // body: value.message_body,
- // },
- // }
- // }
- // }
- // #[derive(sqlx::FromRow)]
- // pub struct RowChatUser {
- // chat_user_jid: JID,
- // chat_user_nick: Option<String>,
- // chat_user_avatar: Option<String>,
- // }
- // impl From<RowChatUser> for User {
- // fn from(value: RowChatUser) -> Self {
- // Self {
- // jid: value.chat_user_jid,
- // nick: value.chat_user_nick,
- // avatar: value.chat_user_avatar,
- // }
- // }
- // }
- // #[derive(sqlx::FromRow)]
- // pub struct RowMessageUser {
- // message_user_jid: JID,
- // message_user_nick: Option<String>,
- // message_user_avatar: Option<String>,
- // }
- // impl From<RowMessageUser> for User {
- // fn from(value: RowMessageUser) -> Self {
- // Self {
- // jid: value.message_user_jid,
- // nick: value.message_user_nick,
- // avatar: value.message_user_avatar,
- // }
- // }
- // }
- // #[derive(sqlx::FromRow)]
- // pub struct ChatWithMessageAndUsersRow {
- // #[sqlx(flatten)]
- // pub chat: RowChat,
- // #[sqlx(flatten)]
- // pub chat_user: RowChatUser,
- // #[sqlx(flatten)]
- // pub message: RowMessage,
- // #[sqlx(flatten)]
- // pub message_user: RowMessageUser,
- // }
-
- // impl From<ChatWithMessageAndUsersRow> for ChatWithMessageAndUsers {
- // fn from(value: ChatWithMessageAndUsersRow) -> Self {
- // Self {
- // chat: value.chat.into(),
- // chat_user: value.chat_user.into(),
- // message: value.message.into(),
- // message_user: value.message_user.into(),
- // }
- // }
- // }
-
- // pub struct ChatWithMessageAndUsers {
- // chat: Chat,
- // chat_user: User,
- // message: Message,
- // message_user: User,
- // }
-
- // let chats: Vec<ChatWithMessageAndUsersRow> = sqlx::query_as("select c.id as chat_id, c.correspondent as chat_correspondent, c.have_chatted as chat_have_chatted, m.id as message_id, m.body as message_body, m.delivery as message_delivery, m.timestamp as message_timestamp, m.from_jid as message_from_jid, cu.jid as chat_user_jid, cu.nick as chat_user_nick, cu.avatar as chat_user_avatar, mu.jid as message_user_jid, mu.nick as message_user_nick, mu.avatar as message_user_avatar from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp join users as cu on cu.jid = c.correspondent join users as mu on mu.jid = m.from_jid order by m.timestamp desc")
- // .fetch_all(&self.db)
- // .await?;
-
- // let chats = chats
- // .into_iter()
- // .map(|chat_with_message_and_users_row| {
- // let chat_with_message_and_users: ChatWithMessageAndUsers =
- // chat_with_message_and_users_row.into();
- // (
- // (
- // chat_with_message_and_users.chat,
- // chat_with_message_and_users.chat_user,
- // ),
- // (
- // chat_with_message_and_users.message,
- // chat_with_message_and_users.message_user,
- // ),
- // )
- // })
- // .collect();
-
- // Ok(chats)
- // }
+ /// chats ordered by date of last message
+ // greatest-n-per-group
+ pub(crate) fn read_chats_ordered_with_latest_messages(
+ &self,
+ ) -> Result<Vec<(Chat, Message)>, Error> {
+ let chats = self
+ .db
+ .prepare("select c.correspondent, c.have_chatted, m.id, m.from_jid, m.delivery, m.timestamp, m.body from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp order by m.timestamp desc")?
+ .query_map([], |row| {
+ Ok((
+ Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ },
+ Message {
+ id: row.get(2)?,
+ from: row.get(3)?,
+ delivery: row.get(4)?,
+ timestamp: row.get(5)?,
+ body: Body {
+ body: row.get(6)?,
+ },
+ }
+ ))
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(chats)
+ }
- // async fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // id: Uuid,
- // }
- // let chat = chat.as_bare();
- // let chat_id: Row = sqlx::query_as("select id from chats where correspondent = ?")
- // .bind(chat)
- // .fetch_one(&self.db)
- // .await?;
- // let chat_id = chat_id.id;
- // Ok(chat_id)
- // }
+ /// chats ordered by date of last message
+ // greatest-n-per-group
+ pub(crate) fn read_chats_ordered_with_latest_messages_and_users(
+ &self,
+ ) -> Result<Vec<((Chat, User), (Message, User))>, Error> {
+ let chats = self
+ .db
+ .prepare("select c.id as chat_id, c.correspondent as chat_correspondent, c.have_chatted as chat_have_chatted, m.id as message_id, m.body as message_body, m.delivery as message_delivery, m.timestamp as message_timestamp, m.from_jid as message_from_jid, cu.jid as chat_user_jid, cu.nick as chat_user_nick, cu.avatar as chat_user_avatar, mu.jid as message_user_jid, mu.nick as message_user_nick, mu.avatar as message_user_avatar from chats c join (select chat_id, max(timestamp) max_timestamp from messages group by chat_id) max_timestamps on c.id = max_timestamps.chat_id join messages m on max_timestamps.chat_id = m.chat_id and max_timestamps.max_timestamp = m.timestamp join users as cu on cu.jid = c.correspondent join users as mu on mu.jid = m.from_jid order by m.timestamp desc")?
+ .query_map([], |row| {
+ Ok((
+ (
+ Chat {
+ correspondent: row.get("chat_correspondent")?,
+ have_chatted: row.get("chat_have_chatted")?,
+ },
+ User {
+ jid: row.get("chat_user_jid")?,
+ nick: row.get("chat_user_nick")?,
+ avatar: row.get("chat_user_avatar")?,
+ }
+ ),
+ (
+ Message {
+ id: row.get("message_id")?,
+ from: row.get("message_from_jid")?,
+ delivery: row.get("message_delivery")?,
+ timestamp: row.get("message_timestamp")?,
+ body: Body {
+ body: row.get("message_body")?,
+ },
+ },
+ User {
+ jid: row.get("message_user_jid")?,
+ nick: row.get("message_user_nick")?,
+ avatar: row.get("message_user_avatar")?,
+ }
+ ),
+ ))
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(chats)
+ }
- // async fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // id: Uuid,
- // }
- // let chat_id: Option<Row> = sqlx::query_as("select id from chats where correspondent = ?")
- // .bind(chat)
- // .fetch_optional(&self.db)
- // .await?;
- // let chat_id = chat_id.map(|row| row.id);
- // Ok(chat_id)
- // }
+ #[tracing::instrument]
+ fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> {
+ let chat_id = self.db.query_row(
+ "select id from chats where correspondent = ?1",
+ [chat],
+ |row| Ok(row.get(0)?),
+ )?;
+ Ok(chat_id)
+ }
- // /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function.
- // pub(crate) async fn create_message(
- // &self,
- // message: Message,
- // chat: JID,
- // from: JID,
- // ) -> Result<(), Error> {
- // // TODO: one query
- // let from_jid = from.as_bare();
- // let chat_id = self.read_chat_id(chat).await?;
- // sqlx::query!("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp) values (?, ?, ?, ?, ?, ?)", message.id, message.body.body, chat_id, from_jid, from.resourcepart, message.timestamp).execute(&self.db).await?;
- // Ok(())
- // }
+ fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> {
+ let chat_id = self
+ .db
+ .query_row(
+ "select id from chats where correspondent = ?1",
+ [chat],
+ |row| Ok(row.get(0)?),
+ )
+ .optional()?;
+ Ok(chat_id)
+ }
- // pub(crate) async fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> {
- // let bare_chat = chat.as_bare();
- // sqlx::query!(
- // "insert into users (jid) values (?) on conflict do nothing",
- // bare_chat,
- // )
- // .execute(&self.db)
- // .await?;
- // let id = Uuid::new_v4();
- // let chat: Chat = sqlx::query_as("insert into chats (id, correspondent, have_chatted) values (?, ?, ?) on conflict do nothing; select * from chats where correspondent = ?")
- // .bind(id)
- // .bind(bare_chat.clone())
- // .bind(false)
- // .bind(bare_chat)
- // .fetch_one(&self.db)
- // .await?;
- // tracing::debug!("CHECKING chat: {:?}", chat);
- // Ok(chat.have_chatted)
- // }
+ /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function.
+ #[tracing::instrument]
+ pub(crate) fn create_message(
+ &self,
+ message: Message,
+ chat: JID,
+ from: JID,
+ ) -> Result<(), Error> {
+ let from_jid = from.as_bare();
+ let chat_id = self.read_chat_id(chat)?;
+ tracing::debug!("creating message");
+ self.db.execute("insert into messages (id, body, chat_id, from_jid, from_resource, timestamp, delivery) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)", (&message.id, &message.body.body, &chat_id, &from_jid, &from.resourcepart, &message.timestamp, &message.delivery))?;
+ Ok(())
+ }
- // /// MUST upsert chat beforehand
- // pub(crate) async fn create_message_with_self_resource(
- // &self,
- // message: Message,
- // chat: JID,
- // // full jid
- // from: JID,
- // ) -> Result<(), Error> {
- // let from_jid = from.as_bare();
- // if let Some(resource) = &from.resourcepart {
- // sqlx::query!(
- // "insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing",
- // from_jid,
- // resource
- // )
- // .execute(&self.db)
- // .await?;
- // }
- // self.create_message(message, chat, from).await?;
- // Ok(())
- // }
+ pub(crate) fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> {
+ let bare_chat = chat.as_bare();
+ let db = &self.db;
+ db.execute(
+ "insert into users (jid) values (?1) on conflict do nothing",
+ [&bare_chat],
+ )?;
+ let id = Uuid::new_v4();
+ db.execute("insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3) on conflict do nothing", (id, &bare_chat, false))?;
+ let chat = db.query_row(
+ "select correspondent, have_chatted from chats where correspondent = ?1",
+ [&bare_chat],
+ |row| {
+ Ok(Chat {
+ correspondent: row.get(0)?,
+ have_chatted: row.get(1)?,
+ })
+ },
+ )?;
+ Ok(chat.have_chatted)
+ }
- // /// create direct message from incoming. MUST upsert chat and user
- // pub(crate) async fn create_message_with_user_resource(
- // &self,
- // message: Message,
- // chat: JID,
- // // full jid
- // from: JID,
- // ) -> Result<(), Error> {
- // let bare_chat = chat.as_bare();
- // let resource = &chat.resourcepart;
- // // sqlx::query!(
- // // "insert into users (jid) values (?) on conflict do nothing",
- // // bare_chat
- // // )
- // // .execute(&self.db)
- // // .await?;
- // // let id = Uuid::new_v4();
- // // sqlx::query!(
- // // "insert into chats (id, correspondent) values (?, ?) on conflict do nothing",
- // // id,
- // // bare_chat
- // // )
- // // .execute(&self.db)
- // // .await?;
- // if let Some(resource) = resource {
- // sqlx::query!(
- // "insert into resources (bare_jid, resource) values (?, ?) on conflict do nothing",
- // bare_chat,
- // resource
- // )
- // .execute(&self.db)
- // .await?;
- // }
- // self.create_message(message, chat, from).await?;
- // Ok(())
- // }
+ /// create direct message from incoming. MUST upsert chat and user
+ #[tracing::instrument]
+ pub(crate) fn create_message_with_user_resource(
+ &self,
+ message: Message,
+ // TODO: enforce two kinds of jid. bare and full
+ // must be bare jid
+ chat: JID,
+ // full jid
+ from: JID,
+ ) -> Result<(), Error> {
+ let from_jid = from.as_bare();
+ let chat = chat.as_bare();
+ tracing::debug!("creating resource");
+ if let Some(resource) = &from.resourcepart {
+ self.db.execute(
+ "insert into resources (bare_jid, resource) values (?1, ?2) on conflict do nothing",
+ (&from_jid, resource),
+ )?;
+ }
+ self.create_message(message, chat, from)?;
+ Ok(())
+ }
- // pub(crate) async fn read_message(&self, message: Uuid) -> Result<Message, Error> {
- // let message: Message = sqlx::query_as("select * from messages where id = ?")
- // .bind(message)
- // .fetch_one(&self.db)
- // .await?;
- // Ok(message)
+ pub(crate) fn update_message_delivery(
+ &self,
+ message: Uuid,
+ delivery: Delivery,
+ ) -> Result<(), Error> {
+ self.db.execute(
+ "update messages set delivery = ?1 where id = ?2",
+ (delivery, message),
+ )?;
+ Ok(())
+ }
+
+ // pub(crate) fn read_message(&self, message: Uuid) -> Result<Message, Error> {
+ // Ok(Message {
+ // id: Uuid,
+ // from: todo!(),
+ // delivery: todo!(),
+ // timestamp: todo!(),
+ // body: todo!(),
+ // })
// }
- // // TODO: message updates/edits pub(crate) async fn update_message(&self, message: Message) -> Result<(), Error> {}
+ // TODO: message updates/edits pub(crate) fn update_message(&self, message: Message) -> Result<(), Error> {}
- // pub(crate) async fn delete_message(&self, message: Uuid) -> Result<(), Error> {
- // sqlx::query!("delete from messages where id = ?", message)
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ pub(crate) fn delete_message(&self, message: Uuid) -> Result<(), Error> {
+ self.db
+ .execute("delete from messages where id = ?1", [message])?;
+ Ok(())
+ }
- // // TODO: paging
- // pub(crate) async fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> {
- // let chat_id = self.read_chat_id(chat).await?;
- // let messages: Vec<Message> =
- // sqlx::query_as("select * from messages where chat_id = ? order by timestamp asc")
- // .bind(chat_id)
- // .fetch_all(&self.db)
- // .await?;
- // Ok(messages)
- // }
+ pub(crate) fn read_message(&self, message: Uuid) -> Result<Message, Error> {
+ let message = self.db.query_row(
+ "select id, from_jid, delivery, timestamp, body from messages where id = ?1",
+ [&message],
+ |row| {
+ Ok(Message {
+ id: row.get(0)?,
+ // TODO: full from
+ from: row.get(1)?,
+ delivery: row.get(2)?,
+ timestamp: row.get(3)?,
+ body: Body { body: row.get(4)? },
+ })
+ },
+ )?;
+ Ok(message)
+ }
- // pub(crate) async fn read_message_history_with_users(
- // &self,
- // chat: JID,
- // ) -> Result<Vec<(Message, User)>, Error> {
- // let chat_id = self.read_chat_id(chat).await?;
- // #[derive(sqlx::FromRow)]
- // pub struct Row {
- // #[sqlx(flatten)]
- // user: User,
- // #[sqlx(flatten)]
- // message: Message,
- // }
- // let messages: Vec<Row> =
- // sqlx::query_as("select * from messages join users on jid = from_jid where chat_id = ? order by timestamp asc")
- // .bind(chat_id)
- // .fetch_all(&self.db)
- // .await?;
- // let messages = messages
- // .into_iter()
- // .map(|row| (row.message, row.user))
- // .collect();
- // Ok(messages)
- // }
+ // TODO: paging
+ pub(crate) fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> {
+ let chat_id = self.read_chat_id(chat)?;
+ let messages = self
+ .db
+ .prepare(
+ "select id, from_jid, delivery, timestamp, body from messages where chat_id = ?1",
+ )?
+ .query_map([chat_id], |row| {
+ Ok(Message {
+ id: row.get(0)?,
+ // TODO: full from
+ from: row.get(1)?,
+ delivery: row.get(2)?,
+ timestamp: row.get(3)?,
+ body: Body { body: row.get(4)? },
+ })
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(messages)
+ }
- // pub(crate) async fn read_cached_status(&self) -> Result<Online, Error> {
- // let online: Online = sqlx::query_as("select * from cached_status where id = 0")
- // .fetch_one(&self.db)
- // .await?;
- // Ok(online)
- // }
+ pub(crate) fn read_message_history_with_users(
+ &self,
+ chat: JID,
+ ) -> Result<Vec<(Message, User)>, Error> {
+ let chat_id = self.read_chat_id(chat)?;
+ let messages = self
+ .db
+ .prepare(
+ "select id, from_jid, delivery, timestamp, body, jid, nick, avatar from messages join users on jid = from_jid where chat_id = ? order by timestamp asc",
+ )?
+ .query_map([chat_id], |row| {
+ Ok((
+ Message {
+ id: row.get(0)?,
+ // TODO: full from
+ from: row.get(1)?,
+ delivery: row.get(2)?,
+ timestamp: row.get(3)?,
+ body: Body { body: row.get(4)? },
+ },
+ User {
+ jid: row.get(5)?,
+ nick: row.get(6)?,
+ avatar: row.get(7)?,
+ }
+ ))
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(messages)
+ }
- // pub(crate) async fn upsert_cached_status(&self, status: Online) -> Result<(), Error> {
- // sqlx::query!(
- // "insert into cached_status (id, show, message) values (0, ?, ?) on conflict do update set show = ?, message = ?",
- // status.show,
- // status.status,
- // status.show,
- // status.status
- // ).execute(&self.db).await?;
- // Ok(())
- // }
+ pub(crate) fn read_cached_status(&self) -> Result<Online, Error> {
+ let status = self.db.query_row(
+ "select show, message from cached_status where id = 0",
+ [],
+ |row| {
+ Ok(Online {
+ show: row.get(0)?,
+ status: row.get(1)?,
+ priority: None,
+ })
+ },
+ )?;
+ Ok(status)
+ }
- // pub(crate) async fn delete_cached_status(&self) -> Result<(), Error> {
- // sqlx::query!("update cached_status set show = null, message = null where id = 0")
- // .execute(&self.db)
- // .await?;
- // Ok(())
- // }
+ pub(crate) fn upsert_cached_status(&self, status: Online) -> Result<(), Error> {
+ self.db.execute("insert into cached_status (id, show, message) values (0, ?1, ?2) on conflict do update set show = ?3, message = ?4", (status.show, &status.status, status.show, &status.status))?;
+ Ok(())
+ }
- // pub(crate) async fn read_capabilities(&self, node: &str) -> Result<String, Error> {
- // #[derive(sqlx::FromRow)]
- // struct Row {
- // capabilities: String,
- // }
- // let row: Row =
- // sqlx::query_as("select capabilities from capability_hash_nodes where node = ?")
- // .bind(node)
- // .fetch_one(&self.db)
- // .await?;
- // Ok(row.capabilities)
- // }
+ pub(crate) fn delete_cached_status(&self) -> Result<(), Error> {
+ self.db.execute(
+ "update cached_status set show = null, message = null where id = 0",
+ [],
+ )?;
+ Ok(())
+ }
- // pub(crate) async fn upsert_capabilities(
- // &self,
- // node: &str,
- // capabilities: &str,
- // ) -> Result<(), Error> {
- // let now = Utc::now();
- // sqlx::query!(
- // "insert into capability_hash_nodes (node, timestamp, capabilities) values (?, ?, ?) on conflict do update set timestamp = ?, capabilities = ?", node, now, capabilities, now, capabilities
- // ).execute(&self.db).await?;
- // Ok(())
- // }
+ pub(crate) fn read_capabilities(&self, node: String) -> Result<String, Error> {
+ let capabilities = self.db.query_row(
+ "select capabilities from capability_hash_nodes where node = ?1",
+ [node],
+ |row| Ok(row.get(0)?),
+ )?;
+ Ok(capabilities)
+ }
+
+ pub(crate) fn upsert_capabilities(
+ &self,
+ node: String,
+ capabilities: String,
+ ) -> Result<(), Error> {
+ let now = Utc::now();
+ self.db.execute("insert into capability_hash_nodes (node, timestamp, capabilities) values (?1, ?2, ?3) on conflict do update set timestamp = ?, capabilities = ?", (node, now, &capabilities, now, &capabilities))?;
+ Ok(())
+ }
}
diff --git a/filamento/src/error.rs b/filamento/src/error.rs
index 6b7d0ae..af3320f 100644
--- a/filamento/src/error.rs
+++ b/filamento/src/error.rs
@@ -3,12 +3,16 @@ use std::{num::TryFromIntError, string::FromUtf8Error, sync::Arc};
use base64::DecodeError;
use image::ImageError;
use jid::JID;
-use lampada::error::{ActorError, ConnectionError, ReadError, WriteError};
+use lampada::error::{ActorError, ReadError, WriteError};
use stanza::client::{Stanza, iq::Query};
use thiserror::Error;
pub use lampada::error::CommandError;
+pub use lampada::error::ConnectionError;
+use tokio::sync::mpsc::error::SendError;
+use tokio::sync::oneshot::error::RecvError;
+use crate::db::DbCommand;
use crate::files::FileStore;
// for the client logic impl
@@ -165,12 +169,99 @@ pub enum ResponseError {
}
#[derive(Debug, Error, Clone)]
-#[error("database error: {0}")]
-pub struct DatabaseError(pub Arc<rusqlite::Error>);
+pub enum DatabaseError {
+ #[error("database error: {0}")]
+ Database(Serializeable<Arc<rusqlite::Error>>),
+ #[error("database command send: {0}")]
+ Send(Arc<SendError<DbCommand>>),
+ #[error("database result recv: {0}")]
+ Recv(#[from] RecvError),
+}
+
+impl From<SendError<DbCommand>> for DatabaseError {
+ fn from(e: SendError<DbCommand>) -> Self {
+ Self::Send(Arc::new(e))
+ }
+}
+
+pub enum Serializeable<T> {
+ String(String),
+ Unserialized(T),
+}
+
+impl<T: std::fmt::Display> std::fmt::Display for Serializeable<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match &self {
+ Serializeable::String(s) => s.fmt(f),
+ Serializeable::Unserialized(t) => t.fmt(f),
+ }
+ }
+}
+
+impl<T: std::fmt::Debug> std::fmt::Debug for Serializeable<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match &self {
+ Serializeable::String(s) => s.fmt(f),
+ Serializeable::Unserialized(t) => t.fmt(f),
+ }
+ }
+}
+
+impl<T: Clone> Clone for Serializeable<T> {
+ fn clone(&self) -> Self {
+ match self {
+ Serializeable::String(s) => Self::String(s.clone()),
+ Serializeable::Unserialized(t) => Self::Unserialized(t.clone()),
+ }
+ }
+}
+
+#[cfg(feature = "serde")]
+struct StringVisitor;
+
+#[cfg(feature = "serde")]
+impl<'de> serde::de::Visitor<'de> for StringVisitor {
+ type Value = String;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ formatter.write_str("a string")
+ }
+
+ fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error,
+ {
+ Ok(v)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> serde::Deserialize<'de> for DatabaseError {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let string = deserializer.deserialize_string(StringVisitor)?;
+ Ok(Self::Database(Serializeable::String(string)))
+ }
+}
+
+#[cfg(feature = "serde")]
+impl serde::Serialize for DatabaseError {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ match &self.0 {
+ Serializeable::String(s) => serializer.serialize_str(s),
+ Serializeable::Unserialized(u) => serializer.serialize_str(&u.to_string()),
+ }
+ }
+}
impl From<rusqlite::Error> for DatabaseError {
fn from(e: rusqlite::Error) -> Self {
- Self(Arc::new(e))
+ Self::Database(Serializeable::Unserialized(Arc::new(e)))
}
}
@@ -209,6 +300,8 @@ pub enum DatabaseOpenError {
Io(Arc<tokio::io::Error>),
#[error("invalid path")]
InvalidPath,
+ #[error("tokio oneshot recv error: {0}")]
+ Recv(#[from] tokio::sync::oneshot::error::RecvError),
}
// impl From<sqlx::migrate::MigrateError> for DatabaseOpenError {
@@ -237,8 +330,8 @@ pub enum PresenceError {
Unsupported,
#[error("missing from")]
MissingFrom,
- #[error("stanza error: {0}")]
- StanzaError(#[from] stanza::client::error::Error),
+ #[error("stanza error: {0:?}")]
+ StanzaError(Option<stanza::client::error::Error>),
}
#[derive(Debug, Error, Clone)]
diff --git a/filamento/src/files.rs b/filamento/src/files.rs
index 644f883..dcc9cd2 100644
--- a/filamento/src/files.rs
+++ b/filamento/src/files.rs
@@ -9,6 +9,7 @@ use std::{
use tokio::io;
use tokio::sync::Mutex;
+#[cfg(not(target_arch = "wasm32"))]
pub trait FileStore {
type Err: Clone + Send + Error;
@@ -27,6 +28,19 @@ pub trait FileStore {
) -> impl std::future::Future<Output = Result<(), Self::Err>> + std::marker::Send;
}
+#[cfg(target_arch = "wasm32")]
+pub trait FileStore {
+ type Err: Clone + Send + Error;
+
+ fn is_stored(&self, name: &str) -> impl std::future::Future<Output = Result<bool, Self::Err>>;
+ fn store(
+ &self,
+ name: &str,
+ data: &[u8],
+ ) -> impl std::future::Future<Output = Result<(), Self::Err>>;
+ fn delete(&self, name: &str) -> impl std::future::Future<Output = Result<(), Self::Err>>;
+}
+
#[derive(Clone, Debug)]
pub struct FilesMem {
files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
@@ -38,8 +52,19 @@ impl FilesMem {
files: Arc::new(Mutex::new(HashMap::new())),
}
}
+
+ pub async fn get_file(&self, name: impl AsRef<str>) -> Option<Vec<u8>> {
+ let name = name.as_ref();
+ self.files.lock().await.get(name).cloned()
+ }
}
+#[cfg(all(feature = "opfs", target_arch = "wasm32"))]
+pub mod opfs;
+
+#[cfg(all(feature = "opfs", target_arch = "wasm32"))]
+pub use opfs::FilesOPFS;
+
impl FileStore for FilesMem {
type Err = Infallible;
diff --git a/filamento/src/files/opfs.rs b/filamento/src/files/opfs.rs
new file mode 100644
index 0000000..fb32c6e
--- /dev/null
+++ b/filamento/src/files/opfs.rs
@@ -0,0 +1,128 @@
+use std::path::Path;
+
+use thiserror::Error;
+use wasm_bindgen::{JsCast, JsValue};
+use wasm_bindgen_futures::JsFuture;
+use web_sys::{
+ File, FileSystemDirectoryHandle, FileSystemFileHandle, FileSystemGetDirectoryOptions,
+ FileSystemGetFileOptions, FileSystemWritableFileStream, Url, js_sys, window,
+};
+
+use crate::FileStore;
+
+#[derive(Clone)]
+pub struct FilesOPFS {
+ directory: String,
+}
+
+impl FilesOPFS {
+ pub async fn new(directory: impl AsRef<str>) -> Result<Self, OPFSError> {
+ let directory = directory.as_ref();
+ let directory_string = directory.to_string();
+ let promise = window().unwrap().navigator().storage().get_directory();
+ let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into();
+ let options = FileSystemGetDirectoryOptions::new();
+ options.set_create(true);
+ let directory: FileSystemDirectoryHandle =
+ JsFuture::from(opfs_root.get_directory_handle_with_options(directory, &options))
+ .await?
+ .into();
+ Ok(Self {
+ directory: directory_string,
+ })
+ }
+
+ pub async fn get_src(&self, file_name: impl AsRef<str>) -> Result<String, OPFSError> {
+ let promise = window().unwrap().navigator().storage().get_directory();
+ let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into();
+ let directory: FileSystemDirectoryHandle =
+ JsFuture::from(opfs_root.get_directory_handle(&self.directory))
+ .await?
+ .into();
+ let handle: FileSystemFileHandle =
+ JsFuture::from(directory.get_file_handle(file_name.as_ref()))
+ .await?
+ .into();
+ let file: File = JsFuture::from(handle.get_file()).await?.into();
+ let src = Url::create_object_url_with_blob(&file)?;
+ Ok(src)
+ }
+}
+
+impl FileStore for FilesOPFS {
+ type Err = OPFSError;
+
+ async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> {
+ let promise = window().unwrap().navigator().storage().get_directory();
+ let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into();
+ let directory: FileSystemDirectoryHandle =
+ JsFuture::from(opfs_root.get_directory_handle(&self.directory))
+ .await?
+ .into();
+ let stored = JsFuture::from(directory.get_file_handle(name))
+ .await
+ .map(|_| true)
+ // TODO: distinguish between other errors and notfound
+ .unwrap_or(false);
+ Ok(stored)
+ }
+
+ async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> {
+ let promise = window().unwrap().navigator().storage().get_directory();
+ let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into();
+ let directory: FileSystemDirectoryHandle =
+ JsFuture::from(opfs_root.get_directory_handle(&self.directory))
+ .await?
+ .into();
+ let options = FileSystemGetFileOptions::new();
+ options.set_create(true);
+ let handle: FileSystemFileHandle =
+ JsFuture::from(directory.get_file_handle_with_options(name, &options))
+ .await?
+ .into();
+ let write_handle: FileSystemWritableFileStream =
+ JsFuture::from(handle.create_writable()).await?.into();
+
+ let buffer = js_sys::ArrayBuffer::new(data.len() as u32);
+ let u8arr = js_sys::Uint8Array::new(&buffer);
+ for (idx, v) in data.iter().enumerate() {
+ u8arr.set_index(idx as u32, *v);
+ }
+
+ let write_promise = write_handle.write_with_js_u8_array(&u8arr).unwrap();
+ // let write_promise = write_handle.write_with_u8_array(data)?;
+ let _ = JsFuture::from(write_promise).await?;
+ let _ = JsFuture::from(write_handle.close()).await?;
+ Ok(())
+ }
+
+ async fn delete(&self, name: &str) -> Result<(), Self::Err> {
+ let promise = window().unwrap().navigator().storage().get_directory();
+ let opfs_root: FileSystemDirectoryHandle = JsFuture::from(promise).await?.into();
+ let directory: FileSystemDirectoryHandle =
+ JsFuture::from(opfs_root.get_directory_handle(&self.directory))
+ .await?
+ .into();
+ let _ = JsFuture::from(directory.remove_entry(name)).await?;
+ Ok(())
+ }
+}
+
+#[derive(Error, Clone, Debug)]
+pub enum OPFSError {
+ #[error("js opfs error: {0}")]
+ Error(String),
+}
+
+// TODO: better errors
+impl From<JsValue> for OPFSError {
+ fn from(value: JsValue) -> Self {
+ Self::Error(
+ value
+ .dyn_into::<js_sys::Error>()
+ .ok()
+ .and_then(|err| err.message().as_string())
+ .unwrap_or(String::from("<no string>")),
+ )
+ }
+}
diff --git a/filamento/src/lib.rs b/filamento/src/lib.rs
index e06f7c6..068bfe8 100644
--- a/filamento/src/lib.rs
+++ b/filamento/src/lib.rs
@@ -69,7 +69,10 @@ pub enum Command<Fs: FileStore> {
),
/// get a specific chat by jid
GetChat(JID, oneshot::Sender<Result<Chat, DatabaseError>>),
+ /// get a specific chat and user by jid
+ GetChatAndUser(JID, oneshot::Sender<Result<(Chat, User), DatabaseError>>),
/// get message history for chat (does appropriate mam things)
+ GetMessage(Uuid, oneshot::Sender<Result<Message, DatabaseError>>),
// TODO: paging and filtering
GetMessages(JID, oneshot::Sender<Result<Vec<Message>, DatabaseError>>),
/// get message history for chat (does appropriate mam things)
@@ -253,7 +256,7 @@ impl<Fs: FileStore + Clone + Send + Sync + 'static> Client<Fs> {
let client = Self {
sender: command_sender,
// TODO: configure timeout
- timeout: Duration::from_secs(10),
+ timeout: Duration::from_secs(20),
};
let logic = ClientLogic::new(client.clone(), jid.as_bare(), db, update_send, file_store);
@@ -268,9 +271,17 @@ impl<Fs: FileStore + Clone + Send + Sync + 'static> Client<Fs> {
}
impl<Fs: FileStore> Client<Fs> {
- pub async fn connect(&self) -> Result<(), ActorError> {
- self.send(CoreClientCommand::Connect).await?;
- Ok(())
+ /// returns the resource
+ pub async fn connect(&self) -> Result<String, CommandError<ConnectionError>> {
+ let (send, recv) = oneshot::channel::<Result<String, ConnectionError>>();
+ self.send(CoreClientCommand::Connect(send))
+ .await
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?;
+ let result = timeout(self.timeout, recv)
+ .await
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??;
+ Ok(result)
}
pub async fn disconnect(&self, offline: Offline) -> Result<(), ActorError> {
@@ -374,6 +385,30 @@ impl<Fs: FileStore> Client<Fs> {
Ok(chat)
}
+ pub async fn get_chat_and_user(&self, jid: JID) -> Result<(Chat, User), CommandError<DatabaseError>> {
+ let (send, recv) = oneshot::channel();
+ self.send(CoreClientCommand::Command(Command::GetChatAndUser(jid, send)))
+ .await
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?;
+ let result= timeout(self.timeout, recv)
+ .await
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??;
+ Ok(result)
+ }
+
+ pub async fn get_message(&self, id: Uuid) -> Result<Message, CommandError<DatabaseError>> {
+ let (send, recv) = oneshot::channel();
+ self.send(CoreClientCommand::Command(Command::GetMessage(id, send)))
+ .await
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?;
+ let message = timeout(self.timeout, recv)
+ .await
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?
+ .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??;
+ Ok(message)
+ }
+
pub async fn get_messages(
&self,
jid: JID,
diff --git a/filamento/src/logic/local_only.rs b/filamento/src/logic/local_only.rs
index dc94d2c..f5705f4 100644
--- a/filamento/src/logic/local_only.rs
+++ b/filamento/src/logic/local_only.rs
@@ -44,6 +44,20 @@ pub async fn handle_get_chat<Fs: FileStore + Clone>(
Ok(logic.db().read_chat(jid).await?)
}
+pub async fn handle_get_chat_and_user<Fs: FileStore + Clone>(
+ logic: &ClientLogic<Fs>,
+ jid: JID,
+) -> Result<(Chat, User), DatabaseError> {
+ Ok(logic.db().read_chat_and_user(jid).await?)
+}
+
+pub async fn handle_get_message<Fs: FileStore + Clone>(
+ logic: &ClientLogic<Fs>,
+ id: Uuid,
+) -> Result<Message, DatabaseError> {
+ Ok(logic.db().read_message(id).await?)
+}
+
pub async fn handle_get_messages<Fs: FileStore + Clone>(
logic: &ClientLogic<Fs>,
jid: JID,
diff --git a/filamento/src/logic/offline.rs b/filamento/src/logic/offline.rs
index b87484c..606b04f 100644
--- a/filamento/src/logic/offline.rs
+++ b/filamento/src/logic/offline.rs
@@ -19,13 +19,9 @@ use crate::{
};
use super::{
- ClientLogic,
local_only::{
- handle_delete_chat, handle_delete_messaage, handle_get_chat, handle_get_chats,
- handle_get_chats_ordered, handle_get_chats_ordered_with_latest_messages,
- handle_get_chats_ordered_with_latest_messages_and_users, handle_get_messages,
- handle_get_messages_with_users, handle_get_user,
- },
+ handle_delete_chat, handle_delete_messaage, handle_get_chat, handle_get_chat_and_user, handle_get_chats, handle_get_chats_ordered, handle_get_chats_ordered_with_latest_messages, handle_get_chats_ordered_with_latest_messages_and_users, handle_get_message, handle_get_messages, handle_get_messages_with_users, handle_get_user
+ }, ClientLogic
};
pub async fn handle_offline<Fs: FileStore + Clone>(logic: ClientLogic<Fs>, command: Command<Fs>) {
@@ -89,6 +85,14 @@ pub async fn handle_offline_result<Fs: FileStore + Clone>(
let chats = handle_get_chat(logic, jid).await;
sender.send(chats);
}
+ Command::GetChatAndUser(jid, sender) => {
+ let chat = handle_get_chat_and_user(logic, jid).await;
+ let _ = sender.send(chat);
+ }
+ Command::GetMessage(id, sender) => {
+ let message = handle_get_message(logic, id).await;
+ let _ = sender.send(message);
+ }
Command::GetMessages(jid, sender) => {
let messages = handle_get_messages(logic, jid).await;
sender.send(messages);
@@ -159,7 +163,7 @@ pub async fn handle_offline_result<Fs: FileStore + Clone>(
// TODO: mark these as potentially failed upon client launch
if let Err(e) = logic
.db()
- .create_message_with_self_resource(
+ .create_message_with_user_resource(
message.clone(),
jid.clone(),
// TODO: when message is queued and sent, the from must also be updated with the correct resource
diff --git a/filamento/src/logic/online.rs b/filamento/src/logic/online.rs
index 767f923..9814ff2 100644
--- a/filamento/src/logic/online.rs
+++ b/filamento/src/logic/online.rs
@@ -23,7 +23,7 @@ use crate::{
use super::{
local_only::{
- handle_delete_chat, handle_delete_messaage, handle_get_chat, handle_get_chats, handle_get_chats_ordered, handle_get_chats_ordered_with_latest_messages, handle_get_chats_ordered_with_latest_messages_and_users, handle_get_messages, handle_get_messages_with_users, handle_get_user
+ handle_delete_chat, handle_delete_messaage, handle_get_chat, handle_get_chat_and_user, handle_get_chats, handle_get_chats_ordered, handle_get_chats_ordered_with_latest_messages, handle_get_chats_ordered_with_latest_messages_and_users, handle_get_message, handle_get_messages, handle_get_messages_with_users, handle_get_user
}, ClientLogic
};
@@ -477,7 +477,7 @@ pub async fn handle_set_status<Fs: FileStore + Clone>(
pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, connection: Connected, jid: JID, body: Body) {
// upsert the chat and user the message will be delivered to. if there is a conflict, it will return whatever was there, otherwise it will return false by default.
// let have_chatted = logic.db().upsert_chat_and_user(&jid).await.unwrap_or(false);
- let have_chatted = match logic.db().upsert_chat_and_user(&jid).await {
+ let have_chatted = match logic.db().upsert_chat_and_user(jid.clone()).await {
Ok(have_chatted) => {
have_chatted
},
@@ -523,7 +523,7 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>,
// TODO: mark these as potentially failed upon client launch
if let Err(e) = logic
.db()
- .create_message_with_self_resource(message.clone(), jid.clone(), connection.jid().clone())
+ .create_message_with_user_resource(message.clone(), jid.clone(), connection.jid().clone())
.await
{
// TODO: should these really be handle_error or just the error macro?
@@ -583,6 +583,9 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>,
match result {
Ok(_) => {
info!("sent message: {:?}", message_stanza);
+ if let Err(e) = logic.db().update_message_delivery(id, Delivery::Written).await {
+ error!("updating message delivery: {}", e);
+ }
logic
.update_sender()
.send(UpdateMessage::MessageDelivery {
@@ -1107,6 +1110,14 @@ pub async fn handle_online_result<Fs: FileStore + Clone>(
let chat = handle_get_chat(logic, jid).await;
let _ = sender.send(chat);
}
+ Command::GetChatAndUser(jid, sender) => {
+ let chat = handle_get_chat_and_user(logic, jid).await;
+ let _ = sender.send(chat);
+ }
+ Command::GetMessage(id, sender) => {
+ let message = handle_get_message(logic, id).await;
+ let _ = sender.send(message);
+ }
Command::GetMessages(jid, sender) => {
let messages = handle_get_messages(logic, jid).await;
let _ = sender.send(messages);
diff --git a/filamento/src/logic/process_stanza.rs b/filamento/src/logic/process_stanza.rs
index cdaff97..30d0830 100644
--- a/filamento/src/logic/process_stanza.rs
+++ b/filamento/src/logic/process_stanza.rs
@@ -77,9 +77,10 @@ pub async fn recv_message<Fs: FileStore + Clone>(
},
delivery: None,
};
+ // TODO: process message type="error"
// save the message to the database
- match logic.db().upsert_chat_and_user(&from).await {
+ match logic.db().upsert_chat_and_user(from.clone()).await {
Ok(_) => {
if let Err(e) = logic
.db()
@@ -90,17 +91,11 @@ pub async fn recv_message<Fs: FileStore + Clone>(
)
.await
{
- logic
- .handle_error(Error::MessageRecv(MessageRecvError::MessageHistory(e)))
- .await;
- error!("failed to upsert chat and user")
+ error!("failed to create message: {}", e);
}
}
Err(e) => {
- logic
- .handle_error(Error::MessageRecv(MessageRecvError::MessageHistory(e)))
- .await;
- error!("failed to upsert chat and user")
+ error!("failed to upsert chat and user: {}", e);
}
};
@@ -484,13 +479,7 @@ pub async fn recv_presence(
stanza::client::presence::PresenceType::Error => {
// TODO: is there any other information that should go with the error? also MUST have an error, otherwise it's a different error. maybe it shoulnd't be an option.
// TODO: ughhhhhhhhhhhhh these stanza errors should probably just have an option, and custom display
- Err(PresenceError::StanzaError(
- presence
- .errors
- .first()
- .cloned()
- .expect("error MUST have error"),
- ))
+ Err(PresenceError::StanzaError(presence.errors.first().cloned()))
}
// should not happen (error to server)
stanza::client::presence::PresenceType::Probe => {
@@ -595,7 +584,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>(
} else {
match logic
.db()
- .read_capabilities(&query.node.clone().unwrap())
+ .read_capabilities(query.node.clone().unwrap())
.await
{
Ok(c) => match caps::decode_info_base64(c) {
diff --git a/filamento/src/presence.rs b/filamento/src/presence.rs
index e406cce..de4dd7c 100644
--- a/filamento/src/presence.rs
+++ b/filamento/src/presence.rs
@@ -1,4 +1,8 @@
use chrono::{DateTime, Utc};
+use rusqlite::{
+ ToSql,
+ types::{FromSql, ToSqlOutput, Value},
+};
use stanza::{client::presence::String1024, xep_0203::Delay};
use crate::caps;
@@ -10,7 +14,7 @@ pub struct Online {
pub priority: Option<i8>,
}
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Show {
Away,
Chat,
@@ -18,6 +22,30 @@ pub enum Show {
ExtendedAway,
}
+impl ToSql for Show {
+ fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
+ Ok(match self {
+ Show::Away => ToSqlOutput::Owned(Value::Text("away".to_string())),
+ Show::Chat => ToSqlOutput::Owned(Value::Text("chat".to_string())),
+ Show::DoNotDisturb => ToSqlOutput::Owned(Value::Text("do-not-disturb".to_string())),
+ Show::ExtendedAway => ToSqlOutput::Owned(Value::Text("extended-away".to_string())),
+ })
+ }
+}
+
+impl FromSql for Show {
+ fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
+ Ok(match value.as_str()? {
+ "away" => Self::Away,
+ "chat" => Self::Chat,
+ "do-not-disturb" => Self::DoNotDisturb,
+ "extended-away" => Self::ExtendedAway,
+ // TODO: horrible
+ value => panic!("unexpected {value}"),
+ })
+ }
+}
+
#[derive(Debug, Default, Clone)]
pub struct Offline {
pub status: Option<String>,
diff --git a/filamento/src/roster.rs b/filamento/src/roster.rs
index ba5b3cd..6b61e10 100644
--- a/filamento/src/roster.rs
+++ b/filamento/src/roster.rs
@@ -1,13 +1,18 @@
-use std::collections::HashSet;
+use std::{collections::HashSet, fmt::Display};
use jid::JID;
+use rusqlite::{
+ ToSql,
+ types::{FromSql, ToSqlOutput, Value},
+};
pub struct ContactUpdate {
pub name: Option<String>,
pub groups: HashSet<String>,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "reactive_stores", derive(reactive_stores::Store))]
pub struct Contact {
// jid is the id used to reference everything, but not the primary key
pub user_jid: JID,
@@ -17,24 +22,99 @@ pub struct Contact {
// TODO: avatar, nickname
/// nickname picked by contact
// nickname: Option<String>,
+ #[cfg_attr(feature = "reactive_stores", store(key: String = |group| group.clone()))]
pub groups: HashSet<String>,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+/// Contact subscription state.
pub enum Subscription {
+ /// No subscriptions.
None,
+ /// Pending outgoing subscription request.
PendingOut,
+ /// Pending incoming subscription request.
PendingIn,
+ /// Pending incoming & pending outgoing subscription requests.
PendingInPendingOut,
+ /// Subscribed to.
OnlyOut,
+ /// Subscription from.
OnlyIn,
+ /// Subscribed to & pending incoming subscription request.
OutPendingIn,
+ /// Subscription from & pending outgoing subscription request.
InPendingOut,
+ /// Buddy (subscriptions both ways).
Buddy,
// TODO: perhaps don't need, just emit event to remove contact
// Remove,
}
+impl ToSql for Subscription {
+ fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
+ Ok(match self {
+ Subscription::None => ToSqlOutput::Owned(Value::Text("none".to_string())),
+ Subscription::PendingOut => ToSqlOutput::Owned(Value::Text("pending-out".to_string())),
+ Subscription::PendingIn => ToSqlOutput::Owned(Value::Text("pending-in".to_string())),
+ Subscription::PendingInPendingOut => {
+ ToSqlOutput::Owned(Value::Text("pending-in-pending-out".to_string()))
+ }
+ Subscription::OnlyOut => ToSqlOutput::Owned(Value::Text("only-out".to_string())),
+ Subscription::OnlyIn => ToSqlOutput::Owned(Value::Text("only-in".to_string())),
+ Subscription::OutPendingIn => {
+ ToSqlOutput::Owned(Value::Text("out-pending-in".to_string()))
+ }
+ Subscription::InPendingOut => {
+ ToSqlOutput::Owned(Value::Text("in-pending-out".to_string()))
+ }
+ Subscription::Buddy => ToSqlOutput::Owned(Value::Text("buddy".to_string())),
+ })
+ }
+}
+
+impl FromSql for Subscription {
+ fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
+ Ok(match value.as_str()? {
+ "none" => Self::None,
+ "pending-out" => Self::PendingOut,
+ "pending-in" => Self::PendingIn,
+ "pending-in-pending-out" => Self::PendingInPendingOut,
+ "only-out" => Self::OnlyOut,
+ "only-in" => Self::OnlyIn,
+ "out-pending-in" => Self::OutPendingIn,
+ "in-pending-out" => Self::InPendingOut,
+ "buddy" => Self::Buddy,
+ // TODO: don't have these lol
+ value => panic!("unexpected subscription `{value}`"),
+ })
+ }
+}
+
+impl Display for Subscription {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Subscription::None => write!(f, "No Subscriptions"),
+ Subscription::PendingOut => write!(f, "Pending Outgoing Subscription Request"),
+ Subscription::PendingIn => write!(f, "Pending Incoming Subscription Request"),
+ Subscription::PendingInPendingOut => write!(
+ f,
+ "Pending Incoming & Pending Outgoing Subscription Requests"
+ ),
+ Subscription::OnlyOut => write!(f, "Subscribed To"),
+ Subscription::OnlyIn => write!(f, "Subscription From"),
+ Subscription::OutPendingIn => {
+ write!(f, "Subscribed To & Pending Incoming Subscription Request")
+ }
+ Subscription::InPendingOut => write!(
+ f,
+ "Subscription From & Pending Outgoing Subscription Request"
+ ),
+ Subscription::Buddy => write!(f, "Buddy (Subscriptions Both Ways)"),
+ }
+ }
+}
+
// none
// >
// >>
diff --git a/filamento/src/user.rs b/filamento/src/user.rs
index b2ea8e4..f30933c 100644
--- a/filamento/src/user.rs
+++ b/filamento/src/user.rs
@@ -1,6 +1,8 @@
use jid::JID;
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
+#[cfg_attr(feature = "reactive_stores", derive(reactive_stores::Store))]
pub struct User {
pub jid: JID,
pub nick: Option<String>,
diff --git a/jid/Cargo.toml b/jid/Cargo.toml
index e3cf7c7..58d59a4 100644
--- a/jid/Cargo.toml
+++ b/jid/Cargo.toml
@@ -5,9 +5,13 @@ edition = "2021"
[features]
# default = []
+rusqlite = ["dep:rusqlite"]
+serde = ["dep:serde"]
# sqlx = ["dep:sqlx"]
[dependencies]
+serde = { workspace = true, features = ["derive"], optional = true }
+rusqlite = { git = "https://github.com/Spxg/rusqlite.git", optional = true, branch = "wasm-demo" }
# sqlx = { version = "0.8.3", features = ["sqlite"], optional = true }
# sqlx = { path = "../../remote/sqlx", features = ["sqlite"], optional = true }
diff --git a/jid/src/lib.rs b/jid/src/lib.rs
index 8f297c6..47ca497 100644
--- a/jid/src/lib.rs
+++ b/jid/src/lib.rs
@@ -1,9 +1,10 @@
use std::{borrow::Cow, error::Error, fmt::Display, str::FromStr};
-#[cfg(feature = "sqlx")]
-use sqlx::Sqlite;
+// #[cfg(feature = "sqlx")]
+// use sqlx::Sqlite;
#[derive(PartialEq, Debug, Clone, Eq, Hash)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct JID {
// TODO: validate localpart (length, char]
pub localpart: Option<String>,
@@ -33,35 +34,58 @@ impl Display for JID {
}
}
-#[cfg(feature = "sqlx")]
-impl sqlx::Type<Sqlite> for JID {
- fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo {
- <&str as sqlx::Type<Sqlite>>::type_info()
+#[cfg(feature = "rusqlite")]
+impl rusqlite::ToSql for JID {
+ fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
+ Ok(rusqlite::types::ToSqlOutput::Owned(
+ rusqlite::types::Value::Text(self.to_string()),
+ ))
}
}
-#[cfg(feature = "sqlx")]
-impl sqlx::Decode<'_, Sqlite> for JID {
- fn decode(
- value: <Sqlite as sqlx::Database>::ValueRef<'_>,
- ) -> Result<Self, sqlx::error::BoxDynError> {
- let value = <&str as sqlx::Decode<Sqlite>>::decode(value)?;
-
- Ok(value.parse()?)
+#[cfg(feature = "rusqlite")]
+impl rusqlite::types::FromSql for JID {
+ fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> {
+ Ok(JID::from_str(value.as_str()?)?)
}
}
-#[cfg(feature = "sqlx")]
-impl sqlx::Encode<'_, Sqlite> for JID {
- fn encode_by_ref(
- &self,
- buf: &mut <Sqlite as sqlx::Database>::ArgumentBuffer<'_>,
- ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
- let jid = self.to_string();
- <String as sqlx::Encode<Sqlite>>::encode(jid, buf)
+#[cfg(feature = "rusqlite")]
+impl From<ParseError> for rusqlite::types::FromSqlError {
+ fn from(value: ParseError) -> Self {
+ Self::Other(Box::new(value))
}
}
+// #[cfg(feature = "sqlx")]
+// impl sqlx::Type<Sqlite> for JID {
+// fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo {
+// <&str as sqlx::Type<Sqlite>>::type_info()
+// }
+// }
+
+// #[cfg(feature = "sqlx")]
+// impl sqlx::Decode<'_, Sqlite> for JID {
+// fn decode(
+// value: <Sqlite as sqlx::Database>::ValueRef<'_>,
+// ) -> Result<Self, sqlx::error::BoxDynError> {
+// let value = <&str as sqlx::Decode<Sqlite>>::decode(value)?;
+
+// Ok(value.parse()?)
+// }
+// }
+
+// #[cfg(feature = "sqlx")]
+// impl sqlx::Encode<'_, Sqlite> for JID {
+// fn encode_by_ref(
+// &self,
+// buf: &mut <Sqlite as sqlx::Database>::ArgumentBuffer<'_>,
+// ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
+// let jid = self.to_string();
+// <String as sqlx::Encode<Sqlite>>::encode(jid, buf)
+// }
+// }
+
#[derive(Debug, Clone)]
pub enum JIDError {
NoResourcePart,
diff --git a/lampada/Cargo.toml b/lampada/Cargo.toml
index 090aa9f..1937162 100644
--- a/lampada/Cargo.toml
+++ b/lampada/Cargo.toml
@@ -3,19 +3,26 @@ name = "lampada"
version = "0.1.0"
edition = "2021"
+[features]
+serde = ["dep:serde"]
+
[dependencies]
-futures = "0.3.31"
-luz = { version = "0.1.0", path = "../luz" }
-peanuts = { version = "0.1.0", git = "https://bunny.garden/peanuts" }
-jid = { version = "0.1.0", path = "../jid" }
-stanza = { version = "0.1.0", path = "../stanza", features = ["xep_0203"] }
+futures = { workspace = true }
+luz = { workspace = true }
+peanuts = { workspace = true }
+jid = { workspace = true }
+stanza = { workspace = true, features = ["xep_0203"] }
+tracing = { workspace = true }
+thiserror = { workspace = true }
+serde = { workspace = true, features = ["derive"], optional = true }
+
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { workspace = true, features = ["macros", "sync"] }
-tracing = "0.1.41"
-thiserror = "2.0.11"
[target.'cfg(target_arch = "wasm32")'.dependencies]
-tokio = { workspace = true, features = ["macros", "rt", "time", "sync"] }
-tokio_with_wasm = { version = "0.8.2", features = ["macros", "rt", "time", "sync"] }
-
-# [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
-# tokio = { version = "1.42.0", features = ["rt-multi-thread"] }
+tokio_with_wasm = { workspace = true, features = [
+ "macros",
+ "rt",
+ "time",
+ "sync",
+] }
diff --git a/lampada/src/error.rs b/lampada/src/error.rs
index 40be012..f29d0cc 100644
--- a/lampada/src/error.rs
+++ b/lampada/src/error.rs
@@ -1,10 +1,10 @@
use std::sync::Arc;
-#[cfg(not(target_arch = "wasm32"))]
-use ::tokio::time::error::Elapsed;
use stanza::client::Stanza;
use thiserror::Error;
use tokio::sync::{mpsc::error::SendError, oneshot::error::RecvError};
+#[cfg(not(target_arch = "wasm32"))]
+use tokio::time::error::Elapsed;
#[cfg(target_arch = "wasm32")]
use tokio::time::Elapsed;
#[cfg(target_arch = "wasm32")]
@@ -28,6 +28,7 @@ pub enum ConnectionError {
}
#[derive(Debug, Error, Clone)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum CommandError<T> {
#[error("actor: {0}")]
Actor(ActorError),
@@ -61,6 +62,7 @@ pub enum ReadError {
}
#[derive(Debug, Error, Clone)]
+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ActorError {
#[error("receive timed out")]
Timeout,
diff --git a/lampada/src/lib.rs b/lampada/src/lib.rs
index dacc56d..6b6cbe8 100644
--- a/lampada/src/lib.rs
+++ b/lampada/src/lib.rs
@@ -217,9 +217,10 @@ where
else => break,
};
match msg {
- CoreClientCommand::Connect => {
+ CoreClientCommand::Connect(sender) => {
match self.connected {
Some(_) => {
+ sender.send(Err(ConnectionError::AlreadyConnected));
self.logic
.clone()
.handle_connection_error(ConnectionError::AlreadyConnected)
@@ -238,9 +239,10 @@ where
self.logic
.clone()
.handle_connection_error(ConnectionError::InvalidServerJID(
- e,
+ e.clone(),
))
.await;
+ sender.send(Err(ConnectionError::InvalidServerJID(e)));
continue;
}
};
@@ -260,6 +262,7 @@ where
let shutdown_recv = shutdown_recv.fuse();
self.connection_supervisor_shutdown = shutdown_recv;
+ let resource = jid.resourcepart.clone().expect("client somehow connected without binding");
let connected = Connected {
jid,
write_handle: writer,
@@ -269,15 +272,18 @@ where
self.logic.clone().handle_connect(connected.clone()).await;
self.connected = Some((connected, supervisor));
+ // REMEMBER TO NOTIFY IT@S GOOD
+ sender.send(Ok(resource));
}
Err(e) => {
tracing::error!("error: {}", e);
self.logic
.clone()
.handle_connection_error(ConnectionError::ConnectionFailed(
- e.into(),
+ e.clone().into(),
))
.await;
+ sender.send(Err(ConnectionError::ConnectionFailed(e)));
}
}
}
@@ -315,7 +321,7 @@ where
pub enum CoreClientCommand<C> {
// TODO: login invisible xep-0186
/// connect to XMPP chat server. gets roster and publishes initial presence.
- Connect,
+ Connect(oneshot::Sender<Result<String, ConnectionError>>),
/// disconnect from XMPP chat server, sending unavailable presence then closing stream.
Disconnect,
/// TODO: generics
diff --git a/luz/Cargo.toml b/luz/Cargo.toml
index 51c6936..e9cccd9 100644
--- a/luz/Cargo.toml
+++ b/luz/Cargo.toml
@@ -10,51 +10,55 @@ crate-type = ["cdylib", "rlib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-async-recursion = "1.0.4"
-async-trait = "0.1.68"
-lazy_static = "1.4.0"
-uuid = { version = "1.13.1", features = ["v4"] }
-# TODO: remove unneeded features and dependencies
-rsasl = { version = "2.0.1", default_features = false, features = [
+rsasl = { version = "2.0.1", default-features = false, features = [
"provider_base64",
"plain",
"config_builder",
"scram-sha-1",
] }
-tokio = { workspace = true, features = ["io-util"] }
-tracing = "0.1.40"
-try_map = "0.3.1"
-stanza = { version = "0.1.0", path = "../stanza" }
-peanuts = { version = "0.1.0", git = "https://bunny.garden/peanuts" }
-# peanuts = { version = "0.1.0", path = "../../peanuts" }
-jid = { version = "0.1.0", path = "../jid" }
-futures = "0.3.31"
-take_mut = "0.2.2"
-pin-project-lite = "0.2.15"
-pin-project = "1.1.7"
-thiserror = "2.0.11"
+uuid = { workspace = true, features = ["v4"] }
+tracing = { workspace = true }
+stanza = { workspace = true, features = ["xep_0156"] }
+peanuts = { workspace = true }
+jid = { workspace = true }
+thiserror = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
-tokio = { workspace = true, features = ["io-util", "sync"] }
-uuid = { version = "1.13.1", features = ["js", "v4"] }
+tokio = { workspace = true, features = ["macros"] }
+uuid = { workspace = true, features = ["js", "v4"] }
+# TODO: check this
getrandom = { version = "0.2.15", features = ["js"] }
-stanza = { version = "0.1.0", path = "../stanza", features = ["rfc_7395"] }
-web-sys = { version = "0.3", features = ["Request", "WebSocket"] }
-wasm-bindgen = "0.2"
+stanza = { workspace = true, features = [
+ "rfc_7395",
+ "xep_0156",
+] }
+web-sys = { workspace = true, features = [
+ "Request",
+ "WebSocket",
+ "RequestInit",
+ "Request",
+ "Window",
+ "Response",
+ "ErrorEvent",
+] }
+js-sys = { workspace = true }
+wasm-bindgen = { workspace = true }
+wasm-bindgen-futures = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
-tokio = { workspace = true, features = ["io-util", "sync"] }
+tokio = { workspace = true }
tokio-native-tls = "0.3.1"
trust-dns-resolver = "0.22.0"
[dev-dependencies]
-tracing-wasm = "0.2.1"
-wasm-bindgen-test = "0.3.0"
+# TODO: clean up dev dependencies and write tests
+tracing-wasm = { workspace = true }
+wasm-bindgen-test = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt", "time"] }
-test-log = { version = "0.2", features = ["trace"] }
-env_logger = "*"
-tracing-subscriber = { version = "0.3", default-features = false, features = [
+test-log = { workspace = true, features = ["trace"] }
+env_logger = { workspace = true }
+tracing-subscriber = { workspace = true, default-features = false, features = [
"env-filter",
"fmt",
] }
-stanza = { version = "0.1.0", path = "../stanza", features = ["xep_0199"] }
+stanza = { workspace = true, features = ["xep_0199"] }
diff --git a/luz/src/client/ws.rs b/luz/src/client/ws.rs
index ecb64cb..13c3cdf 100644
--- a/luz/src/client/ws.rs
+++ b/luz/src/client/ws.rs
@@ -5,8 +5,7 @@ use stanza::{
};
use crate::{
- connection::Ws, jabber_stream::bound_stream::BoundJabberStream, Connection, Error,
- JabberStream, Result, JID,
+ jabber_stream::bound_stream::BoundJabberStream, Connection, Error, JabberStream, Result, JID,
};
pub async fn connect_and_login(
diff --git a/luz/src/connection/ws.rs b/luz/src/connection/ws.rs
index fc983b1..e64a96e 100644
--- a/luz/src/connection/ws.rs
+++ b/luz/src/connection/ws.rs
@@ -1,9 +1,14 @@
+use js_sys::Error;
+use peanuts::{ReadableString, Reader};
+use stanza::xep_0156::XRD;
use tokio::sync::mpsc;
+use tracing::debug;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
-use web_sys::WebSocket;
+use wasm_bindgen_futures::JsFuture;
+use web_sys::{ErrorEvent, Request, RequestInit, Response, WebSocket};
-use crate::Result;
+use crate::error::ConnectionError;
pub type Ws = WebSocket;
@@ -11,10 +16,70 @@ pub type Ws = WebSocket;
pub struct Connection(pub Ws);
impl Connection {
- pub async fn connect(server: impl AsRef<str> + std::fmt::Debug) -> Result<Self> {
+ pub async fn connect(
+ server: impl AsRef<str> + std::fmt::Debug,
+ ) -> Result<Self, ConnectionError> {
// TODO: get the connection url here
- let ws = WebSocket::new_with_str("wss://xmpp.bunny.garden/ws", "xmpp").unwrap();
- let (send, mut recv) = mpsc::unbounded_channel();
+ debug!("creating websocket");
+
+ let opts = RequestInit::new();
+ opts.set_method("GET");
+ let host_meta_url = format!("https://{}/.well-known/host-meta", server.as_ref());
+
+ let request = Request::new_with_str_and_init(&host_meta_url, &opts).map_err(|e| {
+ let error: Error = e.into();
+ ConnectionError::CreateHostMeta(error.message().as_string().unwrap())
+ })?;
+
+ let window = web_sys::window().unwrap();
+ let resp_value = JsFuture::from(window.fetch_with_request(&request))
+ .await
+ .map_err(|e| {
+ let error: Error = e.into();
+ ConnectionError::FetchHostMeta(error.message().as_string().unwrap())
+ })?;
+
+ let resp: Response = resp_value.dyn_into().unwrap();
+
+ let text = JsFuture::from(resp.text().map_err(|e| {
+ let error: Error = e.into();
+ ConnectionError::FetchHostMeta(error.message().as_string().unwrap())
+ })?)
+ .await
+ .map_err(|e| {
+ let error: Error = e.into();
+ ConnectionError::FetchHostMeta(error.message().as_string().unwrap())
+ })?;
+
+ let host_meta = text.as_string().ok_or(ConnectionError::HostMetaText)?;
+
+ let readable_string = ReadableString(host_meta);
+ let mut reader = Reader::new(readable_string);
+
+ reader.read_prolog().await.unwrap();
+
+ let xrd: XRD = reader.read().await?;
+
+ let link = xrd
+ .links
+ .iter()
+ .find(|link| link.rel.as_deref() == Some("urn:xmpp:alt-connections:websocket"))
+ .ok_or(ConnectionError::MissingWebsocketLink)?;
+
+ let url = link.href.as_ref().ok_or(ConnectionError::LinkMissingHref)?;
+
+ Connection::connect_url(url).await
+ }
+
+ pub async fn connect_url(url: impl AsRef<str>) -> Result<Self, ConnectionError> {
+ let url = url.as_ref();
+ let ws = WebSocket::new_with_str(url, "xmpp").map_err(|error| {
+ let error: js_sys::Error = error.into();
+ let message = error.message().as_string().unwrap();
+ ConnectionError::Create(url.to_string(), message)
+ })?;
+ debug!("created websocket");
+ let (send, mut open_recv) = mpsc::unbounded_channel();
let onopen = Closure::<dyn FnMut()>::new(Box::new(move || {
tracing::info!("socket opened");
let send = send.clone();
@@ -25,9 +90,29 @@ impl Connection {
}
}
}) as Box<dyn FnMut()>);
+ let (send, mut error_recv) = mpsc::unbounded_channel();
+ // TODO: get error event message
+ let onerror = Closure::<dyn FnMut(_)>::new(Box::new(move |_e: ErrorEvent| {
+ // error will always be 1006, so doesn't matter.
+ tracing::error!("connection error");
+ match send.send(()) {
+ Ok(()) => (),
+ Err(e) => {
+ tracing::error!("socket error notify: {:?}", e);
+ }
+ }
+ }) as Box<dyn FnMut(_)>);
ws.set_onopen(Some(onopen.as_ref().unchecked_ref()));
+ ws.set_onerror(Some(onerror.as_ref().unchecked_ref()));
+
+ tokio::select! {
+ _error = error_recv.recv() => { Err(ConnectionError::Connect(url.to_string()))? },
+ Some(_open) = open_recv.recv() => { },
+ else => { Err(ConnectionError::Connect(url.to_string()))? }
+ }
- recv.recv().await.unwrap();
+ ws.set_onopen(None);
+ ws.set_onerror(None);
// TODO: check reply if it's xmpp too
Ok(Self(ws))
diff --git a/luz/src/error.rs b/luz/src/error.rs
index 6b08c15..fcb32a0 100644
--- a/luz/src/error.rs
+++ b/luz/src/error.rs
@@ -13,6 +13,9 @@ pub enum Error {
#[cfg(not(target_arch = "wasm32"))]
#[error("connection")]
Connection,
+ #[cfg(target_arch = "wasm32")]
+ #[error("connection: {0}")]
+ Connection(#[from] ConnectionError),
#[error("utf8 decode: {0}")]
Utf8Decode(#[from] Utf8Error),
#[error("negotiation")]
@@ -57,3 +60,24 @@ impl From<rsasl::prelude::SASLError> for SASLError {
Self::SASL(Arc::new(e))
}
}
+
+#[cfg(target_arch = "wasm32")]
+#[derive(Error, Debug, Clone)]
+pub enum ConnectionError {
+ #[error("creating websocket at \"{0}\": {1}")]
+ Create(String, String),
+ #[error("failed to connect to \"{0}\"")]
+ Connect(String),
+ #[error("failed to create host-meta request: {0}")]
+ CreateHostMeta(String),
+ #[error("fetching host meta: {0}")]
+ FetchHostMeta(String),
+ #[error("getting host meta text")]
+ HostMetaText,
+ #[error("parsing host meta xrd: {0}")]
+ XRDParse(#[from] peanuts::Error),
+ #[error("XRD missing websocket Link")]
+ MissingWebsocketLink,
+ #[error("XRD websocket Link missing href")]
+ LinkMissingHref,
+}
diff --git a/luz/src/jabber_stream.rs b/luz/src/jabber_stream.rs
index 4332366..f77e6a9 100644
--- a/luz/src/jabber_stream.rs
+++ b/luz/src/jabber_stream.rs
@@ -8,9 +8,9 @@ use std::str::{self, FromStr};
use std::sync::Arc;
use jid::JID;
-use peanuts::element::IntoElement;
+use peanuts::IntoElement;
#[cfg(target_arch = "wasm32")]
-use peanuts::reader::WebSocketOnMessageRead;
+use peanuts::WebSocketOnMessageRead;
use peanuts::{Reader, Writer};
use rsasl::prelude::{Mechname, SASLClient, SASLConfig};
use stanza::bind::{Bind, BindType, FullJidType, ResourceType};
@@ -19,8 +19,12 @@ use stanza::client::Stanza;
#[cfg(target_arch = "wasm32")]
use stanza::rfc_7395::Open;
use stanza::sasl::{Auth, Challenge, Mechanisms, Response, ServerResponse};
+#[cfg(not(target_arch = "wasm32"))]
use stanza::starttls::{Proceed, StartTls};
-use stanza::stream::{Features, Stream};
+use stanza::stream::Features;
+#[cfg(not(target_arch = "wasm32"))]
+use stanza::stream::Stream;
+#[cfg(not(target_arch = "wasm32"))]
use stanza::XML_VERSION;
#[cfg(not(target_arch = "wasm32"))]
use tokio_native_tls::native_tls::TlsConnector;
@@ -31,8 +35,6 @@ use web_sys::{wasm_bindgen::JsCast, WebSocket};
use crate::connection::Connection;
#[cfg(not(target_arch = "wasm32"))]
use crate::connection::Tls;
-#[cfg(target_arch = "wasm32")]
-use crate::connection::Ws;
use crate::error::Error;
use crate::Result;
diff --git a/luz/src/jabber_stream/bound_stream.rs b/luz/src/jabber_stream/bound_stream.rs
index 13f8b2d..74ced14 100644
--- a/luz/src/jabber_stream/bound_stream.rs
+++ b/luz/src/jabber_stream/bound_stream.rs
@@ -1,7 +1,5 @@
use std::ops::{Deref, DerefMut};
-use tokio::io::{AsyncRead, AsyncWrite};
-
use super::{JabberReader, JabberStream, JabberWriter};
pub struct BoundJabberStream(JabberStream);
diff --git a/luz/src/jabber_stream/tcp.rs b/luz/src/jabber_stream/tcp.rs
index 77305e3..550c308 100644
--- a/luz/src/jabber_stream/tcp.rs
+++ b/luz/src/jabber_stream/tcp.rs
@@ -1,4 +1,4 @@
-use peanuts::loggable::Loggable;
+use peanuts::Loggable;
use peanuts::{Reader, Writer};
use tokio::io::{ReadHalf, WriteHalf};
diff --git a/luz/src/jabber_stream/ws.rs b/luz/src/jabber_stream/ws.rs
index 35b6f60..72801e6 100644
--- a/luz/src/jabber_stream/ws.rs
+++ b/luz/src/jabber_stream/ws.rs
@@ -1,10 +1,9 @@
-use peanuts::loggable::Loggable;
-use peanuts::reader::WebSocketOnMessageRead;
+use peanuts::WebSocketOnMessageRead;
use peanuts::{Reader, Writer};
use stanza::rfc_7395::Close;
use web_sys::WebSocket;
-use crate::{Connection, Result};
+use crate::Result;
// open stream (streams started)
#[derive(Debug)]
@@ -43,7 +42,7 @@ impl JabberReader {
impl JabberReader {
pub async fn try_close(&mut self) -> Result<()> {
- let close: Close = self.read().await?;
+ let _close: Close = self.read().await?;
Ok(())
}
}
diff --git a/stanza/Cargo.toml b/stanza/Cargo.toml
index 2832ed6..884584a 100644
--- a/stanza/Cargo.toml
+++ b/stanza/Cargo.toml
@@ -4,10 +4,10 @@ version = "0.1.0"
edition = "2021"
[dependencies]
-peanuts = { version = "0.1.0", git = "https://bunny.garden/peanuts" }
-jid = { version = "0.1.0", path = "../jid" }
-thiserror = "2.0.11"
-chrono = { version = "0.4.40", optional = true }
+peanuts = { workspace = true }
+jid = { workspace = true }
+thiserror = { workspace = true }
+chrono = { workspace = true, optional = true }
[features]
rfc_6121 = []
@@ -20,6 +20,7 @@ xep_0084 = []
xep_0115 = []
xep_0128 = ["xep_0004"]
xep_0131 = []
+xep_0156 = ["dep:chrono"]
xep_0172 = []
xep_0199 = []
xep_0203 = ["dep:chrono"]
diff --git a/stanza/src/bind.rs b/stanza/src/bind.rs
index f72c510..3ce2246 100644
--- a/stanza/src/bind.rs
+++ b/stanza/src/bind.rs
@@ -1,8 +1,5 @@
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-bind";
@@ -12,7 +9,7 @@ pub struct Bind {
}
impl FromElement for Bind {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("bind")?;
element.check_namespace(XMLNS)?;
@@ -23,7 +20,7 @@ impl FromElement for Bind {
}
impl IntoElement for Bind {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("bind", Some(XMLNS)).push_child_opt(self.r#type.clone())
}
}
@@ -35,7 +32,7 @@ pub enum BindType {
}
impl FromElement for BindType {
- fn from_element(element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(XMLNS), "resource") => {
Ok(BindType::Resource(ResourceType::from_element(element)?))
@@ -47,7 +44,7 @@ impl FromElement for BindType {
}
impl IntoElement for BindType {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
BindType::Resource(resource_type) => resource_type.builder(),
BindType::Jid(full_jid_type) => full_jid_type.builder(),
@@ -60,7 +57,7 @@ impl IntoElement for BindType {
pub struct FullJidType(pub JID);
impl FromElement for FullJidType {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("jid")?;
element.check_namespace(XMLNS)?;
@@ -71,7 +68,7 @@ impl FromElement for FullJidType {
}
impl IntoElement for FullJidType {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("jid", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -81,7 +78,7 @@ impl IntoElement for FullJidType {
pub struct ResourceType(pub String);
impl FromElement for ResourceType {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("resource")?;
element.check_namespace(XMLNS)?;
@@ -92,7 +89,7 @@ impl FromElement for ResourceType {
}
impl IntoElement for ResourceType {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("resource", Some(XMLNS)).push_text(self.0.clone())
}
}
diff --git a/stanza/src/client/error.rs b/stanza/src/client/error.rs
index c4ab517..9cc85a9 100644
--- a/stanza/src/client/error.rs
+++ b/stanza/src/client/error.rs
@@ -1,8 +1,7 @@
use std::fmt::Display;
use std::str::FromStr;
-use peanuts::element::{FromElement, IntoElement};
-use peanuts::{DeserializeError, Element};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
use thiserror::Error;
use crate::stanza_error::Error as StanzaError;
@@ -40,7 +39,7 @@ impl Display for Error {
}
impl FromElement for Error {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("error")?;
element.check_name(XMLNS)?;
@@ -59,7 +58,7 @@ impl FromElement for Error {
}
impl IntoElement for Error {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("error", Some(XMLNS))
.push_attribute_opt("by", self.by.clone())
.push_attribute("type", self.r#type)
diff --git a/stanza/src/client/iq.rs b/stanza/src/client/iq.rs
index a1d58f6..478530a 100644
--- a/stanza/src/client/iq.rs
+++ b/stanza/src/client/iq.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element, XML_NS,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS};
use crate::{
bind::{self, Bind},
@@ -60,7 +57,7 @@ pub enum Query {
}
impl FromElement for Query {
- fn from_element(element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(bind::XMLNS), "bind") => Ok(Query::Bind(Bind::from_element(element)?)),
#[cfg(feature = "xep_0199")]
@@ -89,7 +86,7 @@ impl FromElement for Query {
}
impl IntoElement for Query {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
Query::Bind(bind) => bind.builder(),
#[cfg(feature = "xep_0199")]
@@ -111,7 +108,7 @@ impl IntoElement for Query {
}
impl FromElement for Iq {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("iq")?;
element.check_namespace(XMLNS)?;
@@ -136,7 +133,7 @@ impl FromElement for Iq {
}
impl IntoElement for Iq {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("iq", Some(XMLNS))
.push_attribute_opt("from", self.from.clone())
.push_attribute("id", self.id.clone())
diff --git a/stanza/src/client/message.rs b/stanza/src/client/message.rs
index 78258ca..41761d2 100644
--- a/stanza/src/client/message.rs
+++ b/stanza/src/client/message.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element, XML_NS,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS};
#[cfg(feature = "xep_0060")]
use crate::xep_0060::event::Event;
@@ -40,7 +37,7 @@ pub struct Message {
}
impl FromElement for Message {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("message")?;
element.check_namespace(XMLNS)?;
@@ -88,7 +85,7 @@ impl FromElement for Message {
}
impl IntoElement for Message {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("message", Some(XMLNS))
.push_attribute_opt("from", self.from.clone())
.push_attribute_opt("id", self.id.clone())
@@ -166,7 +163,7 @@ pub struct Body {
}
impl FromElement for Body {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("body")?;
element.check_namespace(XMLNS)?;
@@ -178,7 +175,7 @@ impl FromElement for Body {
}
impl IntoElement for Body {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("body", Some(XMLNS))
.push_attribute_opt_namespaced(XML_NS, "lang", self.lang.clone())
.push_text_opt(self.body.clone())
@@ -192,7 +189,7 @@ pub struct Subject {
}
impl FromElement for Subject {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subject")?;
element.check_namespace(XMLNS)?;
@@ -204,7 +201,7 @@ impl FromElement for Subject {
}
impl IntoElement for Subject {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subject", Some(XMLNS))
.push_attribute_opt_namespaced(XML_NS, "lang", self.lang.clone())
.push_text_opt(self.subject.clone())
@@ -218,7 +215,7 @@ pub struct Thread {
}
impl FromElement for Thread {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("thread")?;
element.check_namespace(XMLNS)?;
@@ -230,7 +227,7 @@ impl FromElement for Thread {
}
impl IntoElement for Thread {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("thread", Some(XMLNS))
.push_attribute_opt("parent", self.parent.clone())
.push_text_opt(self.thread.clone())
diff --git a/stanza/src/client/mod.rs b/stanza/src/client/mod.rs
index a1b2de5..aca4fad 100644
--- a/stanza/src/client/mod.rs
+++ b/stanza/src/client/mod.rs
@@ -1,9 +1,7 @@
+use peanuts::{Content, ContentBuilder, DeserializeError, FromContent, FromElement, IntoContent};
+
use iq::Iq;
use message::Message;
-use peanuts::{
- element::{Content, ContentBuilder, FromContent, FromElement, IntoContent},
- DeserializeError,
-};
use presence::Presence;
use super::stream::{self, Error as StreamError};
@@ -26,7 +24,7 @@ pub enum Stanza {
}
impl FromContent for Stanza {
- fn from_content(content: Content) -> peanuts::element::DeserializeResult<Self> {
+ fn from_content(content: Content) -> peanuts::DeserializeResult<Self> {
match content {
Content::Element(element) => Ok(Stanza::from_element(element)?),
Content::Text(_) => Ok(Stanza::OtherContent(content)),
@@ -37,7 +35,7 @@ impl FromContent for Stanza {
}
impl FromElement for Stanza {
- fn from_element(element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(XMLNS), "message") => Ok(Stanza::Message(Message::from_element(element)?)),
(Some(XMLNS), "presence") => Ok(Stanza::Presence(Presence::from_element(element)?)),
@@ -51,7 +49,7 @@ impl FromElement for Stanza {
}
impl IntoContent for Stanza {
- fn builder(&self) -> peanuts::element::ContentBuilder {
+ fn builder(&self) -> peanuts::ContentBuilder {
match self {
Stanza::Message(message) => <Message as IntoContent>::builder(message),
Stanza::Presence(presence) => <Presence as IntoContent>::builder(presence),
diff --git a/stanza/src/client/presence.rs b/stanza/src/client/presence.rs
index a8c35d0..b0a0bc0 100644
--- a/stanza/src/client/presence.rs
+++ b/stanza/src/client/presence.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element, XML_NS,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS};
#[cfg(feature = "xep_0115")]
use crate::xep_0115::C;
@@ -41,7 +38,7 @@ pub struct Presence {
}
impl FromElement for Presence {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("presence")?;
element.check_namespace(XMLNS)?;
@@ -91,7 +88,7 @@ impl FromElement for Presence {
}
impl IntoElement for Presence {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("presence", Some(XMLNS))
.push_attribute_opt("from", self.from.clone())
.push_attribute_opt("id", self.id.clone())
@@ -174,7 +171,7 @@ pub enum Show {
}
impl FromElement for Show {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("show")?;
element.check_namespace(XMLNS)?;
@@ -197,7 +194,7 @@ impl FromStr for Show {
}
impl IntoElement for Show {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("show", Some(XMLNS)).push_text(*self)
}
}
@@ -220,7 +217,7 @@ pub struct Status {
}
impl FromElement for Status {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("status")?;
element.check_namespace(XMLNS)?;
@@ -232,7 +229,7 @@ impl FromElement for Status {
}
impl IntoElement for Status {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("status", Some(XMLNS))
.push_attribute_opt_namespaced(XML_NS, "lang", self.lang.clone())
.push_text(self.status.clone())
@@ -263,7 +260,7 @@ impl ToString for String1024 {
pub struct Priority(pub i8);
impl FromElement for Priority {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("priority")?;
element.check_namespace(XMLNS)?;
@@ -272,7 +269,7 @@ impl FromElement for Priority {
}
impl IntoElement for Priority {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("priority", Some(XMLNS)).push_text(self.0)
}
}
diff --git a/stanza/src/lib.rs b/stanza/src/lib.rs
index 5e30cd0..8f8d430 100644
--- a/stanza/src/lib.rs
+++ b/stanza/src/lib.rs
@@ -25,6 +25,8 @@ pub mod xep_0084;
pub mod xep_0115;
#[cfg(feature = "xep_0131")]
pub mod xep_0131;
+#[cfg(feature = "xep_0156")]
+pub mod xep_0156;
#[cfg(feature = "xep_0172")]
pub mod xep_0172;
#[cfg(feature = "xep_0199")]
diff --git a/stanza/src/rfc_7395.rs b/stanza/src/rfc_7395.rs
index 23b9e5d..64d9f70 100644
--- a/stanza/src/rfc_7395.rs
+++ b/stanza/src/rfc_7395.rs
@@ -1,8 +1,5 @@
use jid::JID;
-use peanuts::{
- element::{ElementBuilder, FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, ElementBuilder, FromElement, IntoElement};
pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-framing";
diff --git a/stanza/src/roster.rs b/stanza/src/roster.rs
index 0181193..14f65ef 100644
--- a/stanza/src/roster.rs
+++ b/stanza/src/roster.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
pub const XMLNS: &str = "jabber:iq:roster";
@@ -15,7 +12,7 @@ pub struct Query {
}
impl FromElement for Query {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("query")?;
element.check_namespace(XMLNS)?;
@@ -27,7 +24,7 @@ impl FromElement for Query {
}
impl IntoElement for Query {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("query", Some(XMLNS))
.push_attribute_opt("ver", self.ver.clone())
.push_children(self.items.clone())
@@ -50,7 +47,7 @@ pub struct Item {
}
impl FromElement for Item {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("item")?;
element.check_namespace(XMLNS)?;
@@ -83,7 +80,7 @@ impl FromElement for Item {
}
impl IntoElement for Item {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("item", Some(XMLNS))
.push_attribute_opt("approved", self.approved)
.push_attribute_opt(
@@ -143,7 +140,7 @@ impl ToString for Subscription {
pub struct Group(pub Option<String>);
impl FromElement for Group {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("group")?;
element.check_namespace(XMLNS)?;
@@ -154,7 +151,7 @@ impl FromElement for Group {
}
impl IntoElement for Group {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("group", Some(XMLNS)).push_text_opt(self.0.clone())
}
}
diff --git a/stanza/src/sasl.rs b/stanza/src/sasl.rs
index 598a91b..58aab84 100644
--- a/stanza/src/sasl.rs
+++ b/stanza/src/sasl.rs
@@ -1,9 +1,6 @@
use std::{fmt::Display, ops::Deref};
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
use thiserror::Error;
pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-sasl";
@@ -14,7 +11,7 @@ pub struct Mechanisms {
}
impl FromElement for Mechanisms {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("mechanisms")?;
element.check_namespace(XMLNS)?;
let mechanisms: Vec<Mechanism> = element.pop_children()?;
@@ -27,7 +24,7 @@ impl FromElement for Mechanisms {
}
impl IntoElement for Mechanisms {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("mechanisms", Some(XMLNS)).push_children(
self.mechanisms
.iter()
@@ -40,7 +37,7 @@ impl IntoElement for Mechanisms {
pub struct Mechanism(String);
impl FromElement for Mechanism {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("mechanism")?;
element.check_namespace(XMLNS)?;
@@ -51,7 +48,7 @@ impl FromElement for Mechanism {
}
impl IntoElement for Mechanism {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("mechanism", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -71,7 +68,7 @@ pub struct Auth {
}
impl IntoElement for Auth {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("auth", Some(XMLNS))
.push_attribute("mechanism", self.mechanism.clone())
.push_text(self.sasl_data.clone())
@@ -90,7 +87,7 @@ impl Deref for Challenge {
}
impl FromElement for Challenge {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("challenge")?;
element.check_namespace(XMLNS)?;
@@ -112,7 +109,7 @@ impl Deref for Success {
}
impl FromElement for Success {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("success")?;
element.check_namespace(XMLNS)?;
@@ -130,7 +127,7 @@ pub enum ServerResponse {
}
impl FromElement for ServerResponse {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(XMLNS), "challenge") => {
Ok(ServerResponse::Challenge(Challenge::from_element(element)?))
@@ -164,7 +161,7 @@ impl Deref for Response {
}
impl IntoElement for Response {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("response", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -212,7 +209,7 @@ impl Display for Failure {
}
impl FromElement for Failure {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("failure")?;
element.check_namespace(XMLNS)?;
@@ -250,7 +247,7 @@ pub enum FailureType {
}
impl FromElement for FailureType {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(XMLNS), "aborted") => Ok(FailureType::Aborted),
(Some(XMLNS), "account-disabled") => Ok(FailureType::AccountDisabled),
@@ -276,7 +273,7 @@ pub struct Text {
}
impl FromElement for Text {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("text")?;
element.check_namespace(XMLNS)?;
diff --git a/stanza/src/stanza_error.rs b/stanza/src/stanza_error.rs
index 664a168..8fb862f 100644
--- a/stanza/src/stanza_error.rs
+++ b/stanza/src/stanza_error.rs
@@ -1,9 +1,6 @@
// https://datatracker.ietf.org/doc/html/rfc6120#appendix-A.8
-use peanuts::{
- element::{FromElement, IntoElement},
- Element, XML_NS,
-};
+use peanuts::{Element, FromElement, IntoElement, XML_NS};
use thiserror::Error;
#[cfg(feature = "xep_0060")]
@@ -64,7 +61,7 @@ pub enum Error {
}
impl FromElement for Error {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
let error;
match element.identify() {
(Some(XMLNS), "bad-request") => error = Error::BadRequest,
@@ -101,7 +98,7 @@ impl FromElement for Error {
}
impl IntoElement for Error {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
Error::BadRequest => Element::builder("bad-request", Some(XMLNS)),
Error::Conflict => Element::builder("conflict", Some(XMLNS)),
@@ -142,7 +139,7 @@ pub struct Text {
}
impl FromElement for Text {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("text")?;
element.check_name(XMLNS)?;
@@ -154,7 +151,7 @@ impl FromElement for Text {
}
impl IntoElement for Text {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("text", Some(XMLNS))
.push_attribute_opt_namespaced(XML_NS, "lang", self.lang.clone())
.push_text_opt(self.text.clone())
diff --git a/stanza/src/starttls.rs b/stanza/src/starttls.rs
index b0e0f0f..730c044 100644
--- a/stanza/src/starttls.rs
+++ b/stanza/src/starttls.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-tls";
@@ -11,7 +8,7 @@ pub struct StartTls {
}
impl IntoElement for StartTls {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let mut builder = Element::builder("starttls", Some(XMLNS));
if self.required {
@@ -42,7 +39,7 @@ impl FromElement for StartTls {
pub struct Required;
impl FromElement for Required {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("required")?;
element.check_namespace(XMLNS)?;
@@ -51,7 +48,7 @@ impl FromElement for Required {
}
impl IntoElement for Required {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("required", Some(XMLNS))
}
}
@@ -60,13 +57,13 @@ impl IntoElement for Required {
pub struct Proceed;
impl IntoElement for Proceed {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("proceed", Some(XMLNS))
}
}
impl FromElement for Proceed {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("proceed")?;
element.check_namespace(XMLNS)?;
@@ -77,13 +74,13 @@ impl FromElement for Proceed {
pub struct Failure;
impl IntoElement for Failure {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("failure", Some(XMLNS))
}
}
impl FromElement for Failure {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("failure")?;
element.check_namespace(XMLNS)?;
diff --git a/stanza/src/stream.rs b/stanza/src/stream.rs
index eb07999..5be235a 100644
--- a/stanza/src/stream.rs
+++ b/stanza/src/stream.rs
@@ -1,8 +1,7 @@
use std::fmt::Display;
use jid::JID;
-use peanuts::element::{ElementBuilder, FromElement, IntoElement};
-use peanuts::Element;
+use peanuts::{Element, ElementBuilder, FromElement, IntoElement};
use thiserror::Error;
use crate::bind;
@@ -165,7 +164,7 @@ impl IntoElement for Feature {
}
impl FromElement for Feature {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(starttls::XMLNS), "starttls") => {
Ok(Feature::StartTls(StartTls::from_element(element)?))
@@ -198,7 +197,7 @@ impl Display for Error {
}
impl FromElement for Error {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("error")?;
element.check_namespace(XMLNS)?;
diff --git a/stanza/src/stream_error.rs b/stanza/src/stream_error.rs
index 03d48eb..19ad1ae 100644
--- a/stanza/src/stream_error.rs
+++ b/stanza/src/stream_error.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element, XML_NS,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS};
use thiserror::Error;
pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-streams";
@@ -61,7 +58,7 @@ pub enum Error {
}
impl FromElement for Error {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
let error;
match element.identify() {
(Some(XMLNS), "bad-format") => error = Error::BadFormat,
@@ -99,7 +96,7 @@ impl FromElement for Error {
}
impl IntoElement for Error {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
Error::BadFormat => Element::builder("bad-format", Some(XMLNS)),
Error::BadNamespacePrefix => Element::builder("bad-namespace-prefix", Some(XMLNS)),
@@ -143,7 +140,7 @@ pub struct Text {
}
impl FromElement for Text {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("text")?;
element.check_name(XMLNS)?;
@@ -155,7 +152,7 @@ impl FromElement for Text {
}
impl IntoElement for Text {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("text", Some(XMLNS))
.push_attribute_opt_namespaced(XML_NS, "lang", self.lang.clone())
.push_text_opt(self.text.clone())
diff --git a/stanza/src/xep_0004.rs b/stanza/src/xep_0004.rs
index f929517..f6ff7a0 100644
--- a/stanza/src/xep_0004.rs
+++ b/stanza/src/xep_0004.rs
@@ -1,9 +1,6 @@
use std::str::FromStr;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
pub const XMLNS: &str = "jabber:x:data";
@@ -18,7 +15,7 @@ pub struct X {
}
impl FromElement for X {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("x")?;
element.check_namespace(XMLNS)?;
@@ -42,7 +39,7 @@ impl FromElement for X {
}
impl IntoElement for X {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("x", Some(XMLNS))
.push_attribute("type", self.r#type.clone())
.push_children(self.instructions.clone())
@@ -91,7 +88,7 @@ impl ToString for XType {
pub struct Instructions(pub String);
impl FromElement for Instructions {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("instructions")?;
element.check_namespace(XMLNS)?;
@@ -100,7 +97,7 @@ impl FromElement for Instructions {
}
impl IntoElement for Instructions {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("instructions", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -109,7 +106,7 @@ impl IntoElement for Instructions {
pub struct Title(pub String);
impl FromElement for Title {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("instructions")?;
element.check_namespace(XMLNS)?;
@@ -118,7 +115,7 @@ impl FromElement for Title {
}
impl IntoElement for Title {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("title", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -135,7 +132,7 @@ pub struct Field {
}
impl FromElement for Field {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("field")?;
element.check_namespace(XMLNS)?;
@@ -166,7 +163,7 @@ impl FromElement for Field {
}
impl IntoElement for Field {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let mut builder = Element::builder("field", Some(XMLNS))
.push_attribute_opt("label", self.label.clone())
.push_attribute_opt("type", self.r#type.clone())
@@ -239,7 +236,7 @@ impl ToString for FieldType {
pub struct Desc(pub String);
impl FromElement for Desc {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("desc")?;
element.check_namespace(XMLNS)?;
@@ -248,7 +245,7 @@ impl FromElement for Desc {
}
impl IntoElement for Desc {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("desc", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -257,7 +254,7 @@ impl IntoElement for Desc {
pub struct Required;
impl FromElement for Required {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("required")?;
element.check_namespace(XMLNS)?;
@@ -266,7 +263,7 @@ impl FromElement for Required {
}
impl IntoElement for Required {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("required", Some(XMLNS))
}
}
@@ -278,7 +275,7 @@ pub struct XOption {
}
impl FromElement for XOption {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("option")?;
element.check_namespace(XMLNS)?;
@@ -291,7 +288,7 @@ impl FromElement for XOption {
}
impl IntoElement for XOption {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("option", Some(XMLNS))
.push_attribute_opt("label", self.label.clone())
.push_child(self.value.clone())
@@ -302,7 +299,7 @@ impl IntoElement for XOption {
pub struct Value(pub String);
impl FromElement for Value {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("value")?;
element.check_namespace(XMLNS)?;
@@ -311,7 +308,7 @@ impl FromElement for Value {
}
impl IntoElement for Value {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("value", Some(XMLNS)).push_text(self.0.clone())
}
}
@@ -323,7 +320,7 @@ pub struct Reported {
}
impl FromElement for Reported {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("reported")?;
element.check_namespace(XMLNS)?;
@@ -334,7 +331,7 @@ impl FromElement for Reported {
}
impl IntoElement for Reported {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("reported", Some(XMLNS)).push_children(self.fields.clone())
}
}
@@ -345,7 +342,7 @@ pub struct Item {
}
impl FromElement for Item {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("item")?;
element.check_namespace(XMLNS)?;
@@ -356,7 +353,7 @@ impl FromElement for Item {
}
impl IntoElement for Item {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("item", Some(XMLNS)).push_children(self.fields.clone())
}
}
diff --git a/stanza/src/xep_0030/info.rs b/stanza/src/xep_0030/info.rs
index 539934f..0344ccb 100644
--- a/stanza/src/xep_0030/info.rs
+++ b/stanza/src/xep_0030/info.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element, XML_NS,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS};
#[cfg(feature = "xep_0128")]
use crate::xep_0004::X;
@@ -22,7 +19,7 @@ pub struct Query {
}
impl FromElement for Query {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("query")?;
element.check_namespace(XMLNS)?;
@@ -50,7 +47,7 @@ impl FromElement for Query {
}
impl IntoElement for Query {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("query", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_children(self.features.clone())
@@ -78,7 +75,7 @@ pub struct Identity {
}
impl FromElement for Identity {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("identity")?;
element.check_namespace(XMLNS)?;
@@ -109,7 +106,7 @@ impl FromElement for Identity {
}
impl IntoElement for Identity {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("identity", Some(XMLNS))
.push_attribute("category", self.category.clone())
.push_attribute_opt("name", self.name.clone())
@@ -124,7 +121,7 @@ pub struct Feature {
}
impl FromElement for Feature {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("feature")?;
element.check_namespace(XMLNS)?;
@@ -135,7 +132,7 @@ impl FromElement for Feature {
}
impl IntoElement for Feature {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("feature", Some(XMLNS)).push_attribute("var", self.var.clone())
}
}
diff --git a/stanza/src/xep_0030/items.rs b/stanza/src/xep_0030/items.rs
index 471f3e1..7707eac 100644
--- a/stanza/src/xep_0030/items.rs
+++ b/stanza/src/xep_0030/items.rs
@@ -1,8 +1,5 @@
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
#[cfg(feature = "xep_0059")]
use crate::xep_0059::Set;
@@ -18,7 +15,7 @@ pub struct Query {
}
impl FromElement for Query {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("query")?;
element.check_namespace(XMLNS)?;
@@ -39,7 +36,7 @@ impl FromElement for Query {
}
impl IntoElement for Query {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("query", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_children(self.items.clone());
@@ -59,7 +56,7 @@ pub struct Item {
}
impl FromElement for Item {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("item")?;
element.check_namespace(XMLNS)?;
@@ -72,7 +69,7 @@ impl FromElement for Item {
}
impl IntoElement for Item {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("item", Some(XMLNS))
.push_attribute("jid", self.jid.clone())
.push_attribute_opt("name", self.name.clone())
diff --git a/stanza/src/xep_0059.rs b/stanza/src/xep_0059.rs
index 01dbc6c..6490ad1 100644
--- a/stanza/src/xep_0059.rs
+++ b/stanza/src/xep_0059.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "http://jabber.org/protocol/rsm";
@@ -17,7 +14,7 @@ pub struct Set {
}
impl FromElement for Set {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("set")?;
element.check_namespace(XMLNS)?;
@@ -42,7 +39,7 @@ impl FromElement for Set {
}
impl IntoElement for Set {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("set", Some(XMLNS))
.push_child_opt(self.after.clone())
.push_child_opt(self.before.clone())
@@ -58,7 +55,7 @@ impl IntoElement for Set {
pub struct After(pub String);
impl FromElement for After {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("after")?;
element.check_namespace(XMLNS)?;
@@ -67,7 +64,7 @@ impl FromElement for After {
}
impl IntoElement for After {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
// TODO: better way for push_text to work, empty string should be empty element no matter what
let builder = Element::builder("after", Some(XMLNS));
@@ -83,7 +80,7 @@ impl IntoElement for After {
pub struct Before(pub String);
impl FromElement for Before {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("before")?;
element.check_namespace(XMLNS)?;
@@ -92,7 +89,7 @@ impl FromElement for Before {
}
impl IntoElement for Before {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
// TODO: better way for push_text to work, empty string should be empty element no matter what
let builder = Element::builder("before", Some(XMLNS));
@@ -108,7 +105,7 @@ impl IntoElement for Before {
pub struct Count(pub i32);
impl FromElement for Count {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("count")?;
element.check_namespace(XMLNS)?;
@@ -117,7 +114,7 @@ impl FromElement for Count {
}
impl IntoElement for Count {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("count", Some(XMLNS)).push_text(self.0)
}
}
@@ -126,7 +123,7 @@ impl IntoElement for Count {
pub struct Index(pub i32);
impl FromElement for Index {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("index")?;
element.check_namespace(XMLNS)?;
@@ -135,7 +132,7 @@ impl FromElement for Index {
}
impl IntoElement for Index {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("index", Some(XMLNS)).push_text(self.0)
}
}
@@ -144,7 +141,7 @@ impl IntoElement for Index {
pub struct Last(pub String);
impl FromElement for Last {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("last")?;
element.check_namespace(XMLNS)?;
@@ -153,7 +150,7 @@ impl FromElement for Last {
}
impl IntoElement for Last {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
// TODO: better way for push_text to work, empty string should be empty element no matter what
let builder = Element::builder("last", Some(XMLNS));
@@ -169,7 +166,7 @@ impl IntoElement for Last {
pub struct Max(pub i32);
impl FromElement for Max {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("max")?;
element.check_namespace(XMLNS)?;
@@ -178,7 +175,7 @@ impl FromElement for Max {
}
impl IntoElement for Max {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("max", Some(XMLNS)).push_text(self.0)
}
}
@@ -190,7 +187,7 @@ pub struct First {
}
impl FromElement for First {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("first")?;
element.check_namespace(XMLNS)?;
@@ -203,7 +200,7 @@ impl FromElement for First {
}
impl IntoElement for First {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder =
Element::builder("first", Some(XMLNS)).push_attribute_opt("index", self.index);
diff --git a/stanza/src/xep_0060/errors.rs b/stanza/src/xep_0060/errors.rs
index e6817ac..6c6c530 100644
--- a/stanza/src/xep_0060/errors.rs
+++ b/stanza/src/xep_0060/errors.rs
@@ -1,9 +1,6 @@
use std::{fmt::Display, str::FromStr};
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
use thiserror::Error;
use crate::{client::error::ErrorType, stanza_error::Error as StanzaError};
@@ -121,7 +118,7 @@ impl Error {
}
impl FromElement for Error {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(XMLNS), "closed-node") => Ok(Self::ClosedNode),
(Some(XMLNS), "configuration-required") => Ok(Self::ConfigurationRequired),
@@ -154,7 +151,7 @@ impl FromElement for Error {
}
impl IntoElement for Error {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
Error::ClosedNode => Element::builder("closed-node", Some(XMLNS)),
Error::ConfigurationRequired => Element::builder("configuration-required", Some(XMLNS)),
diff --git a/stanza/src/xep_0060/event.rs b/stanza/src/xep_0060/event.rs
index 1be011d..3cb124b 100644
--- a/stanza/src/xep_0060/event.rs
+++ b/stanza/src/xep_0060/event.rs
@@ -2,10 +2,7 @@ use std::str::FromStr;
use chrono::{DateTime, Utc};
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
use crate::xep_0004::X;
#[cfg(feature = "xep_0084")]
@@ -26,7 +23,7 @@ pub enum Event {
}
impl FromElement for Event {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("event")?;
element.check_namespace(XMLNS)?;
@@ -49,7 +46,7 @@ impl FromElement for Event {
}
impl IntoElement for Event {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("event", Some(XMLNS));
match self {
@@ -70,7 +67,7 @@ pub struct Collection {
}
impl FromElement for Collection {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("node")?;
element.check_namespace(XMLNS)?;
@@ -82,7 +79,7 @@ impl FromElement for Collection {
}
impl IntoElement for Collection {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("collection", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_child(self.r#type.clone())
@@ -96,7 +93,7 @@ pub enum CollectionType {
}
impl FromElement for CollectionType {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
(Some(XMLNS), "associate") => {
Ok(CollectionType::Associate(Associate::from_element(element)?))
@@ -110,7 +107,7 @@ impl FromElement for CollectionType {
}
impl IntoElement for CollectionType {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
CollectionType::Associate(associate) => associate.builder(),
CollectionType::Disassociate(disassociate) => disassociate.builder(),
@@ -124,7 +121,7 @@ pub struct Associate {
}
impl FromElement for Associate {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("associate")?;
element.check_namespace(XMLNS)?;
@@ -135,7 +132,7 @@ impl FromElement for Associate {
}
impl IntoElement for Associate {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("associate", Some(XMLNS)).push_attribute("node", self.node.clone())
}
}
@@ -146,7 +143,7 @@ pub struct Disassociate {
}
impl FromElement for Disassociate {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("disassociate")?;
element.check_namespace(XMLNS)?;
@@ -157,7 +154,7 @@ impl FromElement for Disassociate {
}
impl IntoElement for Disassociate {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("disassociate", Some(XMLNS)).push_attribute("node", self.node.clone())
}
}
@@ -169,7 +166,7 @@ pub struct Configuration {
}
impl FromElement for Configuration {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("configuration")?;
element.check_namespace(XMLNS)?;
@@ -185,7 +182,7 @@ impl FromElement for Configuration {
}
impl IntoElement for Configuration {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("configuration", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_child_opt(self.configuration.clone())
@@ -199,7 +196,7 @@ pub struct Delete {
}
impl FromElement for Delete {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("delete")?;
element.check_namespace(XMLNS)?;
@@ -212,7 +209,7 @@ impl FromElement for Delete {
}
impl IntoElement for Delete {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("delete", Some(XMLNS))
.push_attribute("node", self.node.clone())
.push_child_opt(self.redirect.clone())
@@ -226,7 +223,7 @@ pub struct Items {
}
impl FromElement for Items {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("items")?;
element.check_namespace(XMLNS)?;
@@ -243,7 +240,7 @@ impl FromElement for Items {
}
impl IntoElement for Items {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder =
Element::builder("items", Some(XMLNS)).push_attribute("node", self.node.clone());
@@ -268,7 +265,7 @@ pub struct Item {
}
impl FromElement for Item {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("item")?;
element.check_namespace(XMLNS)?;
@@ -286,7 +283,7 @@ impl FromElement for Item {
}
impl IntoElement for Item {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("item", Some(XMLNS))
.push_attribute_opt("id", self.id.clone())
.push_attribute_opt("publisher", self.publisher.clone())
@@ -306,7 +303,7 @@ pub enum Content {
}
impl FromElement for Content {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
#[cfg(feature = "xep_0172")]
(Some(xep_0172::XMLNS), "nick") => Ok(Content::Nick(Nick::from_element(element)?)),
@@ -324,7 +321,7 @@ impl FromElement for Content {
}
impl IntoElement for Content {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
#[cfg(feature = "xep_0172")]
Content::Nick(nick) => nick.builder(),
@@ -343,7 +340,7 @@ pub struct Purge {
}
impl FromElement for Purge {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("purge")?;
element.check_namespace(XMLNS)?;
@@ -354,7 +351,7 @@ impl FromElement for Purge {
}
impl IntoElement for Purge {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("purge", Some(XMLNS)).push_attribute("node", self.node.clone())
}
}
@@ -365,7 +362,7 @@ pub struct Redirect {
}
impl FromElement for Redirect {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("redirect")?;
element.check_namespace(XMLNS)?;
@@ -376,7 +373,7 @@ impl FromElement for Redirect {
}
impl IntoElement for Redirect {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("redirect", Some(XMLNS)).push_attribute("uri", self.uri.clone())
}
}
@@ -387,7 +384,7 @@ pub struct Retract {
}
impl FromElement for Retract {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("retract")?;
element.check_namespace(XMLNS)?;
@@ -398,7 +395,7 @@ impl FromElement for Retract {
}
impl IntoElement for Retract {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("retract", Some(XMLNS)).push_attribute("id", self.id.clone())
}
}
@@ -413,7 +410,7 @@ pub struct Subscription {
}
impl FromElement for Subscription {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscription")?;
element.check_namespace(XMLNS)?;
@@ -434,7 +431,7 @@ impl FromElement for Subscription {
}
impl IntoElement for Subscription {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subscription", Some(XMLNS))
.push_attribute_opt("expiry", self.expiry)
.push_attribute("jid", self.jid.clone())
diff --git a/stanza/src/xep_0060/owner.rs b/stanza/src/xep_0060/owner.rs
index 7cf4355..0617712 100644
--- a/stanza/src/xep_0060/owner.rs
+++ b/stanza/src/xep_0060/owner.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
use crate::xep_0004::X;
@@ -21,7 +18,7 @@ pub enum Pubsub {
}
impl FromElement for Pubsub {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("pubsub")?;
element.check_namespace(XMLNS)?;
@@ -44,7 +41,7 @@ impl FromElement for Pubsub {
}
impl IntoElement for Pubsub {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("pubsub", Some(XMLNS));
match self {
@@ -65,7 +62,7 @@ pub struct Affiliations {
}
impl FromElement for Affiliations {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("affiliations")?;
element.check_namespace(XMLNS)?;
@@ -78,7 +75,7 @@ impl FromElement for Affiliations {
}
impl IntoElement for Affiliations {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("affiliations", Some(XMLNS))
.push_attribute("node", self.node.clone())
.push_children(self.affiliations.clone())
@@ -92,7 +89,7 @@ pub struct Affiliation {
}
impl FromElement for Affiliation {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("affiliation")?;
element.check_namespace(XMLNS)?;
@@ -104,7 +101,7 @@ impl FromElement for Affiliation {
}
impl IntoElement for Affiliation {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("affiliation", Some(XMLNS))
.push_attribute("affiliation", self.affiliation.clone())
.push_attribute("jid", self.jid.clone())
@@ -158,7 +155,7 @@ pub struct Configure {
}
impl FromElement for Configure {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("configure")?;
element.check_namespace(XMLNS)?;
@@ -171,7 +168,7 @@ impl FromElement for Configure {
}
impl IntoElement for Configure {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("configure", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_child_opt(self.configure.clone())
@@ -182,7 +179,7 @@ impl IntoElement for Configure {
pub struct Default(Option<X>);
impl FromElement for Default {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("default")?;
element.check_namespace(XMLNS)?;
@@ -191,7 +188,7 @@ impl FromElement for Default {
}
impl IntoElement for Default {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("default", Some(XMLNS)).push_child_opt(self.0.clone())
}
}
@@ -203,7 +200,7 @@ pub struct Delete {
}
impl FromElement for Delete {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("delete")?;
element.check_namespace(XMLNS)?;
@@ -216,7 +213,7 @@ impl FromElement for Delete {
}
impl IntoElement for Delete {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("delete", Some(XMLNS))
.push_attribute("node", self.node.clone())
.push_child_opt(self.redirect.clone())
@@ -229,7 +226,7 @@ pub struct Purge {
}
impl FromElement for Purge {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("purge")?;
element.check_namespace(XMLNS)?;
@@ -240,7 +237,7 @@ impl FromElement for Purge {
}
impl IntoElement for Purge {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("purge", Some(XMLNS)).push_attribute("node", self.node.clone())
}
}
@@ -251,7 +248,7 @@ pub struct Redirect {
}
impl FromElement for Redirect {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("redirect")?;
element.check_namespace(XMLNS)?;
@@ -262,7 +259,7 @@ impl FromElement for Redirect {
}
impl IntoElement for Redirect {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("redirect", Some(XMLNS)).push_attribute("uri", self.uri.clone())
}
}
@@ -274,7 +271,7 @@ pub struct Subscriptions {
}
impl FromElement for Subscriptions {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscriptions")?;
element.check_namespace(XMLNS)?;
@@ -290,7 +287,7 @@ impl FromElement for Subscriptions {
}
impl IntoElement for Subscriptions {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subscriptions", Some(XMLNS))
.push_attribute("node", self.node.clone())
.push_children(self.subscriptions.clone())
@@ -304,7 +301,7 @@ pub struct Subscription {
}
impl FromElement for Subscription {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscription")?;
element.check_namespace(XMLNS)?;
@@ -316,7 +313,7 @@ impl FromElement for Subscription {
}
impl IntoElement for Subscription {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subscription", Some(XMLNS))
.push_attribute("subscription", self.subscription.clone())
.push_attribute("jid", self.jid.clone())
diff --git a/stanza/src/xep_0060/pubsub.rs b/stanza/src/xep_0060/pubsub.rs
index 0f698dc..0416b78 100644
--- a/stanza/src/xep_0060/pubsub.rs
+++ b/stanza/src/xep_0060/pubsub.rs
@@ -1,10 +1,7 @@
use std::str::FromStr;
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- DeserializeError, Element,
-};
+use peanuts::{DeserializeError, Element, FromElement, IntoElement};
use crate::xep_0004::X;
#[cfg(feature = "xep_0084")]
@@ -30,7 +27,7 @@ pub enum Pubsub {
}
impl FromElement for Pubsub {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("pubsub")?;
element.check_namespace(XMLNS)?;
@@ -81,7 +78,7 @@ impl FromElement for Pubsub {
}
impl IntoElement for Pubsub {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let element = Element::builder("pubsub", Some(XMLNS));
match self {
@@ -113,7 +110,7 @@ pub struct Affiliations {
}
impl FromElement for Affiliations {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("affiliations")?;
element.check_namespace(XMLNS)?;
@@ -126,7 +123,7 @@ impl FromElement for Affiliations {
}
impl IntoElement for Affiliations {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("affilations", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_children(self.affiliations.clone())
@@ -141,7 +138,7 @@ pub struct Affiliation {
}
impl FromElement for Affiliation {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("affiliation")?;
element.check_namespace(XMLNS)?;
@@ -153,7 +150,7 @@ impl FromElement for Affiliation {
}
impl IntoElement for Affiliation {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("affiliation", Some(XMLNS))
.push_attribute("affiliation", self.affiliation.clone())
.push_attribute("node", self.node.clone())
@@ -204,7 +201,7 @@ impl ToString for AffiliationType {
pub struct Configure(Option<X>);
impl FromElement for Configure {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("configure")?;
element.check_namespace(XMLNS)?;
@@ -213,7 +210,7 @@ impl FromElement for Configure {
}
impl IntoElement for Configure {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("configure", Some(XMLNS)).push_child_opt(self.0.clone())
}
}
@@ -224,7 +221,7 @@ pub struct Create {
}
impl FromElement for Create {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("create")?;
element.check_namespace(XMLNS)?;
@@ -235,7 +232,7 @@ impl FromElement for Create {
}
impl IntoElement for Create {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("create", Some(XMLNS)).push_attribute_opt("node", self.node.clone())
}
}
@@ -249,7 +246,7 @@ pub struct Default {
}
impl FromElement for Default {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("default")?;
element.check_namespace(XMLNS)?;
@@ -267,7 +264,7 @@ impl FromElement for Default {
}
impl IntoElement for Default {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("default", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_attribute_opt("type", self.r#type.clone())
@@ -312,7 +309,7 @@ pub struct Items {
}
impl FromElement for Items {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("items")?;
element.check_namespace(XMLNS)?;
@@ -332,7 +329,7 @@ impl FromElement for Items {
}
impl IntoElement for Items {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("items", Some(XMLNS))
.push_attribute_opt("max_items", self.max_items)
.push_attribute("node", self.node.clone())
@@ -349,7 +346,7 @@ pub struct Item {
}
impl FromElement for Item {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("item")?;
element.check_namespace(XMLNS)?;
@@ -367,7 +364,7 @@ impl FromElement for Item {
}
impl IntoElement for Item {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("item", Some(XMLNS))
.push_attribute_opt("id", self.id.clone())
.push_attribute_opt("publisher", self.publisher.clone())
@@ -387,7 +384,7 @@ pub enum Content {
}
impl FromElement for Content {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
match element.identify() {
#[cfg(feature = "xep_0172")]
(Some(xep_0172::XMLNS), "nick") => Ok(Content::Nick(Nick::from_element(element)?)),
@@ -405,7 +402,7 @@ impl FromElement for Content {
}
impl IntoElement for Content {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
match self {
#[cfg(feature = "xep_0172")]
Content::Nick(nick) => nick.builder(),
@@ -427,7 +424,7 @@ pub struct Options {
}
impl FromElement for Options {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("options")?;
element.check_namespace(XMLNS)?;
@@ -447,7 +444,7 @@ impl FromElement for Options {
}
impl IntoElement for Options {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("options", Some(XMLNS))
.push_attribute("jid", self.jid.clone())
.push_attribute_opt("node", self.node.clone())
@@ -463,7 +460,7 @@ pub struct Publish {
}
impl FromElement for Publish {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("publish")?;
element.check_namespace(XMLNS)?;
@@ -476,7 +473,7 @@ impl FromElement for Publish {
}
impl IntoElement for Publish {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("publish", Some(XMLNS))
.push_attribute("node", self.node.clone())
.push_children(self.items.clone())
@@ -487,7 +484,7 @@ impl IntoElement for Publish {
pub struct PublishOptions(pub Option<X>);
impl FromElement for PublishOptions {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("publish-options")?;
element.check_namespace(XMLNS)?;
@@ -496,7 +493,7 @@ impl FromElement for PublishOptions {
}
impl IntoElement for PublishOptions {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("publish-options", Some(XMLNS)).push_child_opt(self.0.clone())
}
}
@@ -510,7 +507,7 @@ pub struct Retract {
}
impl FromElement for Retract {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("retract")?;
element.check_namespace(XMLNS)?;
@@ -528,7 +525,7 @@ impl FromElement for Retract {
}
impl IntoElement for Retract {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("retract", Some(XMLNS))
.push_attribute("node", self.node.clone())
.push_attribute_opt("notify", self.notify)
@@ -543,7 +540,7 @@ pub struct SubscribeOptions {
}
impl FromElement for SubscribeOptions {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscribe-options")?;
element.check_namespace(XMLNS)?;
@@ -559,7 +556,7 @@ impl FromElement for SubscribeOptions {
}
impl IntoElement for SubscribeOptions {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("subscribe-options", Some(XMLNS));
if self.required {
@@ -573,7 +570,7 @@ impl IntoElement for SubscribeOptions {
pub struct Required;
impl FromElement for Required {
- fn from_element(element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("required")?;
element.check_namespace(XMLNS)?;
@@ -582,7 +579,7 @@ impl FromElement for Required {
}
impl IntoElement for Required {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("required", Some(XMLNS))
}
}
@@ -594,7 +591,7 @@ pub struct Subscribe {
}
impl FromElement for Subscribe {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscribe")?;
element.check_namespace(XMLNS)?;
@@ -606,7 +603,7 @@ impl FromElement for Subscribe {
}
impl IntoElement for Subscribe {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subscribe", Some(XMLNS))
.push_attribute("jid", self.jid.clone())
.push_attribute_opt("node", self.node.clone())
@@ -620,7 +617,7 @@ pub struct Subscriptions {
}
impl FromElement for Subscriptions {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscriptions")?;
element.check_namespace(XMLNS)?;
@@ -636,7 +633,7 @@ impl FromElement for Subscriptions {
}
impl IntoElement for Subscriptions {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subscriptions", Some(XMLNS))
.push_attribute_opt("node", self.node.clone())
.push_children(self.subscriptions.clone())
@@ -653,7 +650,7 @@ pub struct Subscription {
}
impl FromElement for Subscription {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("subscription")?;
element.check_namespace(XMLNS)?;
@@ -675,7 +672,7 @@ impl FromElement for Subscription {
}
impl IntoElement for Subscription {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("subscription", Some(XMLNS))
.push_attribute("jid", self.jid.clone())
.push_attribute_opt("node", self.node.clone())
@@ -727,7 +724,7 @@ pub struct Unsubscribe {
}
impl FromElement for Unsubscribe {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("unsubscribe")?;
element.check_namespace(XMLNS)?;
@@ -740,7 +737,7 @@ impl FromElement for Unsubscribe {
}
impl IntoElement for Unsubscribe {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("unsubscribe", Some(XMLNS))
.push_attribute("jid", self.jid.clone())
.push_attribute_opt("node", self.node.clone())
diff --git a/stanza/src/xep_0084/data.rs b/stanza/src/xep_0084/data.rs
index 2a37df4..4b3223f 100644
--- a/stanza/src/xep_0084/data.rs
+++ b/stanza/src/xep_0084/data.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:xmpp:avatar:data";
@@ -9,7 +6,7 @@ pub const XMLNS: &str = "urn:xmpp:avatar:data";
pub struct Data(pub String);
impl FromElement for Data {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("data")?;
element.check_namespace(XMLNS)?;
@@ -18,7 +15,7 @@ impl FromElement for Data {
}
impl IntoElement for Data {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("data", Some(XMLNS));
if self.0.is_empty() {
diff --git a/stanza/src/xep_0084/metadata.rs b/stanza/src/xep_0084/metadata.rs
index c6a3fb4..e4edb2f 100644
--- a/stanza/src/xep_0084/metadata.rs
+++ b/stanza/src/xep_0084/metadata.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:xmpp:avatar:metadata";
@@ -12,7 +9,7 @@ pub struct Metadata {
}
impl FromElement for Metadata {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("metadata")?;
element.check_namespace(XMLNS)?;
@@ -24,7 +21,7 @@ impl FromElement for Metadata {
}
impl IntoElement for Metadata {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("metadata", Some(XMLNS))
.push_children(self.info.clone())
.push_children(self.pointers.clone())
@@ -42,7 +39,7 @@ pub struct Info {
}
impl FromElement for Info {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("info")?;
element.check_namespace(XMLNS)?;
@@ -65,7 +62,7 @@ impl FromElement for Info {
}
impl IntoElement for Info {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("info", Some(XMLNS))
.push_attribute("bytes", self.bytes)
.push_attribute_opt("height", self.height)
@@ -80,7 +77,7 @@ impl IntoElement for Info {
pub struct Pointer(pub PointerInner);
impl FromElement for Pointer {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("pointer")?;
element.check_namespace(XMLNS)?;
@@ -89,7 +86,7 @@ impl FromElement for Pointer {
}
impl IntoElement for Pointer {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let _builder = Element::builder("pointer", Some(XMLNS));
match &self.0 {
diff --git a/stanza/src/xep_0115.rs b/stanza/src/xep_0115.rs
index 1c2ef69..1c9cd6f 100644
--- a/stanza/src/xep_0115.rs
+++ b/stanza/src/xep_0115.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "http://jabber.org/protocol/caps";
@@ -14,7 +11,7 @@ pub struct C {
}
impl FromElement for C {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("c")?;
element.check_namespace(XMLNS)?;
@@ -33,7 +30,7 @@ impl FromElement for C {
}
impl IntoElement for C {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("c", Some(XMLNS))
.push_attribute_opt("ext", self.ext.clone())
.push_attribute("hash", self.hash.clone())
diff --git a/stanza/src/xep_0131.rs b/stanza/src/xep_0131.rs
index 27fc962..68e6e96 100644
--- a/stanza/src/xep_0131.rs
+++ b/stanza/src/xep_0131.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "http://jabber.org/protocol/disco#info";
@@ -9,7 +6,7 @@ pub const XMLNS: &str = "http://jabber.org/protocol/disco#info";
pub struct Headers(pub Vec<Header>);
impl FromElement for Headers {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("headers")?;
element.check_namespace(XMLNS)?;
@@ -18,7 +15,7 @@ impl FromElement for Headers {
}
impl IntoElement for Headers {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("headers", Some(XMLNS)).push_children(self.0.clone())
}
}
@@ -30,7 +27,7 @@ pub struct Header {
}
impl FromElement for Header {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("header")?;
element.check_namespace(XMLNS)?;
@@ -43,7 +40,7 @@ impl FromElement for Header {
}
impl IntoElement for Header {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder =
Element::builder("header", Some(XMLNS)).push_attribute("name", self.name.clone());
diff --git a/stanza/src/xep_0156.rs b/stanza/src/xep_0156.rs
new file mode 100644
index 0000000..bf6eac5
--- /dev/null
+++ b/stanza/src/xep_0156.rs
@@ -0,0 +1,230 @@
+use chrono::{DateTime, Utc};
+use peanuts::{Element, FromElement, IntoElement, XML_NS};
+
+pub const XMLNS: &str = "http://docs.oasis-open.org/ns/xri/xrd-1.0";
+pub const SIGNATURE_XMLNS: &str = "http://www.w3.org/2000/09/xmldsig#";
+
+#[derive(Debug, Clone)]
+pub struct XRD {
+ pub id: Option<String>,
+ pub expires: Option<Expires>,
+ pub subject: Option<Subject>,
+ pub aliases: Vec<Alias>,
+ pub properties: Vec<Property>,
+ pub links: Vec<Link>,
+ pub signature: Vec<Signature>,
+}
+
+impl FromElement for XRD {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("XRD")?;
+ element.check_namespace(XMLNS)?;
+
+ let id = element.attribute_opt_namespaced("id", XML_NS)?;
+
+ let expires = element.child_opt()?;
+ let subject = element.child_opt()?;
+ let aliases = element.children()?;
+ let properties = element.children()?;
+ let links = element.children()?;
+ let signature = element.children()?;
+
+ Ok(Self {
+ id,
+ expires,
+ subject,
+ aliases,
+ properties,
+ links,
+ signature,
+ })
+ }
+}
+
+impl IntoElement for XRD {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("XRD", Some(XMLNS))
+ .push_attribute_opt_namespaced(XML_NS, "id", self.id.clone())
+ .push_child_opt(self.expires.clone())
+ .push_child_opt(self.subject.clone())
+ .push_children(self.aliases.clone())
+ .push_children(self.properties.clone())
+ .push_children(self.links.clone())
+ .push_children(self.signature.clone())
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Expires(pub DateTime<Utc>);
+
+impl FromElement for Expires {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Expires")?;
+ element.check_namespace(XMLNS)?;
+
+ Ok(Self(element.pop_value()?))
+ }
+}
+
+impl IntoElement for Expires {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Expires", Some(XMLNS))
+ .push_text(self.0.format("%C%y-%m-%dT%H:%M:%S%.3f%:z"))
+ }
+}
+
+// anyURI
+#[derive(Debug, Clone)]
+pub struct Subject(pub String);
+
+impl FromElement for Subject {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Subject")?;
+ element.check_namespace(XMLNS)?;
+
+ Ok(Self(element.pop_value()?))
+ }
+}
+
+impl IntoElement for Subject {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Subject", Some(XMLNS)).push_text(self.0.clone())
+ }
+}
+
+// anyURI
+#[derive(Debug, Clone)]
+pub struct Alias(pub String);
+
+impl FromElement for Alias {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Alias")?;
+ element.check_namespace(XMLNS)?;
+
+ Ok(Self(element.pop_value()?))
+ }
+}
+
+impl IntoElement for Alias {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Alias", Some(XMLNS)).push_text(self.0.clone())
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Property {
+ pub r#type: String,
+ pub property: Option<String>,
+}
+
+impl FromElement for Property {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Property")?;
+ element.check_name(XMLNS)?;
+
+ let r#type = element.attribute("type")?;
+
+ let property = element.pop_value_opt()?;
+
+ Ok(Self { r#type, property })
+ }
+}
+
+impl IntoElement for Property {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Property", Some(XMLNS))
+ .push_attribute("type", self.r#type.clone())
+ .push_text_opt(self.property.clone())
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Link {
+ pub rel: Option<String>,
+ pub r#type: Option<String>,
+ pub href: Option<String>,
+ pub template: Option<String>,
+ pub titles: Vec<Title>,
+ pub properties: Vec<Property>,
+}
+
+impl FromElement for Link {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Link")?;
+ element.check_namespace(XMLNS)?;
+
+ let rel = element.attribute_opt("rel")?;
+ let r#type = element.attribute_opt("type")?;
+ let href = element.attribute_opt("href")?;
+ let template = element.attribute_opt("template")?;
+
+ let titles = element.children()?;
+ let properties = element.children()?;
+
+ Ok(Self {
+ rel,
+ r#type,
+ href,
+ template,
+ titles,
+ properties,
+ })
+ }
+}
+
+impl IntoElement for Link {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Link", Some(XMLNS))
+ .push_attribute_opt("rel", self.rel.clone())
+ .push_attribute_opt("type", self.r#type.clone())
+ .push_attribute_opt("href", self.href.clone())
+ .push_attribute_opt("template", self.template.clone())
+ .push_children(self.titles.clone())
+ .push_children(self.properties.clone())
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Title {
+ pub lang: Option<String>,
+ pub title: String,
+}
+
+impl FromElement for Title {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Title")?;
+ element.check_namespace(XMLNS)?;
+
+ let lang = element.attribute_opt_namespaced("lang", XML_NS)?;
+
+ let title = element.pop_value_opt()?.unwrap_or_default();
+
+ Ok(Self { lang, title })
+ }
+}
+
+impl IntoElement for Title {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Title", Some(XMLNS))
+ .push_attribute_opt_namespaced(XML_NS, "lang", self.lang.clone())
+ .push_text(self.title.clone())
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct Signature;
+
+impl FromElement for Signature {
+ fn from_element(element: Element) -> peanuts::DeserializeResult<Self> {
+ element.check_name("Signature")?;
+ element.check_namespace(SIGNATURE_XMLNS)?;
+
+ Ok(Self)
+ }
+}
+
+impl IntoElement for Signature {
+ fn builder(&self) -> peanuts::ElementBuilder {
+ Element::builder("Signature", Some(SIGNATURE_XMLNS))
+ }
+}
diff --git a/stanza/src/xep_0172.rs b/stanza/src/xep_0172.rs
index 1c24200..54846b8 100644
--- a/stanza/src/xep_0172.rs
+++ b/stanza/src/xep_0172.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "http://jabber.org/protocol/nick";
@@ -9,7 +6,7 @@ pub const XMLNS: &str = "http://jabber.org/protocol/nick";
pub struct Nick(pub String);
impl FromElement for Nick {
- fn from_element(mut element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("nick")?;
element.check_namespace(XMLNS)?;
@@ -18,7 +15,7 @@ impl FromElement for Nick {
}
impl IntoElement for Nick {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder = Element::builder("nick", Some(XMLNS));
if self.0.is_empty() {
diff --git a/stanza/src/xep_0199.rs b/stanza/src/xep_0199.rs
index 9605721..2ab3a86 100644
--- a/stanza/src/xep_0199.rs
+++ b/stanza/src/xep_0199.rs
@@ -1,7 +1,4 @@
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:xmpp:ping";
@@ -9,7 +6,7 @@ pub const XMLNS: &str = "urn:xmpp:ping";
pub struct Ping;
impl FromElement for Ping {
- fn from_element(element: peanuts::Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(element: peanuts::Element) -> peanuts::DeserializeResult<Self> {
element.check_name("ping")?;
element.check_namespace(XMLNS)?;
@@ -20,7 +17,7 @@ impl FromElement for Ping {
}
impl IntoElement for Ping {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("ping", Some(XMLNS))
}
}
diff --git a/stanza/src/xep_0203.rs b/stanza/src/xep_0203.rs
index b8f9239..41ff196 100644
--- a/stanza/src/xep_0203.rs
+++ b/stanza/src/xep_0203.rs
@@ -1,9 +1,6 @@
use chrono::{DateTime, Utc};
use jid::JID;
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:xmpp:delay";
@@ -14,7 +11,7 @@ pub struct Delay {
}
impl FromElement for Delay {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("delay")?;
element.check_namespace(XMLNS)?;
@@ -26,7 +23,7 @@ impl FromElement for Delay {
}
impl IntoElement for Delay {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("delay", Some(XMLNS))
.push_attribute_opt("from", self.from.clone())
.push_attribute("stamp", self.stamp.format("%C%y-%m-%dT%H:%M:%S%.3f%:z"))
diff --git a/stanza/src/xep_0300.rs b/stanza/src/xep_0300.rs
index 71a2c36..f522f1c 100644
--- a/stanza/src/xep_0300.rs
+++ b/stanza/src/xep_0300.rs
@@ -1,9 +1,6 @@
use std::{convert::Infallible, str::FromStr};
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:xmpp:hashes:2";
@@ -14,7 +11,7 @@ pub struct Hash {
}
impl FromElement for Hash {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("hash")?;
element.check_namespace(XMLNS)?;
@@ -27,7 +24,7 @@ impl FromElement for Hash {
}
impl IntoElement for Hash {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
let builder =
Element::builder("hash", Some(XMLNS)).push_attribute("algo", self.algo.clone());
@@ -46,7 +43,7 @@ pub struct HashUsed {
}
impl FromElement for HashUsed {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("hash-used")?;
element.check_namespace(XMLNS)?;
@@ -57,7 +54,7 @@ impl FromElement for HashUsed {
}
impl IntoElement for HashUsed {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("hash-used", Some(XMLNS)).push_attribute("algo", self.algo.clone())
}
}
diff --git a/stanza/src/xep_0390.rs b/stanza/src/xep_0390.rs
index bcd331d..1a079c2 100644
--- a/stanza/src/xep_0390.rs
+++ b/stanza/src/xep_0390.rs
@@ -1,8 +1,5 @@
use crate::xep_0300::Hash;
-use peanuts::{
- element::{FromElement, IntoElement},
- Element,
-};
+use peanuts::{Element, FromElement, IntoElement};
pub const XMLNS: &str = "urn:xmpp:caps";
@@ -11,7 +8,7 @@ pub const XMLNS: &str = "urn:xmpp:caps";
pub struct C(pub Vec<Hash>);
impl FromElement for C {
- fn from_element(mut element: Element) -> peanuts::element::DeserializeResult<Self> {
+ fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> {
element.check_name("c")?;
element.check_namespace(XMLNS)?;
@@ -20,7 +17,7 @@ impl FromElement for C {
}
impl IntoElement for C {
- fn builder(&self) -> peanuts::element::ElementBuilder {
+ fn builder(&self) -> peanuts::ElementBuilder {
Element::builder("c", Some(XMLNS)).push_children(self.0.clone())
}
}