diff options
90 files changed, 7062 insertions, 4047 deletions
diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..c91c3f3 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[net] +git-fetch-with-cli = true @@ -1,2 +1,3 @@ /target /Cargo.lock +filamento.db diff --git a/.helix/languages.toml b/.helix/languages.toml index ad628c8..02fab3a 100644 --- a/.helix/languages.toml +++ b/.helix/languages.toml @@ -1,4 +1,9 @@ [language-server.rust-analyzer] command = "rust-analyzer" -environment = { "DATABASE_URL" = "sqlite://filamento/filamento.db" } -config = { cargo.features = "all" } +# environment = { "DATABASE_URL" = "sqlite://filamento/filamento.db" } + # checkOnSave.overrideCommand = "cargo check --message-format=json -p luz", + # check.overrideCommand="cargo check --message-format=json -p luz", + # check.workspace = false, + # cargo.target = "wasm32-unknown-unknown", +# 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", @@ -1,8 +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" } @@ -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/>. @@ -1,51 +1,67 @@ -# jabber client library +# xmpp thingies -- luz: the client. sends and receives messages. contains a message/user store. +## crates: -## TODO: +- filamento: the client logic. handles commands and processes incoming stanzas. contains a message/user store. +- lampada: the client structure. handles connection and reconnection, delegates command and incoming stanza processing to an implementor of Logic. +- luz: jabber client connection and stream base types. +- stanza: type definitions for converting to and from peanuts xml `Element`s for stanza parsing and composition. +- jid: basic JID type, with parsing and display. -- [x] how to know if stanza has been sent -- [ ] error states for all negotiation parts -- [x] better errors -- [x] rename structs -- [x] remove commented code -- [ ] asynchronous connect (with take_mut?) -- [x] split into separate crates: stanza, jabber, and luz -- [ ] use nom for better jid parsing +#### separate: -### specs: +- [macaw](https://bunny.garden/macaw): gui client that utilises filamento +- [peanuts](https://bunny.garden/peanuts): xml serialisation and deserialization library + +## specs: - [x] rfc 6120: core - [x] rfc 6121: im - [x] rfc 7590: tls - [x] xep-0368: srv records for xmpp over tls -- [ ] server side downgrade protection for sasl +- [ ] xep-0474: server side downgrade protection for sasl - [x] xep-0199: xmpp ping - [x] xep-0203: delayed delivery - [x] xep-0030: service discovery - [x] xep-0115: entity capabilities - [x] xep-0163: pep -- [ ] xep-0245: /me -- [ ] xep-0084: user avatar +- [x] xep-0084: user avatar - [x] xep-0172: user nickname - [ ] xep-0280: message carbons - [ ] xep-0191: blocking -- [ ] xep-0313: mam -- [ ] xep-0198: stream management - [ ] xep-0085: chat state notifications - [ ] xep-0428: fallback indication - [ ] xep-0359: unique and stable stanza ids - [ ] xep-0424: message retraction -- [ ] xep-0352: client state indication -- [ ] xep-0166: jingle -- [ ] xep-0292: vcard4 -- [ ] chat read markers - - [ ] xep-0490: message displayed synchronization - - [ ] xep-0333: displayed markers +- [ ] xep-0308: last message correction +- [ ] xep-0461: message replies +- [ ] xep-0490: message displayed synchronization +- [ ] xep-0333: displayed markers - [ ] xep-0184: message delivery receipts +- [ ] xep-0012: last activity +- [~] xep-0059: result set management +- [x] xep-0300: use of cryptographic hash functions +- [~] xep-0131: stanza headers +- [ ] xep-0245: /me +- [ ] xep-0313: mam +- [ ] xep-0166: jingle +- [ ] xep-0449: stickers +- [ ] xep-0154: user profile - [ ] xep-0100: gateway interation -calls: +#### user status: + +- [ ] xep-0107: user mood +- [ ] xep-0108: user activity +- [ ] xep-0118: user tune + +#### connection: + +- [ ] xep-0198: stream management +- [ ] xep-0352: client state indication + +#### calls: + - [ ] xep-0167: jingle rtp sessions - [ ] xep-0353: jingle message initiation - [ ] xep-0176: jingle ice-udp transport @@ -55,37 +71,44 @@ calls: - [ ] xep-0294: jingle trp header extensions negotiation - [ ] xep-0338: jingle grouping framework - [ ] xep-0339: source-specific media attributes in jingle +- [ ] privacy lists + +#### mix: -mix: - [ ] xep-0369: mix -e2ee: +#### e2ee: + - [ ] xep-0380: explicit message encryption - [ ] xep-0420: stanza content encryption - [ ] xep-0384: omemo - [ ] xep-0396: jingle encrypted transports omemo -file/media sharing (further research needed): +#### file/media sharing (further research needed): + - [ ] xep-0363: http file upload +- [ ] xep-0329: file information sharing +- [ ] xep-0447: stateless file sharing - [ ] xep-0385: stateless inline media sharing - [ ] xep-0066: out of band data - [ ] xep-0261: jingle in-band bytestreams - [ ] xep-0234: jingle file transfer -need more research: -- [ ] xep-0154: user profile -- [ ] message editing - - [ ] xep-0308: last message correction (should not be used for older than last message according to spec) +#### need more research: + - [ ] message styling + - [ ] xep-0071: xhtml-im - [ ] 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 - [ ] xep-0153: vcard avatars - [ ] xep-0054: vcard-temp @@ -93,12 +116,14 @@ will prioritise new spec instead of: - [ ] xep-0048: legacy bookmarks - [ ] xep-0049: private xml storage -pubsub: +#### pubsub: + - [ ] xep-0060: pubsub - [ ] xep-0222: public data via pubsub - [ ] xep-0223: private data via pubsub -later (nice to have): +#### later (nice to have): + - [ ] xep-0077: in-band registration - [ ] xep-0157: contact addresses - [ ] xep-0455: service outage status @@ -110,7 +135,7 @@ later (nice to have): - [ ] xep-0386: bind 2.0 - [ ] xep-0409: im routing-ng - [ ] xep-0397: instant stream resumption - - [ ] xep-0390: entity capabilities 2.0 + - [~] xep-0390: entity capabilities 2.0 - [ ] improved on-boarding - [ ] xep-0401: easy user onboarding - [ ] xep-0379: pre-authenticated roster subscription @@ -122,3 +147,24 @@ later (nice to have): - [ ] xep-0388: extensible sasl profile (sasl 2.0) - [ ] xep-xxxx: oauth client login - [ ] xep-xxxx: client access management + +#### to write: + +- [ ] some xmpp user avatar metadata nodes published as jpeg??? +- [ ] need to specify user avatar id as hexadecimal +- [ ] do disco results always have to be in the right order? and can you not both have a normal and a +notify? +- [ ] advanced message body (for custom emoji, styling, etc.). can opt in to mixed content in message body. base as bold, italic, underline, strikethrough, then extensible with new tags for e.g. emoji, color, size, font, chat effects. +- [ ] omemo cross-signing verification or something along those lines, with a main device and linked devices. safety numbers. +- [ ] better stable ids....? +- [ ] better stickers/emoji xep +- [ ] mix voice channels (w/ sfu) +- [ ] mix guilds +- [ ] pep native spaces +- [ ] pinned messages +- [ ] chat settings +- [ ] encrypted chat history share +- [ ] disappearing messages +- [ ] poke +- [ ] polls +- [ ] privacy lists/circles +- [ ] pubsub node items filter for each person 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 ec8a40b..52acf71 100644 --- a/filamento/.gitignore +++ b/filamento/.gitignore @@ -1,2 +1,3 @@ filamento.db +./files/ .sqlx/ diff --git a/filamento/Cargo.toml b/filamento/Cargo.toml index 1c28c39..b89c577 100644 --- a/filamento/Cargo.toml +++ b/filamento/Cargo.toml @@ -3,26 +3,81 @@ 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 = "1.42.0" -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"] } -sqlx = { version = "0.8.3", features = ["sqlite", "runtime-tokio", "uuid", "chrono"] } +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", features = ["sqlx"] } -uuid = { version = "1.13.1", features = ["v4"] } -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", "io-std"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +tokio = { workspace = true, features = ["sync", "time", "rt"] } +js-sys.workspace = true +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", path = "../../peanuts" } +tracing-subscriber = { workspace = true } +peanuts = { workspace = true } +tracing-wasm = { workspace = true } +wasm-bindgen-test = { workspace = true } [[example]] name = "example" diff --git a/filamento/examples/example.rs b/filamento/examples/example.rs index 74a9aa1..65fe166 100644 --- a/filamento/examples/example.rs +++ b/filamento/examples/example.rs @@ -1,63 +1,122 @@ -use std::{path::Path, str::FromStr, time::Duration}; - -use filamento::{Client, db::Db}; -use jid::JID; -use tracing::info; - -#[tokio::main] -async fn main() { - tracing_subscriber::fmt::init(); - let db = Db::create_connect_and_migrate(Path::new("./filamento.db")) - .await - .unwrap(); - let (client, mut recv) = - Client::new("test@blos.sm".try_into().unwrap(), "slayed".to_string(), db); - - tokio::spawn(async move { - while let Some(msg) = recv.recv().await { - info!("{:#?}", msg) - } - }); - - client.connect().await.unwrap(); - tokio::time::sleep(Duration::from_secs(5)).await; - info!("changing nick"); - client.change_nick("britney".to_string()).await.unwrap(); - info!("sending message"); - client - .send_message( - JID::from_str("cel@blos.sm").unwrap(), - filamento::chat::Body { - body: "hallo!!!".to_string(), - }, - ) - .await - .unwrap(); - info!("sent message"); - tokio::time::sleep(Duration::from_secs(5)).await; - // info!("sending disco query"); - // let info = client.disco_info(None, None).await.unwrap(); - // info!("got disco result: {:#?}", info); - // let items = client.disco_items(None, None).await.unwrap(); - // info!("got disco result: {:#?}", items); - // let info = client - // .disco_info(Some("blos.sm".parse().unwrap()), None) - // .await - // .unwrap(); - // info!("got disco result: {:#?}", info); - // let items = client - // .disco_items(Some("blos.sm".parse().unwrap()), None) - // .await - // .unwrap(); - // info!("got disco result: {:#?}", items); - // let info = client - // .disco_info(Some("pubsub.blos.sm".parse().unwrap()), None) - // .await - // .unwrap(); - // info!("got disco result: {:#?}", info); - // let items = client - // .disco_items(Some("pubsub.blos.sm".parse().unwrap()), None) - // .await - // .unwrap(); - // info!("got disco result: {:#?}", items); -} +// use std::{path::Path, str::FromStr, sync::Arc, time::Duration}; + +// use filamento::{Client, db::Db, files::FileStore}; +// use jid::JID; +// use tokio::io::{self, AsyncReadExt}; +// use tracing::info; + +// #[derive(Clone, Debug)] +// pub struct Files; + +// impl FileStore for Files { +// type Err = Arc<io::Error>; + +// async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> { +// tracing::debug!("checking if {} is stored", name); +// let res = tokio::fs::try_exists(format!("files/{}", name)) +// .await +// .map_err(|err| Arc::new(err)); +// tracing::debug!("file check res: {:?}", res); +// res +// } + +// async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> { +// tracing::debug!("storing {} is stored", name); +// let res = tokio::fs::write(format!("files/{}", name), data) +// .await +// .map_err(|err| Arc::new(err)); +// tracing::debug!("file store res: {:?}", res); +// res +// } + +// async fn delete(&self, name: &str) -> Result<(), Self::Err> { +// tracing::debug!("deleting {}", name); +// let res = tokio::fs::remove_file(format!("files/{}", name)) +// .await +// .map_err(|err| Arc::new(err)); +// tracing::debug!("file delete res: {:?}", res); +// res +// } +// } + +// #[tokio::main] +// async fn main() { +// tracing_subscriber::fmt::init(); +// let db = Db::create_connect_and_migrate(Path::new("./filamento.db")) +// .await +// .unwrap(); +// let (client, mut recv) = Client::new( +// "test@blos.sm/testing2".try_into().unwrap(), +// "slayed".to_string(), +// db, +// Files, +// ); + +// tokio::spawn(async move { +// while let Some(msg) = recv.recv().await { +// info!("{:#?}", msg) +// } +// }); + +// client.connect().await.unwrap(); +// tokio::time::sleep(Duration::from_secs(5)).await; +// info!("changing nick"); +// client +// .change_nick(Some("britney".to_string())) +// .await +// .unwrap(); +// let mut profile_pic = tokio::fs::File::open("files/britney_starbies.jpg") +// .await +// .unwrap(); +// let mut data = Vec::new(); +// profile_pic.read_to_end(&mut data).await.unwrap(); +// client.change_avatar(Some(data)).await.unwrap(); +// info!("sending message"); +// client +// .send_message( +// JID::from_str("cel@blos.sm").unwrap(), +// filamento::chat::Body { +// body: "hallo!!!".to_string(), +// }, +// ) +// .await +// .unwrap(); +// info!("sent message"); +// client +// .send_message( +// JID::from_str("cel@blos.sm").unwrap(), +// filamento::chat::Body { +// body: "hallo 2".to_string(), +// }, +// ) +// .await +// .unwrap(); +// tokio::time::sleep(Duration::from_secs(15)).await; +// // info!("sending disco query"); +// // let info = client.disco_info(None, None).await.unwrap(); +// // info!("got disco result: {:#?}", info); +// // let items = client.disco_items(None, None).await.unwrap(); +// // info!("got disco result: {:#?}", items); +// // let info = client +// // .disco_info(Some("blos.sm".parse().unwrap()), None) +// // .await +// // .unwrap(); +// // info!("got disco result: {:#?}", info); +// // let items = client +// // .disco_items(Some("blos.sm".parse().unwrap()), None) +// // .await +// // .unwrap(); +// // info!("got disco result: {:#?}", items); +// // let info = client +// // .disco_info(Some("pubsub.blos.sm".parse().unwrap()), None) +// // .await +// // .unwrap(); +// // info!("got disco result: {:#?}", info); +// // let items = client +// // .disco_items(Some("pubsub.blos.sm".parse().unwrap()), None) +// // .await +// // .unwrap(); +// // info!("got disco result: {:#?}", items); +// } + +fn main() {} diff --git a/filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0 b/filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0 Binary files differnew file mode 100644 index 0000000..0b27b91 --- /dev/null +++ b/filamento/files/4ff6fc2961a36a9439eea239f01e05624f3afbe0 diff --git a/filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377 b/filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377 Binary files differnew file mode 100644 index 0000000..4284eb6 --- /dev/null +++ b/filamento/files/8d7231c2d8c4618fa71979851687737e63ba6377 diff --git a/filamento/files/britney_starbies.jpg b/filamento/files/britney_starbies.jpg Binary files differnew file mode 100644 index 0000000..2e81677 --- /dev/null +++ b/filamento/files/britney_starbies.jpg diff --git a/filamento/migrations/20240113011930_luz.sql b/filamento/migrations/1.sql index 8c1b01c..502c5a9 100644 --- a/filamento/migrations/20240113011930_luz.sql +++ b/filamento/migrations/1.sql @@ -2,10 +2,11 @@ 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, + avatar text, -- can receive presence status from non-contacts cached_status_message text -- TODO: last_seen @@ -28,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), @@ -36,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, @@ -51,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), @@ -66,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, @@ -74,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 @@ -115,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/avatar.rs b/filamento/src/avatar.rs new file mode 100644 index 0000000..a6937df --- /dev/null +++ b/filamento/src/avatar.rs @@ -0,0 +1,34 @@ +#[derive(Clone, Debug)] +pub struct Metadata { + pub bytes: u32, + pub hash: String, + pub r#type: String, +} + +#[derive(Clone, Debug)] +pub struct Data { + pub hash: String, + pub data_b64: String, +} + +#[derive(Clone, Debug)] +pub struct Avatar(Vec<u8>); + +impl From<stanza::xep_0084::Info> for Metadata { + fn from(value: stanza::xep_0084::Info) -> Self { + Self { + bytes: value.bytes, + hash: value.id, + r#type: value.r#type, + } + } +} + +impl From<stanza::xep_0084::Data> for Data { + fn from(value: stanza::xep_0084::Data) -> Self { + Self { + hash: todo!(), + data_b64: todo!(), + } + } +} diff --git a/filamento/src/caps.rs b/filamento/src/caps.rs index 49d05ba..e0587ff 100644 --- a/filamento/src/caps.rs +++ b/filamento/src/caps.rs @@ -5,7 +5,8 @@ use sha1::Sha1; use sha2::{Digest, Sha256}; use sha3::Sha3_256; use stanza::{ - xep_0030::info, + xep_0004, + xep_0030::{self, info}, xep_0115::{self, C}, xep_0300::{self, Algo, Hash}, xep_0390, @@ -35,14 +36,19 @@ pub fn client_info() -> Info { Info { node: None, features: vec![ - "http://jabber.org/protocol/disco#items".to_string(), - "http://jabber.org/protocol/disco#info".to_string(), "http://jabber.org/protocol/caps".to_string(), - "http://jabber.org/protocol/nick".to_string(), + "http://jabber.org/protocol/disco#info".to_string(), + "http://jabber.org/protocol/disco#items".to_string(), "http://jabber.org/protocol/nick+notify".to_string(), + "urn:xmpp:avatar:metadata+notify".to_string(), ], + // "http://jabber.org/protocol/nick".to_string(), identities: vec![Identity { - name: Some("filamento 0.1.0".to_string()), + name: Some(format!( + "{pkg} {version}", + pkg = env!("CARGO_PKG_NAME"), + version = env!("CARGO_PKG_VERSION"), + )), category: Category::Client(identity::Client::PC), }], } @@ -52,17 +58,26 @@ pub fn caps(node: String, query: info::Query) -> Result<xep_0115::C, CapsEncodeE let mut string = String::new(); // identities string - let mut identities = Vec::new(); + let mut identities = Vec::with_capacity(query.identities.len()); for identity in query.identities { - let mut string = String::new(); - string.push_str(&identity.category); + let (category, r#type, lang, name) = ( + identity.category, + identity.r#type, + identity.lang.unwrap_or_default(), + identity.name.unwrap_or_default(), + ); + + let mut string = + String::with_capacity(category.len() + r#type.len() + lang.len() + name.len() + 4); + string.push_str(&category); string.push('/'); - string.push_str(&identity.r#type); + string.push_str(&r#type); string.push('/'); - string.push_str(&identity.lang.unwrap_or_default()); + string.push_str(&lang); string.push('/'); - string.push_str(&identity.name.unwrap_or_default()); + string.push_str(&name); string.push('<'); + identities.push(string); } identities.sort(); @@ -70,11 +85,12 @@ pub fn caps(node: String, query: info::Query) -> Result<xep_0115::C, CapsEncodeE string.push_str(&identities_string); // features string - let mut features = Vec::new(); - for feature in query.features { - let mut string = String::new(); - string.push_str(&feature.var); + let mut features = Vec::with_capacity(query.features.len()); + for xep_0030::info::Feature { var, .. } in query.features { + let mut string = String::with_capacity(var.len() + 1); + string.push_str(&var); string.push('<'); + features.push(string); } features.sort(); @@ -82,45 +98,53 @@ pub fn caps(node: String, query: info::Query) -> Result<xep_0115::C, CapsEncodeE string.push_str(&features_string); // extensions string - let mut extensions = Vec::new(); + let mut extensions = Vec::with_capacity(query.extensions.len()); for extension in query.extensions { - let mut string = String::new(); let form_type = extension .fields .iter() .find(|field| field.var.as_deref() == Some("FORM_TYPE")) .ok_or(CapsEncodeError::InvalidDataForm)? .values - .clone() - .into_iter() - .map(|value| value.0) - .collect::<Vec<String>>() + .iter() + .map(|value| value.0.as_str()) + .collect::<Vec<&str>>() .concat(); - string.push_str(&form_type); - string.push('<'); - let mut fields = Vec::new(); + + let mut fields = Vec::with_capacity(extension.fields.len()); for field in extension.fields { if field.var.as_deref() == Some("FORM_TYPE") { continue; } - let mut string = String::new(); - string.push_str(&field.var.unwrap_or_default()); - string.push('<'); - let mut values = Vec::new(); - for value in field.values { - let mut string = String::new(); - string.push_str(&value.0); + + let var = field.var.unwrap_or_default(); + + let mut values = Vec::with_capacity(field.values.len()); + for xep_0004::Value(value) in field.values { + let mut string = String::with_capacity(value.len() + 1); + string.push_str(&value); string.push('<'); + values.push(string); } values.sort(); let values_string = values.concat(); + + let mut string = String::with_capacity(var.len() + values_string.len() + 1); + string.push_str(&var); + string.push('<'); string.push_str(&values_string); + fields.push(string); } fields.sort(); let fields_string = fields.concat(); + + let mut string = String::with_capacity(form_type.len() + fields_string.len() + 1); + string.push_str(&form_type); + string.push('<'); string.push_str(&fields_string); + extensions.push(string); } extensions.sort(); @@ -148,11 +172,12 @@ pub fn encode_caps2(query: info::Query) -> String { let mut string = String::new(); // features string - let mut features = Vec::new(); - for feature in query.features { - let mut string = String::new(); - string.push_str(&feature.var); + let mut features = Vec::with_capacity(query.features.len()); + for xep_0030::info::Feature { var, .. } in query.features { + let mut string = String::with_capacity(var.len() + 1); + string.push_str(&var); string.push('\x1f'); + features.push(string); } features.sort(); @@ -161,18 +186,27 @@ pub fn encode_caps2(query: info::Query) -> String { string.push('\x1c'); // identities string - let mut identities = Vec::new(); + let mut identities = Vec::with_capacity(query.identities.len()); for identity in query.identities { - let mut string = String::new(); - string.push_str(&identity.category); + let (category, r#type, lang, name) = ( + identity.category, + identity.r#type, + identity.lang.unwrap_or_default(), + identity.name.unwrap_or_default(), + ); + + let mut string = + String::with_capacity(category.len() + r#type.len() + lang.len() + name.len() + 5); + string.push_str(&category); string.push('\x1f'); - string.push_str(&identity.r#type); + string.push_str(&r#type); string.push('\x1f'); - string.push_str(&identity.lang.unwrap_or_default()); + string.push_str(&lang); string.push('\x1f'); - string.push_str(&identity.name.unwrap_or_default()); + string.push_str(&name); string.push('\x1f'); string.push('\x1e'); + identities.push(string); } identities.sort(); @@ -181,37 +215,45 @@ pub fn encode_caps2(query: info::Query) -> String { string.push('\x1c'); // extensions string - let mut extensions = Vec::new(); + let mut extensions = Vec::with_capacity(query.extensions.len()); for extension in query.extensions { - let mut string = String::new(); - let mut fields = Vec::new(); + let mut fields = Vec::with_capacity(extension.fields.len()); for field in extension.fields { - let mut string = String::new(); - string.push_str(&field.var.unwrap_or_default()); - string.push('\x1f'); - let mut values = Vec::new(); - for value in field.values { - let mut string = String::new(); - string.push_str(&value.0); + let var = field.var.unwrap_or_default(); + + let mut values = Vec::with_capacity(field.values.len()); + for xep_0004::Value(value) in field.values { + let mut string = String::with_capacity(value.len() + 1); + string.push_str(&value); string.push('\x1f'); + values.push(string); } values.sort(); let values_string = values.concat(); + + let mut string = String::with_capacity(var.len() + values_string.len() + 2); + string.push_str(&var); + string.push('\x1f'); string.push_str(&values_string); string.push('\x1e'); + fields.push(string); } fields.sort(); let fields_string = fields.concat(); + + let mut string = String::with_capacity(fields_string.len() + 1); string.push_str(&fields_string); string.push('\x1d'); + extensions.push(string); } extensions.sort(); let extensions_string = extensions.concat(); string.push_str(&extensions_string); string.push('\x1c'); + string } @@ -335,7 +377,7 @@ pub fn node_to_hash(node: String) -> Result<Hash, HashNodeConversionError> { #[cfg(test)] mod tests { - use peanuts::{Writer, element::IntoElement}; + use peanuts::Writer; use stanza::{ xep_0004::{Field, FieldType, Value, X, XType}, xep_0030::info::{Feature, Identity}, @@ -343,6 +385,7 @@ mod tests { use super::*; + #[cfg(not(target_arch = "wasm32"))] #[tokio::test] async fn test_caps() { tracing_subscriber::fmt().init(); @@ -447,6 +490,7 @@ mod tests { writer.write(&test_caps).await.unwrap(); } + #[cfg(not(target_arch = "wasm32"))] #[tokio::test] pub async fn test_gen_client_caps() { let stdout = tokio::io::stdout(); diff --git a/filamento/src/chat.rs b/filamento/src/chat.rs index 147c7f7..c02654f 100644 --- a/filamento/src/chat.rs +++ b/filamento/src/chat.rs @@ -1,25 +1,31 @@ +use std::fmt::{Display, Write}; + use chrono::{DateTime, Utc}; -use jid::JID; -use sqlx::Sqlite; +use jid::{BareJID, JID}; +use rusqlite::{ + ToSql, + types::{FromSql, ToSqlOutput, Value}, +}; use uuid::Uuid; -#[derive(Debug, sqlx::FromRow, 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 - #[sqlx(rename = "from_jid")] // bare jid (for now) - pub from: JID, + pub from: BareJID, pub delivery: Option<Delivery>, pub timestamp: DateTime<Utc>, // TODO: originally_from // TODO: message edits // TODO: message timestamp - #[sqlx(flatten)] 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, @@ -30,45 +36,47 @@ pub enum Delivery { Queued, } -impl sqlx::Type<Sqlite> for Delivery { - fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo { - <&str as sqlx::Type<Sqlite>>::type_info() +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 sqlx::Decode<'_, Sqlite> for Delivery { - fn decode( - value: <Sqlite as sqlx::Database>::ValueRef<'_>, - ) -> Result<Self, sqlx::error::BoxDynError> { - let value = <&str as sqlx::Decode<Sqlite>>::decode(value)?; - match value { - "sending" => Ok(Self::Sending), - "written" => Ok(Self::Written), - "sent" => Ok(Self::Sent), - "delivered" => Ok(Self::Delivered), - "read" => Ok(Self::Read), - "failed" => Ok(Self::Failed), - "queued" => Ok(Self::Queued), - _ => unreachable!(), - } +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 sqlx::Encode<'_, Sqlite> for Delivery { - fn encode_by_ref( - &self, - buf: &mut <Sqlite as sqlx::Database>::ArgumentBuffer<'_>, - ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { - let value = match self { - Delivery::Sending => "sending", - Delivery::Written => "written", - Delivery::Sent => "sent", - Delivery::Delivered => "delivered", - Delivery::Read => "read", - Delivery::Failed => "failed", - Delivery::Queued => "queued", - }; - <&str as sqlx::Encode<Sqlite>>::encode(value, buf) +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}`"), + }) } } @@ -78,15 +86,18 @@ impl sqlx::Encode<'_, Sqlite> for Delivery { // Outside, // } -#[derive(Debug, sqlx::FromRow, 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(sqlx::FromRow, 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 correspondent: BareJID, pub have_chatted: bool, // pub unread_messages: i32, // pub latest_message: Message, @@ -98,13 +109,13 @@ pub struct Chat { pub enum ChatUpdate {} impl Chat { - pub fn new(correspondent: JID, have_chatted: bool) -> Self { + pub fn new(correspondent: BareJID, have_chatted: bool) -> Self { Self { correspondent, have_chatted, } } - pub fn correspondent(&self) -> &JID { + pub fn correspondent(&self) -> &BareJID { &self.correspondent } } diff --git a/filamento/src/db.rs b/filamento/src/db.rs index c19f16c..298d54a 100644 --- a/filamento/src/db.rs +++ b/filamento/src/db.rs @@ -1,589 +1,1694 @@ -use std::{collections::HashSet, path::Path}; +use core::fmt::Display; +use std::{collections::HashSet, ops::Deref, path::Path, sync::Arc}; -use chrono::Utc; -use jid::JID; -use sqlx::{SqlitePool, migrate}; +use chrono::{DateTime, Utc}; +use jid::{BareJID, FullJID, 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::{ - chat::{Chat, Message}, + chat::{Body, Chat, Delivery, Message}, error::{DatabaseError as Error, DatabaseOpenError}, presence::Online, roster::Contact, 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> + Send, + ) -> Result<Self, DatabaseOpenError> { + let (sender, receiver) = mpsc::unbounded_channel(); + + let actor = DbActor::new(path, receiver)?; + spawn_blocking(move || actor.run()); + + Ok(Self { sender }) + } + + #[cfg(not(target_arch = "wasm32"))] + pub async fn create_connect_and_migrate_memory() -> Result<Self, DatabaseOpenError> { + let (sender, receiver) = mpsc::unbounded_channel(); + + let actor = DbActor::new_memory(receiver)?; + spawn_blocking(move || actor.run()); + + Ok(Self { sender }) + } + + /// `file_name` should be a file not in a directory + #[cfg(target_arch = "wasm32")] pub async fn create_connect_and_migrate( + file_name: impl AsRef<str> + Send + 'static, + ) -> Result<Self, DatabaseOpenError> { + 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"); + match rusqlite::ffi::install_opfs_sahpool( + Some(&rusqlite::ffi::OpfsSAHPoolCfg::default()), + false, + ) + .await + { + Ok(_) => {} + Err(e) => { + use crate::error::OpfsSAHError; + + let error: OpfsSAHError = e.into(); + result_send.send(Err(error.into())); + return; + } + } + 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()), + } + } + + #[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> { + 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: BareJID) -> Result<User, Error> { + 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: BareJID) -> Result<bool, Error> { + 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: BareJID, nick: String) -> Result<bool, Error> { + 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 + pub(crate) async fn delete_user_avatar( + &self, + jid: BareJID, + ) -> Result<(bool, Option<String>), Error> { + 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 + pub(crate) async fn upsert_user_avatar( + &self, + jid: BareJID, + avatar: String, + ) -> Result<(bool, Option<String>), Error> { + 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> { + 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. + // 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> { + 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: BareJID) -> Result<Contact, Error> { + 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: BareJID, + ) -> 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> { + 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> { + 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: BareJID) -> Result<(), Error> { + 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> { + 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> { + 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> { + 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> { + 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: BareJID) -> Result<Chat, Error> { + 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: BareJID) -> 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: BareJID) -> Result<(), Error> { + 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( + &self, + old_chat: Chat, + new_correspondent: BareJID, + ) -> Result<Chat, Error> { + 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: BareJID) -> Result<(), Error> { + 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> { + 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> { + 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 + // greatest-n-per-group + pub(crate) async fn read_chats_ordered_with_latest_messages( + &self, + ) -> Result<Vec<(Chat, Message)>, Error> { + 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 + // greatest-n-per-group + pub(crate) async fn read_chats_ordered_with_latest_messages_and_users( + &self, + ) -> Result<Vec<((Chat, User), (Message, User))>, Error> { + 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: BareJID, + from: FullJID, + ) -> Result<(), Error> { + 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: BareJID) -> Result<bool, Error> { + let (result, recv) = oneshot::channel(); + let command = DbCommand::UpsertChatAndUser { chat, result }; + self.sender.send(command); + let result = recv.await?; + result + } + + /// 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 + chat: BareJID, + from: FullJID, + ) -> Result<(), Error> { + 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 + } + + pub(crate) async fn update_message_delivery( + &self, + message: Uuid, + delivery: Delivery, + ) -> Result<(), Error> { + 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> { + // 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> {} + + 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: BareJID) -> Vec<(Message, User)>; + // TODO: paging + ReadMessageHistory => read_message_history(chat: BareJID) -> Vec<Message>; + ReadMessage => read_message(message: Uuid) -> Message; + DeleteMessage => delete_message(message: Uuid) -> () + ); + + 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 + } +} + +// TODO: i should really just make an actor macro +#[derive(Debug)] +pub enum DbCommand { + CreateUser { + user: User, + result: oneshot::Sender<Result<(), Error>>, + }, + ReadUser { + user: BareJID, + result: oneshot::Sender<Result<User, Error>>, + }, + DeleteUserNick { + jid: BareJID, + result: oneshot::Sender<Result<bool, Error>>, + }, + UpsertUserNick { + jid: BareJID, + nick: String, + result: oneshot::Sender<Result<bool, Error>>, + }, + DeleteUserAvatar { + jid: BareJID, + result: oneshot::Sender<Result<(bool, Option<String>), Error>>, + }, + UpsertUserAvatar { + jid: BareJID, + 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: BareJID, + result: oneshot::Sender<Result<Contact, Error>>, + }, + ReadContactOpt { + contact: BareJID, + 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: BareJID, + 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: BareJID, + result: oneshot::Sender<Result<Chat, Error>>, + }, + ReadChatAndUser { + chat: BareJID, + result: oneshot::Sender<Result<(Chat, User), Error>>, + }, + MarkChatAsChatted { + chat: BareJID, + result: oneshot::Sender<Result<(), Error>>, + }, + UpdateChatCorrespondent { + old_chat: Chat, + new_correspondent: BareJID, + result: oneshot::Sender<Result<Chat, Error>>, + }, + DeleteChat { + chat: BareJID, + 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: BareJID, + from: FullJID, + result: oneshot::Sender<Result<(), Error>>, + }, + UpsertChatAndUser { + chat: BareJID, + result: oneshot::Sender<Result<bool, Error>>, + }, + CreateMessageWithUserResource { + message: Message, + chat: BareJID, + from: FullJID, + 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: BareJID, + result: oneshot::Sender<Result<Vec<Message>, Error>>, + }, + ReadMessageHistoryWithUsers { + chat: BareJID, + 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", + }) + } +} + +impl DbActor { + /// must be run in blocking spawn + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn new( path: impl AsRef<Path>, + receiver: mpsc::UnboundedReceiver<DbCommand>, ) -> Result<Self, DatabaseOpenError> { if let Some(dir) = path.as_ref().parent() { if dir.is_dir() { } else { - tokio::fs::create_dir_all(dir).await?; + std::fs::create_dir_all(dir)?; } - let _file = tokio::fs::OpenOptions::new() + let _file = std::fs::OpenOptions::new() .append(true) .create(true) - .open(path.as_ref()) - .await?; + .open(path.as_ref())?; } 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 }) + // 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) fn new(db: SqlitePool) -> Self { - Self { db } + /// must be run in blocking spawn + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn new_memory( + receiver: mpsc::UnboundedReceiver<DbCommand>, + ) -> Result<Self, DatabaseOpenError> { + let db = Connection::open_in_memory()?; + db.execute_batch(include_str!("../migrations/1.sql"))?; + Ok(Self { db, receiver }) } - pub(crate) async fn create_user(&self, user: User) -> Result<(), Error> { - sqlx::query!( - "insert into users ( jid, nick, cached_status_message ) values ( ?, ?, ? )", - user.jid, - user.nick, - user.cached_status_message - ) - .execute(&self.db) - .await?; - 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_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) + /// 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_user_nick(&self, jid: JID, nick: String) -> Result<(), Error> { - sqlx::query!( - "insert into users (jid, nick) values (?, ?) on conflict do update set nick = ?", - jid, - nick, - nick - ) - .execute(&self.db) - .await?; + 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 update_user(&self, user: User) -> Result<(), Error> { - sqlx::query!( - "update users set cached_status_message = ?, nick = ? where jid = ?", - user.cached_status_message, - user.nick, - user.jid - ) - .execute(&self.db) - .await?; + // TODO: this is not a 'read' user + pub(crate) fn read_user(&self, user: BareJID) -> 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, + }) + } + } + } + + /// returns whether or not the nickname was updated + pub(crate) fn delete_user_nick(&self, jid: BareJID) -> 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) fn upsert_user_nick(&self, jid: BareJID, 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 avatar was updated, and the file to delete if there existed an old avatar + pub(crate) fn delete_user_avatar(&self, jid: BareJID) -> 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) fn upsert_user_avatar( + &self, + jid: BareJID, + 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)) + } + } + + // 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(()) } // 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> {} + // pub(crate) 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 ? + 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 { - 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?; + 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) 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)) + pub(crate) fn read_contact(&self, contact: BareJID) -> 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) fn read_contact_opt(&self, contact: BareJID) -> 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 + 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 { - 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?; + 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 + 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 { - 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?; + 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 + pub(crate) fn delete_contact(&self, contact: BareJID) -> 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?; + 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).await?; + 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 join users on jid = user_jid") - .fetch_all(&self.db) - .await?; + 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 { - #[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)); + 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> { + 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) fn create_chat(&self, chat: Chat) -> Result<(), Error> { let id = Uuid::new_v4(); let jid = chat.correspondent(); - sqlx::query!( - "insert into chats (id, correspondent) values (?, ?)", - id, - jid - ) - .execute(&self.db) - .await?; + 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. - 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) + /// TODO: this is NOT a read + pub(crate) fn read_chat(&self, chat: BareJID) -> 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?; + pub(crate) fn read_chat_and_user(&self, chat: BareJID) -> 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) fn mark_chat_as_chatted(&self, chat: BareJID) -> Result<(), Error> { + self.db.execute( + "update chats set have_chatted = true where correspondent = ?1", + [chat], + )?; Ok(()) } - pub(crate) async fn update_chat_correspondent( + pub(crate) fn update_chat_correspondent( &self, old_chat: Chat, - new_correspondent: JID, + new_correspondent: BareJID, ) -> 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?; + 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 update_chat + // pub(crate) fn update_chat - pub(crate) async fn delete_chat(&self, chat: JID) -> Result<(), Error> { - sqlx::query!("delete from chats where correspondent = ?", chat) - .execute(&self.db) - .await?; + pub(crate) fn delete_chat(&self, chat: BareJID) -> Result<(), Error> { + self.db + .execute("delete from chats where correspondent = ?1", [chat])?; Ok(()) } /// 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?; + 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(&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?; + 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( + pub(crate) fn read_chats_ordered_with_latest_messages( &self, ) -> Result<Vec<(Chat, Message)>, Error> { - #[derive(sqlx::FromRow)] - pub struct ChatWithMessage { - #[sqlx(flatten)] - pub chat: Chat, - #[sqlx(flatten)] - pub message: Message, - } - - // TODO: i don't know if this will assign the right uuid to the latest message or the chat's id. should probably check but i don't think it matters as nothing ever gets called with the id of the latest message in the chats list - let chats: Vec<ChatWithMessage> = 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| (chat_with_message.chat, chat_with_message.message)) - .collect(); + 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) + } + /// 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(&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; + #[tracing::instrument] + fn read_chat_id(&self, chat: BareJID) -> 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) } - 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); + 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) } /// 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( + #[tracing::instrument] + pub(crate) fn create_message( &self, message: Message, - chat: JID, - from: JID, + chat: BareJID, + from: FullJID, ) -> 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?; + 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(()) } - 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?; + pub(crate) fn upsert_chat_and_user(&self, chat: &BareJID) -> Result<bool, Error> { + let db = &self.db; + db.execute( + "insert into users (jid) values (?1) on conflict do nothing", + [&chat], + )?; let id = Uuid::new_v4(); - let chat: Chat = sqlx::query_as("insert into chats (id, correspondent, have_chatted) values (?, ?, ?) on conflict do nothing returning *") - .bind(id) - .bind(bare_chat) - .bind(false) - .fetch_one(&self.db) - .await?; + db.execute("insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3) on conflict do nothing", (id, &chat, false))?; + let chat = 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)?, + }) + }, + )?; Ok(chat.have_chatted) } - /// 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) fn create_message_with_user_resource( &self, message: Message, - chat: JID, - // full jid - from: JID, + chat: BareJID, + from: FullJID, ) -> 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?; + tracing::debug!("creating resource"); + self.db.execute( + "insert into resources (bare_jid, resource) values (?1, ?2) on conflict do nothing", + (&from_jid, &from.resourcepart), + )?; + self.create_message(message, chat, from)?; Ok(()) } - // create direct message from incoming - pub(crate) async fn create_message_with_user_resource( + pub(crate) fn update_message_delivery( &self, - message: Message, - chat: JID, - // full jid - from: JID, + message: Uuid, + delivery: Delivery, ) -> 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?; + self.db.execute( + "update messages set delivery = ?1 where id = ?2", + (delivery, message), + )?; 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 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?; + pub(crate) fn delete_message(&self, message: Uuid) -> Result<(), Error> { + self.db + .execute("delete from messages where id = ?1", [message])?; Ok(()) } + 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) + } + // 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?; + pub(crate) fn read_message_history(&self, chat: BareJID) -> 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) fn read_message_history_with_users( + &self, + chat: BareJID, + ) -> 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 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_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 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?; + 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 delete_cached_status(&self) -> Result<(), Error> { - sqlx::query!("update cached_status set show = null, message = null where id = 0") - .execute(&self.db) - .await?; + 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 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 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) async fn upsert_capabilities( + pub(crate) fn upsert_capabilities( &self, - node: &str, - capabilities: &str, + node: String, + capabilities: String, ) -> 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?; + 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 5111413..fb7d778 100644 --- a/filamento/src/error.rs +++ b/filamento/src/error.rs @@ -1,15 +1,24 @@ -use std::{string::FromUtf8Error, sync::Arc}; +use std::{num::TryFromIntError, string::FromUtf8Error, sync::Arc}; +use base64::DecodeError; +use image::ImageError; use jid::JID; -use lampada::error::{ConnectionError, ReadError, WriteError}; +use jid::JIDError; +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 #[derive(Debug, Error, Clone)] -pub enum Error { +pub enum Error<Fs: FileStore> { #[error("core error: {0}")] Connection(#[from] ConnectionError), #[error("received unrecognized/unsupported content")] @@ -17,7 +26,7 @@ pub enum Error { // TODO: include content // UnrecognizedContent(peanuts::element::Content), #[error("iq receive error: {0}")] - Iq(#[from] IqError), + Iq(#[from] IqProcessError), // TODO: change to Connecting(ConnectingError) #[error("connecting: {0}")] Connecting(#[from] ConnectionJobError), @@ -33,11 +42,11 @@ pub enum Error { #[error("message send error: {0}")] MessageSend(#[from] MessageSendError), #[error("message receive error: {0}")] - MessageRecv(#[from] MessageRecvError), + MessageRecv(#[from] MessageRecvError<Fs>), #[error("subscripbe error: {0}")] Subscribe(#[from] SubscribeError), #[error("publish error: {0}")] - Publish(#[from] PublishError), + Publish(#[from] PEPError), } #[derive(Debug, Error, Clone)] @@ -53,13 +62,29 @@ pub enum MessageSendError { } #[derive(Debug, Error, Clone)] -pub enum MessageRecvError { +pub enum MessageRecvError<Fs: FileStore> { #[error("could not add to message history: {0}")] MessageHistory(#[from] DatabaseError), #[error("missing from")] MissingFrom, #[error("could not update user nick: {0}")] NickUpdate(DatabaseError), + #[error("could not update user avatar: {0}")] + AvatarUpdate(#[from] AvatarUpdateError<Fs>), +} + +#[derive(Debug, Error, Clone)] +pub enum AvatarUpdateError<Fs: FileStore> { + #[error("could not save to disk: {0}")] + FileStore(Fs::Err), + #[error("could not fetch avatar data: {0}")] + PEPError(#[from] CommandError<PEPError>), + #[error("base64 decode: {0}")] + Base64(#[from] DecodeError), + #[error("pep node missing avatar data")] + MissingData, + #[error("database: {0}")] + Database(#[from] DatabaseError), } #[derive(Debug, Error, Clone)] @@ -97,6 +122,17 @@ pub enum RosterError { StanzaError(#[from] stanza::client::error::Error), #[error("could not reply to roster push: {0}")] PushReply(WriteError), + #[error("actor error: {0}")] + Actor(ActorError), +} + +impl From<CommandError<RosterError>> for RosterError { + fn from(value: CommandError<RosterError>) -> Self { + match value { + CommandError::Actor(actor_error) => Self::Actor(actor_error), + CommandError::Error(e) => e, + } + } } #[derive(Debug, Error, Clone)] @@ -134,17 +170,104 @@ pub enum ResponseError { } #[derive(Debug, Error, Clone)] -#[error("database error: {0}")] -pub struct DatabaseError(pub Arc<sqlx::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 From<sqlx::Error> for DatabaseError { - fn from(e: sqlx::Error) -> Self { - Self(Arc::new(e)) +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 From<sqlx::Error> for DatabaseOpenError { - fn from(e: sqlx::Error) -> Self { +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::Database(Serializeable::Unserialized(Arc::new(e))) + } +} + +impl From<rusqlite::Error> for DatabaseOpenError { + fn from(e: rusqlite::Error) -> Self { Self::Error(Arc::new(e)) } } @@ -161,25 +284,149 @@ pub enum IqError { } #[derive(Debug, Error, Clone)] +pub enum IqProcessError { + #[error("iq error")] + Iq(#[from] IqError), + #[error("roster push")] + Roster(#[from] RosterError), +} + +#[derive(Debug, Error, Clone)] pub enum DatabaseOpenError { + #[cfg(target_arch = "wasm32")] + #[error("opfs: {0}")] + OpfsSAH(#[from] OpfsSAHError), #[error("error: {0}")] - Error(Arc<sqlx::Error>), - #[error("migration: {0}")] - Migration(Arc<sqlx::migrate::MigrateError>), + Error(Arc<rusqlite::Error>), + // #[error("migration: {0}")] + // Migration(Arc<rusqlite::migrate::MigrateError>), #[error("io: {0}")] - Io(Arc<tokio::io::Error>), + Io(Arc<std::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 { - fn from(e: sqlx::migrate::MigrateError) -> Self { - Self::Migration(Arc::new(e)) +// impl From<sqlx::migrate::MigrateError> for DatabaseOpenError { +// fn from(e: sqlx::migrate::MigrateError) -> Self { +// Self::Migration(Arc::new(e)) +// } +// } + +#[cfg(target_arch = "wasm32")] +impl From<rusqlite::ffi::OpfsSAHError> for OpfsSAHError { + fn from(e: rusqlite::ffi::OpfsSAHError) -> Self { + use wasm_bindgen::UnwrapThrowExt; + match e { + rusqlite::ffi::OpfsSAHError::Vfs(_register_vfs_error) => Self::VfsRegistration, + rusqlite::ffi::OpfsSAHError::ImportDb(_import_db_error) => Self::ImportDb, + rusqlite::ffi::OpfsSAHError::NotSuported => Self::NotSupported, + rusqlite::ffi::OpfsSAHError::GetDirHandle(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::GetDirHandle(message) + } + rusqlite::ffi::OpfsSAHError::GetFileHandle(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::GetFileHandle(message) + } + rusqlite::ffi::OpfsSAHError::CreateSyncAccessHandle(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::CreateSyncAccessHandle(message) + } + rusqlite::ffi::OpfsSAHError::IterHandle(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::IterHandle(message) + } + rusqlite::ffi::OpfsSAHError::GetPath(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::GetPath(message) + } + rusqlite::ffi::OpfsSAHError::RemoveEntity(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::RemoveEntity(message) + } + rusqlite::ffi::OpfsSAHError::GetSize(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::GetSize(message) + } + rusqlite::ffi::OpfsSAHError::Read(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::Read(message) + } + rusqlite::ffi::OpfsSAHError::Write(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::Write(message) + } + rusqlite::ffi::OpfsSAHError::Flush(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::Flush(message) + } + rusqlite::ffi::OpfsSAHError::Truncate(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::Truncate(message) + } + rusqlite::ffi::OpfsSAHError::Reflect(js_value) => { + let error: js_sys::Error = js_value.into(); + let message = error.message().as_string().unwrap_throw(); + Self::Reflect(message) + } + rusqlite::ffi::OpfsSAHError::Generic(s) => Self::Generic(s), + rusqlite::ffi::OpfsSAHError::Custom(s) => Self::Generic(s), + } } } -impl From<tokio::io::Error> for DatabaseOpenError { - fn from(e: tokio::io::Error) -> Self { +#[cfg(target_arch = "wasm32")] +#[derive(Debug, Error, Clone)] +pub enum OpfsSAHError { + #[error("VFS registration")] + VfsRegistration, + #[error("import db error")] + ImportDb, + #[error("not supported")] + NotSupported, + #[error("get dir handle: {0}")] + GetDirHandle(String), + #[error("get file handle: {0}")] + GetFileHandle(String), + #[error("create sync access handle: {0}")] + CreateSyncAccessHandle(String), + #[error("iter handle: {0}")] + IterHandle(String), + #[error("get path: {0}")] + GetPath(String), + #[error("remove entity: {0}")] + RemoveEntity(String), + #[error("get size: {0}")] + GetSize(String), + #[error("read: {0}")] + Read(String), + #[error("write: {0}")] + Write(String), + #[error("flush: {0}")] + Flush(String), + #[error("truncate: {0}")] + Truncate(String), + #[error("reflect: {0}")] + Reflect(String), + #[error("generic: {0}")] + Generic(String), +} + +impl From<std::io::Error> for DatabaseOpenError { + fn from(e: std::io::Error) -> Self { Self::Io(Arc::new(e)) } } @@ -198,12 +445,14 @@ 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>), + #[error("received subscription request from a non-bare jid")] + InvalidSubscriptionRequest(#[from] JIDError), } #[derive(Debug, Error, Clone)] -pub enum PublishError { +pub enum PEPError { #[error("received mismatched query")] MismatchedQuery(Query), #[error("missing query")] @@ -216,12 +465,19 @@ pub enum PublishError { UnexpectedStanza(Stanza), #[error("iq response: {0}")] IqResponse(#[from] IqRequestError), + #[error("missing pep item")] + MissingItem, + #[error("incorrect item id: expected {0}, got {1}")] + IncorrectItemID(String, String), + #[error("unsupported pep item")] + UnsupportedItem, + // TODO: should the item be in the error? } #[derive(Debug, Error, Clone)] pub enum NickError { #[error("publishing nick: {0}")] - Publish(#[from] CommandError<PublishError>), + Publish(#[from] CommandError<PEPError>), #[error("updating database: {0}")] Database(#[from] DatabaseError), #[error("disconnected")] @@ -267,5 +523,31 @@ pub enum CapsNodeConversionError { #[error("missing hashtag")] MissingHashtag, } -// #[derive(Debug, Error, Clone)] -// pub enum CapsError {} + +#[derive(Debug, Error, Clone)] +pub enum AvatarPublishError<Fs: FileStore> { + #[error("disconnected")] + Disconnected, + #[error("image read: {0}")] + Read(Arc<std::io::Error>), + #[error("image: {0}")] + Image(Arc<ImageError>), + #[error("pep publish: {0}")] + Publish(#[from] CommandError<PEPError>), + #[error("bytes number conversion: {0}")] + FromInt(#[from] TryFromIntError), + #[error("could not save to disk")] + FileStore(Fs::Err), +} + +impl<Fs: FileStore> From<std::io::Error> for AvatarPublishError<Fs> { + fn from(value: std::io::Error) -> Self { + Self::Read(Arc::new(value)) + } +} + +impl<Fs: FileStore> From<ImageError> for AvatarPublishError<Fs> { + fn from(value: ImageError) -> Self { + Self::Image(Arc::new(value)) + } +} diff --git a/filamento/src/files.rs b/filamento/src/files.rs new file mode 100644 index 0000000..dcc9cd2 --- /dev/null +++ b/filamento/src/files.rs @@ -0,0 +1,143 @@ +use std::{ + collections::HashMap, + convert::Infallible, + error::Error, + path::{Path, PathBuf}, + sync::Arc, +}; + +use tokio::io; +use tokio::sync::Mutex; + +#[cfg(not(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>> + std::marker::Send; + fn store( + &self, + name: &str, + data: &[u8], + ) -> impl std::future::Future<Output = Result<(), Self::Err>> + std::marker::Send; + fn delete( + &self, + name: &str, + ) -> 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>>>>, +} + +impl FilesMem { + pub fn new() -> Self { + Self { + 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; + + async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> { + Ok(self.files.lock().await.contains_key(name)) + } + + async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> { + self.files + .lock() + .await + .insert(name.to_string(), data.to_owned()); + + Ok(()) + } + + async fn delete(&self, name: &str) -> Result<(), Self::Err> { + self.files.lock().await.remove(name); + Ok(()) + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Debug)] +pub struct Files { + root: PathBuf, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Files { + pub fn new(root: impl AsRef<Path>) -> Self { + let root = root.as_ref(); + let root = root.into(); + Self { root } + } + + pub fn root(&self) -> &Path { + &self.root + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl FileStore for Files { + type Err = Arc<io::Error>; + + async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> { + tracing::debug!("checking if {} is stored", name); + // TODO: is this secure ;-; + let name = name.replace("/", "").replace(".", ""); + let res = tokio::fs::try_exists(self.root.join(name)) + .await + .map_err(|err| Arc::new(err)); + tracing::debug!("file check res: {:?}", res); + res + } + + async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> { + tracing::debug!("storing {} is stored", name); + let name = name.replace("/", "").replace(".", ""); + let res = tokio::fs::write(self.root.join(name), data) + .await + .map_err(|err| Arc::new(err)); + tracing::debug!("file store res: {:?}", res); + res + } + + async fn delete(&self, name: &str) -> Result<(), Self::Err> { + tracing::debug!("deleting {}", name); + let name = name.replace("/", "").replace(".", ""); + let res = tokio::fs::remove_file(self.root.join(name)) + .await + .map_err(|err| Arc::new(err)); + tracing::debug!("file delete res: {:?}", res); + res + } +} diff --git a/filamento/src/files/opfs.rs b/filamento/src/files/opfs.rs new file mode 100644 index 0000000..0bcce35 --- /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, Debug)] +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 c44edca..d3033b7 100644 --- a/filamento/src/lib.rs +++ b/filamento/src/lib.rs @@ -11,11 +11,12 @@ use chrono::Utc; use db::Db; use disco::{Info, Items}; use error::{ - ConnectionJobError, DatabaseError, DiscoError, Error, IqError, MessageRecvError, NickError, - PresenceError, PublishError, RosterError, StatusError, SubscribeError, + AvatarPublishError, ConnectionJobError, DatabaseError, DiscoError, Error, IqError, + MessageRecvError, NickError, PEPError, PresenceError, RosterError, StatusError, SubscribeError, }; +use files::FileStore; use futures::FutureExt; -use jid::JID; +use jid::{BareJID, JID}; use lampada::{ Connected, CoreClient, CoreClientCommand, Logic, SupervisorSender, WriteMessage, error::{ActorError, CommandError, ConnectionError, ReadError, WriteError}, @@ -31,24 +32,30 @@ use tokio::{ sync::{Mutex, mpsc, oneshot}, time::timeout, }; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; use tracing::{debug, info}; use user::User; use uuid::Uuid; +pub mod avatar; pub mod caps; pub mod chat; pub mod db; pub mod disco; pub mod error; +pub mod files; mod logic; pub mod pep; pub mod presence; pub mod roster; pub mod user; -pub enum Command { +pub enum Command<Fs: FileStore> { /// get the roster. if offline, retreive cached version from database. should be stored in application memory GetRoster(oneshot::Sender<Result<Vec<Contact>, RosterError>>), + /// get the roster. if offline, retreive cached version from database. should be stored in application memory. includes user associated with each contact + GetRosterWithUsers(oneshot::Sender<Result<Vec<(Contact, User)>, RosterError>>), /// get all chats. chat will include 10 messages in their message Vec (enough for chat previews) // TODO: paging and filtering GetChats(oneshot::Sender<Result<Vec<Chat>, DatabaseError>>), @@ -56,37 +63,60 @@ pub enum Command { GetChatsOrdered(oneshot::Sender<Result<Vec<Chat>, DatabaseError>>), // TODO: paging and filtering GetChatsOrderedWithLatestMessages(oneshot::Sender<Result<Vec<(Chat, Message)>, DatabaseError>>), + // TODO: paging and filtering, nullabillity for latest message + GetChatsOrderedWithLatestMessagesAndUsers( + oneshot::Sender<Result<Vec<((Chat, User), (Message, User))>, DatabaseError>>, + ), /// get a specific chat by jid - GetChat(JID, oneshot::Sender<Result<Chat, DatabaseError>>), + GetChat(BareJID, oneshot::Sender<Result<Chat, DatabaseError>>), + /// get a specific chat and user by jid + GetChatAndUser( + BareJID, + 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( + BareJID, + oneshot::Sender<Result<Vec<Message>, DatabaseError>>, + ), /// get message history for chat (does appropriate mam things) // TODO: paging and filtering - GetMessages(JID, oneshot::Sender<Result<Vec<Message>, DatabaseError>>), + GetMessagesWithUsers( + BareJID, + oneshot::Sender<Result<Vec<(Message, User)>, DatabaseError>>, + ), /// delete a chat from your chat history, along with all the corresponding messages - DeleteChat(JID, oneshot::Sender<Result<(), DatabaseError>>), + DeleteChat(BareJID, oneshot::Sender<Result<(), DatabaseError>>), /// delete a message from your chat history DeleteMessage(Uuid, oneshot::Sender<Result<(), DatabaseError>>), /// get a user from your users database - GetUser(JID, oneshot::Sender<Result<User, DatabaseError>>), + GetUser(BareJID, oneshot::Sender<Result<User, DatabaseError>>), /// add a contact to your roster, with a status of none, no subscriptions. - AddContact(JID, oneshot::Sender<Result<(), RosterError>>), + AddContact(BareJID, oneshot::Sender<Result<(), RosterError>>), /// send a friend request i.e. a subscription request with a subscription pre-approval. if not already added to roster server adds to roster. - BuddyRequest(JID, oneshot::Sender<Result<(), SubscribeError>>), + BuddyRequest(BareJID, oneshot::Sender<Result<(), SubscribeError>>), /// send a subscription request, without pre-approval. if not already added to roster server adds to roster. - SubscriptionRequest(JID, oneshot::Sender<Result<(), SubscribeError>>), + SubscriptionRequest(BareJID, oneshot::Sender<Result<(), SubscribeError>>), /// accept a friend request by accepting a pending subscription and sending a subscription request back. if not already added to roster adds to roster. - AcceptBuddyRequest(JID, oneshot::Sender<Result<(), SubscribeError>>), + AcceptBuddyRequest(BareJID, oneshot::Sender<Result<(), SubscribeError>>), /// accept a pending subscription and doesn't send a subscription request back. if not already added to roster adds to roster. - AcceptSubscriptionRequest(JID, oneshot::Sender<Result<(), SubscribeError>>), + AcceptSubscriptionRequest(BareJID, oneshot::Sender<Result<(), SubscribeError>>), /// unsubscribe to a contact, but don't remove their subscription. - UnsubscribeFromContact(JID, oneshot::Sender<Result<(), WriteError>>), + UnsubscribeFromContact(BareJID, oneshot::Sender<Result<(), WriteError>>), /// stop a contact from being subscribed, but stay subscribed to the contact. - UnsubscribeContact(JID, oneshot::Sender<Result<(), WriteError>>), + UnsubscribeContact(BareJID, oneshot::Sender<Result<(), WriteError>>), /// remove subscriptions to and from contact, but keep in roster. - UnfriendContact(JID, oneshot::Sender<Result<(), WriteError>>), + UnfriendContact(BareJID, oneshot::Sender<Result<(), WriteError>>), /// remove a contact from the contact list. will remove subscriptions if not already done then delete contact from roster. - DeleteContact(JID, oneshot::Sender<Result<(), RosterError>>), + DeleteContact(BareJID, oneshot::Sender<Result<(), RosterError>>), /// update contact. contact details will be overwritten with the contents of the contactupdate struct. - UpdateContact(JID, ContactUpdate, oneshot::Sender<Result<(), RosterError>>), + UpdateContact( + BareJID, + ContactUpdate, + oneshot::Sender<Result<(), RosterError>>, + ), /// set online status. if disconnected, will be cached so when client connects, will be sent as the initial presence. SetStatus(Online, oneshot::Sender<Result<(), StatusError>>), /// send presence stanza @@ -100,7 +130,7 @@ pub enum Command { // TODO: should probably make it so people can add non-contact auto presence sharing in the client (most likely through setting an internal setting) /// send a message to a jid (any kind of jid that can receive a message, e.g. a user or a /// chatroom). if disconnected, will be cached so when client connects, message will be sent. - SendMessage(JID, Body), + SendMessage(BareJID, Body), // TODO: resend failed messages // ResendMessage(Uuid), /// disco info query @@ -115,28 +145,43 @@ pub enum Command { Option<String>, oneshot::Sender<Result<disco::Items, DiscoError>>, ), - /// publish item to a pep node, specified or default according to item. - Publish { + /// publish item to a pep node specified. + PublishPEPItem { item: pep::Item, node: String, - sender: oneshot::Sender<Result<(), PublishError>>, + sender: oneshot::Sender<Result<(), PEPError>>, + }, + DeletePEPNode { + node: String, + sender: oneshot::Sender<Result<(), PEPError>>, + }, + GetPEPItem { + jid: Option<BareJID>, + node: String, + id: String, + sender: oneshot::Sender<Result<pep::Item, PEPError>>, }, - /// change user nickname - ChangeNick(String, oneshot::Sender<Result<(), NickError>>), + /// change client user nickname + ChangeNick(Option<String>, oneshot::Sender<Result<(), NickError>>), + // // TODO + // GetNick(...), + // GetAvatar(...) // /// get capability node // GetCaps(String, oneshot::Sender<Result<Info, CapsError>>), + /// change client user avatar + ChangeAvatar( + Option<Vec<u8>>, + oneshot::Sender<Result<(), AvatarPublishError<Fs>>>, + ), } #[derive(Debug, Clone)] pub enum UpdateMessage { - Online(Online, Vec<Contact>), + Online(Online, Vec<(Contact, User)>), Offline(Offline), - /// received roster from jabber server (replace full app roster state with this) - /// is this needed? - FullRoster(Vec<Contact>), /// (only update app roster state, don't replace) - RosterUpdate(Contact), - RosterDelete(JID), + RosterUpdate(Contact, User), + RosterDelete(BareJID), /// presences should be stored with users in the ui, not contacts, as presences can be received from anyone Presence { from: JID, @@ -145,28 +190,44 @@ pub enum UpdateMessage { // TODO: receipts // MessageDispatched(Uuid), Message { - to: JID, + // TODO: rename to chat? + to: BareJID, + from: User, message: Message, }, MessageDelivery { id: Uuid, + chat: BareJID, delivery: Delivery, }, - SubscriptionRequest(jid::JID), + SubscriptionRequest(BareJID), NickChanged { - jid: JID, - nick: String, + jid: BareJID, + nick: Option<String>, + }, + AvatarChanged { + jid: BareJID, + id: Option<String>, }, } /// an xmpp client that is suited for a chat client use case #[derive(Debug)] -pub struct Client { - sender: mpsc::Sender<CoreClientCommand<Command>>, +pub struct Client<Fs: FileStore> { + sender: mpsc::Sender<CoreClientCommand<Command<Fs>>>, timeout: Duration, } -impl Clone for Client { +impl<Fs: FileStore> Client<Fs> { + pub fn with_timeout(&self, timeout: Duration) -> Self { + Self { + sender: self.sender.clone(), + timeout, + } + } +} + +impl<Fs: FileStore> Clone for Client<Fs> { fn clone(&self) -> Self { Self { sender: self.sender.clone(), @@ -175,32 +236,27 @@ impl Clone for Client { } } -impl Deref for Client { - type Target = mpsc::Sender<CoreClientCommand<Command>>; +impl<Fs: FileStore> Deref for Client<Fs> { + type Target = mpsc::Sender<CoreClientCommand<Command<Fs>>>; fn deref(&self) -> &Self::Target { &self.sender } } -impl DerefMut for Client { +impl<Fs: FileStore> DerefMut for Client<Fs> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.sender } } -impl Client { - pub async fn connect(&self) -> Result<(), ActorError> { - self.send(CoreClientCommand::Connect).await?; - Ok(()) - } - - pub async fn disconnect(&self, offline: Offline) -> Result<(), ActorError> { - self.send(CoreClientCommand::Disconnect).await?; - Ok(()) - } - - pub fn new(jid: JID, password: String, db: Db) -> (Self, mpsc::Receiver<UpdateMessage>) { +impl<Fs: FileStore + Clone + Send + Sync + 'static> Client<Fs> { + pub fn new( + jid: JID, + password: String, + db: Db, + file_store: Fs, + ) -> (Self, mpsc::Receiver<UpdateMessage>) { let (command_sender, command_receiver) = mpsc::channel(20); let (update_send, update_recv) = mpsc::channel(20); @@ -211,17 +267,38 @@ impl Client { 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); + let logic = ClientLogic::new(client.clone(), jid.to_bare(), db, update_send, file_store); - let actor: CoreClient<ClientLogic> = + let actor: CoreClient<ClientLogic<Fs>> = CoreClient::new(jid, password, command_receiver, None, sup_recv, logic); + tokio::spawn(async move { actor.run().await }); (client, update_recv) } +} + +impl<Fs: FileStore> Client<Fs> { + /// 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> { + self.send(CoreClientCommand::Disconnect).await?; + Ok(()) + } pub async fn get_roster(&self) -> Result<Vec<Contact>, CommandError<RosterError>> { let (send, recv) = oneshot::channel(); @@ -235,6 +312,22 @@ impl Client { Ok(roster) } + pub async fn get_roster_with_users( + &self, + ) -> Result<Vec<(Contact, User)>, CommandError<RosterError>> { + let (send, recv) = oneshot::channel(); + self.send(CoreClientCommand::Command(Command::GetRosterWithUsers( + send, + ))) + .await + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?; + let roster = timeout(self.timeout, recv) + .await + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))? + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??; + Ok(roster) + } + pub async fn get_chats(&self) -> Result<Vec<Chat>, CommandError<DatabaseError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::GetChats(send))) @@ -275,7 +368,23 @@ impl Client { Ok(chats) } - pub async fn get_chat(&self, jid: JID) -> Result<Chat, CommandError<DatabaseError>> { + pub async fn get_chats_ordered_with_latest_messages_and_users( + &self, + ) -> Result<Vec<((Chat, User), (Message, User))>, CommandError<DatabaseError>> { + let (send, recv) = oneshot::channel(); + self.send(CoreClientCommand::Command( + Command::GetChatsOrderedWithLatestMessagesAndUsers(send), + )) + .await + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?; + let chats = timeout(self.timeout, recv) + .await + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))? + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??; + Ok(chats) + } + + pub async fn get_chat(&self, jid: BareJID) -> Result<Chat, CommandError<DatabaseError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::GetChat(jid, send))) .await @@ -287,9 +396,38 @@ impl Client { Ok(chat) } + pub async fn get_chat_and_user( + &self, + jid: BareJID, + ) -> 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, + jid: BareJID, ) -> Result<Vec<Message>, CommandError<DatabaseError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::GetMessages(jid, send))) @@ -302,7 +440,24 @@ impl Client { Ok(messages) } - pub async fn delete_chat(&self, jid: JID) -> Result<(), CommandError<DatabaseError>> { + pub async fn get_messages_with_users( + &self, + jid: BareJID, + ) -> Result<Vec<(Message, User)>, CommandError<DatabaseError>> { + let (send, recv) = oneshot::channel(); + self.send(CoreClientCommand::Command(Command::GetMessagesWithUsers( + jid, send, + ))) + .await + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))?; + let messages = timeout(self.timeout, recv) + .await + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))? + .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??; + Ok(messages) + } + + pub async fn delete_chat(&self, jid: BareJID) -> Result<(), CommandError<DatabaseError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::DeleteChat(jid, send))) .await @@ -326,7 +481,7 @@ impl Client { Ok(result) } - pub async fn get_user(&self, jid: JID) -> Result<User, CommandError<DatabaseError>> { + pub async fn get_user(&self, jid: BareJID) -> Result<User, CommandError<DatabaseError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::GetUser(jid, send))) .await @@ -338,7 +493,7 @@ impl Client { Ok(result) } - pub async fn add_contact(&self, jid: JID) -> Result<(), CommandError<RosterError>> { + pub async fn add_contact(&self, jid: BareJID) -> Result<(), CommandError<RosterError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::AddContact(jid, send))) .await @@ -350,7 +505,7 @@ impl Client { Ok(result) } - pub async fn buddy_request(&self, jid: JID) -> Result<(), CommandError<SubscribeError>> { + pub async fn buddy_request(&self, jid: BareJID) -> Result<(), CommandError<SubscribeError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::BuddyRequest(jid, send))) .await @@ -362,7 +517,10 @@ impl Client { Ok(result) } - pub async fn subscription_request(&self, jid: JID) -> Result<(), CommandError<SubscribeError>> { + pub async fn subscription_request( + &self, + jid: BareJID, + ) -> Result<(), CommandError<SubscribeError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::SubscriptionRequest( jid, send, @@ -376,7 +534,10 @@ impl Client { Ok(result) } - pub async fn accept_buddy_request(&self, jid: JID) -> Result<(), CommandError<SubscribeError>> { + pub async fn accept_buddy_request( + &self, + jid: BareJID, + ) -> Result<(), CommandError<SubscribeError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::AcceptBuddyRequest( jid, send, @@ -392,7 +553,7 @@ impl Client { pub async fn accept_subscription_request( &self, - jid: JID, + jid: BareJID, ) -> Result<(), CommandError<SubscribeError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command( @@ -407,7 +568,10 @@ impl Client { Ok(result) } - pub async fn unsubscribe_from_contact(&self, jid: JID) -> Result<(), CommandError<WriteError>> { + pub async fn unsubscribe_from_contact( + &self, + jid: BareJID, + ) -> Result<(), CommandError<WriteError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::UnsubscribeFromContact( jid, send, @@ -421,7 +585,7 @@ impl Client { Ok(result) } - pub async fn unsubscribe_contact(&self, jid: JID) -> Result<(), CommandError<WriteError>> { + pub async fn unsubscribe_contact(&self, jid: BareJID) -> Result<(), CommandError<WriteError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::UnsubscribeContact( jid, send, @@ -435,7 +599,7 @@ impl Client { Ok(result) } - pub async fn unfriend_contact(&self, jid: JID) -> Result<(), CommandError<WriteError>> { + pub async fn unfriend_contact(&self, jid: BareJID) -> Result<(), CommandError<WriteError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::UnfriendContact( jid, send, @@ -449,7 +613,7 @@ impl Client { Ok(result) } - pub async fn delete_contact(&self, jid: JID) -> Result<(), CommandError<RosterError>> { + pub async fn delete_contact(&self, jid: BareJID) -> Result<(), CommandError<RosterError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::DeleteContact( jid, send, @@ -465,7 +629,7 @@ impl Client { pub async fn update_contact( &self, - jid: JID, + jid: BareJID, update: ContactUpdate, ) -> Result<(), CommandError<RosterError>> { let (send, recv) = oneshot::channel(); @@ -493,7 +657,7 @@ impl Client { Ok(result) } - pub async fn send_message(&self, jid: JID, body: Body) -> Result<(), ActorError> { + pub async fn send_message(&self, jid: BareJID, body: Body) -> Result<(), ActorError> { self.send(CoreClientCommand::Command(Command::SendMessage(jid, body))) .await?; Ok(()) @@ -539,9 +703,9 @@ impl Client { &self, item: pep::Item, node: String, - ) -> Result<(), CommandError<PublishError>> { + ) -> Result<(), CommandError<PEPError>> { let (send, recv) = oneshot::channel(); - self.send(CoreClientCommand::Command(Command::Publish { + self.send(CoreClientCommand::Command(Command::PublishPEPItem { item, node, sender: send, @@ -555,7 +719,45 @@ impl Client { Ok(result) } - pub async fn change_nick(&self, nick: String) -> Result<(), CommandError<NickError>> { + pub async fn delete_pep_node(&self, node: String) -> Result<(), CommandError<PEPError>> { + let (send, recv) = oneshot::channel(); + self.send(CoreClientCommand::Command(Command::DeletePEPNode { + node, + sender: 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_pep_item( + &self, + // i think this is correct?, should not be able to send pep requests to a full jid. + jid: Option<BareJID>, + node: String, + id: String, + ) -> Result<pep::Item, CommandError<PEPError>> { + let (send, recv) = oneshot::channel(); + self.send(CoreClientCommand::Command(Command::GetPEPItem { + jid, + node, + id, + sender: 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 change_nick(&self, nick: Option<String>) -> Result<(), CommandError<NickError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::ChangeNick(nick, send))) .await @@ -566,10 +768,117 @@ impl Client { .map_err(|e| CommandError::Actor(Into::<ActorError>::into(e)))??; Ok(result) } + + pub async fn change_avatar( + &self, + avatar: Option<Vec<u8>>, + ) -> Result<(), CommandError<AvatarPublishError<Fs>>> { + let (send, recv) = oneshot::channel(); + self.send(CoreClientCommand::Command(Command::ChangeAvatar( + avatar, 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) + } } -impl From<Command> for CoreClientCommand<Command> { - fn from(value: Command) -> Self { +impl<Fs: FileStore> From<Command<Fs>> for CoreClientCommand<Command<Fs>> { + fn from(value: Command<Fs>) -> Self { CoreClientCommand::Command(value) } } + +#[cfg(test)] +mod tests { + use wasm_bindgen_test::*; + + use super::*; + + wasm_bindgen_test_configure!(run_in_browser); + + use crate::chat; + use crate::files::FilesMem; + use std::path::Path; + use tokio_with_wasm::alias as tokio; + + #[wasm_bindgen_test] + async fn login() -> () { + tracing_wasm::set_as_global_default(); + let db = Db::create_connect_and_migrate(Path::new("./filamento.db")) + .await + .unwrap(); + let (client, mut recv) = Client::new( + "test@blos.sm/testing2".try_into().unwrap(), + "slayed".to_string(), + db, + FilesMem::new(), + ); + + tokio::spawn(async move { + while let Some(msg) = recv.recv().await { + info!("{:#?}", msg) + } + }); + + client.connect().await.unwrap(); + // tokio::time::sleep(Duration::from_secs(5)).await; + info!("changing nick"); + client + .change_nick(Some("britney".to_string())) + .await + .unwrap(); + let mut data = include_bytes!("../files/britney_starbies.jpg"); + client.change_avatar(Some(data.to_vec())).await.unwrap(); + info!("sending message"); + client + .send_message( + BareJID::from_str("cel@blos.sm").unwrap(), + chat::Body { + body: "hallo!!!".to_string(), + }, + ) + .await + .unwrap(); + info!("sent message"); + client + .send_message( + BareJID::from_str("cel@blos.sm").unwrap(), + chat::Body { + body: "hallo 2".to_string(), + }, + ) + .await + .unwrap(); + // tokio::time::sleep(Duration::from_secs(15)).await; + // info!("sending disco query"); + // let info = client.disco_info(None, None).await.unwrap(); + // info!("got disco result: {:#?}", info); + // let items = client.disco_items(None, None).await.unwrap(); + // info!("got disco result: {:#?}", items); + // let info = client + // .disco_info(Some("blos.sm".parse().unwrap()), None) + // .await + // .unwrap(); + // info!("got disco result: {:#?}", info); + // let items = client + // .disco_items(Some("blos.sm".parse().unwrap()), None) + // .await + // .unwrap(); + // info!("got disco result: {:#?}", items); + // let info = client + // .disco_info(Some("pubsub.blos.sm".parse().unwrap()), None) + // .await + // .unwrap(); + // info!("got disco result: {:#?}", info); + // let items = client + // .disco_items(Some("pubsub.blos.sm".parse().unwrap()), None) + // .await + // .unwrap(); + // info!("got disco result: {:#?}", items); let mut jid: JID = "test@blos.sm".try_into().unwrap(); + } +} diff --git a/filamento/src/logic/abort.rs b/filamento/src/logic/abort.rs index df82655..3588b13 100644 --- a/filamento/src/logic/abort.rs +++ b/filamento/src/logic/abort.rs @@ -1,7 +1,9 @@ use lampada::error::ReadError; +use crate::files::FileStore; + use super::ClientLogic; -pub async fn on_abort(logic: ClientLogic) { +pub async fn on_abort<Fs: FileStore + Clone>(logic: ClientLogic<Fs>) { logic.pending().drain().await; } diff --git a/filamento/src/logic/connect.rs b/filamento/src/logic/connect.rs index dc05448..6e392f1 100644 --- a/filamento/src/logic/connect.rs +++ b/filamento/src/logic/connect.rs @@ -5,17 +5,21 @@ use tracing::debug; use crate::{ Command, UpdateMessage, error::{ConnectionJobError, Error, RosterError}, + files::FileStore, presence::{Online, PresenceType}, }; use super::ClientLogic; -pub async fn handle_connect(logic: ClientLogic, connection: Connected) { +pub async fn handle_connect<Fs: FileStore + Clone + Send + Sync + 'static>( + logic: ClientLogic<Fs>, + connection: Connected, +) { let (send, recv) = oneshot::channel(); debug!("getting roster"); logic .clone() - .handle_online(Command::GetRoster(send), connection.clone()) + .handle_online(Command::GetRosterWithUsers(send), connection.clone()) .await; debug!("sent roster req"); let roster = recv.await; diff --git a/filamento/src/logic/connection_error.rs b/filamento/src/logic/connection_error.rs index 081900b..36c1cef 100644 --- a/filamento/src/logic/connection_error.rs +++ b/filamento/src/logic/connection_error.rs @@ -1,7 +1,12 @@ use lampada::error::ConnectionError; +use crate::files::FileStore; + use super::ClientLogic; -pub async fn handle_connection_error(logic: ClientLogic, error: ConnectionError) { +pub async fn handle_connection_error<Fs: FileStore + Clone>( + logic: ClientLogic<Fs>, + error: ConnectionError, +) { logic.handle_error(error.into()).await; } diff --git a/filamento/src/logic/disconnect.rs b/filamento/src/logic/disconnect.rs index 241c3e6..ebcfd4f 100644 --- a/filamento/src/logic/disconnect.rs +++ b/filamento/src/logic/disconnect.rs @@ -1,11 +1,14 @@ use lampada::Connected; use stanza::client::Stanza; -use crate::{UpdateMessage, presence::Offline}; +use crate::{UpdateMessage, files::FileStore, presence::Offline}; use super::ClientLogic; -pub async fn handle_disconnect(logic: ClientLogic, connection: Connected) { +pub async fn handle_disconnect<Fs: FileStore + Clone>( + logic: ClientLogic<Fs>, + connection: Connected, +) { // TODO: be able to set offline status message let offline_presence: stanza::client::presence::Presence = Offline::default().into_stanza(None); let stanza = Stanza::Presence(offline_presence); diff --git a/filamento/src/logic/local_only.rs b/filamento/src/logic/local_only.rs index 3f6fe8d..7f3a2e6 100644 --- a/filamento/src/logic/local_only.rs +++ b/filamento/src/logic/local_only.rs @@ -1,47 +1,94 @@ -use jid::JID; +use jid::{BareJID, JID}; use uuid::Uuid; use crate::{ chat::{Chat, Message}, error::DatabaseError, + files::FileStore, user::User, }; use super::ClientLogic; -pub async fn handle_get_chats(logic: &ClientLogic) -> Result<Vec<Chat>, DatabaseError> { +pub async fn handle_get_chats<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, +) -> Result<Vec<Chat>, DatabaseError> { Ok(logic.db().read_chats().await?) } -pub async fn handle_get_chats_ordered(logic: &ClientLogic) -> Result<Vec<Chat>, DatabaseError> { +pub async fn handle_get_chats_ordered<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, +) -> Result<Vec<Chat>, DatabaseError> { Ok(logic.db().read_chats_ordered().await?) } -pub async fn handle_get_chats_ordered_with_latest_messages( - logic: &ClientLogic, +pub async fn handle_get_chats_ordered_with_latest_messages<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, ) -> Result<Vec<(Chat, Message)>, DatabaseError> { Ok(logic.db().read_chats_ordered_with_latest_messages().await?) } -pub async fn handle_get_chat(logic: &ClientLogic, jid: JID) -> Result<Chat, DatabaseError> { +pub async fn handle_get_chats_ordered_with_latest_messages_and_users<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, +) -> Result<Vec<((Chat, User), (Message, User))>, DatabaseError> { + Ok(logic + .db() + .read_chats_ordered_with_latest_messages_and_users() + .await?) +} + +pub async fn handle_get_chat<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + jid: BareJID, +) -> Result<Chat, DatabaseError> { Ok(logic.db().read_chat(jid).await?) } -pub async fn handle_get_messages( - logic: &ClientLogic, - jid: JID, +pub async fn handle_get_chat_and_user<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + jid: BareJID, +) -> 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: BareJID, ) -> Result<Vec<Message>, DatabaseError> { Ok(logic.db().read_message_history(jid).await?) } -pub async fn handle_delete_chat(logic: &ClientLogic, jid: JID) -> Result<(), DatabaseError> { +pub async fn handle_get_messages_with_users<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + jid: BareJID, +) -> Result<Vec<(Message, User)>, DatabaseError> { + Ok(logic.db().read_message_history_with_users(jid).await?) +} + +pub async fn handle_delete_chat<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + jid: BareJID, +) -> Result<(), DatabaseError> { Ok(logic.db().delete_chat(jid).await?) } -pub async fn handle_delete_messaage(logic: &ClientLogic, uuid: Uuid) -> Result<(), DatabaseError> { +pub async fn handle_delete_messaage<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + uuid: Uuid, +) -> Result<(), DatabaseError> { Ok(logic.db().delete_message(uuid).await?) } -pub async fn handle_get_user(logic: &ClientLogic, jid: JID) -> Result<User, DatabaseError> { +pub async fn handle_get_user<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + jid: BareJID, +) -> Result<User, DatabaseError> { Ok(logic.db().read_user(jid).await?) } diff --git a/filamento/src/logic/mod.rs b/filamento/src/logic/mod.rs index 1ddd7d3..ddf0343 100644 --- a/filamento/src/logic/mod.rs +++ b/filamento/src/logic/mod.rs @@ -1,15 +1,16 @@ use std::{collections::HashMap, sync::Arc}; -use jid::JID; +use jid::{BareJID, JID}; use lampada::{Connected, Logic, error::ReadError}; use stanza::client::Stanza; use tokio::sync::{Mutex, mpsc, oneshot}; -use tracing::{error, info, warn}; +use tracing::{error, info}; use crate::{ Client, Command, UpdateMessage, db::Db, error::{Error, IqRequestError, ResponseError}, + files::FileStore, }; mod abort; @@ -22,12 +23,13 @@ mod online; mod process_stanza; #[derive(Clone)] -pub struct ClientLogic { - client: Client, - bare_jid: JID, +pub struct ClientLogic<Fs: FileStore> { + client: Client<Fs>, + jid: BareJID, db: Db, pending: Pending, update_sender: mpsc::Sender<UpdateMessage>, + file_store: Fs, } #[derive(Clone)] @@ -75,23 +77,25 @@ impl Pending { } } -impl ClientLogic { +impl<Fs: FileStore> ClientLogic<Fs> { pub fn new( - client: Client, - bare_jid: JID, + client: Client<Fs>, + jid: BareJID, db: Db, update_sender: mpsc::Sender<UpdateMessage>, + file_store: Fs, ) -> Self { Self { db, pending: Pending::new(), update_sender, client, - bare_jid, + jid, + file_store, } } - pub fn client(&self) -> &Client { + pub fn client(&self) -> &Client<Fs> { &self.client } @@ -103,6 +107,10 @@ impl ClientLogic { &self.pending } + pub fn file_store(&self) -> &Fs { + &self.file_store + } + pub fn update_sender(&self) -> &mpsc::Sender<UpdateMessage> { &self.update_sender } @@ -113,13 +121,14 @@ impl ClientLogic { self.update_sender().send(update).await; } - pub async fn handle_error(&self, e: Error) { + // TODO: delete this + pub async fn handle_error(&self, e: Error<Fs>) { error!("{}", e); } } -impl Logic for ClientLogic { - type Cmd = Command; +impl<Fs: FileStore + Clone + Send + Sync + 'static> Logic for ClientLogic<Fs> { + type Cmd = Command<Fs>; // pub async fn handle_stream_error(self, error) {} // stanza errors (recoverable) diff --git a/filamento/src/logic/offline.rs b/filamento/src/logic/offline.rs index 6399cf7..aa84f3d 100644 --- a/filamento/src/logic/offline.rs +++ b/filamento/src/logic/offline.rs @@ -1,28 +1,35 @@ +use std::process::id; + use chrono::Utc; +use jid::FullJID; use lampada::error::WriteError; +use tracing::error; use uuid::Uuid; use crate::{ Command, chat::{Delivery, Message}, error::{ - DatabaseError, DiscoError, Error, IqRequestError, MessageSendError, NickError, RosterError, - StatusError, + AvatarPublishError, DatabaseError, DiscoError, Error, IqRequestError, MessageSendError, + NickError, PEPError, RosterError, StatusError, }, + files::FileStore, presence::Online, roster::Contact, + user::User, }; 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_messages, 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, }, }; -pub async fn handle_offline(logic: ClientLogic, command: Command) { +pub async fn handle_offline<Fs: FileStore + Clone>(logic: ClientLogic<Fs>, command: Command<Fs>) { let result = handle_offline_result(&logic, command).await; match result { Ok(_) => {} @@ -30,21 +37,39 @@ pub async fn handle_offline(logic: ClientLogic, command: Command) { } } -pub async fn handle_set_status(logic: &ClientLogic, online: Online) -> Result<(), StatusError> { +pub async fn handle_set_status<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + online: Online, +) -> Result<(), StatusError> { logic.db().upsert_cached_status(online).await?; Ok(()) } -pub async fn handle_get_roster(logic: &ClientLogic) -> Result<Vec<Contact>, RosterError> { +pub async fn handle_get_roster<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, +) -> Result<Vec<Contact>, RosterError> { Ok(logic.db().read_cached_roster().await?) } -pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Result<(), Error> { +pub async fn handle_get_roster_with_users<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, +) -> Result<Vec<(Contact, User)>, RosterError> { + Ok(logic.db().read_cached_roster_with_users().await?) +} + +pub async fn handle_offline_result<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + command: Command<Fs>, +) -> Result<(), Error<Fs>> { match command { Command::GetRoster(sender) => { let roster = handle_get_roster(logic).await; sender.send(roster); } + Command::GetRosterWithUsers(sender) => { + let roster = handle_get_roster_with_users(logic).await; + sender.send(roster); + } Command::GetChats(sender) => { let chats = handle_get_chats(logic).await; sender.send(chats); @@ -57,14 +82,30 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res let chats = handle_get_chats_ordered_with_latest_messages(logic).await; sender.send(chats); } + Command::GetChatsOrderedWithLatestMessagesAndUsers(sender) => { + let chats = handle_get_chats_ordered_with_latest_messages_and_users(logic).await; + sender.send(chats); + } Command::GetChat(jid, sender) => { 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); } + Command::GetMessagesWithUsers(jid, sender) => { + let messages = handle_get_messages_with_users(logic, jid).await; + sender.send(messages); + } Command::DeleteChat(jid, sender) => { let result = handle_delete_chat(logic, jid).await; sender.send(result); @@ -77,7 +118,6 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res let user = handle_get_user(logic, jid).await; sender.send(user); } - // TODO: offline queue to modify roster Command::AddContact(_jid, sender) => { sender.send(Err(RosterError::Write(WriteError::Disconnected))); } @@ -112,14 +152,13 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res let result = handle_set_status(logic, online).await; sender.send(result); } - // TODO: offline message queue Command::SendMessage(jid, body) => { let id = Uuid::new_v4(); let timestamp = Utc::now(); let message = Message { id, - from: logic.bare_jid.clone(), + from: logic.jid.clone(), // TODO: failure reason delivery: Some(Delivery::Failed), timestamp, @@ -129,11 +168,15 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res // TODO: mark these as potentially failed upon client launch if let Err(e) = logic .db() - .create_message_with_self_resource( + // TODO: can create message without a 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 - logic.bare_jid.clone(), + FullJID { + bare_jid: logic.jid.clone(), + resourcepart: "unsent".to_string(), + }, ) .await { @@ -142,11 +185,25 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res .handle_error(MessageSendError::MessageHistory(e.into()).into()) .await; } + + let from = match logic.db().read_user(logic.jid.clone()).await { + Ok(u) => u, + Err(e) => { + error!("{}", e); + User { + jid: logic.jid.clone(), + nick: None, + avatar: None, + } + } + }; + logic .update_sender() .send(crate::UpdateMessage::Message { - to: jid.as_bare(), + to: jid, message, + from, }) .await; } @@ -159,7 +216,7 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res Command::DiscoItems(_jid, _node, sender) => { sender.send(Err(DiscoError::Write(WriteError::Disconnected))); } - Command::Publish { + Command::PublishPEPItem { item: _, node: _, sender, @@ -169,6 +226,24 @@ pub async fn handle_offline_result(logic: &ClientLogic, command: Command) -> Res Command::ChangeNick(_, sender) => { sender.send(Err(NickError::Disconnected)); } + Command::ChangeAvatar(_items, sender) => { + sender.send(Err(AvatarPublishError::Disconnected)); + } + Command::DeletePEPNode { node: _, sender } => { + sender.send(Err(PEPError::IqResponse(IqRequestError::Write( + WriteError::Disconnected, + )))); + } + Command::GetPEPItem { + node: _, + sender, + jid: _, + id: _, + } => { + sender.send(Err(PEPError::IqResponse(IqRequestError::Write( + WriteError::Disconnected, + )))); + } } Ok(()) } diff --git a/filamento/src/logic/online.rs b/filamento/src/logic/online.rs index b069f59..b36f9a9 100644 --- a/filamento/src/logic/online.rs +++ b/filamento/src/logic/online.rs @@ -1,35 +1,35 @@ +use std::{io::Cursor, time::Duration}; + +use base64::{prelude::BASE64_STANDARD, Engine}; use chrono::Utc; -use jid::JID; +use image::ImageReader; +use jid::{BareJID, JID}; use lampada::{Connected, WriteMessage, error::WriteError}; +use sha1::{Digest, Sha1}; use stanza::{ client::{ iq::{self, Iq, IqType, Query}, Stanza - }, - xep_0030::{info, items}, - xep_0060::pubsub::{self, Pubsub}, - xep_0172::{self, Nick}, - xep_0203::Delay, + }, xep_0030::{info, items}, xep_0060::{self, owner, pubsub::{self, Pubsub}}, xep_0084, xep_0172::{self, Nick}, xep_0203::Delay }; -use tokio::sync::oneshot; +use tokio::{sync::oneshot, task::spawn_blocking}; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; use tracing::{debug, error, info}; use uuid::Uuid; use crate::{ - chat::{Body, Chat, Delivery, Message}, disco::{Info, Items}, error::{ - DatabaseError, DiscoError, Error, IqRequestError, MessageSendError, NickError, PublishError, RosterError, StatusError, SubscribeError - }, pep, presence::{Online, Presence, PresenceType}, roster::{Contact, ContactUpdate}, Command, UpdateMessage + avatar, chat::{Body, Chat, Delivery, Message}, disco::{Info, Items}, error::{ + AvatarPublishError, DatabaseError, DiscoError, Error, IqRequestError, MessageSendError, NickError, PEPError, RosterError, StatusError, SubscribeError + }, files::FileStore, pep, presence::{Online, Presence, PresenceType}, roster::{Contact, ContactUpdate}, user::User, Command, UpdateMessage }; 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_messages, 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_online(logic: ClientLogic, command: Command, connection: Connected) { +pub async fn handle_online<Fs: FileStore + Clone + 'static>(logic: ClientLogic<Fs>, command: Command<Fs>, connection: Connected) { let result = handle_online_result(&logic, command, connection).await; match result { Ok(_) => {} @@ -37,13 +37,13 @@ pub async fn handle_online(logic: ClientLogic, command: Command, connection: Con } } -pub async fn handle_get_roster( - logic: &ClientLogic, +pub async fn handle_get_roster<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, ) -> Result<Vec<Contact>, RosterError> { let iq_id = Uuid::new_v4().to_string(); let stanza = Stanza::Iq(Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq_id.to_string(), to: None, r#type: IqType::Get, @@ -96,14 +96,79 @@ pub async fn handle_get_roster( } } -pub async fn handle_add_contact( - logic: &ClientLogic, +// this can't query the client... otherwise there is a hold-up and the connection can't complete +pub async fn handle_get_roster_with_users<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + connection: Connected, +) -> Result<Vec<(Contact, User)>, RosterError> { + let iq_id = Uuid::new_v4().to_string(); + let stanza = Stanza::Iq(Iq { + from: Some(connection.jid().clone().into()), + id: iq_id.to_string(), + to: None, + r#type: IqType::Get, + lang: None, + query: Some(iq::Query::Roster(stanza::roster::Query { + ver: None, + items: Vec::new(), + })), + errors: Vec::new(), + }); + let response = logic + .pending() + .request(&connection, stanza, iq_id.clone()) + .await?; + // TODO: timeout + match response { + Stanza::Iq(Iq { + from: _, + id, + to: _, + r#type, + lang: _, + query: Some(iq::Query::Roster(stanza::roster::Query { ver: _, items })), + errors: _, + }) if id == iq_id && r#type == IqType::Result => { + let contacts: Vec<Contact> = items.into_iter().map(|item| item.into()).collect(); + if let Err(e) = logic.db().replace_cached_roster(contacts.clone()).await { + logic + .handle_error(Error::Roster(RosterError::Cache(e.into()))) + .await; + }; + let mut users = Vec::new(); + for contact in &contacts { + let user = logic.db().read_user(contact.user_jid.clone()).await?; + users.push(user); + } + Ok(contacts.into_iter().zip(users).collect()) + } + ref s @ Stanza::Iq(Iq { + from: _, + ref id, + to: _, + r#type, + lang: _, + query: _, + ref errors, + }) if *id == iq_id && r#type == IqType::Error => { + if let Some(error) = errors.first() { + Err(RosterError::StanzaError(error.clone())) + } else { + Err(RosterError::UnexpectedStanza(s.clone())) + } + } + s => Err(RosterError::UnexpectedStanza(s)), + } +} + +pub async fn handle_add_contact<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), RosterError> { let iq_id = Uuid::new_v4().to_string(); let set_stanza = Stanza::Iq(Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq_id.clone(), to: None, r#type: IqType::Set, @@ -154,12 +219,13 @@ pub async fn handle_add_contact( } } -pub async fn handle_buddy_request( - logic: &ClientLogic, +pub async fn handle_buddy_request<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), SubscribeError> { - let client_user = logic.db.read_user(logic.bare_jid.clone()).await?; + let jid: JID = jid.into(); + let client_user = logic.db.read_user(logic.jid.clone()).await?; let nick = client_user.nick.map(|nick| Nick(nick)); let presence = Stanza::Presence(stanza::client::presence::Presence { to: Some(jid.clone()), @@ -177,16 +243,16 @@ pub async fn handle_buddy_request( Ok(()) } -pub async fn handle_subscription_request( - logic: &ClientLogic, +pub async fn handle_subscription_request<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), SubscribeError> { // TODO: i should probably have builders - let client_user = logic.db.read_user(logic.bare_jid.clone()).await?; + let client_user = logic.db.read_user(logic.jid.clone()).await?; let nick = client_user.nick.map(|nick| Nick(nick)); let presence = Stanza::Presence(stanza::client::presence::Presence { - to: Some(jid), + to: Some(jid.into()), r#type: Some(stanza::client::presence::PresenceType::Subscribe), nick, ..Default::default() @@ -195,18 +261,19 @@ pub async fn handle_subscription_request( Ok(()) } -pub async fn handle_accept_buddy_request( - logic: &ClientLogic, +pub async fn handle_accept_buddy_request<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), SubscribeError> { + let jid: JID = jid.into(); let presence = Stanza::Presence(stanza::client::presence::Presence { to: Some(jid.clone()), r#type: Some(stanza::client::presence::PresenceType::Subscribed), ..Default::default() }); connection.write_handle().write(presence).await?; - let client_user = logic.db.read_user(logic.bare_jid.clone()).await?; + let client_user = logic.db.read_user(logic.jid.clone()).await?; let nick = client_user.nick.map(|nick| Nick(nick)); let presence = Stanza::Presence(stanza::client::presence::Presence { to: Some(jid), @@ -218,17 +285,14 @@ pub async fn handle_accept_buddy_request( Ok(()) } -pub async fn handle_accept_subscription_request( - logic: &ClientLogic, +pub async fn handle_accept_subscription_request<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), SubscribeError> { - let client_user = logic.db.read_user(logic.bare_jid.clone()).await?; - let nick = client_user.nick.map(|nick| Nick(nick)); let presence = Stanza::Presence(stanza::client::presence::Presence { - to: Some(jid), - r#type: Some(stanza::client::presence::PresenceType::Subscribe), - nick, + to: Some(jid.into()), + r#type: Some(stanza::client::presence::PresenceType::Subscribed), ..Default::default() }); connection.write_handle().write(presence).await?; @@ -237,10 +301,10 @@ pub async fn handle_accept_subscription_request( pub async fn handle_unsubscribe_from_contact( connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), WriteError> { let presence = Stanza::Presence(stanza::client::presence::Presence { - to: Some(jid), + to: Some(jid.into()), r#type: Some(stanza::client::presence::PresenceType::Unsubscribe), ..Default::default() }); @@ -248,9 +312,9 @@ pub async fn handle_unsubscribe_from_contact( Ok(()) } -pub async fn handle_unsubscribe_contact(connection: Connected, jid: JID) -> Result<(), WriteError> { +pub async fn handle_unsubscribe_contact(connection: Connected, jid: BareJID) -> Result<(), WriteError> { let presence = Stanza::Presence(stanza::client::presence::Presence { - to: Some(jid), + to: Some(jid.into()), r#type: Some(stanza::client::presence::PresenceType::Unsubscribed), ..Default::default() }); @@ -258,7 +322,8 @@ pub async fn handle_unsubscribe_contact(connection: Connected, jid: JID) -> Resu Ok(()) } -pub async fn handle_unfriend_contact(connection: Connected, jid: JID) -> Result<(), WriteError> { +pub async fn handle_unfriend_contact(connection: Connected, jid: BareJID) -> Result<(), WriteError> { + let jid: JID = jid.into(); let presence = Stanza::Presence(stanza::client::presence::Presence { to: Some(jid.clone()), r#type: Some(stanza::client::presence::PresenceType::Unsubscribe), @@ -274,14 +339,14 @@ pub async fn handle_unfriend_contact(connection: Connected, jid: JID) -> Result< Ok(()) } -pub async fn handle_delete_contact( - logic: &ClientLogic, +pub async fn handle_delete_contact<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, ) -> Result<(), RosterError> { let iq_id = Uuid::new_v4().to_string(); let set_stanza = Stanza::Iq(Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq_id.clone(), to: None, r#type: IqType::Set, @@ -333,10 +398,10 @@ pub async fn handle_delete_contact( } } -pub async fn handle_update_contact( - logic: &ClientLogic, +pub async fn handle_update_contact<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, - jid: JID, + jid: BareJID, contact_update: ContactUpdate, ) -> Result<(), RosterError> { let iq_id = Uuid::new_v4().to_string(); @@ -347,7 +412,8 @@ pub async fn handle_update_contact( .map(|group| stanza::roster::Group(Some(group))), ); let set_stanza = Stanza::Iq(Iq { - from: Some(connection.jid().clone()), + // TODO: these clones could technically be avoided? + from: Some(connection.jid().clone().into()), id: iq_id.clone(), to: None, r#type: IqType::Set, @@ -398,8 +464,8 @@ pub async fn handle_update_contact( } } -pub async fn handle_set_status( - logic: &ClientLogic, +pub async fn handle_set_status<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, online: Online, ) -> Result<(), StatusError> { @@ -411,14 +477,23 @@ pub async fn handle_set_status( Ok(()) } -pub async fn handle_send_message(logic: &ClientLogic, connection: Connected, jid: JID, body: Body) { +pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, connection: Connected, jid: BareJID, 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 = logic.db().upsert_chat_and_user(&jid).await.unwrap_or(false); + let have_chatted = match logic.db().upsert_chat_and_user(jid.clone()).await { + Ok(have_chatted) => { + have_chatted + }, + Err(e) => { + error!("{}", e); + false + }, + }; let nick; let mark_chat_as_chatted; if have_chatted == false { - match logic.db.read_user(logic.bare_jid.clone()).await { + match logic.db.read_user(logic.jid.clone()).await { Ok(u) => { nick = u.nick.map(|nick| Nick(nick)); mark_chat_as_chatted = true; @@ -441,7 +516,7 @@ pub async fn handle_send_message(logic: &ClientLogic, connection: Connected, jid let timestamp = Utc::now(); let message = Message { id, - from: connection.jid().as_bare(), + from: connection.jid().to_bare(), body: body.clone(), timestamp, delivery: Some(Delivery::Sending), @@ -451,7 +526,7 @@ pub async fn handle_send_message(logic: &ClientLogic, connection: Connected, jid // 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? @@ -460,20 +535,33 @@ pub async fn handle_send_message(logic: &ClientLogic, connection: Connected, jid .await; } + let from = match logic.db().read_user(logic.jid.clone()).await { + Ok(u) => u, + Err(e) => { + error!("{}", e); + User { + jid: logic.jid.clone(), + nick: None, + avatar: None, + } + }, + }; + // tell the client a message is being sent logic .update_sender() .send(UpdateMessage::Message { - to: jid.as_bare(), + to: jid.clone(), message, + from, }) .await; // prepare the message stanza let message_stanza = Stanza::Message(stanza::client::message::Message { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: Some(id.to_string()), - to: Some(jid.clone()), + to: Some(jid.clone().into()), // TODO: specify message type r#type: stanza::client::message::MessageType::Chat, // TODO: lang ? @@ -498,14 +586,19 @@ pub async fn handle_send_message(logic: &ClientLogic, connection: Connected, jid 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 { id, delivery: Delivery::Written, + chat: jid.clone(), }) .await; if mark_chat_as_chatted { + debug!("marking chat as chatted"); if let Err(e) = logic.db.mark_chat_as_chatted(jid).await { logic .handle_error(MessageSendError::MarkChatAsChatted(e.into()).into()) @@ -519,6 +612,7 @@ pub async fn handle_send_message(logic: &ClientLogic, connection: Connected, jid .send(UpdateMessage::MessageDelivery { id, delivery: Delivery::Failed, + chat: jid, }) .await; logic.handle_error(MessageSendError::Write(e).into()).await; @@ -540,15 +634,15 @@ pub async fn handle_send_presence( Ok(()) } -pub async fn handle_disco_info( - logic: &ClientLogic, +pub async fn handle_disco_info<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, jid: Option<JID>, node: Option<String>, ) -> Result<Info, DiscoError> { let id = Uuid::new_v4().to_string(); let request = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: id.clone(), to: jid.clone(), r#type: IqType::Get, @@ -576,7 +670,7 @@ pub async fn handle_disco_info( }) if r#type == IqType::Result || r#type == IqType::Error => { if from == jid || { if jid == None { - from == Some(connection.jid().as_bare()) + from == Some(connection.jid().to_bare().into()) } else { false } @@ -603,7 +697,7 @@ pub async fn handle_disco_info( } } else { Err(DiscoError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -611,15 +705,15 @@ pub async fn handle_disco_info( } } -pub async fn handle_disco_items( - logic: &ClientLogic, +pub async fn handle_disco_items<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, jid: Option<JID>, node: Option<String>, ) -> Result<Items, DiscoError> { let id = Uuid::new_v4().to_string(); let request = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: id.clone(), to: jid.clone(), r#type: IqType::Get, @@ -645,7 +739,7 @@ pub async fn handle_disco_items( }) if r#type == IqType::Result || r#type == IqType::Error => { if from == jid || { if jid == None { - from == Some(connection.jid().as_bare()) + from == Some(connection.jid().to_bare().into()) } else { false } @@ -672,7 +766,7 @@ pub async fn handle_disco_items( } } else { Err(DiscoError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -680,24 +774,64 @@ pub async fn handle_disco_items( } } -pub async fn handle_publish( - logic: &ClientLogic, +pub async fn handle_publish_pep_item<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, connection: Connected, item: pep::Item, node: String, -) -> Result<(), PublishError> { +) -> Result<(), PEPError> { let id = Uuid::new_v4().to_string(); let publish = match item { - pep::Item::Nick(n) => pubsub::Publish { - node, - items: vec![pubsub::Item { - item: Some(pubsub::Content::Nick(Nick(n))), - ..Default::default() - }], + pep::Item::Nick(n) => { + if let Some(n) = n { + pubsub::Publish { + node, + items: vec![pubsub::Item { + item: Some(pubsub::Content::Nick(Nick(n))), + ..Default::default() + }], + } + } else { + pubsub::Publish { + node, + items: vec![pubsub::Item { + item: Some(pubsub::Content::Nick(Nick("".to_string()))), + ..Default::default() + }] + } + } + }, + pep::Item::AvatarMetadata(metadata) => { + if let Some(metadata) = metadata { + pubsub::Publish { node, items: vec![pubsub::Item { + item: Some(pubsub::Content::AvatarMetadata(xep_0084::Metadata { info: vec![xep_0084::Info { bytes: metadata.bytes, height: None, id: metadata.hash.clone(), r#type: metadata.r#type, url: None, width: None }], pointers: Vec::new() })), + id: Some(metadata.hash), + ..Default::default() + }]} + } else { + pubsub::Publish { node, items: vec![pubsub::Item { + item: Some(pubsub::Content::AvatarMetadata(xep_0084::Metadata { info: Vec::new(), pointers: Vec::new() })), + ..Default::default() + }]} + } + }, + pep::Item::AvatarData(data) => { + if let Some(data) = data { + pubsub::Publish { node, items: vec![pubsub::Item { + item: Some(pubsub::Content::AvatarData(xep_0084::Data(data.data_b64))), + id: Some(data.hash), + ..Default::default() + }] } + } else { + pubsub::Publish { node, items: vec![pubsub::Item { + item: Some(pubsub::Content::AvatarData(xep_0084::Data("".to_string()))), + ..Default::default() + }]} + } }, }; let request = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: id.clone(), to: None, r#type: IqType::Set, @@ -719,50 +853,251 @@ pub async fn handle_publish( // TODO: maybe abstract a bunch of these different errors related to iqs into an iq error thing? as in like call iq.result(), get the query from inside, error otherwise. }) if r#type == IqType::Result || r#type == IqType::Error => { if from == None || - from == Some(connection.jid().as_bare()) + from == Some(connection.jid().to_bare().into()) { match r#type { IqType::Result => { if let Some(query) = query { match query { Query::Pubsub(_) => Ok(()), - q => Err(PublishError::MismatchedQuery(q)), + q => Err(PEPError::MismatchedQuery(q)), + } + } else { + Err(PEPError::MissingQuery) + } + } + IqType::Error => { + Err(PEPError::StanzaErrors(errors)) + } + _ => unreachable!(), + } + } else { + Err(PEPError::IncorrectEntity( + from.unwrap_or_else(|| connection.jid().to_bare().into()), + )) + } + } + s => Err(PEPError::UnexpectedStanza(s)), + } +} + +pub async fn handle_get_pep_item<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, connection: Connected, jid: Option<BareJID>, node: String, id: String) -> Result<pep::Item, PEPError> { + let jid = jid.map(|jid| Into::<JID>::into(jid)); + let stanza_id = Uuid::new_v4().to_string(); + let request = Iq { + from: Some(connection.jid().clone().into()), + id: stanza_id.clone(), + to: jid.clone(), + r#type: IqType::Get, + lang: None, + query: Some(Query::Pubsub(Pubsub::Items(pubsub::Items { + max_items: None, + node, + subid: None, + items: vec![pubsub::Item { id: Some(id.clone()), publisher: None, item: None }], + }))), + errors: Vec::new(), + }; + match logic + .pending() + .request(&connection, Stanza::Iq(request), stanza_id) + .await? { + + Stanza::Iq(Iq { + from, + r#type, + query, + errors, + .. + // TODO: maybe abstract a bunch of these different errors related to iqs into an iq error thing? as in like call iq.result(), get the query from inside, error otherwise. + }) if r#type == IqType::Result || r#type == IqType::Error => { + if from == jid || { + if jid == None { + from == Some(connection.jid().to_bare().into()) + } else { + false + } + } { + match r#type { + IqType::Result => { + if let Some(query) = query { + match query { + Query::Pubsub(Pubsub::Items(mut items)) => { + if let Some(item) = items.items.pop() { + if item.id == Some(id.clone()) { + match item.item.ok_or(PEPError::MissingItem)? { + pubsub::Content::Nick(nick) => { + if nick.0.is_empty() { + Ok(pep::Item::Nick(None)) + } else { + Ok(pep::Item::Nick(Some(nick.0))) + + } + }, + pubsub::Content::AvatarData(data) => Ok(pep::Item::AvatarData(Some(avatar::Data { hash: id, data_b64: data.0 }))), + pubsub::Content::AvatarMetadata(metadata) => Ok(pep::Item::AvatarMetadata(metadata.info.into_iter().find(|info| info.url.is_none()).map(|info| info.into()))), + pubsub::Content::Unknown(_element) => Err(PEPError::UnsupportedItem), + } + } else { + Err(PEPError::IncorrectItemID(id, item.id.unwrap_or_else(|| "missing id".to_string()))) + } + } else { + Err(PEPError::MissingItem) + } + }, + q => Err(PEPError::MismatchedQuery(q)), } } else { - Err(PublishError::MissingQuery) + Err(PEPError::MissingQuery) } } IqType::Error => { - Err(PublishError::StanzaErrors(errors)) + Err(PEPError::StanzaErrors(errors)) } _ => unreachable!(), } } else { - Err(PublishError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + // TODO: include expected entity + Err(PEPError::IncorrectEntity( + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } - s => Err(PublishError::UnexpectedStanza(s)), + s => Err(PEPError::UnexpectedStanza(s)), } } -pub async fn handle_change_nick(logic: &ClientLogic, nick: String) -> Result<(), NickError> { +pub async fn handle_change_nick<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, nick: Option<String>) -> Result<(), NickError> { logic.client().publish(pep::Item::Nick(nick), xep_0172::XMLNS.to_string()).await?; Ok(()) } +pub async fn handle_change_avatar<Fs: FileStore + Clone + 'static>(logic: &ClientLogic<Fs>, img_data: Option<Vec<u8>>) -> Result<(), AvatarPublishError<Fs>> { + match img_data { + // set avatar + Some(data) => { + let (bytes, hash, data_png, data_b64) = spawn_blocking(move || -> Result<_, _> { + // load the image data and guess the format + let image = ImageReader::new(Cursor::new(data)).with_guessed_format()?.decode()?; + + // convert the image to png; + let mut data_png = Vec::new(); + let image = image.resize(192, 192, image::imageops::FilterType::Nearest); + image.write_to(&mut Cursor::new(&mut data_png), image::ImageFormat::Jpeg)?; + + // calculate the length of the data in bytes. + let bytes = data_png.len().try_into()?; + + // calculate sha1 hash of the data + let mut sha1 = Sha1::new(); + sha1.update(&data_png); + let sha1_result = sha1.finalize(); + let hash = hex::encode(sha1_result); + + // encode the image data as base64 + let data_b64 = BASE64_STANDARD.encode(data_png.clone()); + + Ok::<(u32, String, Vec<u8>, String), AvatarPublishError<Fs>>((bytes, hash, data_png, data_b64)) + }).await.unwrap()?; + + // publish the data to the data node + logic.client().publish(pep::Item::AvatarData(Some(avatar::Data { hash: hash.clone(), data_b64 })), "urn:xmpp:avatar:data".to_string()).await?; + + // publish the metadata to the metadata node + logic.client().publish(pep::Item::AvatarMetadata(Some(avatar::Metadata { bytes, hash: hash.clone(), r#type: "image/jpeg".to_string() })), "urn:xmpp:avatar:metadata".to_string()).await?; + + // if everything went well, save the data to the disk. + + if !logic.file_store().is_stored(&hash).await.map_err(|err| AvatarPublishError::FileStore(err))? { + logic.file_store().store(&hash, &data_png).await.map_err(|err| AvatarPublishError::FileStore(err))? + } + // when the client receives the updated metadata notification from the pep node, it will already have it saved on the disk so will not require a retrieval. + // TODO: should the node be purged? + + Ok(()) + }, + // remove avatar + None => { + logic.client().delete_pep_node("urn:xmpp:avatar:data".to_string()).await?; + logic.client().publish(pep::Item::AvatarMetadata(None), "urn:xmpp:avatar:metadata".to_string(), ).await?; + Ok(()) + }, + } +} + +pub async fn handle_delete_pep_node<Fs: FileStore + Clone>( + logic: &ClientLogic<Fs>, + connection: Connected, + node: String, +) -> Result<(), PEPError> { + let id = Uuid::new_v4().to_string(); + let request = Iq { + from: Some(connection.jid().clone().into()), + id: id.clone(), + to: None, + r#type: IqType::Set, + lang: None, + query: Some(Query::PubsubOwner(xep_0060::owner::Pubsub::Delete(owner::Delete{ node, redirect: None }))), + errors: Vec::new(), + }; + match logic + .pending() + .request(&connection, Stanza::Iq(request), id) + .await? { + + Stanza::Iq(Iq { + from, + r#type, + query, + errors, + .. + // TODO: maybe abstract a bunch of these different errors related to iqs into an iq error thing? as in like call iq.result(), get the query from inside, error otherwise. + }) if r#type == IqType::Result || r#type == IqType::Error => { + if from == None || + from == Some(connection.jid().to_bare().into()) + { + match r#type { + IqType::Result => { + if let Some(query) = query { + match query { + Query::PubsubOwner(_) => Ok(()), + q => Err(PEPError::MismatchedQuery(q)), + } + } else { + // Err(PEPError::MissingQuery) + Ok(()) + } + } + IqType::Error => { + Err(PEPError::StanzaErrors(errors)) + } + _ => unreachable!(), + } + } else { + Err(PEPError::IncorrectEntity( + from.unwrap_or_else(|| connection.jid().to_bare().into()), + )) + } + } + s => Err(PEPError::UnexpectedStanza(s)), + } +} + // TODO: could probably macro-ise? -pub async fn handle_online_result( - logic: &ClientLogic, - command: Command, +pub async fn handle_online_result<Fs: FileStore + Clone + 'static>( + logic: &ClientLogic<Fs>, + command: Command<Fs>, connection: Connected, -) -> Result<(), Error> { +) -> Result<(), Error<Fs>> { match command { Command::GetRoster(result_sender) => { let roster = handle_get_roster(logic, connection).await; let _ = result_sender.send(roster); } + Command::GetRosterWithUsers(result_sender) => { + let roster = handle_get_roster_with_users(logic, connection).await; + let _ = result_sender.send(roster); + } Command::GetChats(sender) => { let chats = handle_get_chats(logic).await; let _ = sender.send(chats); @@ -775,14 +1110,30 @@ pub async fn handle_online_result( let chats = handle_get_chats_ordered_with_latest_messages(logic).await; let _ = sender.send(chats); } + Command::GetChatsOrderedWithLatestMessagesAndUsers(sender) => { + let chats = handle_get_chats_ordered_with_latest_messages_and_users(logic).await; + sender.send(chats); + } Command::GetChat(jid, sender) => { 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); } + Command::GetMessagesWithUsers(jid, sender) => { + let messages = handle_get_messages_with_users(logic, jid).await; + sender.send(messages); + } Command::DeleteChat(jid, sender) => { let result = handle_delete_chat(logic, jid).await; let _ = sender.send(result); @@ -854,14 +1205,26 @@ pub async fn handle_online_result( let result = handle_disco_items(logic, connection, jid, node).await; let _ = sender.send(result); } - Command::Publish { item, node, sender } => { - let result = handle_publish(logic, connection, item, node).await; + Command::PublishPEPItem { item, node, sender } => { + let result = handle_publish_pep_item(logic, connection, item, node).await; let _ = sender.send(result); } Command::ChangeNick(nick, sender) => { let result = handle_change_nick(logic, nick).await; let _ = sender.send(result); } + Command::ChangeAvatar(img_data, sender) => { + let result = handle_change_avatar(logic, img_data).await; + let _ = sender.send(result); + }, + Command::DeletePEPNode { node, sender } => { + let result = handle_delete_pep_node(logic, connection, node).await; + let _ = sender.send(result); + }, + Command::GetPEPItem { node, sender, jid, id } => { + let result = handle_get_pep_item(logic, connection, jid, node, id).await; + let _ = sender.send(result); + }, } Ok(()) } diff --git a/filamento/src/logic/process_stanza.rs b/filamento/src/logic/process_stanza.rs index 11d7588..67b0d3f 100644 --- a/filamento/src/logic/process_stanza.rs +++ b/filamento/src/logic/process_stanza.rs @@ -1,7 +1,9 @@ use std::str::FromStr; +use base64::{Engine, prelude::BASE64_STANDARD}; use chrono::Utc; use lampada::{Connected, SupervisorSender}; +use sha1::{Digest, Sha1}; use stanza::{ client::{ Stanza, @@ -17,14 +19,23 @@ use uuid::Uuid; use crate::{ UpdateMessage, caps, chat::{Body, Message}, - error::{DatabaseError, Error, IqError, MessageRecvError, PresenceError, RosterError}, + error::{ + AvatarUpdateError, DatabaseError, Error, IqError, IqProcessError, MessageRecvError, + PresenceError, RosterError, + }, + files::FileStore, presence::{Offline, Online, Presence, PresenceType, Show}, roster::Contact, + user::User, }; use super::ClientLogic; -pub async fn handle_stanza(logic: ClientLogic, stanza: Stanza, connection: Connected) { +pub async fn handle_stanza<Fs: FileStore + Clone>( + logic: ClientLogic<Fs>, + stanza: Stanza, + connection: Connected, +) { let result = process_stanza(logic.clone(), stanza, connection).await; match result { Ok(u) => match u { @@ -38,10 +49,10 @@ pub async fn handle_stanza(logic: ClientLogic, stanza: Stanza, connection: Conne } } -pub async fn recv_message( - logic: ClientLogic, +pub async fn recv_message<Fs: FileStore + Clone>( + logic: ClientLogic<Fs>, stanza_message: stanza::client::message::Message, -) -> Result<Option<UpdateMessage>, MessageRecvError> { +) -> Result<Option<UpdateMessage>, MessageRecvError<Fs>> { if let Some(from) = stanza_message.from { // TODO: don't ignore delay from. xep says SHOULD send error if incorrect. let timestamp = stanza_message @@ -50,6 +61,7 @@ pub async fn recv_message( .unwrap_or_else(|| Utc::now()); // TODO: group chat messages + // body MUST be before user changes in order to avoid race condition where you e.g. get a nick update before the user is in the client state. // if there is a body, should create chat message if let Some(body) = stanza_message.body { let message = Message { @@ -58,101 +70,398 @@ pub async fn recv_message( // TODO: proper id xep .map(|id| Uuid::from_str(&id).unwrap_or_else(|_| Uuid::new_v4())) .unwrap_or_else(|| Uuid::new_v4()), - from: from.as_bare(), + from: from.to_bare(), timestamp, body: Body { body: body.body.unwrap_or_default(), }, delivery: None, }; + // TODO: process message type="error" // save the message to the database - logic.db().upsert_chat_and_user(&from).await?; - if let Err(e) = logic - .db() - .create_message_with_user_resource(message.clone(), from.clone(), from.clone()) - .await - { - logic - .handle_error(Error::MessageRecv(MessageRecvError::MessageHistory(e))) - .await; - } + match logic.db().upsert_chat_and_user(from.to_bare()).await { + Ok(_) => match from.as_full() { + Ok(from) => { + if let Err(e) = logic + .db() + .create_message_with_user_resource( + message.clone(), + from.to_bare(), + from.clone(), + ) + .await + { + error!("failed to create message: {}", e); + } + } + Err(e) => error!("failed to create message: {}", e), + }, + Err(e) => { + error!("failed to upsert chat and user: {}", e); + } + }; + + let from_user = match logic.db().read_user(from.to_bare()).await { + Ok(u) => u, + Err(e) => { + error!("{}", e); + User { + jid: from.to_bare(), + nick: None, + avatar: None, + } + } + }; // update the client with the new message logic .update_sender() .send(UpdateMessage::Message { - to: from.as_bare(), + to: from.to_bare(), + from: from_user, message, }) .await; } if let Some(nick) = stanza_message.nick { - if let Err(e) = logic - .db() - .upsert_user_nick(from.as_bare(), nick.0.clone()) - .await - { - logic - .handle_error(Error::MessageRecv(MessageRecvError::NickUpdate(e))) - .await; + let nick = nick.0; + if nick.is_empty() { + match logic.db().delete_user_nick(from.to_bare()).await { + Ok(changed) => { + if changed { + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: None, + }) + .await; + } + } + Err(e) => { + logic + .handle_error(Error::MessageRecv(MessageRecvError::NickUpdate(e))) + .await; + // if failed, send user update anyway + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: None, + }) + .await; + } + } + } else { + match logic + .db() + .upsert_user_nick(from.to_bare(), nick.clone()) + .await + { + Ok(changed) => { + if changed { + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: Some(nick), + }) + .await; + } + } + Err(e) => { + logic + .handle_error(Error::MessageRecv(MessageRecvError::NickUpdate(e))) + .await; + // if failed, send user update anyway + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: Some(nick), + }) + .await; + } + } } - - logic - .update_sender() - .send(UpdateMessage::NickChanged { - jid: from.as_bare(), - nick: nick.0, - }) - .await; } if let Some(event) = stanza_message.event { match event { - Event::Items(items) => match items.node.as_str() { - "http://jabber.org/protocol/nick" => match items.items { - ItemsType::Item(items) => { - if let Some(item) = items.first() { - match &item.item { - Some(c) => match c { - Content::Nick(nick) => { - if let Err(e) = logic - .db() - .upsert_user_nick(from.as_bare(), nick.0.clone()) - .await - { - logic - .handle_error(Error::MessageRecv( - MessageRecvError::NickUpdate(e), - )) - .await; + Event::Items(items) => { + match items.node.as_str() { + "http://jabber.org/protocol/nick" => match items.items { + ItemsType::Item(items) => { + if let Some(item) = items.first() { + match &item.item { + Some(c) => match c { + Content::Nick(nick) => { + let nick = nick.0.clone(); + if nick.is_empty() { + match logic + .db() + .delete_user_nick(from.to_bare()) + .await + { + Ok(changed) => { + if changed { + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: None, + }) + .await; + } + } + Err(e) => { + logic + .handle_error(Error::MessageRecv( + MessageRecvError::NickUpdate(e), + )) + .await; + // if failed, send user update anyway + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: None, + }) + .await; + } + } + } else { + match logic + .db() + .upsert_user_nick( + from.to_bare(), + nick.clone(), + ) + .await + { + Ok(changed) => { + if changed { + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: Some(nick), + }) + .await; + } + } + Err(e) => { + logic + .handle_error(Error::MessageRecv( + MessageRecvError::NickUpdate(e), + )) + .await; + // if failed, send user update anyway + logic + .update_sender() + .send(UpdateMessage::NickChanged { + jid: from.to_bare(), + nick: Some(nick), + }) + .await; + } + } + } } + _ => {} + }, + None => {} + } + } + } + _ => {} + }, + "urn:xmpp:avatar:metadata" => { + match items.items { + ItemsType::Item(items) => { + if let Some(item) = items.first() { + debug!("found item"); + match &item.item { + Some(Content::AvatarMetadata(metadata)) => { + debug!("found metadata"); + // check if user avatar has been deleted + if let Some(metadata) = metadata + .info + .iter() + .find(|info| info.url.is_none()) + { + debug!("checking if user avatar has changed"); + // check if user avatar has changed + match logic + .db() + .upsert_user_avatar( + from.to_bare(), + metadata.id.clone(), + ) + .await + { + Ok((changed, old_avatar)) => { + if changed { + if let Some(old_avatar) = old_avatar + { + if let Err(e) = logic + .file_store() + .delete(&old_avatar) + .await.map_err(|err| AvatarUpdateError::FileStore(err)) { + logic.handle_error(MessageRecvError::AvatarUpdate(e).into()).await; + } + } + } - logic - .update_sender() - .send(UpdateMessage::NickChanged { - jid: from.as_bare(), - nick: nick.0.clone(), - }) - .await; + match logic + .file_store() + .is_stored(&metadata.id) + .await + .map_err(|err| { + AvatarUpdateError::<Fs>::FileStore( + err, + ) + }) { + Ok(false) => { + // get data + let pep_item = logic.client().get_pep_item(Some(from.to_bare()), "urn:xmpp:avatar:data".to_string(), metadata.id.clone()).await.map_err(|err| Into::<AvatarUpdateError<Fs>>::into(err))?; + match pep_item { + crate::pep::Item::AvatarData(data) => { + let data = data.map(|data| data.data_b64).unwrap_or_default().replace("\n", ""); + // TODO: these should all be in a separate avatarupdate function + debug!("got avatar data"); + match BASE64_STANDARD.decode(data) { + Ok(data) => { + let mut hasher = Sha1::new(); + hasher.update(&data); + let received_data_hash = hex::encode(hasher.finalize()); + debug!("received_data_hash: {}, metadata_id: {}", received_data_hash, metadata.id); + if received_data_hash.to_lowercase() == metadata.id.to_lowercase() { + if let Err(e) = logic.file_store().store(&received_data_hash, &data).await { + logic.handle_error(Error::MessageRecv(MessageRecvError::AvatarUpdate(AvatarUpdateError::FileStore(e)))).await; + } + if changed { + logic + .update_sender() + .send( + UpdateMessage::AvatarChanged { + jid: from.to_bare(), + id: Some( + metadata.id.clone(), + ), + }, + ) + .await; + } + } + }, + Err(e) => { + logic.handle_error(Error::MessageRecv(MessageRecvError::AvatarUpdate(AvatarUpdateError::Base64(e)))).await; + }, + } + }, + _ => { + logic.handle_error(Error::MessageRecv(MessageRecvError::AvatarUpdate(AvatarUpdateError::MissingData))).await; + } + } + } + Ok(true) => { + // just send the update + if changed { + logic + .update_sender() + .send( + UpdateMessage::AvatarChanged { + jid: from.to_bare(), + id: Some( + metadata.id.clone(), + ), + }, + ) + .await; + } + } + Err(e) => { + logic.handle_error(Error::MessageRecv(MessageRecvError::AvatarUpdate(e))).await; + } + } + } + Err(e) => { + logic + .handle_error(Error::MessageRecv( + MessageRecvError::AvatarUpdate( + AvatarUpdateError::Database( + e, + ), + ), + )) + .await; + } + } + } else { + // delete avatar + match logic + .db() + .delete_user_avatar(from.to_bare()) + .await + { + Ok((changed, old_avatar)) => { + if changed { + if let Some(old_avatar) = old_avatar + { + if let Err(e) = logic + .file_store() + .delete(&old_avatar) + .await.map_err(|err| AvatarUpdateError::FileStore(err)) { + logic.handle_error(MessageRecvError::AvatarUpdate(e).into()).await; + } + } + logic + .update_sender() + .send( + UpdateMessage::AvatarChanged { + jid: from.to_bare(), + id: None, + }, + ) + .await; + } + } + Err(e) => { + logic + .handle_error(Error::MessageRecv( + MessageRecvError::AvatarUpdate( + AvatarUpdateError::Database( + e, + ), + ), + )) + .await; + } + } + } + // check if the new file is in the file store + // if not, retrieve from server and save in the file store (remember to check if the hash matches) + // send the avatar update + } + _ => {} } - Content::Unknown(element) => {} - }, - None => {} + } } + _ => {} } } - ItemsType::Retract(retracts) => {} - }, - _ => {} - }, + _ => {} + } + } // Event::Collection(collection) => todo!(), // Event::Configuration(configuration) => todo!(), // Event::Delete(delete) => todo!(), // Event::Purge(purge) => todo!(), // Event::Subscription(subscription) => todo!(), - _ => {} + _ => {} // TODO: catch these catch-alls in some way } } @@ -173,13 +482,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 => { @@ -188,6 +491,7 @@ pub async fn recv_presence( } stanza::client::presence::PresenceType::Subscribe => { // may get a subscription request from somebody who is not a contact!!! therefore should be its own kind of event + let from = from.try_into()?; Ok(Some(UpdateMessage::SubscriptionRequest(from))) } stanza::client::presence::PresenceType::Unavailable => { @@ -240,15 +544,16 @@ pub async fn recv_presence( } } -pub async fn recv_iq( - logic: ClientLogic, +pub async fn recv_iq<Fs: FileStore + Clone>( + logic: ClientLogic<Fs>, connection: Connected, iq: Iq, -) -> Result<Option<UpdateMessage>, IqError> { +) -> Result<Option<UpdateMessage>, IqProcessError> { if let Some(to) = &iq.to { - if *to == *connection.jid() { + // TODO: this clone could mayb b avoided + if *to == connection.jid().clone().into() { } else { - return Err(IqError::IncorrectAddressee(to.clone())); + return Err(IqProcessError::Iq(IqError::IncorrectAddressee(to.clone()))); } } match iq.r#type { @@ -256,17 +561,24 @@ pub async fn recv_iq( let from = iq .from .clone() - .unwrap_or_else(|| connection.server().clone()); + // TODO: maybe actually store the server in the connection again LOL + // .unwrap_or_else(|| connection.server().clone()); + .unwrap_or_else(|| connection.jid().domainpart.parse().unwrap()); let id = iq.id.clone(); debug!("received iq result with id `{}` from {}", id, from); - logic.pending().respond(Stanza::Iq(iq), id).await?; + logic + .pending() + .respond(Stanza::Iq(iq), id) + .await + .map_err(|e| Into::<IqError>::into(e))?; Ok(None) } stanza::client::iq::IqType::Get => { let from = iq .from .clone() - .unwrap_or_else(|| connection.server().clone()); + // .unwrap_or_else(|| connection.server().clone()); + .unwrap_or_else(|| connection.jid().domainpart.parse().unwrap()); if let Some(query) = iq.query { match query { stanza::client::iq::Query::DiscoInfo(query) => { @@ -280,7 +592,7 @@ pub async fn recv_iq( } 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) { @@ -290,7 +602,7 @@ pub async fn recv_iq( } Err(_e) => { let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -299,14 +611,18 @@ pub async fn recv_iq( errors: vec![StanzaError::ItemNotFound.into()], }; // TODO: log error - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; info!("replied to disco#info request from {}", from); return Ok(None); } }, Err(_e) => { let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -315,14 +631,18 @@ pub async fn recv_iq( errors: vec![StanzaError::ItemNotFound.into()], }; // TODO: log error - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; info!("replied to disco#info request from {}", from); return Ok(None); } } }; let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Result, @@ -330,14 +650,18 @@ pub async fn recv_iq( query: Some(iq::Query::DiscoInfo(disco)), errors: vec![], }; - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; info!("replied to disco#info request from {}", from); Ok(None) } _ => { warn!("received unsupported iq get from {}", from); let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -345,7 +669,11 @@ pub async fn recv_iq( query: None, errors: vec![StanzaError::ServiceUnavailable.into()], }; - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; warn!("replied to unsupported iq get from {}", from); Ok(None) } // stanza::client::iq::Query::Bind(bind) => todo!(), @@ -357,7 +685,7 @@ pub async fn recv_iq( } else { info!("received malformed iq query from {}", from); let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -365,7 +693,11 @@ pub async fn recv_iq( query: None, errors: vec![StanzaError::BadRequest.into()], }; - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; info!("replied to malformed iq query from {}", from); Ok(None) } @@ -374,7 +706,8 @@ pub async fn recv_iq( let from = iq .from .clone() - .unwrap_or_else(|| connection.server().clone()); + // .unwrap_or_else(|| connection.server().clone()); + .unwrap_or_else(|| connection.jid().domainpart.parse().unwrap()); if let Some(query) = iq.query { match query { stanza::client::iq::Query::Roster(mut query) => { @@ -401,7 +734,7 @@ pub async fn recv_iq( .await; } let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Result, @@ -416,13 +749,18 @@ pub async fn recv_iq( .handle_error(RosterError::PushReply(e.into()).into()) .await; } - Ok(Some(UpdateMessage::RosterUpdate(contact))) + let user = logic + .db() + .read_user(contact.user_jid.clone()) + .await + .map_err(|e| Into::<RosterError>::into(e))?; + Ok(Some(UpdateMessage::RosterUpdate(contact, user))) } } } else { warn!("received malformed roster push"); let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -430,7 +768,11 @@ pub async fn recv_iq( query: None, errors: vec![StanzaError::NotAcceptable.into()], }; - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; Ok(None) } } @@ -438,7 +780,7 @@ pub async fn recv_iq( _ => { warn!("received unsupported iq set from {}", from); let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -446,7 +788,11 @@ pub async fn recv_iq( query: None, errors: vec![StanzaError::ServiceUnavailable.into()], }; - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; warn!("replied to unsupported iq set from {}", from); Ok(None) } @@ -454,7 +800,7 @@ pub async fn recv_iq( } else { warn!("received malformed iq set from {}", from); let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Error, @@ -462,24 +808,28 @@ pub async fn recv_iq( query: None, errors: vec![StanzaError::NotAcceptable.into()], }; - connection.write_handle().write(Stanza::Iq(iq)).await?; + connection + .write_handle() + .write(Stanza::Iq(iq)) + .await + .map_err(|e| Into::<IqError>::into(e))?; Ok(None) } } } } -pub async fn process_stanza( - logic: ClientLogic, +pub async fn process_stanza<Fs: FileStore + Clone>( + logic: ClientLogic<Fs>, stanza: Stanza, connection: Connected, -) -> Result<Option<UpdateMessage>, Error> { +) -> Result<Option<UpdateMessage>, Error<Fs>> { let update = match stanza { Stanza::Message(stanza_message) => Ok(recv_message(logic, stanza_message).await?), Stanza::Presence(presence) => Ok(recv_presence(presence).await?), Stanza::Iq(iq) => Ok(recv_iq(logic, connection.clone(), iq).await?), // unreachable, always caught by lampada - // TODO: make cleaner than this in some way + // TODO: make cleaner than this in some way, by just reexporting a stanza enum from lampada ig. Stanza::Error(error) => { unreachable!() } diff --git a/filamento/src/pep.rs b/filamento/src/pep.rs index c71d843..3cd243f 100644 --- a/filamento/src/pep.rs +++ b/filamento/src/pep.rs @@ -1,17 +1,8 @@ -// in commandmessage -// pub struct Publish { -// item: Item, -// node: Option<String>, -// // no need for node, as item has the node -// } -// -// in updatemessage -// pub struct Event { -// from: JID, -// item: Item, -// } +use crate::avatar::{Data as AvatarData, Metadata as AvatarMetadata}; #[derive(Clone, Debug)] pub enum Item { - Nick(String), + Nick(Option<String>), + AvatarMetadata(Option<AvatarMetadata>), + AvatarData(Option<AvatarData>), } diff --git a/filamento/src/presence.rs b/filamento/src/presence.rs index a7a8965..de4dd7c 100644 --- a/filamento/src/presence.rs +++ b/filamento/src/presence.rs @@ -1,19 +1,20 @@ use chrono::{DateTime, Utc}; -use sqlx::Sqlite; +use rusqlite::{ + ToSql, + types::{FromSql, ToSqlOutput, Value}, +}; use stanza::{client::presence::String1024, xep_0203::Delay}; use crate::caps; -#[derive(Debug, Default, sqlx::FromRow, Clone)] +#[derive(Debug, Default, Clone)] pub struct Online { pub show: Option<Show>, - #[sqlx(rename = "message")] pub status: Option<String>, - #[sqlx(skip)] pub priority: Option<i8>, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Show { Away, Chat, @@ -21,39 +22,27 @@ pub enum Show { ExtendedAway, } -impl sqlx::Type<Sqlite> for Show { - fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo { - <&str as sqlx::Type<Sqlite>>::type_info() - } -} - -impl sqlx::Decode<'_, Sqlite> for Show { - fn decode( - value: <Sqlite as sqlx::Database>::ValueRef<'_>, - ) -> Result<Self, sqlx::error::BoxDynError> { - let value = <&str as sqlx::Decode<Sqlite>>::decode(value)?; - match value { - "away" => Ok(Self::Away), - "chat" => Ok(Self::Chat), - "do-not-disturb" => Ok(Self::DoNotDisturb), - "extended-away" => Ok(Self::ExtendedAway), - _ => unreachable!(), - } +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 sqlx::Encode<'_, Sqlite> for Show { - fn encode_by_ref( - &self, - buf: &mut <Sqlite as sqlx::Database>::ArgumentBuffer<'_>, - ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { - let value = match self { - Show::Away => "away", - Show::Chat => "chat", - Show::DoNotDisturb => "do-not-disturb", - Show::ExtendedAway => "extended-away", - }; - <&str as sqlx::Encode<Sqlite>>::encode(value, buf) +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}"), + }) } } diff --git a/filamento/src/roster.rs b/filamento/src/roster.rs index 43c32f5..0498278 100644 --- a/filamento/src/roster.rs +++ b/filamento/src/roster.rs @@ -1,85 +1,117 @@ -use std::collections::HashSet; +use std::{collections::HashSet, fmt::Display}; -use jid::JID; -use sqlx::Sqlite; +use jid::BareJID; +use rusqlite::{ + ToSql, + types::{FromSql, ToSqlOutput, Value}, +}; pub struct ContactUpdate { pub name: Option<String>, pub groups: HashSet<String>, } -#[derive(Debug, sqlx::FromRow, 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, + pub user_jid: BareJID, pub subscription: Subscription, /// client user defined name pub name: Option<String>, // TODO: avatar, nickname /// nickname picked by contact // nickname: Option<String>, - #[sqlx(skip)] + #[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 sqlx::Type<Sqlite> for Subscription { - fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo { - <&str as sqlx::Type<Sqlite>>::type_info() +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 sqlx::Decode<'_, Sqlite> for Subscription { - fn decode( - value: <Sqlite as sqlx::Database>::ValueRef<'_>, - ) -> Result<Self, sqlx::error::BoxDynError> { - let value = <&str as sqlx::Decode<Sqlite>>::decode(value)?; - match value { - "none" => Ok(Self::None), - "pending-out" => Ok(Self::PendingOut), - "pending-in" => Ok(Self::PendingIn), - "pending-in-pending-out" => Ok(Self::PendingInPendingOut), - "only-out" => Ok(Self::OnlyOut), - "only-in" => Ok(Self::OnlyIn), - "out-pending-in" => Ok(Self::OutPendingIn), - "in-pending-out" => Ok(Self::InPendingOut), - "buddy" => Ok(Self::Buddy), - _ => panic!("unexpected subscription `{value}`"), - } +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 sqlx::Encode<'_, Sqlite> for Subscription { - fn encode_by_ref( - &self, - buf: &mut <Sqlite as sqlx::Database>::ArgumentBuffer<'_>, - ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { - let value = match self { - Subscription::None => "none", - Subscription::PendingOut => "pending-out", - Subscription::PendingIn => "pending-in", - Subscription::PendingInPendingOut => "pending-in-pending-out", - Subscription::OnlyOut => "only-out", - Subscription::OnlyIn => "only-in", - Subscription::OutPendingIn => "out-pending-in", - Subscription::InPendingOut => "in-pending-out", - Subscription::Buddy => "buddy", - }; - <&str as sqlx::Encode<Sqlite>>::encode(value, buf) +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)"), + } } } diff --git a/filamento/src/user.rs b/filamento/src/user.rs index 85471d5..f962a4c 100644 --- a/filamento/src/user.rs +++ b/filamento/src/user.rs @@ -1,8 +1,11 @@ -use jid::JID; +use jid::BareJID; -#[derive(Debug, sqlx::FromRow, 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 jid: BareJID, pub nick: Option<String>, - pub cached_status_message: Option<String>, + pub avatar: Option<String>, + // pub cached_status_message: Option<String>, } diff --git a/jid/Cargo.toml b/jid/Cargo.toml index d5983ea..58d59a4 100644 --- a/jid/Cargo.toml +++ b/jid/Cargo.toml @@ -4,7 +4,19 @@ version = "0.1.0" edition = "2021" [features] -sqlx = ["dep:sqlx"] +# default = [] +rusqlite = ["dep:rusqlite"] +serde = ["dep:serde"] +# sqlx = ["dep:sqlx"] [dependencies] -sqlx = { version = "0.8.3", features = ["sqlite"], optional = true } +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 } + +# [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# sqlx = { version = "0.8.3", features = ["sqlite"], optional = true } + +# [target.'cfg(target_arch = "wasm32")'.dependencies] +# sqlx = { path = "../../remote/sqlx", features = ["sqlite-precompiled-wasm"], optional = true } diff --git a/jid/src/lib.rs b/jid/src/lib.rs index 8f297c6..3b40094 100644 --- a/jid/src/lib.rs +++ b/jid/src/lib.rs @@ -1,14 +1,53 @@ -use std::{borrow::Cow, error::Error, fmt::Display, str::FromStr}; +use std::{borrow::Cow, error::Error, fmt::Display, ops::Deref, str::FromStr}; -#[cfg(feature = "sqlx")] -use sqlx::Sqlite; +// #[cfg(feature = "sqlx")] +// use sqlx::Sqlite; -#[derive(PartialEq, Debug, Clone, Eq, Hash)] -pub struct JID { - // TODO: validate localpart (length, char] - pub localpart: Option<String>, - pub domainpart: String, - pub resourcepart: Option<String>, +#[derive(PartialEq, Debug, Clone, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum JID { + Full(FullJID), + Bare(BareJID), +} + +impl JID { + pub fn resourcepart(&self) -> Option<&String> { + match self { + JID::Full(full_jid) => Some(&full_jid.resourcepart), + JID::Bare(_bare_jid) => None, + } + } +} + +impl From<FullJID> for JID { + fn from(value: FullJID) -> Self { + Self::Full(value) + } +} + +impl From<BareJID> for JID { + fn from(value: BareJID) -> Self { + Self::Bare(value) + } +} + +impl Deref for JID { + type Target = BareJID; + + fn deref(&self) -> &Self::Target { + match self { + JID::Full(full_jid) => full_jid.as_bare(), + JID::Bare(bare_jid) => bare_jid, + } + } +} + +impl Deref for FullJID { + type Target = BareJID; + + fn deref(&self) -> &Self::Target { + &self.bare_jid + } } impl<'a> Into<Cow<'a, str>> for &'a JID { @@ -20,45 +59,108 @@ impl<'a> Into<Cow<'a, str>> for &'a JID { impl Display for JID { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + JID::Full(full_jid) => full_jid.fmt(f), + JID::Bare(bare_jid) => bare_jid.fmt(f), + } + } +} + +#[derive(PartialEq, Debug, Clone, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct FullJID { + pub bare_jid: BareJID, + pub resourcepart: String, +} + +impl Display for FullJID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.bare_jid.fmt(f)?; + f.write_str("/")?; + f.write_str(&self.resourcepart)?; + Ok(()) + } +} + +#[derive(PartialEq, Debug, Clone, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct BareJID { + // TODO: validate and don't have public fields + // TODO: validate localpart (length, char] + pub localpart: Option<String>, + pub domainpart: String, +} + +impl Display for BareJID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(localpart) = &self.localpart { f.write_str(localpart)?; f.write_str("@")?; } f.write_str(&self.domainpart)?; - if let Some(resourcepart) = &self.resourcepart { - f.write_str("/")?; - f.write_str(resourcepart)?; - } Ok(()) } } -#[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 = "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 = "rusqlite")] +impl rusqlite::ToSql for FullJID { + 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)?; +#[cfg(feature = "rusqlite")] +impl rusqlite::types::FromSql for FullJID { + fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> { + Ok(JID::from_str(value.as_str()?)?.try_into()?) + } +} - Ok(value.parse()?) +#[cfg(feature = "rusqlite")] +impl rusqlite::ToSql for BareJID { + 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::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 rusqlite::types::FromSql for BareJID { + fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult<Self> { + Ok(JID::from_str(value.as_str()?)?.try_into()?) + } +} + +#[cfg(feature = "rusqlite")] +impl From<ParseError> for rusqlite::types::FromSqlError { + fn from(value: ParseError) -> Self { + Self::Other(Box::new(value)) + } +} + +#[cfg(feature = "rusqlite")] +impl From<JIDError> for rusqlite::types::FromSqlError { + fn from(value: JIDError) -> Self { + Self::Other(Box::new(value)) } } @@ -66,13 +168,16 @@ impl sqlx::Encode<'_, Sqlite> for JID { pub enum JIDError { NoResourcePart, ParseError(ParseError), + ContainsResourcepart, } impl Display for JIDError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + // TODO: separate jid errors? JIDError::NoResourcePart => f.write_str("resourcepart missing"), JIDError::ParseError(parse_error) => parse_error.fmt(f), + JIDError::ContainsResourcepart => f.write_str("contains resourcepart"), } } } @@ -98,36 +203,105 @@ impl Display for ParseError { impl Error for ParseError {} +impl FullJID { + pub fn new(localpart: Option<String>, domainpart: String, resourcepart: String) -> Self { + Self { + bare_jid: BareJID::new(localpart, domainpart), + resourcepart, + } + } + + pub fn as_bare(&self) -> &BareJID { + &self.bare_jid + } + + pub fn to_bare(&self) -> BareJID { + self.bare_jid.clone() + } +} + +impl BareJID { + pub fn new(localpart: Option<String>, domainpart: String) -> Self { + Self { + localpart, + domainpart, + } + } +} + +impl TryFrom<JID> for BareJID { + type Error = JIDError; + + fn try_from(value: JID) -> Result<Self, Self::Error> { + match value { + JID::Full(_full_jid) => Err(JIDError::ContainsResourcepart), + JID::Bare(bare_jid) => Ok(bare_jid), + } + } +} + impl JID { pub fn new( localpart: Option<String>, domainpart: String, resourcepart: Option<String>, ) -> Self { - Self { - localpart, - domainpart: domainpart.parse().unwrap(), - resourcepart, + if let Some(resourcepart) = resourcepart { + Self::Full(FullJID::new(localpart, domainpart, resourcepart)) + } else { + Self::Bare(BareJID::new(localpart, domainpart)) } } - pub fn as_bare(&self) -> Self { - Self { - localpart: self.localpart.clone(), - domainpart: self.domainpart.clone(), - resourcepart: None, + pub fn as_bare(&self) -> &BareJID { + match self { + JID::Full(full_jid) => full_jid.as_bare(), + JID::Bare(bare_jid) => &bare_jid, } } - pub fn as_full(&self) -> Result<&Self, JIDError> { - if let Some(_) = self.resourcepart { - Ok(&self) - } else { - Err(JIDError::NoResourcePart) + pub fn to_bare(&self) -> BareJID { + match self { + JID::Full(full_jid) => full_jid.to_bare(), + JID::Bare(bare_jid) => bare_jid.clone(), + } + } + + pub fn as_full(&self) -> Result<&FullJID, JIDError> { + match self { + JID::Full(full_jid) => Ok(full_jid), + JID::Bare(_bare_jid) => Err(JIDError::NoResourcePart), + } + } +} + +impl TryFrom<JID> for FullJID { + type Error = JIDError; + + fn try_from(value: JID) -> Result<Self, Self::Error> { + match value { + JID::Full(full_jid) => Ok(full_jid), + JID::Bare(_bare_jid) => Err(JIDError::NoResourcePart), } } } +impl FromStr for BareJID { + type Err = JIDError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Ok(JID::from_str(s)?.try_into()?) + } +} + +impl FromStr for FullJID { + type Err = JIDError; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + Ok(JID::from_str(s)?.try_into()?) + } +} + impl FromStr for JID { type Err = ParseError; @@ -168,6 +342,12 @@ impl FromStr for JID { } } +impl From<ParseError> for JIDError { + fn from(value: ParseError) -> Self { + JIDError::ParseError(value) + } +} + impl TryFrom<String> for JID { type Error = ParseError; @@ -232,3 +412,32 @@ mod tests { ) } } + +// #[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) +// } +// } diff --git a/lampada/Cargo.toml b/lampada/Cargo.toml index 9b42aad..1937162 100644 --- a/lampada/Cargo.toml +++ b/lampada/Cargo.toml @@ -3,12 +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", path = "../../peanuts" } -jid = { version = "0.1.0", path = "../jid", features = ["sqlx"] } -stanza = { version = "0.1.0", path = "../stanza", features = ["xep_0203"] } -tokio = "1.42.0" -tracing = "0.1.41" -thiserror = "2.0.11" +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"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +tokio_with_wasm = { workspace = true, features = [ + "macros", + "rt", + "time", + "sync", +] } diff --git a/lampada/src/connection/mod.rs b/lampada/src/connection/mod.rs index 2d570ae..51c3758 100644 --- a/lampada/src/connection/mod.rs +++ b/lampada/src/connection/mod.rs @@ -7,14 +7,16 @@ use std::{ time::Duration, }; -use jid::JID; -use luz::{connection::Tls, jabber_stream::bound_stream::BoundJabberStream}; +use jid::{BareJID, FullJID, JID}; +use luz::jabber_stream::bound_stream::BoundJabberStream; use read::{ReadControl, ReadControlHandle, ReadState}; use stanza::{client::Stanza, stream_error::Error as StreamError}; use tokio::{ sync::{mpsc, oneshot, Mutex}, task::{JoinHandle, JoinSet}, }; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; use tracing::info; use write::{WriteControl, WriteControlHandle, WriteHandle, WriteMessage, WriteState}; @@ -46,7 +48,12 @@ pub enum SupervisorCommand { Reconnect(ReadState), } -impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { +impl<Lgc> Supervisor<Lgc> +where + Lgc: Logic + Clone + 'static, + #[cfg(not(target_arch = "wasm32"))] + Lgc: Send, +{ fn new( command_recv: mpsc::Receiver<SupervisorCommand>, reader_crash: oneshot::Receiver<(Option<StreamError>, ReadState)>, @@ -86,13 +93,13 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { info!("sent disconnect command"); tokio::select! { _ = async { tokio::join!( - async { let _ = (&mut self.write_control_handle.handle).await; }, - async { let _ = (&mut self.read_control_handle.handle).await; } + // async { let _ = (&mut self.write_control_handle.handle).await; }, + // async { let _ = (&mut self.read_control_handle.handle).await; } ) } => {}, // TODO: config timeout _ = async { tokio::time::sleep(Duration::from_secs(5)) } => { - (&mut self.read_control_handle.handle).abort(); - (&mut self.write_control_handle.handle).abort(); + // (&mut self.read_control_handle.handle).abort(); + // (&mut self.write_control_handle.handle).abort(); } } info!("disconnected"); @@ -114,12 +121,11 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { break } - let mut jid = self.connected.jid.clone(); - let mut domain = jid.domainpart.clone(); + let mut jid = self.connected.jid.clone().into(); // TODO: make sure connect_and_login does not modify the jid, but instead returns a jid. or something like that - let connection = luz::connect_and_login(&mut jid, &*self.password, &mut domain).await; + let connection = luz::connect_and_login(&jid, &*self.password).await; match connection { - Ok(c) => { + Ok((c, full_jid)) => { let (read, write) = c.split(); let (send, recv) = oneshot::channel(); self.writer_crash = recv; @@ -129,7 +135,7 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { self.reader_crash = recv; self.read_control_handle = ReadControlHandle::reconnect( read, - read_state.tasks, + // read_state.tasks, self.connected.clone(), self.logic.clone(), read_state.supervisor_control, @@ -162,12 +168,11 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { else => break, }; - let mut jid = self.connected.jid.clone(); - let mut domain = jid.domainpart.clone(); + let mut jid = self.connected.jid.clone().into(); // TODO: same here - let connection = luz::connect_and_login(&mut jid, &*self.password, &mut domain).await; + let connection = luz::connect_and_login(&jid, &*self.password).await; match connection { - Ok(c) => { + Ok((c, full_jid)) => { let (read, write) = c.split(); let (send, recv) = oneshot::channel(); self.writer_crash = recv; @@ -177,7 +182,7 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { self.reader_crash = recv; self.read_control_handle = ReadControlHandle::reconnect( read, - read_state.tasks, + // read_state.tasks, self.connected.clone(), self.logic.clone(), read_state.supervisor_control, @@ -207,11 +212,10 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { else => break, }; - let mut jid = self.connected.jid.clone(); - let mut domain = jid.domainpart.clone(); - let connection = luz::connect_and_login(&mut jid, &*self.password, &mut domain).await; + let mut jid = self.connected.jid.clone().into(); + let connection = luz::connect_and_login(&jid, &*self.password).await; match connection { - Ok(c) => { + Ok((c, full_jid)) => { let (read, write) = c.split(); let (send, recv) = oneshot::channel(); self.writer_crash = recv; @@ -225,7 +229,7 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { self.reader_crash = recv; self.read_control_handle = ReadControlHandle::reconnect( read, - read_state.tasks, + // read_state.tasks, self.connected.clone(), self.logic.clone(), read_state.supervisor_control, @@ -257,7 +261,8 @@ impl<Lgc: Logic + Clone + Send + 'static> Supervisor<Lgc> { pub struct SupervisorHandle { sender: SupervisorSender, - handle: JoinHandle<()>, + // TODO: is not having handles fine? + // handle: JoinHandle<()>, } impl Deref for SupervisorHandle { @@ -294,14 +299,18 @@ impl DerefMut for SupervisorSender { } impl SupervisorHandle { - pub fn new<Lgc: Logic + Clone + Send + 'static>( - streams: BoundJabberStream<Tls>, + pub fn new<Lgc>( + streams: BoundJabberStream, on_crash: oneshot::Sender<()>, - jid: JID, - server: JID, + jid: FullJID, password: Arc<String>, logic: Lgc, - ) -> (WriteHandle, Self) { + ) -> (WriteHandle, Self) + where + Lgc: Logic + Clone + 'static, + #[cfg(not(target_arch = "wasm32"))] + Lgc: Send, + { let (command_send, command_recv) = mpsc::channel(20); let (writer_crash_send, writer_crash_recv) = oneshot::channel(); let (reader_crash_send, reader_crash_recv) = oneshot::channel(); @@ -314,7 +323,6 @@ impl SupervisorHandle { let connected = Connected { jid, write_handle: write_handle.clone(), - server, }; let supervisor_sender = SupervisorSender { @@ -341,13 +349,12 @@ impl SupervisorHandle { logic, ); - let handle = tokio::spawn(async move { actor.run().await }); + tokio::spawn(async move { actor.run().await }); ( write_handle, Self { sender: supervisor_sender, - handle, }, ) } diff --git a/lampada/src/connection/read.rs b/lampada/src/connection/read.rs index 640ca8e..591a2cb 100644 --- a/lampada/src/connection/read.rs +++ b/lampada/src/connection/read.rs @@ -7,7 +7,8 @@ use std::{ time::Duration, }; -use luz::{connection::Tls, jabber_stream::bound_stream::BoundJabberReader}; +use futures::{future::Fuse, FutureExt}; +use luz::jabber_stream::bound_stream::BoundJabberReader; use stanza::client::Stanza; use stanza::stream::Error as StreamErrorStanza; use stanza::stream_error::Error as StreamError; @@ -15,6 +16,8 @@ use tokio::{ sync::{mpsc, oneshot, Mutex}, task::{JoinHandle, JoinSet}, }; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; use tracing::info; use crate::{Connected, Logic, WriteMessage}; @@ -23,12 +26,12 @@ use super::{write::WriteHandle, SupervisorCommand, SupervisorSender}; /// read actor pub struct Read<Lgc> { - stream: BoundJabberReader<Tls>, + stream: BoundJabberReader, disconnecting: bool, - disconnect_timedout: oneshot::Receiver<()>, + disconnect_timedout: Fuse<oneshot::Receiver<()>>, // all the threads spawned by the current connection session - tasks: JoinSet<()>, + // tasks: JoinSet<()>, // for handling incoming stanzas // jabber server must be able to both terminate the connection from error, and ask for data from the client (such as supported XEPs) @@ -45,13 +48,13 @@ pub struct Read<Lgc> { pub struct ReadState { pub supervisor_control: SupervisorSender, // TODO: when a stream dies, the iq gets from the server should not be replied to on the new stream - pub tasks: JoinSet<()>, + // pub tasks: JoinSet<()>, } impl<Lgc> Read<Lgc> { fn new( - stream: BoundJabberReader<Tls>, - tasks: JoinSet<()>, + stream: BoundJabberReader, + // tasks: JoinSet<()>, connected: Connected, logic: Lgc, supervisor_control: SupervisorSender, @@ -62,8 +65,8 @@ impl<Lgc> Read<Lgc> { Self { stream, disconnecting: false, - disconnect_timedout: recv, - tasks, + disconnect_timedout: recv.fuse(), + // tasks, connected, logic, supervisor_control, @@ -73,7 +76,12 @@ impl<Lgc> Read<Lgc> { } } -impl<Lgc: Clone + Logic + Send + 'static> Read<Lgc> { +impl<Lgc> Read<Lgc> +where + Lgc: Logic + Clone + 'static, + #[cfg(not(target_arch = "wasm32"))] + Lgc: Send, +{ async fn run(mut self) { println!("started read thread"); // let stanza = self.stream.read::<Stanza>().await; @@ -91,7 +99,7 @@ impl<Lgc: Clone + Logic + Send + 'static> Read<Lgc> { // when disconnect received, ReadControl::Disconnect => { let (send, recv) = oneshot::channel(); - self.disconnect_timedout = recv; + self.disconnect_timedout = recv.fuse(); self.disconnecting = true; tokio::spawn(async { tokio::time::sleep(Duration::from_secs(10)).await; @@ -99,7 +107,7 @@ impl<Lgc: Clone + Logic + Send + 'static> Read<Lgc> { }) }, ReadControl::Abort(sender) => { - let _ = sender.send(ReadState { supervisor_control: self.supervisor_control, tasks: self.tasks }); + let _ = sender.send(ReadState { supervisor_control: self.supervisor_control }); break; }, }; @@ -111,11 +119,11 @@ impl<Lgc: Clone + Logic + Send + 'static> Read<Lgc> { match s { Stanza::Error(error) => { self.logic.clone().handle_stream_error(error).await; - self.supervisor_control.send(SupervisorCommand::Reconnect(ReadState { supervisor_control: self.supervisor_control.clone(), tasks: self.tasks })).await; + self.supervisor_control.send(SupervisorCommand::Reconnect(ReadState { supervisor_control: self.supervisor_control.clone() })).await; break; }, _ => { - self.tasks.spawn(self.logic.clone().handle_stanza(s, self.connected.clone())); + tokio::spawn(self.logic.clone().handle_stanza(s, self.connected.clone())); } }; }, @@ -128,7 +136,7 @@ impl<Lgc: Clone + Logic + Send + 'static> Read<Lgc> { let stream_error = match e { peanuts::Error::ReadError(error) => None, peanuts::Error::Utf8Error(utf8_error) => Some(StreamError::UnsupportedEncoding), - peanuts::Error::ParseError(_) => Some(StreamError::BadFormat), + peanuts::Error::ParseError(_, _) => Some(StreamError::BadFormat), peanuts::Error::EntityProcessError(_) => Some(StreamError::RestrictedXml), peanuts::Error::InvalidCharRef(char_ref_error) => Some(StreamError::UnsupportedEncoding), peanuts::Error::DuplicateNameSpaceDeclaration(namespace_declaration) => Some(StreamError::NotWellFormed), @@ -139,9 +147,10 @@ impl<Lgc: Clone + Logic + Send + 'static> Read<Lgc> { peanuts::Error::UndeclaredNamespace(_) => Some(StreamError::InvalidNamespace), peanuts::Error::Deserialize(deserialize_error) => Some(StreamError::InvalidXml), peanuts::Error::RootElementEnded => Some(StreamError::InvalidXml), + _ => None, }; - let _ = self.on_crash.send((stream_error, ReadState { supervisor_control: self.supervisor_control, tasks: self.tasks })); + let _ = self.on_crash.send((stream_error, ReadState { supervisor_control: self.supervisor_control })); } break; }, @@ -168,7 +177,8 @@ pub enum ReadControl { pub struct ReadControlHandle { sender: mpsc::Sender<ReadControl>, - pub(crate) handle: JoinHandle<()>, + // TODO: same here + // pub(crate) handle: JoinHandle<()>, } impl Deref for ReadControlHandle { @@ -186,56 +196,64 @@ impl DerefMut for ReadControlHandle { } impl ReadControlHandle { - pub fn new<Lgc: Clone + Logic + Send + 'static>( - stream: BoundJabberReader<Tls>, + pub fn new<Lgc>( + stream: BoundJabberReader, connected: Connected, logic: Lgc, supervisor_control: SupervisorSender, on_crash: oneshot::Sender<(Option<StreamError>, ReadState)>, - ) -> Self { + ) -> Self + where + Lgc: Logic + Clone + 'static, + #[cfg(not(target_arch = "wasm32"))] + Lgc: Send, + { let (control_sender, control_receiver) = mpsc::channel(20); let actor = Read::new( stream, - JoinSet::new(), + // JoinSet::new(), connected, logic, supervisor_control, control_receiver, on_crash, ); - let handle = tokio::spawn(async move { actor.run().await }); + tokio::spawn(async move { actor.run().await }); Self { sender: control_sender, - handle, } } - pub fn reconnect<Lgc: Clone + Logic + Send + 'static>( - stream: BoundJabberReader<Tls>, - tasks: JoinSet<()>, + pub fn reconnect<Lgc>( + stream: BoundJabberReader, + // tasks: JoinSet<()>, connected: Connected, logic: Lgc, supervisor_control: SupervisorSender, on_crash: oneshot::Sender<(Option<StreamError>, ReadState)>, - ) -> Self { + ) -> Self + where + Lgc: Logic + Clone + 'static, + #[cfg(not(target_arch = "wasm32"))] + Lgc: Send, + { let (control_sender, control_receiver) = mpsc::channel(20); let actor = Read::new( stream, - tasks, + // tasks, connected, logic, supervisor_control, control_receiver, on_crash, ); - let handle = tokio::spawn(async move { actor.run().await }); + tokio::spawn(async move { actor.run().await }); Self { sender: control_sender, - handle, } } } diff --git a/lampada/src/connection/write.rs b/lampada/src/connection/write.rs index 1070cdf..b982eea 100644 --- a/lampada/src/connection/write.rs +++ b/lampada/src/connection/write.rs @@ -1,6 +1,6 @@ use std::ops::{Deref, DerefMut}; -use luz::{connection::Tls, jabber_stream::bound_stream::BoundJabberWriter}; +use luz::jabber_stream::bound_stream::BoundJabberWriter; use stanza::{ client::Stanza, stream::Error as StreamErrorStanza, stream_error::Error as StreamError, }; @@ -8,12 +8,14 @@ use tokio::{ sync::{mpsc, oneshot}, task::JoinHandle, }; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; use crate::error::WriteError; /// actor that receives jabber stanzas to write, and if there is an error, sends a message back to the supervisor then aborts, so the supervisor can spawn a new stream. pub struct Write { - stream: BoundJabberWriter<Tls>, + stream: BoundJabberWriter, /// connection session write queue stanza_receiver: mpsc::Receiver<WriteMessage>, @@ -41,7 +43,7 @@ pub enum WriteControl { impl Write { fn new( - stream: BoundJabberWriter<Tls>, + stream: BoundJabberWriter, stanza_receiver: mpsc::Receiver<WriteMessage>, control_receiver: mpsc::Receiver<WriteControl>, on_crash: oneshot::Sender<(WriteMessage, WriteState)>, @@ -192,7 +194,7 @@ impl DerefMut for WriteHandle { pub struct WriteControlHandle { sender: mpsc::Sender<WriteControl>, - pub(crate) handle: JoinHandle<()>, + // pub(crate) handle: JoinHandle<()>, } impl Deref for WriteControlHandle { @@ -211,14 +213,14 @@ impl DerefMut for WriteControlHandle { impl WriteControlHandle { pub fn new( - stream: BoundJabberWriter<Tls>, + stream: BoundJabberWriter, on_crash: oneshot::Sender<(WriteMessage, WriteState)>, ) -> (WriteHandle, Self) { let (control_sender, control_receiver) = mpsc::channel(20); let (stanza_sender, stanza_receiver) = mpsc::channel(20); let actor = Write::new(stream, stanza_receiver, control_receiver, on_crash); - let handle = tokio::spawn(async move { actor.run().await }); + tokio::spawn(async move { actor.run().await }); ( WriteHandle { @@ -226,13 +228,12 @@ impl WriteControlHandle { }, Self { sender: control_sender, - handle, }, ) } pub fn reconnect_retry( - stream: BoundJabberWriter<Tls>, + stream: BoundJabberWriter, on_crash: oneshot::Sender<(WriteMessage, WriteState)>, stanza_receiver: mpsc::Receiver<WriteMessage>, retry_msg: WriteMessage, @@ -240,27 +241,26 @@ impl WriteControlHandle { let (control_sender, control_receiver) = mpsc::channel(20); let actor = Write::new(stream, stanza_receiver, control_receiver, on_crash); - let handle = tokio::spawn(async move { actor.run_reconnected(retry_msg).await }); + tokio::spawn(async move { actor.run_reconnected(retry_msg).await }); Self { sender: control_sender, - handle, } } pub fn reconnect( - stream: BoundJabberWriter<Tls>, + stream: BoundJabberWriter, on_crash: oneshot::Sender<(WriteMessage, WriteState)>, stanza_receiver: mpsc::Receiver<WriteMessage>, ) -> Self { let (control_sender, control_receiver) = mpsc::channel(20); let actor = Write::new(stream, stanza_receiver, control_receiver, on_crash); - let handle = tokio::spawn(async move { actor.run().await }); + + tokio::spawn(async move { actor.run().await }); Self { sender: control_sender, - handle, } } } diff --git a/lampada/src/error.rs b/lampada/src/error.rs index 8104155..a5af3a2 100644 --- a/lampada/src/error.rs +++ b/lampada/src/error.rs @@ -2,10 +2,13 @@ use std::sync::Arc; use stanza::client::Stanza; use thiserror::Error; -use tokio::{ - sync::{mpsc::error::SendError, oneshot::error::RecvError}, - time::error::Elapsed, -}; +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")] +use tokio_with_wasm::alias as tokio; #[derive(Debug, Error, Clone)] pub enum ConnectionError { @@ -21,10 +24,11 @@ pub enum ConnectionError { #[error("disconnected")] Disconnected, #[error("invalid server jid: {0}")] - InvalidServerJID(#[from] jid::ParseError), + InvalidServerJID(#[from] jid::JIDError), } #[derive(Debug, Error, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum CommandError<T> { #[error("actor: {0}")] Actor(ActorError), @@ -58,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 7346c42..d1d451e 100644 --- a/lampada/src/lib.rs +++ b/lampada/src/lib.rs @@ -1,3 +1,5 @@ +#![feature(where_clause_attrs)] + use std::{ collections::HashMap, ops::{Deref, DerefMut}, @@ -10,6 +12,7 @@ pub use connection::write::WriteMessage; pub use connection::SupervisorSender; use error::ConnectionError; use futures::{future::Fuse, FutureExt}; +use jid::{BareJID, FullJID}; use luz::JID; use stanza::client::{ iq::{self, Iq, IqType}, @@ -21,6 +24,8 @@ use tokio::{ task::JoinSet, time::timeout, }; +#[cfg(target_arch = "wasm32")] +use tokio_with_wasm::alias as tokio; use tracing::{debug, info}; use crate::connection::write::WriteHandle; @@ -32,24 +37,18 @@ pub mod error; #[derive(Clone)] pub struct Connected { // full jid will stay stable across reconnections - jid: JID, + jid: FullJID, write_handle: WriteHandle, - // the server jid - server: JID, } impl Connected { - pub fn jid(&self) -> &JID { + pub fn jid(&self) -> &FullJID { &self.jid } pub fn write_handle(&self) -> &WriteHandle { &self.write_handle } - - pub fn server(&self) -> &JID { - &self.server - } } /// everything that a particular xmpp client must implement @@ -58,20 +57,24 @@ pub trait Logic { type Cmd; /// run after binding to the stream (e.g. for a chat client, ) + #[cfg(not(target_arch = "wasm32"))] fn handle_connect(self, connection: Connected) -> impl std::future::Future<Output = ()> + Send; /// run before closing the stream (e.g. send unavailable presence in a chat client) + #[cfg(not(target_arch = "wasm32"))] fn handle_disconnect( self, connection: Connected, ) -> impl std::future::Future<Output = ()> + Send; + #[cfg(not(target_arch = "wasm32"))] fn handle_stream_error( self, stream_error: StreamError, ) -> impl std::future::Future<Output = ()> + Send; /// run to handle an incoming xmpp stanza + #[cfg(not(target_arch = "wasm32"))] fn handle_stanza( self, stanza: Stanza, @@ -79,6 +82,7 @@ pub trait Logic { ) -> impl std::future::Future<Output = ()> + std::marker::Send; /// run to handle a command message when a connection is currently established + #[cfg(not(target_arch = "wasm32"))] fn handle_online( self, command: Self::Cmd, @@ -86,21 +90,67 @@ pub trait Logic { ) -> impl std::future::Future<Output = ()> + std::marker::Send; /// run to handle a command message when disconnected + #[cfg(not(target_arch = "wasm32"))] fn handle_offline( self, command: Self::Cmd, ) -> impl std::future::Future<Output = ()> + std::marker::Send; /// run as cleanup after either an abort or a disconnect (e.g. reply to all pending requests with a disconnected error) + #[cfg(not(target_arch = "wasm32"))] fn on_abort(self) -> impl std::future::Future<Output = ()> + std::marker::Send; /// handle connection errors from the core client logic + #[cfg(not(target_arch = "wasm32"))] fn handle_connection_error( self, error: ConnectionError, ) -> impl std::future::Future<Output = ()> + std::marker::Send; // async fn handle_stream_error(self, error) {} + #[cfg(target_arch = "wasm32")] + fn handle_connect(self, connection: Connected) -> impl std::future::Future<Output = ()>; + + /// run before closing the stream (e.g. send unavailable presence in a chat client) + #[cfg(target_arch = "wasm32")] + fn handle_disconnect(self, connection: Connected) -> impl std::future::Future<Output = ()>; + + #[cfg(target_arch = "wasm32")] + fn handle_stream_error( + self, + stream_error: StreamError, + ) -> impl std::future::Future<Output = ()>; + + /// run to handle an incoming xmpp stanza + #[cfg(target_arch = "wasm32")] + fn handle_stanza( + self, + stanza: Stanza, + connection: Connected, + ) -> impl std::future::Future<Output = ()>; + + /// run to handle a command message when a connection is currently established + #[cfg(target_arch = "wasm32")] + fn handle_online( + self, + command: Self::Cmd, + connection: Connected, + ) -> impl std::future::Future<Output = ()>; + + /// run to handle a command message when disconnected + #[cfg(target_arch = "wasm32")] + fn handle_offline(self, command: Self::Cmd) -> impl std::future::Future<Output = ()>; + + /// run as cleanup after either an abort or a disconnect (e.g. reply to all pending requests with a disconnected error) + #[cfg(target_arch = "wasm32")] + fn on_abort(self) -> impl std::future::Future<Output = ()>; + + /// handle connection errors from the core client logic + #[cfg(target_arch = "wasm32")] + fn handle_connection_error( + self, + error: ConnectionError, + ) -> impl std::future::Future<Output = ()>; } /// an actor that implements xmpp core (rfc6120), manages connection/stream status, and delegates any other logic to the generic which implements Logic, allowing different kinds of clients (e.g. chat, social, pubsub) to be built upon the same core @@ -117,10 +167,15 @@ pub struct CoreClient<Lgc: Logic> { logic: Lgc, // config: LampConfig, // TODO: will grow forever at this point, maybe not required as tasks will naturally shut down anyway? - tasks: JoinSet<()>, + // tasks: JoinSet<()>, } -impl<Lgc: Logic + Clone + Send + 'static> CoreClient<Lgc> { +impl<Lgc> CoreClient<Lgc> +where + Lgc: Logic + Clone + 'static, + #[cfg(not(target_arch = "wasm32"))] + Lgc: Send, +{ /// create a new actor pub fn new( jid: JID, @@ -137,7 +192,7 @@ impl<Lgc: Logic + Clone + Send + 'static> CoreClient<Lgc> { receiver, connection_supervisor_shutdown, logic, - tasks: JoinSet::new(), + // tasks: JoinSet::new(), } } @@ -157,42 +212,27 @@ impl<Lgc: Logic + Clone + Send + 'static> CoreClient<Lgc> { 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) .await; } None => { - let mut jid = self.jid.clone(); - let mut domain = jid.domainpart.clone(); // TODO: check what happens upon reconnection with same resource (this is probably what one wants to do and why jid should be mutated from a bare jid to one with a resource) let streams_result = - luz::connect_and_login(&mut jid, &*self.password, &mut domain) - .await; - let server: JID = match domain.parse() { - Ok(j) => j, - Err(e) => { - self.logic - .clone() - .handle_connection_error(ConnectionError::InvalidServerJID( - e, - )) - .await; - continue; - } - }; + luz::connect_and_login(&self.jid, &*self.password).await; match streams_result { - Ok(s) => { + Ok((s, full_jid)) => { debug!("ok stream result"); let (shutdown_send, shutdown_recv) = oneshot::channel::<()>(); let (writer, supervisor) = SupervisorHandle::new( s, shutdown_send, - jid.clone(), - server.clone(), + full_jid.clone(), self.password.clone(), self.logic.clone(), ); @@ -201,23 +241,25 @@ impl<Lgc: Logic + Clone + Send + 'static> CoreClient<Lgc> { self.connection_supervisor_shutdown = shutdown_recv; let connected = Connected { - jid, + jid: full_jid.clone(), write_handle: writer, - server, }; self.logic.clone().handle_connect(connected.clone()).await; self.connected = Some((connected, supervisor)); + // REMEMBER TO NOTIFY IT@S GOOD + sender.send(Ok(full_jid.resourcepart)); } 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))); } } } @@ -240,10 +282,10 @@ impl<Lgc: Logic + Clone + Send + 'static> CoreClient<Lgc> { }, CoreClientCommand::Command(command) => { match self.connected.as_ref() { - Some((w, s)) => self - .tasks - .spawn(self.logic.clone().handle_online(command, w.clone())), - None => self.tasks.spawn(self.logic.clone().handle_offline(command)), + Some((w, s)) => { + tokio::spawn(self.logic.clone().handle_online(command, w.clone())) + } + None => tokio::spawn(self.logic.clone().handle_offline(command)), }; } } @@ -255,7 +297,7 @@ impl<Lgc: Logic + Clone + Send + 'static> CoreClient<Lgc> { 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.lock b/luz/Cargo.lock deleted file mode 100644 index d45d7c1..0000000 --- a/luz/Cargo.lock +++ /dev/null @@ -1,1935 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "addr2line" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" - -[[package]] -name = "aho-corasick" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] - -[[package]] -name = "anstream" -version = "0.6.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" - -[[package]] -name = "anstyle-parse" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" -dependencies = [ - "windows-sys 0.59.0", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" -dependencies = [ - "anstyle", - "windows-sys 0.59.0", -] - -[[package]] -name = "async-recursion" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "async-trait" -version = "0.1.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "autocfg" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" - -[[package]] -name = "backtrace" -version = "0.3.74" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-targets 0.52.6", -] - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bitflags" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" - -[[package]] -name = "cc" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" -dependencies = [ - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "circular" -version = "0.3.0" -dependencies = [ - "bytes", -] - -[[package]] -name = "colorchoice" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" - -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49ba7ef1ad6107f8824dbe97de947cbaac53c44e7f9756a1fba0d37c1eec505" -dependencies = [ - "memchr", -] - -[[package]] -name = "cpufeatures" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" -dependencies = [ - "libc", -] - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "data-encoding" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "enum-as-inner" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "env_filter" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" -dependencies = [ - "log", - "regex", -] - -[[package]] -name = "env_logger" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "humantime", - "log", -] - -[[package]] -name = "errno" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "fastrand" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" - -[[package]] -name = "foreign-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" -dependencies = [ - "foreign-types-shared", -] - -[[package]] -name = "foreign-types-shared" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" - -[[package]] -name = "form_urlencoded" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" - -[[package]] -name = "futures-executor" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" - -[[package]] -name = "futures-macro" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "futures-sink" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" - -[[package]] -name = "futures-task" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" - -[[package]] -name = "futures-util" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "gimli" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "hostname" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c731c3e10504cc8ed35cfe2f1db4c9274c3d35fa486e3b31df46f068ef3e867" -dependencies = [ - "libc", - "match_cfg", - "winapi", -] - -[[package]] -name = "humantime" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" - -[[package]] -name = "icu_collections" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locid" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_locid_transform" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" -dependencies = [ - "displaydoc", - "icu_locid", - "icu_locid_transform_data", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locid_transform_data" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" - -[[package]] -name = "icu_normalizer" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "utf16_iter", - "utf8_iter", - "write16", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" - -[[package]] -name = "icu_properties" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locid_transform", - "icu_properties_data", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" - -[[package]] -name = "icu_provider" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" -dependencies = [ - "displaydoc", - "icu_locid", - "icu_provider_macros", - "stable_deref_trait", - "tinystr", - "writeable", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_provider_macros" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "idna" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" -dependencies = [ - "matches", - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "idna" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "ipconfig" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f" -dependencies = [ - "socket2", - "widestring", - "windows-sys 0.48.0", - "winreg", -] - -[[package]] -name = "ipnet" -version = "2.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" - -[[package]] -name = "itoa" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a73e9fe3c49d7afb2ace819fa181a287ce54a0983eda4e0eb05c22f82ffe534" - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "libc" -version = "0.2.164" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "433bfe06b8c75da9b2e3fbea6e5329ff87748f0b144ef75306e674c3f6f7c13f" - -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" - -[[package]] -name = "linux-raw-sys" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" - -[[package]] -name = "litemap" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" - -[[package]] -name = "lock_api" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" - -[[package]] -name = "lru-cache" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c" -dependencies = [ - "linked-hash-map", -] - -[[package]] -name = "luz" -version = "0.0.1" -dependencies = [ - "async-recursion", - "async-trait", - "env_logger", - "futures", - "lazy_static", - "nanoid", - "peanuts", - "rsasl", - "test-log", - "tokio", - "tokio-native-tls", - "tracing", - "tracing-subscriber", - "trust-dns-resolver", - "try_map", -] - -[[package]] -name = "match_cfg" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4" - -[[package]] -name = "matchers" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" -dependencies = [ - "regex-automata 0.1.10", -] - -[[package]] -name = "matches" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - -[[package]] -name = "miniz_oxide" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" -dependencies = [ - "adler2", -] - -[[package]] -name = "mio" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" -dependencies = [ - "hermit-abi", - "libc", - "wasi", - "windows-sys 0.52.0", -] - -[[package]] -name = "nanoid" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8" -dependencies = [ - "rand", -] - -[[package]] -name = "native-tls" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8614eb2c83d59d1c8cc974dd3f920198647674a0a035e1af1fa58707e317466" -dependencies = [ - "libc", - "log", - "openssl", - "openssl-probe", - "openssl-sys", - "schannel", - "security-framework", - "security-framework-sys", - "tempfile", -] - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - -[[package]] -name = "nu-ansi-term" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" -dependencies = [ - "overload", - "winapi", -] - -[[package]] -name = "object" -version = "0.36.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" -dependencies = [ - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" - -[[package]] -name = "openssl" -version = "0.10.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6174bc48f102d208783c2c84bf931bb75927a617866870de8a4ea85597f871f5" -dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "once_cell", - "openssl-macros", - "openssl-sys", -] - -[[package]] -name = "openssl-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "openssl-probe" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" - -[[package]] -name = "openssl-sys" -version = "0.9.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741" -dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "overload" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" - -[[package]] -name = "parking_lot" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-targets 0.52.6", -] - -[[package]] -name = "pbkdf2" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" -dependencies = [ - "digest", -] - -[[package]] -name = "peanuts" -version = "0.1.0" -dependencies = [ - "async-recursion", - "circular", - "futures", - "nom", - "tokio", - "tracing", -] - -[[package]] -name = "percent-encoding" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" - -[[package]] -name = "pin-project-lite" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "pkg-config" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" - -[[package]] -name = "ppv-lite86" -version = "0.2.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "proc-macro2" -version = "1.0.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - -[[package]] -name = "quote" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom", -] - -[[package]] -name = "redox_syscall" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata 0.4.9", - "regex-syntax 0.8.5", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" -dependencies = [ - "regex-syntax 0.6.29", -] - -[[package]] -name = "regex-automata" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax 0.8.5", -] - -[[package]] -name = "regex-syntax" -version = "0.6.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" - -[[package]] -name = "regex-syntax" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" - -[[package]] -name = "resolv-conf" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52e44394d2086d010551b14b53b1f24e31647570cd1deb0379e2c21b329aba00" -dependencies = [ - "hostname", - "quick-error", -] - -[[package]] -name = "rsasl" -version = "2.2.0" -dependencies = [ - "base64", - "core2", - "digest", - "hmac", - "pbkdf2", - "rand", - "serde_json", - "sha1", - "stringprep", - "thiserror", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" - -[[package]] -name = "rustix" -version = "0.38.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.52.0", -] - -[[package]] -name = "ryu" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" - -[[package]] -name = "schannel" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f29ebaa345f945cec9fbbc532eb307f0fdad8161f281b6369539c8d84876b3d" -dependencies = [ - "windows-sys 0.59.0", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa39c7303dc58b5543c94d22c1766b0d31f2ee58306363ea622b10bbc075eaa2" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "serde" -version = "1.0.215" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.215" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "serde_json" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" -dependencies = [ - "itoa", - "memchr", - "ryu", - "serde", -] - -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" - -[[package]] -name = "socket2" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "synstructure" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tempfile" -version = "3.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" -dependencies = [ - "cfg-if", - "fastrand", - "once_cell", - "rustix", - "windows-sys 0.59.0", -] - -[[package]] -name = "test-log" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dffced63c2b5c7be278154d76b479f9f9920ed34e7574201407f0b14e2bbb93" -dependencies = [ - "env_logger", - "test-log-macros", - "tracing-subscriber", -] - -[[package]] -name = "test-log-macros" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5999e24eaa32083191ba4e425deb75cdf25efefabe5aaccb7446dd0d4122a3f5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "thread_local" -version = "1.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" -dependencies = [ - "cfg-if", - "once_cell", -] - -[[package]] -name = "tinystr" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.41.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" -dependencies = [ - "backtrace", - "bytes", - "libc", - "mio", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.52.0", -] - -[[package]] -name = "tokio-macros" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", -] - -[[package]] -name = "tracing" -version = "0.1.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tracing-core" -version = "0.1.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" -dependencies = [ - "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex", - "sharded-slab", - "thread_local", - "tracing", - "tracing-core", - "tracing-log", -] - -[[package]] -name = "trust-dns-proto" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f7f83d1e4a0e4358ac54c5c3681e5d7da5efc5a7a632c90bb6d6669ddd9bc26" -dependencies = [ - "async-trait", - "cfg-if", - "data-encoding", - "enum-as-inner", - "futures-channel", - "futures-io", - "futures-util", - "idna 0.2.3", - "ipnet", - "lazy_static", - "rand", - "smallvec", - "thiserror", - "tinyvec", - "tokio", - "tracing", - "url", -] - -[[package]] -name = "trust-dns-resolver" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aff21aa4dcefb0a1afbfac26deb0adc93888c7d295fb63ab273ef276ba2b7cfe" -dependencies = [ - "cfg-if", - "futures-util", - "ipconfig", - "lazy_static", - "lru-cache", - "parking_lot", - "resolv-conf", - "smallvec", - "thiserror", - "tokio", - "tracing", - "trust-dns-proto", -] - -[[package]] -name = "try_map" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb1626d07cb5c1bb2cf17d94c0be4852e8a7c02b041acec9a8c5bdda99f9d580" - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "unicode-bidi" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" - -[[package]] -name = "unicode-ident" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" - -[[package]] -name = "unicode-normalization" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-properties" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" - -[[package]] -name = "url" -version = "2.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" -dependencies = [ - "form_urlencoded", - "idna 1.0.3", - "percent-encoding", -] - -[[package]] -name = "utf16_iter" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "valuable" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" - -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "widestring" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winreg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" -dependencies = [ - "cfg-if", - "windows-sys 0.48.0", -] - -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" - -[[package]] -name = "writeable" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" - -[[package]] -name = "yoke" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" -dependencies = [ - "serde", - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" -dependencies = [ - "byteorder", - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "zerofrom" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "synstructure", -] - -[[package]] -name = "zerovec" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] diff --git a/luz/Cargo.toml b/luz/Cargo.toml index c1c1511..e9cccd9 100644 --- a/luz/Cargo.toml +++ b/luz/Cargo.toml @@ -4,39 +4,61 @@ authors = ["cel <cel@bunny.garden>"] version = "0.1.0" edition = "2021" +[lib] +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" -nanoid = "0.4.0" -# 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 = { version = "1.28", features = ["full"] } +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 = ["macros"] } +uuid = { workspace = true, features = ["js", "v4"] } +# TODO: check this +getrandom = { version = "0.2.15", features = ["js"] } +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 } tokio-native-tls = "0.3.1" -tracing = "0.1.40" trust-dns-resolver = "0.22.0" -try_map = "0.3.1" -stanza = { version = "0.1.0", path = "../stanza" } -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" [dev-dependencies] -test-log = { version = "0.2", features = ["trace"] } -env_logger = "*" -tracing-subscriber = { version = "0.3", default-features = false, features = [ +# 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 = { 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.rs b/luz/src/client.rs index de2be08..ab0aa6d 100644 --- a/luz/src/client.rs +++ b/luz/src/client.rs @@ -1,111 +1,12 @@ -use rsasl::config::SASLConfig; -use stanza::{ - sasl::Mechanisms, - stream::{Feature, Features}, -}; +#[cfg(not(target_arch = "wasm32"))] +mod tcp; +#[cfg(target_arch = "wasm32")] +mod ws; -use crate::{ - connection::{Tls, Unencrypted}, - jabber_stream::bound_stream::BoundJabberStream, - Connection, Error, JabberStream, Result, JID, -}; - -pub async fn connect_and_login( - jid: &mut JID, - password: impl AsRef<str>, - server: &mut String, -) -> Result<BoundJabberStream<Tls>> { - let auth = SASLConfig::with_credentials( - None, - jid.localpart.clone().ok_or(Error::NoLocalpart)?, - password.as_ref().to_string(), - ) - .map_err(|e| Error::SASL(e.into()))?; - let mut conn_state = Connecting::start(&server).await?; - loop { - match conn_state { - Connecting::InsecureConnectionEstablised(tcp_stream) => { - conn_state = Connecting::InsecureStreamStarted( - JabberStream::start_stream(tcp_stream, server).await?, - ) - } - Connecting::InsecureStreamStarted(jabber_stream) => { - conn_state = Connecting::InsecureGotFeatures(jabber_stream.get_features().await?) - } - Connecting::InsecureGotFeatures((features, jabber_stream)) => { - match features.negotiate().ok_or(Error::Negotiation)? { - Feature::StartTls(_start_tls) => { - conn_state = Connecting::StartTls(jabber_stream) - } - // TODO: better error - _ => return Err(Error::TlsRequired), - } - } - Connecting::StartTls(jabber_stream) => { - conn_state = - Connecting::ConnectionEstablished(jabber_stream.starttls(&server).await?) - } - Connecting::ConnectionEstablished(tls_stream) => { - conn_state = - Connecting::StreamStarted(JabberStream::start_stream(tls_stream, server).await?) - } - Connecting::StreamStarted(jabber_stream) => { - conn_state = Connecting::GotFeatures(jabber_stream.get_features().await?) - } - Connecting::GotFeatures((features, jabber_stream)) => { - match features.negotiate().ok_or(Error::Negotiation)? { - Feature::StartTls(_start_tls) => return Err(Error::AlreadyTls), - Feature::Sasl(mechanisms) => { - conn_state = Connecting::Sasl(mechanisms, jabber_stream) - } - Feature::Bind => conn_state = Connecting::Bind(jabber_stream), - Feature::Unknown => return Err(Error::Unsupported), - } - } - Connecting::Sasl(mechanisms, jabber_stream) => { - conn_state = Connecting::ConnectionEstablished( - jabber_stream.sasl(mechanisms, auth.clone()).await?, - ) - } - Connecting::Bind(jabber_stream) => { - return Ok(jabber_stream.bind(jid).await?.to_bound_jabber()); - } - } - } -} - -pub enum Connecting { - InsecureConnectionEstablised(Unencrypted), - InsecureStreamStarted(JabberStream<Unencrypted>), - InsecureGotFeatures((Features, JabberStream<Unencrypted>)), - StartTls(JabberStream<Unencrypted>), - ConnectionEstablished(Tls), - StreamStarted(JabberStream<Tls>), - GotFeatures((Features, JabberStream<Tls>)), - Sasl(Mechanisms, JabberStream<Tls>), - Bind(JabberStream<Tls>), -} - -impl Connecting { - pub async fn start(server: &str) -> Result<Self> { - match Connection::connect(server).await? { - Connection::Encrypted(tls_stream) => Ok(Connecting::ConnectionEstablished(tls_stream)), - Connection::Unencrypted(tcp_stream) => { - Ok(Connecting::InsecureConnectionEstablised(tcp_stream)) - } - } - } -} - -pub enum InsecureConnecting { - Disconnected, - ConnectionEstablished(Connection), - PreStarttls(JabberStream<Unencrypted>), - PreAuthenticated(JabberStream<Tls>), - Authenticated(Tls), - PreBound(JabberStream<Tls>), - Bound(JabberStream<Tls>), -} +#[cfg(not(target_arch = "wasm32"))] +pub use tcp::connect_and_login; +#[cfg(target_arch = "wasm32")] +pub use ws::connect_and_login; #[cfg(test)] mod tests { @@ -122,20 +23,29 @@ mod tests { use test_log::test; use tokio::time::sleep; use tracing::info; + use wasm_bindgen_test::*; use super::connect_and_login; - #[test(tokio::test)] - async fn login() { + wasm_bindgen_test_configure!(run_in_browser); + + // #[test(tokio::test)] + #[wasm_bindgen_test] + async fn login() -> () { + tracing_wasm::set_as_global_default(); + let mut jid: JID = "test@blos.sm".try_into().unwrap(); - let _client = connect_and_login(&mut jid, "slayed", &mut "blos.sm".to_string()) + let _client = connect_and_login(&mut jid, "slayedaaa", &mut "blos.sm".to_string()) .await .unwrap(); - sleep(Duration::from_secs(5)).await + sleep(Duration::from_secs(5)).await; } - #[test(tokio::test)] + #[wasm_bindgen_test] + // #[test(tokio::test)] async fn ping_parallel() { + tracing_wasm::set_as_global_default(); + let mut jid: JID = "test@blos.sm".try_into().unwrap(); let mut server = "blos.sm".to_string(); let client = connect_and_login(&mut jid, "slayed", &mut server) diff --git a/luz/src/client/tcp.rs b/luz/src/client/tcp.rs new file mode 100644 index 0000000..a30eccc --- /dev/null +++ b/luz/src/client/tcp.rs @@ -0,0 +1,115 @@ +use jid::FullJID; +use rsasl::config::SASLConfig; +use stanza::{ + sasl::Mechanisms, + stream::{Feature, Features}, +}; + +use crate::{ + connection::Unencrypted, jabber_stream::bound_stream::BoundJabberStream, Connection, Error, + JabberStream, Result, JID, +}; + +pub async fn connect_and_login( + jid: &JID, + // jid: &mut JID, + password: impl AsRef<str>, + // server: &mut String, +) -> Result<(BoundJabberStream, FullJID)> { + let auth = SASLConfig::with_credentials( + None, + jid.localpart.clone().ok_or(Error::NoLocalpart)?, + password.as_ref().to_string(), + ) + .map_err(|e| Error::SASL(e.into()))?; + let mut server = jid.domainpart.clone(); + let mut conn_state = Connecting::start(&server).await?; + loop { + match conn_state { + Connecting::InsecureConnectionEstablised(tcp_stream) => { + conn_state = Connecting::InsecureStreamStarted( + JabberStream::start_stream(Connection::Unencrypted(tcp_stream), &mut server) + .await?, + ) + } + Connecting::InsecureStreamStarted(jabber_stream) => { + conn_state = Connecting::InsecureGotFeatures(jabber_stream.get_features().await?) + } + Connecting::InsecureGotFeatures((features, jabber_stream)) => { + match features.negotiate().ok_or(Error::Negotiation)? { + Feature::StartTls(_start_tls) => { + conn_state = Connecting::StartTls(jabber_stream) + } + // TODO: better error + _ => return Err(Error::TlsRequired), + } + } + Connecting::StartTls(jabber_stream) => { + conn_state = Connecting::ConnectionEstablished(Connection::Encrypted( + jabber_stream.starttls(&server).await?, + )) + } + Connecting::ConnectionEstablished(connection) => { + conn_state = Connecting::StreamStarted( + JabberStream::start_stream(connection, &mut server).await?, + ) + } + Connecting::StreamStarted(jabber_stream) => { + conn_state = Connecting::GotFeatures(jabber_stream.get_features().await?) + } + Connecting::GotFeatures((features, jabber_stream)) => { + match features.negotiate().ok_or(Error::Negotiation)? { + Feature::StartTls(_start_tls) => return Err(Error::AlreadyTls), + Feature::Sasl(mechanisms) => { + conn_state = Connecting::Sasl(mechanisms, jabber_stream) + } + Feature::Bind => conn_state = Connecting::Bind(jabber_stream), + Feature::Unknown => return Err(Error::Unsupported), + } + } + Connecting::Sasl(mechanisms, jabber_stream) => { + conn_state = Connecting::ConnectionEstablished( + jabber_stream.sasl(mechanisms, auth.clone()).await?, + ) + } + Connecting::Bind(jabber_stream) => { + return Ok(jabber_stream.bind(jid).await?); + } + } + } +} + +pub enum Connecting { + InsecureConnectionEstablised(Unencrypted), + InsecureStreamStarted(JabberStream), + InsecureGotFeatures((Features, JabberStream)), + StartTls(JabberStream), + ConnectionEstablished(Connection), + StreamStarted(JabberStream), + GotFeatures((Features, JabberStream)), + Sasl(Mechanisms, JabberStream), + Bind(JabberStream), +} + +impl Connecting { + pub async fn start(server: &str) -> Result<Self> { + match Connection::connect(server).await? { + Connection::Encrypted(tls_stream) => Ok(Connecting::ConnectionEstablished( + Connection::Encrypted(tls_stream), + )), + Connection::Unencrypted(tcp_stream) => { + Ok(Connecting::InsecureConnectionEstablised(tcp_stream)) + } + } + } +} + +// pub enum InsecureConnecting { +// Disconnected, +// ConnectionEstablished(Connection), +// PreStarttls(JabberStream<Unencrypted>), +// PreAuthenticated(JabberStream<Tls>), +// Authenticated(Tls), +// PreBound(JabberStream<Tls>), +// Bound(JabberStream<Tls>), +// } diff --git a/luz/src/client/ws.rs b/luz/src/client/ws.rs new file mode 100644 index 0000000..0ad8d0e --- /dev/null +++ b/luz/src/client/ws.rs @@ -0,0 +1,68 @@ +use jid::FullJID; +use rsasl::config::SASLConfig; +use stanza::{ + sasl::Mechanisms, + stream::{Feature, Features}, +}; + +use crate::{ + jabber_stream::bound_stream::BoundJabberStream, Connection, Error, JabberStream, Result, JID, +}; + +pub async fn connect_and_login( + jid: &JID, + password: impl AsRef<str>, +) -> Result<(BoundJabberStream, FullJID)> { + let auth = SASLConfig::with_credentials( + None, + jid.localpart.clone().ok_or(Error::NoLocalpart)?, + password.as_ref().to_string(), + ) + .map_err(|e| Error::SASL(e.into()))?; + let mut server = jid.domainpart.clone(); + let mut conn_state = Connecting::start(&server).await?; + loop { + match conn_state { + Connecting::ConnectionEstablished(ws) => { + conn_state = + Connecting::StreamStarted(JabberStream::start_stream(ws, &mut server).await?) + } + Connecting::StreamStarted(jabber_stream) => { + conn_state = Connecting::GotFeatures(jabber_stream.get_features().await?) + } + Connecting::GotFeatures((features, jabber_stream)) => { + match features.negotiate().ok_or(Error::Negotiation)? { + Feature::StartTls(_start_tls) => return Err(Error::AlreadyTls), + Feature::Sasl(mechanisms) => { + conn_state = Connecting::Sasl(mechanisms, jabber_stream) + } + Feature::Bind => conn_state = Connecting::Bind(jabber_stream), + Feature::Unknown => return Err(Error::Unsupported), + } + } + Connecting::Sasl(mechanisms, jabber_stream) => { + conn_state = Connecting::ConnectionEstablished( + jabber_stream.sasl(mechanisms, auth.clone()).await?, + ) + } + Connecting::Bind(jabber_stream) => { + return Ok(jabber_stream.bind(jid).await?); + } + } + } +} + +pub enum Connecting { + ConnectionEstablished(Connection), + StreamStarted(JabberStream), + GotFeatures((Features, JabberStream)), + Sasl(Mechanisms, JabberStream), + Bind(JabberStream), +} + +impl Connecting { + pub async fn start(server: &str) -> Result<Self> { + let connection = Connection::connect(server).await?; + Ok(Connecting::ConnectionEstablished(Connection(connection.0))) + } +} diff --git a/luz/src/connection.rs b/luz/src/connection.rs index b185eca..d0bdadc 100644 --- a/luz/src/connection.rs +++ b/luz/src/connection.rs @@ -1,164 +1,12 @@ -use std::net::{IpAddr, SocketAddr}; -use std::str; -use std::str::FromStr; - -use tokio::net::TcpStream; -use tokio_native_tls::native_tls::TlsConnector; -// TODO: use rustls -use tokio_native_tls::TlsStream; -use tracing::{debug, info, instrument, trace}; - -use crate::Result; -use crate::{Error, JID}; - -pub type Tls = TlsStream<TcpStream>; -pub type Unencrypted = TcpStream; - -#[derive(Debug)] -pub enum Connection { - Encrypted(Tls), - Unencrypted(Unencrypted), -} - -impl Connection { - // #[instrument] - /// stream not started - // pub async fn ensure_tls(self) -> Result<Jabber<Tls>> { - // match self { - // Connection::Encrypted(j) => Ok(j), - // Connection::Unencrypted(mut j) => { - // j.start_stream().await?; - // info!("upgrading connection to tls"); - // j.get_features().await?; - // let j = j.starttls().await?; - // Ok(j) - // } - // } - // } - - pub async fn connect_user(jid: impl AsRef<str>) -> Result<Self> { - let jid: JID = JID::from_str(jid.as_ref())?; - let server = jid.domainpart.clone(); - Self::connect(&server).await - } - - #[instrument] - pub async fn connect(server: impl AsRef<str> + std::fmt::Debug) -> Result<Self> { - info!("connecting to {}", server.as_ref()); - let sockets = Self::get_sockets(server.as_ref()).await; - debug!("discovered sockets: {:?}", sockets); - for (socket_addr, tls) in sockets { - match tls { - true => { - if let Ok(connection) = Self::connect_tls(socket_addr, server.as_ref()).await { - info!("connected via encrypted stream to {}", socket_addr); - // let (readhalf, writehalf) = tokio::io::split(connection); - return Ok(Self::Encrypted(connection)); - } - } - false => { - if let Ok(connection) = Self::connect_unencrypted(socket_addr).await { - info!("connected via unencrypted stream to {}", socket_addr); - // let (readhalf, writehalf) = tokio::io::split(connection); - return Ok(Self::Unencrypted(connection)); - } - } - } - } - Err(Error::Connection) - } - - #[instrument] - async fn get_sockets(address: &str) -> Vec<(SocketAddr, bool)> { - let mut socket_addrs = Vec::new(); - - // if it's a socket/ip then just return that - - // socket - trace!("checking if address is a socket address"); - if let Ok(socket_addr) = SocketAddr::from_str(address) { - debug!("{} is a socket address", address); - match socket_addr.port() { - 5223 => socket_addrs.push((socket_addr, true)), - _ => socket_addrs.push((socket_addr, false)), - } - - return socket_addrs; - } - // ip - trace!("checking if address is an ip"); - if let Ok(ip) = IpAddr::from_str(address) { - debug!("{} is an ip", address); - socket_addrs.push((SocketAddr::new(ip, 5222), false)); - socket_addrs.push((SocketAddr::new(ip, 5223), true)); - return socket_addrs; - } - - // otherwise resolve - debug!("resolving {}", address); - if let Ok(resolver) = trust_dns_resolver::AsyncResolver::tokio_from_system_conf() { - if let Ok(lookup) = resolver - .srv_lookup(format!("_xmpp-client._tcp.{}", address)) - .await - { - for srv in lookup { - resolver - .lookup_ip(srv.target().to_owned()) - .await - .map(|ips| { - for ip in ips { - socket_addrs.push((SocketAddr::new(ip, srv.port()), false)) - } - }); - } - } - if let Ok(lookup) = resolver - .srv_lookup(format!("_xmpps-client._tcp.{}", address)) - .await - { - for srv in lookup { - resolver - .lookup_ip(srv.target().to_owned()) - .await - .map(|ips| { - for ip in ips { - socket_addrs.push((SocketAddr::new(ip, srv.port()), true)) - } - }); - } - } - - // in case cannot connect through SRV records - resolver.lookup_ip(address).await.map(|ips| { - for ip in ips { - socket_addrs.push((SocketAddr::new(ip, 5222), false)); - socket_addrs.push((SocketAddr::new(ip, 5223), true)); - } - }); - } - socket_addrs - } - - /// establishes a connection to the server - #[instrument] - pub async fn connect_tls(socket_addr: SocketAddr, domain_name: &str) -> Result<Tls> { - let socket = TcpStream::connect(socket_addr) - .await - .map_err(|_| Error::Connection)?; - let connector = TlsConnector::new().map_err(|_| Error::Connection)?; - tokio_native_tls::TlsConnector::from(connector) - .connect(domain_name, socket) - .await - .map_err(|_| Error::Connection) - } - - #[instrument] - pub async fn connect_unencrypted(socket_addr: SocketAddr) -> Result<Unencrypted> { - TcpStream::connect(socket_addr) - .await - .map_err(|_| Error::Connection) - } -} +#[cfg(not(target_arch = "wasm32"))] +mod tcp; +#[cfg(target_arch = "wasm32")] +mod ws; + +#[cfg(not(target_arch = "wasm32"))] +pub use tcp::{Connection, Tls, Unencrypted}; +#[cfg(target_arch = "wasm32")] +pub use ws::{Connection, Ws}; #[cfg(test)] mod tests { diff --git a/luz/src/connection/tcp.rs b/luz/src/connection/tcp.rs new file mode 100644 index 0000000..7409a47 --- /dev/null +++ b/luz/src/connection/tcp.rs @@ -0,0 +1,220 @@ +use std::net::{IpAddr, SocketAddr}; +use std::pin::pin; +use std::str; +use std::str::FromStr; +use std::task::ready; + +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::net::TcpStream; +use tokio_native_tls::native_tls::TlsConnector; +// TODO: use rustls +use tokio_native_tls::TlsStream; +use tracing::{debug, info, instrument, trace}; + +use crate::Result; +use crate::{Error, JID}; + +pub type Tls = TlsStream<TcpStream>; +pub type Unencrypted = TcpStream; + +#[derive(Debug)] +pub enum Connection { + Encrypted(Tls), + Unencrypted(Unencrypted), +} + +impl AsyncRead for Connection { + fn poll_read( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll<std::io::Result<()>> { + match self.get_mut() { + Connection::Encrypted(tls_stream) => ready!(pin!(tls_stream).poll_read(cx, buf)).into(), + Connection::Unencrypted(tcp_stream) => { + ready!(pin!(tcp_stream).poll_read(cx, buf)).into() + } + } + } +} + +impl Unpin for Connection {} + +impl AsyncWrite for Connection { + fn poll_write( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll<std::result::Result<usize, std::io::Error>> { + match self.get_mut() { + Connection::Encrypted(tls_stream) => { + ready!(pin!(tls_stream).poll_write(cx, buf)).into() + } + Connection::Unencrypted(tcp_stream) => { + ready!(pin!(tcp_stream).poll_write(cx, buf)).into() + } + } + } + + fn poll_flush( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { + match self.get_mut() { + Connection::Encrypted(tls_stream) => ready!(pin!(tls_stream).poll_flush(cx)).into(), + Connection::Unencrypted(tcp_stream) => ready!(pin!(tcp_stream).poll_flush(cx)).into(), + } + } + + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll<std::result::Result<(), std::io::Error>> { + match self.get_mut() { + Connection::Encrypted(tls_stream) => ready!(pin!(tls_stream).poll_shutdown(cx)).into(), + Connection::Unencrypted(tcp_stream) => { + ready!(pin!(tcp_stream).poll_shutdown(cx)).into() + } + } + } +} + +impl Connection { + // #[instrument] + /// stream not started + // pub async fn ensure_tls(self) -> Result<Jabber<Tls>> { + // match self { + // Connection::Encrypted(j) => Ok(j), + // Connection::Unencrypted(mut j) => { + // j.start_stream().await?; + // info!("upgrading connection to tls"); + // j.get_features().await?; + // let j = j.starttls().await?; + // Ok(j) + // } + // } + // } + + pub async fn connect_user(jid: impl AsRef<str>) -> Result<Self> { + let jid: JID = JID::from_str(jid.as_ref()).map_err(|e| Error::JID(e.into()))?; + let server = jid.domainpart.clone(); + Self::connect(&server).await + } + + #[instrument] + pub async fn connect(server: impl AsRef<str> + std::fmt::Debug) -> Result<Self> { + info!("connecting to {}", server.as_ref()); + let sockets = Self::get_sockets(server.as_ref()).await; + debug!("discovered sockets: {:?}", sockets); + for (socket_addr, tls) in sockets { + match tls { + true => { + if let Ok(connection) = Self::connect_tls(socket_addr, server.as_ref()).await { + info!("connected via encrypted stream to {}", socket_addr); + // let (readhalf, writehalf) = tokio::io::split(connection); + return Ok(Self::Encrypted(connection)); + } + } + false => { + if let Ok(connection) = Self::connect_unencrypted(socket_addr).await { + info!("connected via unencrypted stream to {}", socket_addr); + // let (readhalf, writehalf) = tokio::io::split(connection); + return Ok(Self::Unencrypted(connection)); + } + } + } + } + Err(Error::Connection) + } + + #[instrument] + async fn get_sockets(address: &str) -> Vec<(SocketAddr, bool)> { + let mut socket_addrs = Vec::new(); + + // if it's a socket/ip then just return that + + // socket + trace!("checking if address is a socket address"); + if let Ok(socket_addr) = SocketAddr::from_str(address) { + debug!("{} is a socket address", address); + match socket_addr.port() { + 5223 => socket_addrs.push((socket_addr, true)), + _ => socket_addrs.push((socket_addr, false)), + } + + return socket_addrs; + } + // ip + trace!("checking if address is an ip"); + if let Ok(ip) = IpAddr::from_str(address) { + debug!("{} is an ip", address); + socket_addrs.push((SocketAddr::new(ip, 5222), false)); + socket_addrs.push((SocketAddr::new(ip, 5223), true)); + return socket_addrs; + } + + // otherwise resolve + debug!("resolving {}", address); + if let Ok(resolver) = trust_dns_resolver::AsyncResolver::tokio_from_system_conf() { + if let Ok(lookup) = resolver + .srv_lookup(format!("_xmpp-client._tcp.{}", address)) + .await + { + for srv in lookup { + resolver + .lookup_ip(srv.target().to_owned()) + .await + .map(|ips| { + for ip in ips { + socket_addrs.push((SocketAddr::new(ip, srv.port()), false)) + } + }); + } + } + if let Ok(lookup) = resolver + .srv_lookup(format!("_xmpps-client._tcp.{}", address)) + .await + { + for srv in lookup { + resolver + .lookup_ip(srv.target().to_owned()) + .await + .map(|ips| { + for ip in ips { + socket_addrs.push((SocketAddr::new(ip, srv.port()), true)) + } + }); + } + } + + // in case cannot connect through SRV records + resolver.lookup_ip(address).await.map(|ips| { + for ip in ips { + socket_addrs.push((SocketAddr::new(ip, 5222), false)); + socket_addrs.push((SocketAddr::new(ip, 5223), true)); + } + }); + } + socket_addrs + } + + /// establishes a connection to the server + #[instrument] + pub async fn connect_tls(socket_addr: SocketAddr, domain_name: &str) -> Result<Tls> { + let socket = TcpStream::connect(socket_addr) + .await + .map_err(|_| Error::Connection)?; + let connector = TlsConnector::new().map_err(|_| Error::Connection)?; + tokio_native_tls::TlsConnector::from(connector) + .connect(domain_name, socket) + .await + .map_err(|_| Error::Connection) + } + + #[instrument] + pub async fn connect_unencrypted(socket_addr: SocketAddr) -> Result<Unencrypted> { + TcpStream::connect(socket_addr) + .await + .map_err(|_| Error::Connection) + } +} diff --git a/luz/src/connection/ws.rs b/luz/src/connection/ws.rs new file mode 100644 index 0000000..e64a96e --- /dev/null +++ b/luz/src/connection/ws.rs @@ -0,0 +1,120 @@ +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 wasm_bindgen_futures::JsFuture; +use web_sys::{ErrorEvent, Request, RequestInit, Response, WebSocket}; + +use crate::error::ConnectionError; + +pub type Ws = WebSocket; + +#[derive(Debug)] +pub struct Connection(pub Ws); + +impl Connection { + pub async fn connect( + server: impl AsRef<str> + std::fmt::Debug, + ) -> Result<Self, ConnectionError> { + // TODO: get the connection url here + 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(); + match send.send(()) { + Ok(()) => (), + Err(e) => { + tracing::error!("socket opened notify: {:?}", e); + } + } + }) 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()))? } + } + + 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 ec60778..d9b2930 100644 --- a/luz/src/error.rs +++ b/luz/src/error.rs @@ -1,7 +1,7 @@ use std::str::Utf8Error; use std::sync::Arc; -use jid::ParseError; +use jid::JIDError; use rsasl::mechname::MechanismNameError; use stanza::client::error::Error as ClientError; use stanza::sasl::Failure; @@ -10,8 +10,12 @@ use thiserror::Error; #[derive(Error, Debug, Clone)] 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")] @@ -32,7 +36,7 @@ pub enum Error { #[error("sasl error: {0}")] SASL(#[from] SASLError), #[error("jid error: {0}")] - JID(#[from] ParseError), + JID(#[from] JIDError), #[error("client stanza error: {0}")] ClientError(#[from] ClientError), #[error("stream error: {0}")] @@ -56,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 302350d..490a0f7 100644 --- a/luz/src/jabber_stream.rs +++ b/luz/src/jabber_stream.rs @@ -1,135 +1,56 @@ +pub mod bound_stream; +#[cfg(not(target_arch = "wasm32"))] +mod tcp; +#[cfg(target_arch = "wasm32")] +mod ws; + use std::str::{self, FromStr}; use std::sync::Arc; -use jid::JID; -use peanuts::element::IntoElement; +use bound_stream::BoundJabberStream; +use jid::{FullJID, JID}; +use peanuts::IntoElement; +#[cfg(target_arch = "wasm32")] +use peanuts::WebSocketOnMessageRead; use peanuts::{Reader, Writer}; use rsasl::prelude::{Mechname, SASLClient, SASLConfig}; use stanza::bind::{Bind, BindType, FullJidType, ResourceType}; use stanza::client::iq::{Iq, IqType, Query}; 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; -use tokio::io::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf}; +#[cfg(not(target_arch = "wasm32"))] use tokio_native_tls::native_tls::TlsConnector; use tracing::{debug, instrument}; +#[cfg(target_arch = "wasm32")] +use web_sys::{wasm_bindgen::JsCast, WebSocket}; -use crate::connection::{Tls, Unencrypted}; +use crate::connection::Connection; +#[cfg(not(target_arch = "wasm32"))] +use crate::connection::Tls; use crate::error::Error; use crate::Result; -pub mod bound_stream; - -// open stream (streams started) -pub struct JabberStream<S> { - reader: JabberReader<S>, - writer: JabberWriter<S>, -} - -impl<S> JabberStream<S> { - fn split(self) -> (JabberReader<S>, JabberWriter<S>) { - let reader = self.reader; - let writer = self.writer; - (reader, writer) - } -} - -pub struct JabberReader<S>(Reader<ReadHalf<S>>); - -impl<S> JabberReader<S> { - // TODO: consider taking a readhalf and creating peanuts::Reader here, only one inner - fn new(reader: Reader<ReadHalf<S>>) -> Self { - Self(reader) - } - - fn unsplit(self, writer: JabberWriter<S>) -> JabberStream<S> { - JabberStream { - reader: self, - writer, - } - } - - fn into_inner(self) -> Reader<ReadHalf<S>> { - self.0 - } -} - -impl<S> JabberReader<S> -where - S: AsyncRead + Unpin, -{ - pub async fn try_close(&mut self) -> Result<()> { - self.read_end_tag().await?; - Ok(()) - } -} - -impl<S> std::ops::Deref for JabberReader<S> { - type Target = Reader<ReadHalf<S>>; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl<S> std::ops::DerefMut for JabberReader<S> { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -pub struct JabberWriter<S>(Writer<WriteHalf<S>>); - -impl<S> JabberWriter<S> { - fn new(writer: Writer<WriteHalf<S>>) -> Self { - Self(writer) - } - - fn unsplit(self, reader: JabberReader<S>) -> JabberStream<S> { - JabberStream { - reader, - writer: self, - } - } - - fn into_inner(self) -> Writer<WriteHalf<S>> { - self.0 - } -} - -impl<S> JabberWriter<S> -where - S: AsyncWrite + Unpin + Send, -{ - pub async fn try_close(&mut self) -> Result<()> { - self.write_end().await?; - Ok(()) - } -} - -impl<S> std::ops::Deref for JabberWriter<S> { - type Target = Writer<WriteHalf<S>>; +#[cfg(not(target_arch = "wasm32"))] +pub use tcp::{JabberReader, JabberStream, JabberWriter}; +#[cfg(target_arch = "wasm32")] +pub use ws::{JabberReader, JabberStream, JabberWriter}; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl<S> std::ops::DerefMut for JabberWriter<S> { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - -impl<S> JabberStream<S> -where - S: AsyncRead + AsyncWrite + Unpin + Send + std::fmt::Debug, - JabberStream<S>: std::fmt::Debug, -{ +impl JabberStream { #[instrument] - pub async fn sasl(mut self, mechanisms: Mechanisms, sasl_config: Arc<SASLConfig>) -> Result<S> { + pub async fn sasl( + mut self, + mechanisms: Mechanisms, + sasl_config: Arc<SASLConfig>, + ) -> Result<Connection> { let sasl = SASLClient::new(sasl_config); let mut offered_mechs: Vec<&Mechname> = Vec::new(); for mechanism in &mechanisms.mechanisms { @@ -212,16 +133,24 @@ where } } } - let writer = self.writer.into_inner().into_inner(); - let reader = self.reader.into_inner().into_inner(); - let stream = reader.unsplit(writer); - Ok(stream) + #[cfg(not(target_arch = "wasm32"))] + { + let writer = self.writer.into_inner().into_inner(); + let reader = self.reader.into_inner().into_inner(); + let stream = reader.unsplit(writer); + Ok(stream) + } + #[cfg(target_arch = "wasm32")] + { + let writer = self.writer.into_inner().into_inner(); + Ok(Connection(writer)) + } } #[instrument] - pub async fn bind(mut self, jid: &mut JID) -> Result<Self> { - let iq_id = nanoid::nanoid!(); - if let Some(resource) = &jid.resourcepart { + pub async fn bind(mut self, jid: &JID) -> Result<(BoundJabberStream, FullJID)> { + let iq_id = uuid::Uuid::new_v4().to_string(); + if let Some(resource) = &jid.resourcepart() { let iq = Iq { from: None, id: iq_id.clone(), @@ -248,8 +177,7 @@ where })), errors: _, } if id == iq_id => { - *jid = new_jid; - return Ok(self); + return Ok((self.to_bound_jabber(), new_jid)); } Iq { from: _, @@ -291,8 +219,7 @@ where })), errors: _, } if id == iq_id => { - *jid = new_jid; - return Ok(self); + return Ok((self.to_bound_jabber(), new_jid)); } Iq { from: _, @@ -312,8 +239,49 @@ where } } + #[cfg(target_arch = "wasm32")] #[instrument] - pub async fn start_stream(connection: S, server: &mut String) -> Result<Self> { + pub async fn start_stream(connection: Connection, server: &mut String) -> Result<Self> { + // client to server + let writer = connection.0; + let (onmessage, reader) = WebSocketOnMessageRead::new(); + writer.set_onmessage(Some(onmessage.as_ref().unchecked_ref())); + onmessage.forget(); + let mut reader = JabberReader::new(Reader::new_unendable(reader)); + let mut writer = JabberWriter::new(Writer::<WebSocket>::new_unendable(writer)); + + // open element + let open = Open { + from: None, + id: None, + lang: None, + version: Some("1.0".to_string()), + to: Some( + JID::from_str(server.as_ref()) + .map_err(|e| Error::JID(e.into()))? + .try_into()?, + ), + }; + writer.write(&open).await?; + + // server to client + + // may or may not send a declaration + let _decl = reader.read_prolog().await?; + + // receive open element and validate + let open: Open = reader.read().await?; + debug!("got open: {:?}", open); + if let Some(from) = open.from { + *server = from.to_string(); + } + + Ok(Self { reader, writer }) + } + + #[cfg(not(target_arch = "wasm32"))] + #[instrument] + pub async fn start_stream(connection: Connection, server: &mut String) -> Result<Self> { // client to server let (reader, writer) = tokio::io::split(connection); let mut reader = JabberReader::new(Reader::new(reader)); @@ -325,7 +293,9 @@ where // opening stream element let stream = Stream::new_client( None, - JID::from_str(server.as_ref())?, + JID::from_str(server.as_ref()) + .map_err(|e| Error::JID(e.into()))? + .try_into()?, None, "en".to_string(), ); @@ -354,20 +324,28 @@ where Ok((features, self)) } - pub fn into_inner(self) -> S { - self.reader + pub fn into_inner(self) -> Connection { + let writer = self.writer.into_inner(); + + #[cfg(not(target_arch = "wasm32"))] + let output = self + .reader .into_inner() .into_inner() - .unsplit(self.writer.into_inner().into_inner()) + .unsplit(writer.into_inner()); + + #[cfg(target_arch = "wasm32")] + let output = Connection(writer.into_inner()); + + output } pub async fn send_stanza(&mut self, stanza: &Stanza) -> Result<()> { self.writer.write(stanza).await?; Ok(()) } -} -impl JabberStream<Unencrypted> { + #[cfg(not(target_arch = "wasm32"))] #[instrument] pub async fn starttls(mut self, domain: impl AsRef<str> + std::fmt::Debug) -> Result<Tls> { self.writer @@ -381,34 +359,23 @@ impl JabberStream<Unencrypted> { .into_inner() .into_inner() .unsplit(self.writer.into_inner().into_inner()); - if let Ok(tls_stream) = tokio_native_tls::TlsConnector::from(connector) - .connect(domain.as_ref(), stream) - .await - { - return Ok(tls_stream); - } else { - return Err(Error::Connection); + match stream { + Connection::Encrypted(_tls_stream) => return Err(Error::AlreadyTls), + Connection::Unencrypted(tcp_stream) => { + if let Ok(tls_stream) = tokio_native_tls::TlsConnector::from(connector) + .connect(domain.as_ref(), tcp_stream) + .await + { + return Ok(tls_stream); + } else { + return Err(Error::Connection); + } + } } } } - -impl std::fmt::Debug for JabberStream<Tls> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Jabber") - .field("connection", &"tls") - .finish() - } -} - -impl std::fmt::Debug for JabberStream<Unencrypted> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Jabber") - .field("connection", &"unencrypted") - .finish() - } -} - #[cfg(test)] + mod tests { use test_log::test; diff --git a/luz/src/jabber_stream/bound_stream.rs b/luz/src/jabber_stream/bound_stream.rs index 25b79ff..74ced14 100644 --- a/luz/src/jabber_stream/bound_stream.rs +++ b/luz/src/jabber_stream/bound_stream.rs @@ -1,87 +1,76 @@ use std::ops::{Deref, DerefMut}; -use tokio::io::{AsyncRead, AsyncWrite}; - use super::{JabberReader, JabberStream, JabberWriter}; -pub struct BoundJabberStream<S>(JabberStream<S>); +pub struct BoundJabberStream(JabberStream); -impl<S> Deref for BoundJabberStream<S> -where - S: AsyncWrite + AsyncRead + Unpin + Send, -{ - type Target = JabberStream<S>; +impl Deref for BoundJabberStream { + type Target = JabberStream; fn deref(&self) -> &Self::Target { &self.0 } } -impl<S> DerefMut for BoundJabberStream<S> -where - S: AsyncWrite + AsyncRead + Unpin + Send, -{ +impl DerefMut for BoundJabberStream { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -impl<S> BoundJabberStream<S> { - pub fn split(self) -> (BoundJabberReader<S>, BoundJabberWriter<S>) { +impl BoundJabberStream { + pub fn split(self) -> (BoundJabberReader, BoundJabberWriter) { let (reader, writer) = self.0.split(); (BoundJabberReader(reader), BoundJabberWriter(writer)) } } -pub struct BoundJabberReader<S>(JabberReader<S>); +pub struct BoundJabberReader(JabberReader); -impl<S> BoundJabberReader<S> { - pub fn unsplit(self, writer: BoundJabberWriter<S>) -> BoundJabberStream<S> { +impl BoundJabberReader { + pub fn unsplit(self, writer: BoundJabberWriter) -> BoundJabberStream { BoundJabberStream(self.0.unsplit(writer.0)) } } -impl<S> std::ops::Deref for BoundJabberReader<S> { - type Target = JabberReader<S>; +impl std::ops::Deref for BoundJabberReader { + type Target = JabberReader; fn deref(&self) -> &Self::Target { &self.0 } } -impl<S> std::ops::DerefMut for BoundJabberReader<S> { +impl std::ops::DerefMut for BoundJabberReader { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -pub struct BoundJabberWriter<S>(JabberWriter<S>); +pub struct BoundJabberWriter(JabberWriter); -impl<S> BoundJabberWriter<S> { - pub fn unsplit(self, reader: BoundJabberReader<S>) -> BoundJabberStream<S> { +impl BoundJabberWriter { + pub fn unsplit(self, reader: BoundJabberReader) -> BoundJabberStream { BoundJabberStream(self.0.unsplit(reader.0)) } } -impl<S> std::ops::Deref for BoundJabberWriter<S> { - type Target = JabberWriter<S>; +impl std::ops::Deref for BoundJabberWriter { + type Target = JabberWriter; fn deref(&self) -> &Self::Target { &self.0 } } -impl<S> std::ops::DerefMut for BoundJabberWriter<S> { +impl std::ops::DerefMut for BoundJabberWriter { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -impl<S> JabberStream<S> -where - S: AsyncWrite + AsyncRead + Unpin + Send, -{ - pub fn to_bound_jabber(self) -> BoundJabberStream<S> { +impl JabberStream { + pub fn to_bound_jabber(self) -> BoundJabberStream { BoundJabberStream(self) } } diff --git a/luz/src/jabber_stream/tcp.rs b/luz/src/jabber_stream/tcp.rs new file mode 100644 index 0000000..550c308 --- /dev/null +++ b/luz/src/jabber_stream/tcp.rs @@ -0,0 +1,103 @@ +use peanuts::Loggable; +use peanuts::{Reader, Writer}; +use tokio::io::{ReadHalf, WriteHalf}; + +use crate::{Connection, Result}; + +// open stream (streams started) +#[derive(Debug)] +pub struct JabberStream { + pub(super) reader: JabberReader, + pub(super) writer: JabberWriter, +} + +impl JabberStream { + pub fn split(self) -> (JabberReader, JabberWriter) { + let reader = self.reader; + let writer = self.writer; + (reader, writer) + } +} + +#[derive(Debug)] +pub struct JabberReader(Reader<ReadHalf<Connection>>); + +impl JabberReader { + // TODO: consider taking a readhalf and creating peanuts::Reader here, only one inner + pub fn new(reader: Reader<ReadHalf<Connection>>) -> Self { + Self(reader) + } + + pub fn unsplit(self, writer: JabberWriter) -> JabberStream { + JabberStream { + reader: self, + writer, + } + } + + pub fn into_inner(self) -> Reader<ReadHalf<Connection>> { + self.0 + } +} + +impl JabberReader { + pub async fn try_close(&mut self) -> Result<()> { + self.read_end_tag().await?; + Ok(()) + } +} + +impl std::ops::Deref for JabberReader { + type Target = Reader<ReadHalf<Connection>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for JabberReader { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[derive(Debug)] +pub struct JabberWriter(Writer<Loggable<WriteHalf<Connection>>>); + +impl JabberWriter { + pub fn new(writer: Writer<Loggable<WriteHalf<Connection>>>) -> Self { + Self(writer) + } + + pub fn unsplit(self, reader: JabberReader) -> JabberStream { + JabberStream { + reader, + writer: self, + } + } + + pub fn into_inner(self) -> Writer<Loggable<WriteHalf<Connection>>> { + self.0 + } +} + +impl JabberWriter { + pub async fn try_close(&mut self) -> Result<()> { + self.write_end().await?; + Ok(()) + } +} + +impl std::ops::Deref for JabberWriter { + type Target = Writer<Loggable<WriteHalf<Connection>>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for JabberWriter { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} diff --git a/luz/src/jabber_stream/ws.rs b/luz/src/jabber_stream/ws.rs new file mode 100644 index 0000000..72801e6 --- /dev/null +++ b/luz/src/jabber_stream/ws.rs @@ -0,0 +1,104 @@ +use peanuts::WebSocketOnMessageRead; +use peanuts::{Reader, Writer}; +use stanza::rfc_7395::Close; +use web_sys::WebSocket; + +use crate::Result; + +// open stream (streams started) +#[derive(Debug)] +pub struct JabberStream { + pub(super) reader: JabberReader, + pub(super) writer: JabberWriter, +} + +impl JabberStream { + pub fn split(self) -> (JabberReader, JabberWriter) { + let reader = self.reader; + let writer = self.writer; + (reader, writer) + } +} + +#[derive(Debug)] +pub struct JabberReader(Reader<WebSocketOnMessageRead>); + +impl JabberReader { + pub fn new(reader: Reader<WebSocketOnMessageRead>) -> Self { + Self(reader) + } + + pub fn unsplit(self, writer: JabberWriter) -> JabberStream { + JabberStream { + reader: self, + writer, + } + } + + pub fn into_inner(self) -> Reader<WebSocketOnMessageRead> { + self.0 + } +} + +impl JabberReader { + pub async fn try_close(&mut self) -> Result<()> { + let _close: Close = self.read().await?; + Ok(()) + } +} + +impl std::ops::Deref for JabberReader { + type Target = Reader<WebSocketOnMessageRead>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for JabberReader { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[derive(Debug)] +pub struct JabberWriter(Writer<WebSocket>); + +impl JabberWriter { + pub fn new(writer: Writer<WebSocket>) -> Self { + Self(writer) + } + + pub fn unsplit(self, reader: JabberReader) -> JabberStream { + JabberStream { + reader, + writer: self, + } + } + + pub fn into_inner(self) -> Writer<WebSocket> { + self.0 + } +} + +impl JabberWriter { + pub async fn try_close(&mut self) -> Result<()> { + let close = Close::default(); + self.write(&close).await?; + Ok(()) + } +} + +impl std::ops::Deref for JabberWriter { + type Target = Writer<WebSocket>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for JabberWriter { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} diff --git a/stanza/Cargo.toml b/stanza/Cargo.toml index 69fabc2..ec68499 100644 --- a/stanza/Cargo.toml +++ b/stanza/Cargo.toml @@ -4,13 +4,14 @@ version = "0.1.0" edition = "2021" [dependencies] -peanuts = { version = "0.1.0", path = "../../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 = [] +rfc_7395 = [] xep_0004 = [] xep_0030 = [] xep_0059 = [] @@ -19,8 +20,10 @@ xep_0084 = [] xep_0115 = [] xep_0128 = ["xep_0004"] xep_0131 = [] +xep_0156 = ["dep:chrono"] xep_0172 = [] xep_0199 = [] xep_0203 = ["dep:chrono"] +xep_0297 = ["xep_0203"] xep_0300 = [] xep_0390 = ["xep_0300"] diff --git a/stanza/src/bind.rs b/stanza/src/bind.rs index f72c510..0f0f681 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 jid::FullJID; +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(), @@ -57,10 +54,10 @@ impl IntoElement for BindType { // minLength 8 maxLength 3071 #[derive(Clone, Debug)] -pub struct FullJidType(pub JID); +pub struct FullJidType(pub FullJID); 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 50884aa..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}, @@ -18,7 +15,10 @@ use crate::roster; use crate::xep_0030::{self, info, items}; #[cfg(feature = "xep_0060")] -use crate::xep_0060::pubsub::{self, Pubsub}; +use crate::xep_0060::{ + self, + pubsub::{self, Pubsub}, +}; #[cfg(feature = "xep_0199")] use crate::xep_0199::{self, Ping}; @@ -47,6 +47,8 @@ pub enum Query { DiscoItems(items::Query), #[cfg(feature = "xep_0060")] Pubsub(Pubsub), + #[cfg(feature = "xep_0060")] + PubsubOwner(xep_0060::owner::Pubsub), #[cfg(feature = "xep_0199")] Ping(Ping), #[cfg(feature = "rfc_6121")] @@ -55,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")] @@ -74,13 +76,17 @@ impl FromElement for Query { } #[cfg(feature = "xep_0060")] (Some(pubsub::XMLNS), "pubsub") => Ok(Query::Pubsub(Pubsub::from_element(element)?)), + #[cfg(feature = "xep_0060")] + (Some(xep_0060::owner::XMLNS), "pubsub") => Ok(Query::PubsubOwner( + xep_0060::owner::Pubsub::from_element(element)?, + )), _ => Ok(Query::Unsupported), } } } 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")] @@ -95,12 +101,14 @@ impl IntoElement for Query { Query::DiscoItems(query) => query.builder(), #[cfg(feature = "xep_0060")] Query::Pubsub(pubsub) => pubsub.builder(), + #[cfg(feature = "xep_0060")] + Query::PubsubOwner(pubsub) => pubsub.builder(), } } } 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)?; @@ -125,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..13ee6f1 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; @@ -14,6 +11,8 @@ use crate::xep_0131::Headers; use crate::xep_0172::Nick; #[cfg(feature = "xep_0203")] use crate::xep_0203::Delay; +#[cfg(feature = "xep_0297")] +use crate::xep_0297::Forwarded; use super::XMLNS; @@ -37,10 +36,12 @@ pub struct Message { pub nick: Option<Nick>, #[cfg(feature = "xep_0060")] pub event: Option<Event>, + #[cfg(feature = "xep_0297")] + pub forwarded: Option<Forwarded>, } 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)?; @@ -66,6 +67,9 @@ impl FromElement for Message { #[cfg(feature = "xep_0060")] let event = element.child_opt()?; + #[cfg(feature = "xep_0297")] + let forwarded = element.child_opt()?; + Ok(Message { from, id, @@ -83,12 +87,14 @@ impl FromElement for Message { nick, #[cfg(feature = "xep_0060")] event, + #[cfg(feature = "xep_0297")] + forwarded, }) } } 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()) @@ -117,6 +123,9 @@ impl IntoElement for Message { #[cfg(feature = "xep_0060")] let builder = builder.push_child_opt(self.event.clone()); + #[cfg(feature = "xep_0297")] + let builder = builder.push_child_opt(self.forwarded.clone()); + builder } } @@ -166,7 +175,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 +187,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 +201,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 +213,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 +227,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 +239,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 569b891..8f9b788 100644 --- a/stanza/src/lib.rs +++ b/stanza/src/lib.rs @@ -2,6 +2,8 @@ use peanuts::declaration::VersionInfo; pub mod bind; pub mod client; +#[cfg(feature = "rfc_7395")] +pub mod rfc_7395; #[cfg(feature = "rfc_6121")] pub mod roster; pub mod sasl; @@ -23,12 +25,16 @@ 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")] pub mod xep_0199; #[cfg(feature = "xep_0203")] pub mod xep_0203; +#[cfg(feature = "xep_0297")] +pub mod xep_0297; #[cfg(feature = "xep_0300")] pub mod xep_0300; #[cfg(feature = "xep_0390")] diff --git a/stanza/src/rfc_7395.rs b/stanza/src/rfc_7395.rs new file mode 100644 index 0000000..73e947d --- /dev/null +++ b/stanza/src/rfc_7395.rs @@ -0,0 +1,90 @@ +use jid::BareJID; +use peanuts::{Element, ElementBuilder, FromElement, IntoElement}; + +pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-framing"; + +#[derive(Debug)] +pub struct Open { + pub from: Option<BareJID>, + pub to: Option<BareJID>, + pub id: Option<String>, + pub version: Option<String>, + pub lang: Option<String>, +} + +impl FromElement for Open { + fn from_element(mut element: Element) -> std::result::Result<Self, peanuts::DeserializeError> { + element.check_name("open")?; + element.check_namespace(XMLNS)?; + + let from = element.attribute_opt("from")?; + let to = element.attribute_opt("to")?; + let id = element.attribute_opt("id")?; + let version = element.attribute_opt("version")?; + let lang = element.attribute_opt_namespaced("lang", peanuts::XML_NS)?; + + Ok(Open { + from, + to, + id, + version, + lang, + }) + } +} + +impl IntoElement for Open { + fn builder(&self) -> ElementBuilder { + Element::builder("open", Some(XMLNS.to_string())) + .push_attribute_opt("to", self.to.clone()) + .push_attribute_opt("from", self.from.clone()) + .push_attribute_opt("id", self.id.clone()) + .push_attribute_opt("version", self.version.clone()) + .push_attribute_opt_namespaced(peanuts::XML_NS, "lang", self.lang.clone()) + } +} + +#[derive(Debug, Default)] +pub struct Close { + pub from: Option<BareJID>, + pub to: Option<BareJID>, + pub id: Option<String>, + pub version: Option<String>, + pub lang: Option<String>, + pub see_other_uri: Option<String>, +} + +impl FromElement for Close { + fn from_element(mut element: Element) -> std::result::Result<Self, peanuts::DeserializeError> { + element.check_name("close")?; + element.check_namespace(XMLNS)?; + + let from = element.attribute_opt("from")?; + let to = element.attribute_opt("to")?; + let id = element.attribute_opt("id")?; + let version = element.attribute_opt("version")?; + let lang = element.attribute_opt_namespaced("lang", peanuts::XML_NS)?; + let see_other_uri = element.attribute_opt("see-other-uri")?; + + Ok(Close { + from, + to, + id, + version, + lang, + see_other_uri, + }) + } +} + +impl IntoElement for Close { + fn builder(&self) -> ElementBuilder { + Element::builder("close", Some(XMLNS.to_string())) + .push_attribute_opt("to", self.to.clone()) + .push_attribute_opt("from", self.from.clone()) + .push_attribute_opt("id", self.id.clone()) + .push_attribute_opt("version", self.version.clone()) + .push_attribute_opt_namespaced(peanuts::XML_NS, "lang", self.lang.clone()) + .push_attribute_opt("see-other-uri", self.see_other_uri.clone()) + } +} diff --git a/stanza/src/roster.rs b/stanza/src/roster.rs index 0181193..dcbf017 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 jid::BareJID; +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()) @@ -41,7 +38,7 @@ pub struct Item { /// signals subscription sub-states (server only) pub ask: bool, /// uniquely identifies item - pub jid: JID, + pub jid: BareJID, /// handle that is determined by user, not contact pub name: Option<String>, /// state of the presence subscription @@ -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 732a826..e2f4f9b 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 jid::BareJID; +use peanuts::{Element, ElementBuilder, FromElement, IntoElement}; use thiserror::Error; use crate::bind; @@ -19,8 +18,8 @@ pub const XMLNS: &str = "http://etherx.jabber.org/streams"; // #[peanuts(xmlns = XMLNS)] #[derive(Debug)] pub struct Stream { - pub from: Option<JID>, - to: Option<JID>, + pub from: Option<BareJID>, + to: Option<BareJID>, id: Option<String>, version: Option<String>, // TODO: lang enum @@ -59,14 +58,14 @@ impl IntoElement for Stream { .push_attribute_opt("from", self.from.clone()) .push_attribute_opt("id", self.id.clone()) .push_attribute_opt("version", self.version.clone()) - .push_attribute_opt_namespaced(peanuts::XML_NS, "to", self.lang.clone()) + .push_attribute_opt_namespaced(peanuts::XML_NS, "lang", self.lang.clone()) } } impl<'s> Stream { pub fn new( - from: Option<JID>, - to: Option<JID>, + from: Option<BareJID>, + to: Option<BareJID>, id: Option<String>, version: Option<String>, lang: Option<String>, @@ -82,7 +81,12 @@ impl<'s> Stream { /// For initial stream headers, the initiating entity SHOULD include the 'xml:lang' attribute. /// For privacy, it is better to not set `from` when sending a client stanza over an unencrypted connection. - pub fn new_client(from: Option<JID>, to: JID, id: Option<String>, lang: String) -> Self { + pub fn new_client( + from: Option<BareJID>, + to: BareJID, + id: Option<String>, + lang: String, + ) -> Self { Self { from, to: Some(to), @@ -165,7 +169,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 +202,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 1fedc60..4876bf5 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 jid::{BareJID, JID}; +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()) @@ -88,11 +85,11 @@ impl IntoElement for Affiliations { #[derive(Clone, Debug)] pub struct Affiliation { affiliation: AffiliationType, - jid: JID, + jid: BareJID, } 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,19 +188,19 @@ 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()) } } #[derive(Clone, Debug)] pub struct Delete { - node: String, - redirect: Option<Redirect>, + pub node: String, + pub redirect: Option<Redirect>, } 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_0297.rs b/stanza/src/xep_0297.rs new file mode 100644 index 0000000..4dc8a26 --- /dev/null +++ b/stanza/src/xep_0297.rs @@ -0,0 +1,69 @@ +use peanuts::{Element, FromElement, IntoElement}; + +use crate::{ + client::{self, iq::Iq, message::Message, presence::Presence}, + xep_0203::Delay, +}; + +pub const XMLNS: &str = "urn:xmpp:forward:0"; + +#[derive(Clone, Debug)] +pub struct Forwarded { + delay: Option<Delay>, + stanza: Option<Box<Stanza>>, +} + +impl FromElement for Forwarded { + fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("forwarded")?; + element.check_namespace(XMLNS)?; + + let delay = element.pop_child_opt()?; + let stanza = element.pop_child_opt()?; + let stanza = stanza.map(|stanza| Box::new(stanza)); + + Ok(Self { delay, stanza }) + } +} + +impl IntoElement for Forwarded { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("forwarded", Some(XMLNS)) + .push_child_opt(self.delay.clone()) + .push_child_opt(self.stanza.clone().map(|stanza| *stanza)) + } +} + +#[derive(Clone, Debug)] +pub enum Stanza { + Message(Message), + Presence(Presence), + Iq(Iq), + // TODO: raw elements are received with reads. + // Raw(Element), +} + +impl FromElement for Stanza { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + match element.identify() { + (Some(client::XMLNS), "message") => { + Ok(Stanza::Message(Message::from_element(element)?)) + } + (Some(client::XMLNS), "presence") => { + Ok(Stanza::Presence(Presence::from_element(element)?)) + } + (Some(client::XMLNS), "iq") => Ok(Stanza::Iq(Iq::from_element(element)?)), + _ => Err(peanuts::DeserializeError::UnexpectedElement(element)), + } + } +} + +impl IntoElement for Stanza { + fn builder(&self) -> peanuts::ElementBuilder { + match self { + Stanza::Message(message) => message.builder(), + Stanza::Presence(presence) => presence.builder(), + Stanza::Iq(iq) => iq.builder(), + } + } +} 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()) } } |