diff options
Diffstat (limited to '')
97 files changed, 1789 insertions, 1237 deletions
diff --git a/.cargo/config.toml b/.cargo/config.toml index c91c3f3..313fa6a 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,6 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [net] git-fetch-with-cli = true @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + /target /Cargo.lock filamento.db diff --git a/.helix/languages.toml b/.helix/languages.toml index 7662fff..6e3ac7b 100644 --- a/.helix/languages.toml +++ b/.helix/languages.toml @@ -1,9 +1,14 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [language-server.rust-analyzer] command = "rust-analyzer" -environment = { "DATABASE_URL" = "sqlite://filamento/filamento.db" } +# 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"] } +# config = { 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", "stanza/xep_0297", "stanza/xep_0280", "stanza/xep_0334"] } # "sqlx/sqlite", "sqlx/runtime-tokio", "sqlx/uuid", "sqlx/chrono", "jid/sqlx", @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [workspace] resolver = "2" diff --git a/LICENSE b/LICENSE deleted file mode 100644 index be3f7b2..0000000 --- a/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - <one line to give the program's name and a brief idea of what it does.> - Copyright (C) <year> <name of author> - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see <https://www.gnu.org/licenses/>. - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -<https://www.gnu.org/licenses/>. diff --git a/LICENSES/AGPL-3.0-or-later.txt b/LICENSES/AGPL-3.0-or-later.txt new file mode 100644 index 0000000..0c97efd --- /dev/null +++ b/LICENSES/AGPL-3.0-or-later.txt @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>. @@ -1,3 +1,9 @@ +<!-- +SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> + +SPDX-License-Identifier: AGPL-3.0-or-later +--> + # xmpp thingies ## crates: @@ -168,3 +174,5 @@ - [ ] polls - [ ] privacy lists/circles - [ ] pubsub node items filter for each person +- [ ] unreadification, notify somebody that you unread their message + - and extended, settings for this. like if you want to have to manually mark as read, etc. @@ -1,3 +1,9 @@ +<!-- +SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> + +SPDX-License-Identifier: AGPL-3.0-or-later +--> + # TODO ## next diff --git a/filamento/.cargo/config.toml b/filamento/.cargo/config.toml index 319101a..6166dc4 100644 --- a/filamento/.cargo/config.toml +++ b/filamento/.cargo/config.toml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [build] rustflags = [ # LLD (shipped with the Rust toolchain) is used as the default linker diff --git a/filamento/.gitignore b/filamento/.gitignore index 52acf71..bcab57c 100644 --- a/filamento/.gitignore +++ b/filamento/.gitignore @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + filamento.db ./files/ .sqlx/ diff --git a/filamento/Cargo.toml b/filamento/Cargo.toml index 7d7af0c..246ee13 100644 --- a/filamento/Cargo.toml +++ b/filamento/Cargo.toml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [package] name = "filamento" version = "0.1.0" @@ -35,6 +39,7 @@ uuid = { workspace = true, features = ["v4"] } rusqlite = { git = "https://github.com/Spxg/rusqlite.git", branch = "wasm-demo", features = [ "uuid", "chrono", + "trace", ] } tracing = { workspace = true } chrono = { workspace = true } @@ -52,6 +57,7 @@ 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", @@ -68,6 +74,7 @@ wasm-bindgen-futures = { workspace = true } rusqlite = { git = "https://github.com/Spxg/rusqlite.git", branch = "wasm-demo", features = [ "uuid", "chrono", + "trace", "precompiled-wasm", ] } tokio_with_wasm = { workspace = true, features = ["sync", "time", "rt"] } diff --git a/filamento/README.md b/filamento/README.md index 57b4135..ba906b2 100644 --- a/filamento/README.md +++ b/filamento/README.md @@ -1,3 +1,9 @@ +<!-- +SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> + +SPDX-License-Identifier: AGPL-3.0-or-later +--> + # filament a high-level xmpp chat client using luz diff --git a/filamento/examples/example.rs b/filamento/examples/example.rs index 65fe166..c330459 100644 --- a/filamento/examples/example.rs +++ b/filamento/examples/example.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + // use std::{path::Path, str::FromStr, sync::Arc, time::Duration}; // use filamento::{Client, db::Db, files::FileStore}; diff --git a/filamento/migrations/1.sql b/filamento/migrations/1.sql index 502c5a9..1b40d89 100644 --- a/filamento/migrations/1.sql +++ b/filamento/migrations/1.sql @@ -1,9 +1,12 @@ +-- SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +-- +-- SPDX-License-Identifier: AGPL-3.0-or-later + PRAGMA foreign_keys = on; -- a user jid will never change, only a chat user will change --- TODO: avatar, nick, etc. create table if not exists users( - -- TODO: enforce bare jid + -- bare jid jid text primary key not null, nick text, avatar text, @@ -12,28 +15,26 @@ create table if not exists users( -- TODO: last_seen ); --- -- links to messages, jabber users, stores jid history, etc. --- create table identities( --- id text primary key not null --- ); - --- create table identities_users( --- id text not null, --- jid text not null, --- -- whichever has the newest timestamp is the active one. --- -- what to do when somebody moves, but then the old jid is used again without having explicitly moved back? create new identity to assign ownership to? --- -- merging of identities? --- activated_timestamp not null, --- foreign key(id) references identities(id), --- foreign key(jid) references users(jid), --- primary key(activated timestamp, id, jid) --- ); - -create table if not exists resources( - bare_jid text not null, - resource text not null, - foreign key(bare_jid) references users(jid), - primary key(bare_jid, resource) +-- links to messages, jabber users, stores jid history, etc. +-- every identity requires a user, so imported messages must be assigned to an existing jabber account. +create table if not exists identities( + id text primary key not null, + -- each time a user moves, their identity's primary jid is updated, and the new jid is added to the identities log + primary_jid text not null unique, + foreign key(primary_jid) references users(jid) +); +-- this also allows e.g. mucs with imported histories to assign messages temporarily to muc-generated temporary users, then send user move events to assign message ownership once that person joins the new group chat with a jabber account. + +-- identities log basically. +create table if not exists identities_users( + id text not null, + jid text not null, + -- what to do when somebody moves, but then the old jid is used again without having explicitly moved back? create new identity to assign ownership to? + -- merging of identities? + activated_timestamp not null, + foreign key(id) references identities(id), + foreign key(jid) references users(jid), + primary key(id, jid) ); -- enum for subscription state @@ -71,7 +72,8 @@ create table if not exists chats ( id text primary key not null, have_chatted bool not null, correspondent text not null unique, - foreign key(correspondent) references users(jid) + -- TODO: how many messages to store locally/rely on mam, whether to auto-download/store media too. + foreign key(correspondent) references identities(id) ); -- enum for subscription state @@ -92,27 +94,17 @@ create table if not exists messages ( -- channel_id uuid, -- check ((chat_id == null) <> (channel_id == null)), -- check ((chat_id == null) or (channel_id == null)), - -- user is the current "owner" of the message -- TODO: queued messages offline - -- TODO: timestamp timestamp text not null, - -- TODO: icky - -- the user to show it coming from (not necessarily the original sender) - -- from_identity text not null, - -- original sender details (only from jabber supported for now) - from_jid text not null, - -- resource can be null - from_resource text, - -- check (from_jid != original_sender), + -- the identity to show it coming from (not necessarily the original sender) + from_identity text not null, + + -- TODO: unread message count, read bool not null, foreign key(delivery) references delivery(state), - -- TODO: from can be either a jid, a moved jid (for when a contact moves, save original sender jid/user but link to new user), or imported (from another service (save details), linked to new user) - -- TODO: read bool not null, foreign key(chat_id) references chats(id) on delete cascade, - -- foreign key(from_identity) references identities(id), - foreign key(from_jid) references users(jid), - foreign key(from_jid, from_resource) references resources(bare_jid, resource) + foreign key(from_identity) references identities(id) ); -- enum for subscription state @@ -139,3 +131,17 @@ create table if not exists capability_hash_nodes ( ); insert into capability_hash_nodes ( node, capabilities ) values ('https://bunny.garden/filamento#mSavc/SLnHm8zazs5RlcbD/iXoc=', 'aHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvY2Fwcx9odHRwOi8vamFiYmVyLm9yZy9wcm90b2NvbC9kaXNjbyNpbmZvH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL2Rpc2NvI2l0ZW1zH2h0dHA6Ly9qYWJiZXIub3JnL3Byb3RvY29sL25pY2sfaHR0cDovL2phYmJlci5vcmcvcHJvdG9jb2wvbmljaytub3RpZnkfHGNsaWVudB9wYx8fZmlsYW1lbnRvIDAuMS4wHx4cHA==') on conflict do nothing; + +-- TODO: later maybe just a full stanza log period? +create table if not exists message_stanzas ( + id integer primary key not null, + raw text not null, + timestamp text not null, + -- should be 1 to many as the same original stanza could technically have multiple envelopes...(e.g. message sync, mam), also makes making dangling stanzas not possible easier when modeling the relationship this way. + envelope_of integer, + linked_message text, + -- check that stanza is either linked to another stanza, or a message (no dangling stanzas) + check ((envelope_of == null) <> (linked_message == null)), + foreign key(linked_message) references messages(id), + foreign key(envelope_of) references message_stanzas(id) +) diff --git a/filamento/src/avatar.rs b/filamento/src/avatar.rs index a6937df..df30a6a 100644 --- a/filamento/src/avatar.rs +++ b/filamento/src/avatar.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + #[derive(Clone, Debug)] pub struct Metadata { pub bytes: u32, diff --git a/filamento/src/caps.rs b/filamento/src/caps.rs index 43f1cf4..305c9b7 100644 --- a/filamento/src/caps.rs +++ b/filamento/src/caps.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use base64::{Engine, prelude::BASE64_STANDARD}; @@ -377,7 +381,7 @@ pub fn node_to_hash(node: String) -> Result<Hash, HashNodeConversionError> { #[cfg(test)] mod tests { - use peanuts::{Writer, element::IntoElement, loggable::Loggable}; + use peanuts::Writer; use stanza::{ xep_0004::{Field, FieldType, Value, X, XType}, xep_0030::info::{Feature, Identity}, diff --git a/filamento/src/chat.rs b/filamento/src/chat.rs index 5f58866..687da82 100644 --- a/filamento/src/chat.rs +++ b/filamento/src/chat.rs @@ -1,7 +1,11 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::fmt::{Display, Write}; use chrono::{DateTime, Utc}; -use jid::JID; +use jid::{BareJID, JID}; use rusqlite::{ ToSql, types::{FromSql, ToSqlOutput, Value}, @@ -13,17 +17,43 @@ use uuid::Uuid; #[cfg_attr(feature = "reactive_stores", derive(reactive_stores::Store))] pub struct Message { pub id: Uuid, - // does not contain full user information - // bare jid (for now) - pub from: JID, + /// jid of user currently tied to the original sender, updated by jid move event. original sender can be found within the source data. + pub from: BareJID, pub delivery: Option<Delivery>, pub timestamp: DateTime<Utc>, - // TODO: originally_from - // TODO: message edits - // TODO: message timestamp + // TODO: message edits. message edits will need to include the edit and the source stanza that caused the edit. + /// original message sources (XMPP, imported, etc.). cannot change, but may be deleted or have information redacted. can be multiple because a message may be updated, have reactions appended to it, delivery receipt, user moved, etc. + pub source: Vec<Source>, pub body: Body, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Source { + XMPP(XMPPMessage), + // TODO: imported information + Imported, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct XMPPMessage { + // TODO: upon software updates, upgrade all message and xmppmessage structs with missed data from old XMPP raw messages. maybe just don't store parsed message in xmpp message, have it be a method + /// the raw data received from the xml stream + pub raw: String, + /// the timestamp the client received the stanza, or associated with the <delay> in the envelope. + pub timestamp: DateTime<Utc>, + /// if message was received in a carbon envolope, forwarded, or in an encrypted envelope, etc., the full xmpp message it came from is included here, linked. there could technically be multiple envelopes (same stanza received through multiple envelopes). + pub envelopes: Vec<XMPPMessage>, +} + +impl XMPPMessage { + // TODO: syncify + // pub async fn parsed(&self) -> stanza::client::message::Message { + // let reader = peanuts::Reader::new(peanuts::ReadableString(self.raw.to_string())); + // let message = reader.read().await?; + // message + // } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Delivery { @@ -97,7 +127,7 @@ pub struct Body { #[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, @@ -109,13 +139,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 bac1b7c..b9858db 100644 --- a/filamento/src/db.rs +++ b/filamento/src/db.rs @@ -1,8 +1,15 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use core::fmt::Display; +use std::ffi::c_int; use std::{collections::HashSet, ops::Deref, path::Path, sync::Arc}; use chrono::{DateTime, Utc}; -use jid::JID; +use jid::{BareJID, FullJID, JID}; +use rusqlite::trace::TraceEventCodes; +use rusqlite::trace::config_log; use rusqlite::{Connection, OptionalExtension}; use tokio::sync::{Mutex, MutexGuard}; use tokio::sync::{mpsc, oneshot}; @@ -53,6 +60,41 @@ macro_rules! impl_db_sends { } } +unsafe fn enable_log() -> Result<(), DatabaseOpenError> { + unsafe { + config_log(Some(|_, log| debug!("rusqlite (db): {}", log)))?; + } + Ok(()) +} + +fn enable_trace(connection: &mut Connection) { + connection.trace_v2( + TraceEventCodes::all(), + Some(|trace| match trace { + rusqlite::trace::TraceEvent::Stmt(stmt_ref, _) => { + debug!( + "rusqlite (db) statement: {}", + stmt_ref.expanded_sql().unwrap_or_default() + ) + } + rusqlite::trace::TraceEvent::Profile(stmt_ref, duration) => {} + rusqlite::trace::TraceEvent::Row(stmt_ref) => { + debug!( + "rusqlite (db) row: {}", + stmt_ref.expanded_sql().unwrap_or_default() + ) + } + rusqlite::trace::TraceEvent::Close(conn_ref) => { + debug!( + "rusqlite (db) connection closed: {}", + conn_ref.db_filename().unwrap_or_default() + ) + } + _ => {} + }), + ); +} + impl Db { #[cfg(not(target_arch = "wasm32"))] pub async fn create_connect_and_migrate( @@ -88,12 +130,21 @@ impl Db { spawn_blocking(move || { spawn_local(async move { debug!("installing opfs in spawn"); - rusqlite::ffi::install_opfs_sahpool( + match rusqlite::ffi::install_opfs_sahpool( Some(&rusqlite::ffi::OpfsSAHPoolCfg::default()), false, ) .await - .unwrap(); + { + 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); @@ -152,7 +203,7 @@ impl Db { } // TODO: this is not a 'read' user - pub(crate) async fn read_user(&self, user: JID) -> Result<User, Error> { + 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); @@ -161,7 +212,7 @@ impl Db { } /// returns whether or not the nickname was updated - pub(crate) async fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> { + 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); @@ -170,7 +221,7 @@ impl Db { } /// returns whether or not the nickname was updated - pub(crate) async fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> { + 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); @@ -181,7 +232,7 @@ impl Db { /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar pub(crate) async fn delete_user_avatar( &self, - jid: JID, + jid: BareJID, ) -> Result<(bool, Option<String>), Error> { let (result, recv) = oneshot::channel(); let command = DbCommand::DeleteUserAvatar { jid, result }; @@ -193,7 +244,7 @@ impl Db { /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar pub(crate) async fn upsert_user_avatar( &self, - jid: JID, + jid: BareJID, avatar: String, ) -> Result<(bool, Option<String>), Error> { let (result, recv) = oneshot::channel(); @@ -228,7 +279,7 @@ impl Db { result } - pub(crate) async fn read_contact(&self, contact: JID) -> Result<Contact, Error> { + 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); @@ -236,7 +287,10 @@ impl Db { result } - pub(crate) async fn read_contact_opt(&self, contact: JID) -> Result<Option<Contact>, Error> { + 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); @@ -261,7 +315,7 @@ impl Db { result } - pub(crate) async fn delete_contact(&self, contact: JID) -> Result<(), Error> { + 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); @@ -305,7 +359,7 @@ impl Db { // 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> { + 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); @@ -313,7 +367,7 @@ impl Db { result } - pub(crate) async fn read_chat_and_user(&self, chat: JID) -> Result<(Chat, User), Error> { + 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); @@ -321,7 +375,7 @@ impl Db { result } - pub(crate) async fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> { + 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); @@ -329,25 +383,9 @@ impl Db { result } - pub(crate) async fn update_chat_correspondent( - &self, - old_chat: Chat, - new_correspondent: JID, - ) -> 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: JID) -> Result<(), Error> { + 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); @@ -403,8 +441,8 @@ impl Db { pub(crate) async fn create_message( &self, message: Message, - chat: JID, - from: JID, + chat: BareJID, + from: BareJID, ) -> Result<(), Error> { let (result, recv) = oneshot::channel(); let command = DbCommand::CreateMessage { @@ -418,7 +456,7 @@ impl Db { result } - pub(crate) async fn upsert_chat_and_user(&self, chat: JID) -> Result<bool, Error> { + 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); @@ -426,30 +464,6 @@ impl Db { 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 - // must be bare jid - chat: JID, - // full jid - from: JID, - ) -> 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, @@ -483,9 +497,9 @@ impl Db { DeleteCachedStatus => delete_cached_status() -> (); UpsertCachedStatus => upsert_cached_status(status: Online) -> (); ReadCachedStatus => read_cached_status() -> Online; - ReadMessageHistoryWithUsers => read_message_history_with_users(chat: JID) -> Vec<(Message, User)>; + ReadMessageHistoryWithUsers => read_message_history_with_users(chat: BareJID) -> Vec<(Message, User)>; // TODO: paging - ReadMessageHistory => read_message_history(chat: JID) -> Vec<Message>; + ReadMessageHistory => read_message_history(chat: BareJID) -> Vec<Message>; ReadMessage => read_message(message: Uuid) -> Message; DeleteMessage => delete_message(message: Uuid) -> () ); @@ -515,24 +529,24 @@ pub enum DbCommand { result: oneshot::Sender<Result<(), Error>>, }, ReadUser { - user: JID, + user: BareJID, result: oneshot::Sender<Result<User, Error>>, }, DeleteUserNick { - jid: JID, + jid: BareJID, result: oneshot::Sender<Result<bool, Error>>, }, UpsertUserNick { - jid: JID, + jid: BareJID, nick: String, result: oneshot::Sender<Result<bool, Error>>, }, DeleteUserAvatar { - jid: JID, + jid: BareJID, result: oneshot::Sender<Result<(bool, Option<String>), Error>>, }, UpsertUserAvatar { - jid: JID, + jid: BareJID, avatar: String, result: oneshot::Sender<Result<(bool, Option<String>), Error>>, }, @@ -545,11 +559,11 @@ pub enum DbCommand { result: oneshot::Sender<Result<(), Error>>, }, ReadContact { - contact: JID, + contact: BareJID, result: oneshot::Sender<Result<Contact, Error>>, }, ReadContactOpt { - contact: JID, + contact: BareJID, result: oneshot::Sender<Result<Option<Contact>, Error>>, }, UpdateContact { @@ -561,7 +575,7 @@ pub enum DbCommand { result: oneshot::Sender<Result<(), Error>>, }, DeleteContact { - contact: JID, + contact: BareJID, result: oneshot::Sender<Result<(), Error>>, }, ReplaceCachedRoster { @@ -579,24 +593,19 @@ pub enum DbCommand { result: oneshot::Sender<Result<(), Error>>, }, ReadChat { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<Chat, Error>>, }, ReadChatAndUser { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<(Chat, User), Error>>, }, MarkChatAsChatted { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<(), Error>>, }, - UpdateChatCorrespondent { - old_chat: Chat, - new_correspondent: JID, - result: oneshot::Sender<Result<Chat, Error>>, - }, DeleteChat { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<(), Error>>, }, ReadChats { @@ -621,20 +630,14 @@ pub enum DbCommand { // }, CreateMessage { message: Message, - chat: JID, - from: JID, + chat: BareJID, + from: BareJID, result: oneshot::Sender<Result<(), Error>>, }, UpsertChatAndUser { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<bool, Error>>, }, - CreateMessageWithUserResource { - message: Message, - chat: JID, - from: JID, - result: oneshot::Sender<Result<(), Error>>, - }, UpdateMessageDelivery { message: Uuid, delivery: Delivery, @@ -649,11 +652,11 @@ pub enum DbCommand { result: oneshot::Sender<Result<Message, Error>>, }, ReadMessageHistory { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<Vec<Message>, Error>>, }, ReadMessageHistoryWithUsers { - chat: JID, + chat: BareJID, result: oneshot::Sender<Result<Vec<(Message, User)>, Error>>, }, ReadCachedStatus { @@ -700,7 +703,6 @@ impl Display for DbCommand { 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", @@ -708,7 +710,6 @@ impl Display for DbCommand { 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", @@ -750,7 +751,9 @@ impl DbActor { // let db = SqlitePool::connect(&url).await?; // migrate!().run(&db).await?; // Ok(Self { db }) - let db = Connection::open(url)?; + unsafe { enable_log()? } + let mut db = Connection::open(url)?; + enable_trace(&mut db); db.execute_batch(include_str!("../migrations/1.sql"))?; Ok(Self { db, receiver }) } @@ -760,7 +763,9 @@ impl DbActor { pub(crate) fn new_memory( receiver: mpsc::UnboundedReceiver<DbCommand>, ) -> Result<Self, DatabaseOpenError> { - let db = Connection::open_in_memory()?; + unsafe { enable_log()? } + let mut db = Connection::open_in_memory()?; + enable_trace(&mut db); db.execute_batch(include_str!("../migrations/1.sql"))?; Ok(Self { db, receiver }) } @@ -770,7 +775,9 @@ impl DbActor { pub fn new_memory( receiver: mpsc::UnboundedReceiver<DbCommand>, ) -> Result<Self, DatabaseOpenError> { - let db = Connection::open("mem.db")?; + unsafe { enable_log()? } + let mut db = Connection::open("mem.db")?; + enable_trace(&mut db); db.execute_batch(include_str!("../migrations/1.sql"))?; Ok(Self { db, receiver }) } @@ -781,7 +788,9 @@ impl DbActor { file_name: impl AsRef<Path>, receiver: mpsc::UnboundedReceiver<DbCommand>, ) -> Result<Self, DatabaseOpenError> { - let db = Connection::open(file_name)?; + unsafe { enable_log()? } + let mut db = Connection::open(file_name)?; + enable_trace(&mut db); db.execute_batch(include_str!("../migrations/1.sql"))?; Ok(Self { db, receiver }) } @@ -823,7 +832,7 @@ impl DbActor { result.send(self.read_contact(contact)); } DbCommand::ReadContactOpt { contact, result } => { - result.send(self.read_contact_opt(&contact)); + result.send(self.read_contact_opt(contact)); } DbCommand::UpdateContact { contact, result } => { result.send(self.update_contact(contact)); @@ -855,13 +864,6 @@ impl DbActor { 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)); } @@ -888,14 +890,6 @@ impl DbActor { 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, @@ -951,7 +945,7 @@ impl DbActor { } // TODO: this is not a 'read' user - pub(crate) fn read_user(&self, user: JID) -> Result<User, Error> { + pub(crate) fn read_user(&self, user: BareJID) -> Result<User, Error> { let db = &self.db; let user_opt = db .query_row( @@ -980,7 +974,7 @@ impl DbActor { } /// returns whether or not the nickname was updated - pub(crate) fn delete_user_nick(&self, jid: JID) -> Result<bool, Error> { + 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>))?; @@ -993,7 +987,7 @@ impl DbActor { } /// returns whether or not the nickname was updated - pub(crate) fn upsert_user_nick(&self, jid: JID, nick: String) -> Result<bool, Error> { + 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))?; @@ -1006,7 +1000,7 @@ impl DbActor { } /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar - pub(crate) fn delete_user_avatar(&self, jid: JID) -> Result<(bool, Option<String>), Error> { + 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; @@ -1027,7 +1021,7 @@ impl DbActor { /// returns whether or not the avatar was updated, and the file to delete if there existed an old avatar pub(crate) fn upsert_user_avatar( &self, - jid: JID, + jid: BareJID, avatar: String, ) -> Result<(bool, Option<String>), Error> { let (old_avatar, rows_affected): (Option<String>, _); @@ -1049,7 +1043,7 @@ impl DbActor { } } - // TODO: use references everywhere + // 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", @@ -1081,7 +1075,7 @@ impl DbActor { Ok(()) } - pub(crate) fn read_contact(&self, contact: JID) -> Result<Contact, Error> { + 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", @@ -1103,7 +1097,7 @@ impl DbActor { Ok(contact_item) } - pub(crate) fn read_contact_opt(&self, contact: &JID) -> Result<Option<Contact>, Error> { + pub(crate) fn read_contact_opt(&self, contact: BareJID) -> Result<Option<Contact>, Error> { let db = &self.db; let contact_item = db .query_row( @@ -1183,7 +1177,7 @@ impl DbActor { Ok(()) } - pub(crate) fn delete_contact(&self, contact: JID) -> Result<(), Error> { + pub(crate) fn delete_contact(&self, contact: BareJID) -> Result<(), Error> { self.db .execute("delete from roster where user_jid = ?1", [&contact])?; Ok(()) @@ -1250,30 +1244,34 @@ impl DbActor { } pub(crate) fn create_chat(&self, chat: Chat) -> Result<(), Error> { - let id = Uuid::new_v4(); let jid = chat.correspondent(); + debug!("aick: before user identity upsert {jid}"); + let identity = self.upsert_user_identity(jid)?; + debug!("aick: chat user identity: {identity}"); + let id = Uuid::new_v4(); + debug!("aick: chat uuid: {id}"); self.db.execute( "insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3)", - (id, jid, chat.have_chatted), + (id, identity, 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. - - /// should be a bare jid /// TODO: this is NOT a read - pub(crate) fn read_chat(&self, chat: JID) -> Result<Chat, Error> { - let chat_opt = self.db.query_row( - "select correspondent, have_chatted from chats where correspondent = ?1", - [&chat], - |row| { - Ok(Chat { - correspondent: row.get(0)?, - have_chatted: row.get(1)?, - }) - }, - ).optional()?; + pub(crate) fn read_chat(&self, chat: BareJID) -> Result<Chat, Error> { + let chat_opt = self + .db + .query_row( + "select primary_jid, have_chatted from chats join identities on correspondent = identities.id where primary_jid = ?1", + [&chat], + |row| { + Ok(Chat { + correspondent: row.get(0)?, + have_chatted: row.get(1)?, + }) + }, + ) + .optional()?; match chat_opt { Some(chat) => return Ok(chat), None => { @@ -1287,10 +1285,10 @@ impl DbActor { } } - pub(crate) fn read_chat_and_user(&self, chat: JID) -> Result<(Chat, User), Error> { + 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", + "select primary_jid, have_chatted, jid, nick, avatar from chats join identities i on chats.correspondent = i.id join users on jid = primary_jid where primary_jid = ?1", [&chat], |row| { Ok(( @@ -1313,43 +1311,25 @@ impl DbActor { correspondent: chat, have_chatted: false, }; + debug!("aick: creating chat"); self.create_chat(chat.clone())?; + debug!("aick: created chat"); Ok((chat, user)) } } } - pub(crate) fn mark_chat_as_chatted(&self, chat: JID) -> Result<(), Error> { + pub(crate) fn mark_chat_as_chatted(&self, chat: BareJID) -> Result<(), Error> { self.db.execute( - "update chats set have_chatted = true where correspondent = ?1", + "update chats set have_chatted = true where correspondent = (select id from identities where primary_jid = ?1)", [chat], )?; Ok(()) } - pub(crate) fn update_chat_correspondent( - &self, - old_chat: Chat, - new_correspondent: JID, - ) -> Result<Chat, Error> { - let new_jid = &new_correspondent; - let old_jid = old_chat.correspondent(); - let chat = self.db.query_row( - "update chats set correspondent = ?1 where correspondent = ?2 returning correspondent, have_chatted", - [new_jid, old_jid], - |row| Ok(Chat { - correspondent: row.get(0)?, - have_chatted: row.get(1)?, - }) - )?; - Ok(chat) - } - - // pub(crate) fn update_chat - - pub(crate) fn delete_chat(&self, chat: JID) -> Result<(), Error> { + pub(crate) fn delete_chat(&self, chat: BareJID) -> Result<(), Error> { self.db - .execute("delete from chats where correspondent = ?1", [chat])?; + .execute("delete from chats where correspondent = (select id from identities where primary_jid = ?1)", [chat])?; Ok(()) } @@ -1357,7 +1337,7 @@ impl DbActor { pub(crate) fn read_chats(&self) -> Result<Vec<Chat>, Error> { let chats = self .db - .prepare("select correspondent, have_chatted from chats")? + .prepare("select primary_jid, have_chatted from chats join identities on correspondent = identities.id")? .query_map([], |row| { Ok(Chat { correspondent: row.get(0)?, @@ -1373,7 +1353,7 @@ impl DbActor { 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")? + .prepare("select i.primary_jid, c.have_chatted, m.* from chats c join identities i on c.correspondent = i.id 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)?, @@ -1389,9 +1369,32 @@ impl DbActor { pub(crate) fn read_chats_ordered_with_latest_messages( &self, ) -> Result<Vec<(Chat, Message)>, Error> { - let chats = self + let mut 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")? + .prepare( + " +SELECT ci.primary_jid, + c.have_chatted, + m.id, + ui.primary_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 + JOIN identities AS ci + ON ci.id = c.correspondent + JOIN identities AS ui + ON ui.id = m.from_identity +ORDER BY m.timestamp DESC", + )? .query_map([], |row| { Ok(( Chat { @@ -1403,10 +1406,10 @@ impl DbActor { from: row.get(3)?, delivery: row.get(4)?, timestamp: row.get(5)?, - body: Body { - body: row.get(6)?, - }, - } + body: Body { body: row.get(6)? }, + // TODO: query raw sources. + source: Vec::new(), + }, )) })? .collect::<Result<Vec<_>, _>>()?; @@ -1420,7 +1423,41 @@ impl DbActor { ) -> 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")? + .prepare( + " +SELECT c.id AS chat_id, + ci.primary_jid 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, + ui.primary_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 identities AS ci + ON ci.id = c.correspondent + JOIN identities AS ui + ON ui.id = m.from_identity + JOIN users AS cu + ON cu.jid = ci.primary_jid + JOIN users AS mu + ON mu.jid = ui.primary_jid +ORDER BY m.timestamp DESC", + )? .query_map([], |row| { Ok(( ( @@ -1432,7 +1469,7 @@ impl DbActor { jid: row.get("chat_user_jid")?, nick: row.get("chat_user_nick")?, avatar: row.get("chat_user_avatar")?, - } + }, ), ( Message { @@ -1443,12 +1480,14 @@ impl DbActor { body: Body { body: row.get("message_body")?, }, + // TODO: query raw sources. + source: Vec::new(), }, User { jid: row.get("message_user_jid")?, nick: row.get("message_user_nick")?, avatar: row.get("message_user_avatar")?, - } + }, ), )) })? @@ -1457,20 +1496,20 @@ impl DbActor { } #[tracing::instrument] - fn read_chat_id(&self, chat: JID) -> Result<Uuid, Error> { + fn read_chat_id(&self, chat: BareJID) -> Result<Uuid, Error> { let chat_id = self.db.query_row( - "select id from chats where correspondent = ?1", + "select id from chats where correspondent = (select id from identities where primary_jid = ?1)", [chat], |row| Ok(row.get(0)?), )?; Ok(chat_id) } - fn read_chat_id_opt(&self, chat: JID) -> Result<Option<Uuid>, Error> { + fn read_chat_id_opt(&self, chat: BareJID) -> Result<Option<Uuid>, Error> { let chat_id = self .db .query_row( - "select id from chats where correspondent = ?1", + "select id from chats where correspondent = (select id from identities where primary_jid = ?1)", [chat], |row| Ok(row.get(0)?), ) @@ -1479,64 +1518,60 @@ impl DbActor { } /// if the chat doesn't already exist, it must be created by calling create_chat() before running this function. + /// create direct message from incoming. MUST upsert user w/ identity, and chat w/identity #[tracing::instrument] pub(crate) fn create_message( &self, message: Message, - chat: JID, - from: JID, + chat: BareJID, + from: BareJID, ) -> Result<(), Error> { - let from_jid = from.as_bare(); - let chat_id = self.read_chat_id(chat)?; + debug!("oomla: 1"); + let chat_identity = self.upsert_user_identity(&chat)?; + debug!("oomla: upserted chat user and got identity {chat_identity}"); + let (chat_id, _) = self.upsert_chat(chat_identity)?; + debug!("oomla: upserted chat and got chat id {chat_id}"); + let from_identity = self.upsert_user_identity(&from)?; + debug!("oomla: upserted from user and got user identity {from_identity}"); 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))?; + self.db.execute("insert into messages (id, body, chat_id, from_identity, timestamp, delivery) values (?1, ?2, ?3, ?4, ?5, ?6)", (&message.id, &message.body.body, &chat_id, &from_identity, &message.timestamp, &message.delivery))?; Ok(()) } - pub(crate) fn upsert_chat_and_user(&self, chat: &JID) -> Result<bool, Error> { - let bare_chat = chat.as_bare(); - let db = &self.db; - db.execute( + // returns the user identity + pub(crate) fn upsert_user_identity(&self, chat: &BareJID) -> Result<Uuid, Error> { + self.db.execute( "insert into users (jid) values (?1) on conflict do nothing", - [&bare_chat], + [&chat], )?; - let id = Uuid::new_v4(); - db.execute("insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3) on conflict do nothing", (id, &bare_chat, false))?; - let chat = db.query_row( - "select correspondent, have_chatted from chats where correspondent = ?1", - [&bare_chat], - |row| { - Ok(Chat { - correspondent: row.get(0)?, - have_chatted: row.get(1)?, - }) - }, + let identity = Uuid::new_v4(); + self.db.execute( + "insert into identities (id, primary_jid) values (?1, ?2) on conflict do nothing", + (identity, &chat), )?; - Ok(chat.have_chatted) + let identity = self.db.query_row( + "select id from identities where primary_jid = ?1", + [&chat], + |row| Ok(row.get(0)?), + )?; + Ok(identity) } - /// create direct message from incoming. MUST upsert chat and user - #[tracing::instrument] - pub(crate) fn create_message_with_user_resource( - &self, - message: Message, - // TODO: enforce two kinds of jid. bare and full - // must be bare jid - chat: JID, - // full jid - from: JID, - ) -> Result<(), Error> { - let from_jid = from.as_bare(); - let chat = chat.as_bare(); - tracing::debug!("creating resource"); - if let Some(resource) = &from.resourcepart { - self.db.execute( - "insert into resources (bare_jid, resource) values (?1, ?2) on conflict do nothing", - (&from_jid, resource), - )?; - } - self.create_message(message, chat, from)?; - Ok(()) + pub(crate) fn upsert_chat(&self, identity: Uuid) -> Result<(Uuid, bool), Error> { + let chat_id = Uuid::new_v4(); + self.db.execute("insert into chats (id, correspondent, have_chatted) values (?1, ?2, ?3) on conflict do nothing", (chat_id, &identity, false))?; + let (chat_id, have_chatted) = self.db.query_row( + "select id, have_chatted from chats where correspondent = ?1", + [identity], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + Ok((chat_id, have_chatted)) + } + + pub(crate) fn upsert_chat_and_user(&self, chat: &BareJID) -> Result<bool, Error> { + let chat_identity = self.upsert_user_identity(&chat)?; + let (_chat_id, have_chatted) = self.upsert_chat(chat_identity)?; + Ok(have_chatted) } pub(crate) fn update_message_delivery( @@ -1571,7 +1606,7 @@ impl DbActor { 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", + "select id, primary_jid, delivery, timestamp, body from messages join identities on identities.id = messages.from_identity where messages.id = ?1", [&message], |row| { Ok(Message { @@ -1581,6 +1616,8 @@ impl DbActor { delivery: row.get(2)?, timestamp: row.get(3)?, body: Body { body: row.get(4)? }, + // TODO: query raw sources + source: Vec::new(), }) }, )?; @@ -1588,21 +1625,22 @@ impl DbActor { } // TODO: paging - pub(crate) fn read_message_history(&self, chat: JID) -> Result<Vec<Message>, Error> { + 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", + "select id, primary_jid, delivery, timestamp, body from messages join identities on identities.id = messages.from_identity where chat_id = (select id from identities where primary_jid = ?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)? }, + // TODO: query raw sources + source: Vec::new(), }) })? .collect::<Result<Vec<_>, _>>()?; @@ -1611,13 +1649,13 @@ impl DbActor { pub(crate) fn read_message_history_with_users( &self, - chat: JID, + 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", + "select id, jid, delivery, timestamp, body, jid, nick, avatar from messages join users on jid = (select primary_jid from identities where id = from_identity) where chat_id = ? order by timestamp asc", )? .query_map([chat_id], |row| { Ok(( @@ -1628,6 +1666,8 @@ impl DbActor { delivery: row.get(2)?, timestamp: row.get(3)?, body: Body { body: row.get(4)? }, + // TODO: query raw sources + source: Vec::new(), }, User { jid: row.get(5)?, diff --git a/filamento/src/disco.rs b/filamento/src/disco.rs index 580f647..f9a51b1 100644 --- a/filamento/src/disco.rs +++ b/filamento/src/disco.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use jid::JID; use stanza::xep_0030::{info, items}; diff --git a/filamento/src/error.rs b/filamento/src/error.rs index f9f9199..be7af92 100644 --- a/filamento/src/error.rs +++ b/filamento/src/error.rs @@ -1,8 +1,13 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{num::TryFromIntError, string::FromUtf8Error, sync::Arc}; use base64::DecodeError; use image::ImageError; use jid::JID; +use jid::JIDError; use lampada::error::{ActorError, ReadError, WriteError}; use stanza::client::{Stanza, iq::Query}; use thiserror::Error; @@ -292,6 +297,9 @@ pub enum IqProcessError { #[derive(Debug, Error, Clone)] pub enum DatabaseOpenError { + #[cfg(target_arch = "wasm32")] + #[error("opfs: {0}")] + OpfsSAH(#[from] OpfsSAHError), #[error("error: {0}")] Error(Arc<rusqlite::Error>), // #[error("migration: {0}")] @@ -310,6 +318,117 @@ pub enum DatabaseOpenError { // } // } +#[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), + } + } +} + +#[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)) @@ -332,6 +451,8 @@ pub enum PresenceError { MissingFrom, #[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)] diff --git a/filamento/src/files.rs b/filamento/src/files.rs index dcc9cd2..bd8daba 100644 --- a/filamento/src/files.rs +++ b/filamento/src/files.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{ collections::HashMap, convert::Infallible, diff --git a/filamento/src/files/opfs.rs b/filamento/src/files/opfs.rs index fb32c6e..41acc71 100644 --- a/filamento/src/files/opfs.rs +++ b/filamento/src/files/opfs.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::path::Path; use thiserror::Error; @@ -10,7 +14,7 @@ use web_sys::{ use crate::FileStore; -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct FilesOPFS { directory: String, } diff --git a/filamento/src/lib.rs b/filamento/src/lib.rs index 068bfe8..40a2867 100644 --- a/filamento/src/lib.rs +++ b/filamento/src/lib.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{ collections::HashMap, ops::{Deref, DerefMut}, @@ -16,7 +20,7 @@ use error::{ }; 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}, @@ -68,45 +72,55 @@ pub enum Command<Fs: FileStore> { 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(JID, oneshot::Sender<Result<(Chat, User), DatabaseError>>), + 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(JID, oneshot::Sender<Result<Vec<Message>, DatabaseError>>), + GetMessages( + BareJID, + oneshot::Sender<Result<Vec<Message>, DatabaseError>>, + ), /// get message history for chat (does appropriate mam things) // TODO: paging and filtering GetMessagesWithUsers( - JID, + 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 @@ -120,7 +134,7 @@ pub enum Command<Fs: FileStore> { // 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 @@ -146,7 +160,7 @@ pub enum Command<Fs: FileStore> { sender: oneshot::Sender<Result<(), PEPError>>, }, GetPEPItem { - jid: Option<JID>, + jid: Option<BareJID>, node: String, id: String, sender: oneshot::Sender<Result<pep::Item, PEPError>>, @@ -171,7 +185,7 @@ pub enum UpdateMessage { Offline(Offline), /// (only update app roster state, don't replace) RosterUpdate(Contact, User), - RosterDelete(JID), + RosterDelete(BareJID), /// presences should be stored with users in the ui, not contacts, as presences can be received from anyone Presence { from: JID, @@ -180,22 +194,23 @@ pub enum UpdateMessage { // TODO: receipts // MessageDispatched(Uuid), Message { - to: JID, + // TODO: rename to chat? + to: BareJID, from: User, message: Message, }, MessageDelivery { id: Uuid, - chat: JID, + chat: BareJID, delivery: Delivery, }, - SubscriptionRequest(jid::JID), + SubscriptionRequest(BareJID), NickChanged { - jid: JID, + jid: BareJID, nick: Option<String>, }, AvatarChanged { - jid: JID, + jid: BareJID, id: Option<String>, }, } @@ -259,7 +274,7 @@ impl<Fs: FileStore + Clone + Send + Sync + 'static> Client<Fs> { timeout: Duration::from_secs(20), }; - let logic = ClientLogic::new(client.clone(), jid.as_bare(), db, update_send, file_store); + let logic = ClientLogic::new(client.clone(), jid.to_bare(), db, update_send, file_store); let actor: CoreClient<ClientLogic<Fs>> = CoreClient::new(jid, password, command_receiver, None, sup_recv, logic); @@ -373,7 +388,7 @@ impl<Fs: FileStore> Client<Fs> { Ok(chats) } - pub async fn get_chat(&self, jid: JID) -> Result<Chat, CommandError<DatabaseError>> { + 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 @@ -385,12 +400,17 @@ impl<Fs: FileStore> Client<Fs> { Ok(chat) } - pub async fn get_chat_and_user(&self, jid: JID) -> Result<(Chat, User), CommandError<DatabaseError>> { + 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) + 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)))??; @@ -411,7 +431,7 @@ impl<Fs: FileStore> Client<Fs> { 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))) @@ -426,7 +446,7 @@ impl<Fs: FileStore> Client<Fs> { pub async fn get_messages_with_users( &self, - jid: JID, + jid: BareJID, ) -> Result<Vec<(Message, User)>, CommandError<DatabaseError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command(Command::GetMessagesWithUsers( @@ -441,7 +461,7 @@ impl<Fs: FileStore> Client<Fs> { Ok(messages) } - pub async fn delete_chat(&self, jid: JID) -> Result<(), CommandError<DatabaseError>> { + 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 @@ -465,7 +485,7 @@ impl<Fs: FileStore> Client<Fs> { 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 @@ -477,7 +497,7 @@ impl<Fs: FileStore> Client<Fs> { 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 @@ -489,7 +509,7 @@ impl<Fs: FileStore> Client<Fs> { 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 @@ -501,7 +521,10 @@ impl<Fs: FileStore> Client<Fs> { 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, @@ -515,7 +538,10 @@ impl<Fs: FileStore> Client<Fs> { 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, @@ -531,7 +557,7 @@ impl<Fs: FileStore> Client<Fs> { pub async fn accept_subscription_request( &self, - jid: JID, + jid: BareJID, ) -> Result<(), CommandError<SubscribeError>> { let (send, recv) = oneshot::channel(); self.send(CoreClientCommand::Command( @@ -546,7 +572,10 @@ impl<Fs: FileStore> Client<Fs> { 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, @@ -560,7 +589,7 @@ impl<Fs: FileStore> Client<Fs> { 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, @@ -574,7 +603,7 @@ impl<Fs: FileStore> Client<Fs> { 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, @@ -588,7 +617,7 @@ impl<Fs: FileStore> Client<Fs> { 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, @@ -604,7 +633,7 @@ impl<Fs: FileStore> Client<Fs> { pub async fn update_contact( &self, - jid: JID, + jid: BareJID, update: ContactUpdate, ) -> Result<(), CommandError<RosterError>> { let (send, recv) = oneshot::channel(); @@ -632,7 +661,7 @@ impl<Fs: FileStore> Client<Fs> { 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(()) @@ -711,7 +740,8 @@ impl<Fs: FileStore> Client<Fs> { pub async fn get_pep_item( &self, - jid: Option<JID>, + // 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>> { @@ -777,13 +807,12 @@ mod tests { 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")) + let db = Db::create_connect_and_migrate("./filamento.db") .await .unwrap(); let (client, mut recv) = Client::new( @@ -811,7 +840,7 @@ mod tests { info!("sending message"); client .send_message( - JID::from_str("cel@blos.sm").unwrap(), + BareJID::from_str("cel@blos.sm").unwrap(), chat::Body { body: "hallo!!!".to_string(), }, @@ -821,7 +850,7 @@ mod tests { info!("sent message"); client .send_message( - JID::from_str("cel@blos.sm").unwrap(), + BareJID::from_str("cel@blos.sm").unwrap(), chat::Body { body: "hallo 2".to_string(), }, diff --git a/filamento/src/logic/abort.rs b/filamento/src/logic/abort.rs index 3588b13..1de905a 100644 --- a/filamento/src/logic/abort.rs +++ b/filamento/src/logic/abort.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use lampada::error::ReadError; use crate::files::FileStore; diff --git a/filamento/src/logic/connect.rs b/filamento/src/logic/connect.rs index 9d61ca4..a4d6f72 100644 --- a/filamento/src/logic/connect.rs +++ b/filamento/src/logic/connect.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use lampada::{Connected, Logic, error::WriteError}; use tokio::sync::oneshot; use tracing::debug; @@ -11,7 +15,7 @@ use crate::{ use super::ClientLogic; -pub async fn handle_connect<Fs: FileStore + Clone + Send + Sync>( +pub async fn handle_connect<Fs: FileStore + Clone + Send + Sync + 'static>( logic: ClientLogic<Fs>, connection: Connected, ) { diff --git a/filamento/src/logic/connection_error.rs b/filamento/src/logic/connection_error.rs index 36c1cef..7cb39b6 100644 --- a/filamento/src/logic/connection_error.rs +++ b/filamento/src/logic/connection_error.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use lampada::error::ConnectionError; use crate::files::FileStore; diff --git a/filamento/src/logic/disconnect.rs b/filamento/src/logic/disconnect.rs index ebcfd4f..bbff8be 100644 --- a/filamento/src/logic/disconnect.rs +++ b/filamento/src/logic/disconnect.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use lampada::Connected; use stanza::client::Stanza; diff --git a/filamento/src/logic/local_only.rs b/filamento/src/logic/local_only.rs index f5705f4..5dc8793 100644 --- a/filamento/src/logic/local_only.rs +++ b/filamento/src/logic/local_only.rs @@ -1,4 +1,8 @@ -use jid::JID; +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use jid::{BareJID, JID}; use uuid::Uuid; use crate::{ @@ -39,14 +43,14 @@ pub async fn handle_get_chats_ordered_with_latest_messages_and_users<Fs: FileSto pub async fn handle_get_chat<Fs: FileStore + Clone>( logic: &ClientLogic<Fs>, - jid: JID, + jid: BareJID, ) -> Result<Chat, DatabaseError> { Ok(logic.db().read_chat(jid).await?) } pub async fn handle_get_chat_and_user<Fs: FileStore + Clone>( logic: &ClientLogic<Fs>, - jid: JID, + jid: BareJID, ) -> Result<(Chat, User), DatabaseError> { Ok(logic.db().read_chat_and_user(jid).await?) } @@ -60,21 +64,21 @@ pub async fn handle_get_message<Fs: FileStore + Clone>( pub async fn handle_get_messages<Fs: FileStore + Clone>( logic: &ClientLogic<Fs>, - jid: JID, + jid: BareJID, ) -> Result<Vec<Message>, DatabaseError> { Ok(logic.db().read_message_history(jid).await?) } pub async fn handle_get_messages_with_users<Fs: FileStore + Clone>( logic: &ClientLogic<Fs>, - jid: JID, + 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: JID, + jid: BareJID, ) -> Result<(), DatabaseError> { Ok(logic.db().delete_chat(jid).await?) } @@ -88,7 +92,7 @@ pub async fn handle_delete_messaage<Fs: FileStore + Clone>( pub async fn handle_get_user<Fs: FileStore + Clone>( logic: &ClientLogic<Fs>, - jid: JID, + 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 5e05dac..7ae0235 100644 --- a/filamento/src/logic/mod.rs +++ b/filamento/src/logic/mod.rs @@ -1,6 +1,10 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + 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}; @@ -25,7 +29,7 @@ mod process_stanza; #[derive(Clone)] pub struct ClientLogic<Fs: FileStore> { client: Client<Fs>, - bare_jid: JID, + jid: BareJID, db: Db, pending: Pending, update_sender: mpsc::Sender<UpdateMessage>, @@ -80,7 +84,7 @@ impl Pending { impl<Fs: FileStore> ClientLogic<Fs> { pub fn new( client: Client<Fs>, - bare_jid: JID, + jid: BareJID, db: Db, update_sender: mpsc::Sender<UpdateMessage>, file_store: Fs, @@ -90,7 +94,7 @@ impl<Fs: FileStore> ClientLogic<Fs> { pending: Pending::new(), update_sender, client, - bare_jid, + jid, file_store, } } @@ -127,7 +131,7 @@ impl<Fs: FileStore> ClientLogic<Fs> { } } -impl<Fs: FileStore + Clone + Send + Sync> Logic for ClientLogic<Fs> { +impl<Fs: FileStore + Clone + Send + Sync + 'static> Logic for ClientLogic<Fs> { type Cmd = Command<Fs>; // pub async fn handle_stream_error(self, error) {} diff --git a/filamento/src/logic/offline.rs b/filamento/src/logic/offline.rs index 606b04f..1d79f86 100644 --- a/filamento/src/logic/offline.rs +++ b/filamento/src/logic/offline.rs @@ -1,6 +1,11 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::process::id; use chrono::Utc; +use jid::FullJID; use lampada::error::WriteError; use tracing::error; use uuid::Uuid; @@ -19,9 +24,13 @@ use crate::{ }; use super::{ + ClientLogic, local_only::{ - 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 + 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<Fs: FileStore + Clone>(logic: ClientLogic<Fs>, command: Command<Fs>) { @@ -153,22 +162,19 @@ pub async fn handle_offline_result<Fs: FileStore + Clone>( let message = Message { id, - from: logic.bare_jid.clone(), + from: logic.jid.clone(), // TODO: failure reason delivery: Some(Delivery::Failed), timestamp, body, + source: Vec::new(), }; // try to store in message history that there is a new message that is sending. if client is quit mid-send then can mark as failed and re-send // TODO: mark these as potentially failed upon client launch if let Err(e) = logic .db() - .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(), - ) + // TODO: can create message without a resource.... + .create_message(message.clone(), jid.clone(), logic.jid.clone()) .await { // TODO: should these really be handle_error or just the error macro? @@ -177,12 +183,12 @@ pub async fn handle_offline_result<Fs: FileStore + Clone>( .await; } - let from = match logic.db().read_user(logic.bare_jid.clone()).await { + let from = match logic.db().read_user(logic.jid.clone()).await { Ok(u) => u, Err(e) => { error!("{}", e); User { - jid: logic.bare_jid.clone(), + jid: logic.jid.clone(), nick: None, avatar: None, } @@ -192,7 +198,7 @@ pub async fn handle_offline_result<Fs: FileStore + Clone>( logic .update_sender() .send(crate::UpdateMessage::Message { - to: jid.as_bare(), + to: jid, message, from, }) diff --git a/filamento/src/logic/online.rs b/filamento/src/logic/online.rs index 9814ff2..d49a844 100644 --- a/filamento/src/logic/online.rs +++ b/filamento/src/logic/online.rs @@ -1,9 +1,13 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{io::Cursor, time::Duration}; use base64::{prelude::BASE64_STANDARD, Engine}; use chrono::Utc; use image::ImageReader; -use jid::JID; +use jid::{BareJID, JID}; use lampada::{Connected, WriteMessage, error::WriteError}; use sha1::{Digest, Sha1}; use stanza::{ @@ -11,7 +15,9 @@ use stanza::{ iq::{self, Iq, IqType, Query}, Stanza }, 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; @@ -27,7 +33,7 @@ use super::{ }, ClientLogic }; -pub async fn handle_online<Fs: FileStore + Clone>(logic: ClientLogic<Fs>, command: Command<Fs>, 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(_) => {} @@ -41,7 +47,7 @@ pub async fn handle_get_roster<Fs: FileStore + Clone>( ) -> 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, @@ -101,7 +107,7 @@ pub async fn handle_get_roster_with_users<Fs: FileStore + Clone>( ) -> Result<Vec<(Contact, User)>, 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, @@ -162,11 +168,11 @@ pub async fn handle_get_roster_with_users<Fs: FileStore + Clone>( 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, @@ -220,9 +226,10 @@ pub async fn handle_add_contact<Fs: FileStore + Clone>( 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()), @@ -243,13 +250,13 @@ pub async fn handle_buddy_request<Fs: FileStore + Clone>( 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() @@ -261,15 +268,16 @@ pub async fn handle_subscription_request<Fs: FileStore + Clone>( 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), @@ -284,14 +292,11 @@ pub async fn handle_accept_buddy_request<Fs: FileStore + Clone>( 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?; @@ -300,10 +305,10 @@ pub async fn handle_accept_subscription_request<Fs: FileStore + Clone>( 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() }); @@ -311,9 +316,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() }); @@ -321,7 +326,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), @@ -340,11 +346,11 @@ pub async fn handle_unfriend_contact(connection: Connected, jid: JID) -> Result< 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, @@ -399,7 +405,7 @@ pub async fn handle_delete_contact<Fs: FileStore + Clone>( 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(); @@ -410,7 +416,8 @@ pub async fn handle_update_contact<Fs: FileStore + Clone>( .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, @@ -474,7 +481,7 @@ pub async fn handle_set_status<Fs: FileStore + Clone>( Ok(()) } -pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, 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 = match logic.db().upsert_chat_and_user(jid.clone()).await { @@ -490,7 +497,7 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, 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; @@ -513,17 +520,19 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, 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), + // TODO: raw stanza logging + source: Vec::new(), }; // try to store in message history that there is a new message that is sending. if client is quit mid-send then can mark as failed and re-send // TODO: mark these as potentially failed upon client launch if let Err(e) = logic .db() - .create_message_with_user_resource(message.clone(), jid.clone(), connection.jid().clone()) + .create_message(message.clone(), jid.clone(), connection.jid().to_bare()) .await { // TODO: should these really be handle_error or just the error macro? @@ -532,12 +541,12 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, .await; } - let from = match logic.db().read_user(logic.bare_jid.clone()).await { + let from = match logic.db().read_user(logic.jid.clone()).await { Ok(u) => u, Err(e) => { error!("{}", e); User { - jid: logic.bare_jid.clone(), + jid: logic.jid.clone(), nick: None, avatar: None, } @@ -548,7 +557,7 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, logic .update_sender() .send(UpdateMessage::Message { - to: jid.as_bare(), + to: jid.clone(), message, from, }) @@ -556,9 +565,9 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, // 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 ? @@ -583,6 +592,7 @@ pub async fn handle_send_message<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, match result { Ok(_) => { info!("sent message: {:?}", message_stanza); + // TODO: raw stanza if let Err(e) = logic.db().update_message_delivery(id, Delivery::Written).await { error!("updating message delivery: {}", e); } @@ -639,7 +649,7 @@ pub async fn handle_disco_info<Fs: FileStore + Clone>( ) -> 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, @@ -667,7 +677,7 @@ pub async fn handle_disco_info<Fs: FileStore + Clone>( }) 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 } @@ -694,7 +704,7 @@ pub async fn handle_disco_info<Fs: FileStore + Clone>( } } else { Err(DiscoError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -710,7 +720,7 @@ pub async fn handle_disco_items<Fs: FileStore + Clone>( ) -> 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, @@ -736,7 +746,7 @@ pub async fn handle_disco_items<Fs: FileStore + Clone>( }) 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 } @@ -763,7 +773,7 @@ pub async fn handle_disco_items<Fs: FileStore + Clone>( } } else { Err(DiscoError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -828,7 +838,7 @@ pub async fn handle_publish_pep_item<Fs: FileStore + Clone>( }, }; let request = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: id.clone(), to: None, r#type: IqType::Set, @@ -850,7 +860,7 @@ pub async fn handle_publish_pep_item<Fs: FileStore + Clone>( // 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 => { @@ -870,7 +880,7 @@ pub async fn handle_publish_pep_item<Fs: FileStore + Clone>( } } else { Err(PEPError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -878,10 +888,11 @@ pub async fn handle_publish_pep_item<Fs: FileStore + Clone>( } } -pub async fn handle_get_pep_item<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, connection: Connected, jid: Option<JID>, node: String, id: String) -> Result<pep::Item, PEPError> { +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()), + from: Some(connection.jid().clone().into()), id: stanza_id.clone(), to: jid.clone(), r#type: IqType::Get, @@ -909,7 +920,7 @@ pub async fn handle_get_pep_item<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, }) 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 } @@ -955,7 +966,7 @@ pub async fn handle_get_pep_item<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, } else { // TODO: include expected entity Err(PEPError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -968,29 +979,33 @@ pub async fn handle_change_nick<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, Ok(()) } -pub async fn handle_change_avatar<Fs: FileStore + Clone>(logic: &ClientLogic<Fs>, img_data: Option<Vec<u8>>) -> Result<(), AvatarPublishError<Fs>> { +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) => { - // load the image data and guess the format - let image = ImageReader::new(Cursor::new(data)).with_guessed_format()?.decode()?; + 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)?; - // 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 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); - // 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()); - // 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?; @@ -1024,7 +1039,7 @@ pub async fn handle_delete_pep_node<Fs: FileStore + Clone>( ) -> Result<(), PEPError> { 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: None, r#type: IqType::Set, @@ -1046,7 +1061,7 @@ pub async fn handle_delete_pep_node<Fs: FileStore + Clone>( // 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 => { @@ -1067,7 +1082,7 @@ pub async fn handle_delete_pep_node<Fs: FileStore + Clone>( } } else { Err(PEPError::IncorrectEntity( - from.unwrap_or_else(|| connection.jid().as_bare()), + from.unwrap_or_else(|| connection.jid().to_bare().into()), )) } } @@ -1076,7 +1091,7 @@ pub async fn handle_delete_pep_node<Fs: FileStore + Clone>( } // TODO: could probably macro-ise? -pub async fn handle_online_result<Fs: FileStore + Clone>( +pub async fn handle_online_result<Fs: FileStore + Clone + 'static>( logic: &ClientLogic<Fs>, command: Command<Fs>, connection: Connected, diff --git a/filamento/src/logic/process_stanza.rs b/filamento/src/logic/process_stanza.rs index 30d0830..dab475d 100644 --- a/filamento/src/logic/process_stanza.rs +++ b/filamento/src/logic/process_stanza.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use base64::{Engine, prelude::BASE64_STANDARD}; @@ -70,41 +74,32 @@ pub async fn recv_message<Fs: FileStore + Clone>( // 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: log raw stanza + source: Vec::new(), }; // TODO: process message type="error" // save the message to the database - match logic.db().upsert_chat_and_user(from.clone()).await { - Ok(_) => { - if let Err(e) = logic - .db() - .create_message_with_user_resource( - message.clone(), - from.clone(), - from.clone(), - ) - .await - { - error!("failed to create message: {}", e); - } - } - Err(e) => { - error!("failed to upsert chat and user: {}", e); - } - }; + if let Err(e) = logic + .db() + .create_message(message.clone(), from.to_bare(), from.to_bare()) + .await + { + error!("failed to create message: {}", e); + } - let from_user = match logic.db().read_user(from.as_bare()).await { + let from_user = match logic.db().read_user(from.to_bare()).await { Ok(u) => u, Err(e) => { error!("{}", e); User { - jid: from.as_bare(), + jid: from.to_bare(), nick: None, avatar: None, } @@ -115,7 +110,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::Message { - to: from.as_bare(), + to: from.to_bare(), from: from_user, message, }) @@ -125,13 +120,13 @@ pub async fn recv_message<Fs: FileStore + Clone>( if let Some(nick) = stanza_message.nick { let nick = nick.0; if nick.is_empty() { - match logic.db().delete_user_nick(from.as_bare()).await { + match logic.db().delete_user_nick(from.to_bare()).await { Ok(changed) => { if changed { logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: None, }) .await; @@ -145,7 +140,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: None, }) .await; @@ -154,7 +149,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( } else { match logic .db() - .upsert_user_nick(from.as_bare(), nick.clone()) + .upsert_user_nick(from.to_bare(), nick.clone()) .await { Ok(changed) => { @@ -162,7 +157,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: Some(nick), }) .await; @@ -176,7 +171,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: Some(nick), }) .await; @@ -199,7 +194,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( if nick.is_empty() { match logic .db() - .delete_user_nick(from.as_bare()) + .delete_user_nick(from.to_bare()) .await { Ok(changed) => { @@ -207,7 +202,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: None, }) .await; @@ -223,7 +218,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: None, }) .await; @@ -233,7 +228,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( match logic .db() .upsert_user_nick( - from.as_bare(), + from.to_bare(), nick.clone(), ) .await @@ -243,7 +238,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: Some(nick), }) .await; @@ -259,7 +254,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( logic .update_sender() .send(UpdateMessage::NickChanged { - jid: from.as_bare(), + jid: from.to_bare(), nick: Some(nick), }) .await; @@ -294,7 +289,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( match logic .db() .upsert_user_avatar( - from.as_bare(), + from.to_bare(), metadata.id.clone(), ) .await @@ -323,7 +318,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( }) { Ok(false) => { // get data - let pep_item = logic.client().get_pep_item(Some(from.as_bare()), "urn:xmpp:avatar:data".to_string(), metadata.id.clone()).await.map_err(|err| Into::<AvatarUpdateError<Fs>>::into(err))?; + 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", ""); @@ -344,7 +339,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( .update_sender() .send( UpdateMessage::AvatarChanged { - jid: from.as_bare(), + jid: from.to_bare(), id: Some( metadata.id.clone(), ), @@ -371,7 +366,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( .update_sender() .send( UpdateMessage::AvatarChanged { - jid: from.as_bare(), + jid: from.to_bare(), id: Some( metadata.id.clone(), ), @@ -401,7 +396,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( // delete avatar match logic .db() - .delete_user_avatar(from.as_bare()) + .delete_user_avatar(from.to_bare()) .await { Ok((changed, old_avatar)) => { @@ -419,7 +414,7 @@ pub async fn recv_message<Fs: FileStore + Clone>( .update_sender() .send( UpdateMessage::AvatarChanged { - jid: from.as_bare(), + jid: from.to_bare(), id: None, }, ) @@ -488,6 +483,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 => { @@ -546,7 +542,8 @@ pub async fn recv_iq<Fs: FileStore + Clone>( iq: Iq, ) -> 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(IqProcessError::Iq(IqError::IncorrectAddressee(to.clone()))); } @@ -556,7 +553,9 @@ pub async fn recv_iq<Fs: FileStore + Clone>( 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 @@ -570,7 +569,8 @@ pub async fn recv_iq<Fs: FileStore + Clone>( 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) => { @@ -594,7 +594,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( } 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, @@ -614,7 +614,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( }, 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, @@ -634,7 +634,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( } }; let iq = Iq { - from: Some(connection.jid().clone()), + from: Some(connection.jid().clone().into()), id: iq.id, to: iq.from, r#type: IqType::Result, @@ -653,7 +653,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( _ => { 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, @@ -677,7 +677,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( } 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, @@ -698,7 +698,8 @@ pub async fn recv_iq<Fs: FileStore + Clone>( 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) => { @@ -725,7 +726,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( .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, @@ -751,7 +752,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( } 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, @@ -771,7 +772,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( _ => { 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, @@ -791,7 +792,7 @@ pub async fn recv_iq<Fs: FileStore + Clone>( } 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, @@ -820,7 +821,7 @@ pub async fn process_stanza<Fs: FileStore + Clone>( 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 3cd243f..4985eeb 100644 --- a/filamento/src/pep.rs +++ b/filamento/src/pep.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use crate::avatar::{Data as AvatarData, Metadata as AvatarMetadata}; #[derive(Clone, Debug)] diff --git a/filamento/src/presence.rs b/filamento/src/presence.rs index de4dd7c..5ebf8af 100644 --- a/filamento/src/presence.rs +++ b/filamento/src/presence.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use chrono::{DateTime, Utc}; use rusqlite::{ ToSql, diff --git a/filamento/src/roster.rs b/filamento/src/roster.rs index 6b61e10..70f5bca 100644 --- a/filamento/src/roster.rs +++ b/filamento/src/roster.rs @@ -1,6 +1,10 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{collections::HashSet, fmt::Display}; -use jid::JID; +use jid::BareJID; use rusqlite::{ ToSql, types::{FromSql, ToSqlOutput, Value}, @@ -15,7 +19,7 @@ pub struct ContactUpdate { #[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>, diff --git a/filamento/src/user.rs b/filamento/src/user.rs index f30933c..dc632ea 100644 --- a/filamento/src/user.rs +++ b/filamento/src/user.rs @@ -1,10 +1,14 @@ -use jid::JID; +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use jid::BareJID; #[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 avatar: Option<String>, // pub cached_status_message: Option<String>, diff --git a/jid/Cargo.toml b/jid/Cargo.toml index 58d59a4..1c3aefd 100644 --- a/jid/Cargo.toml +++ b/jid/Cargo.toml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [package] name = "jid" version = "0.1.0" diff --git a/jid/src/lib.rs b/jid/src/lib.rs index 3b40094..9d21382 100644 --- a/jid/src/lib.rs +++ b/jid/src/lib.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{borrow::Cow, error::Error, fmt::Display, ops::Deref, str::FromStr}; // #[cfg(feature = "sqlx")] diff --git a/lampada/Cargo.toml b/lampada/Cargo.toml index 1937162..20ede3a 100644 --- a/lampada/Cargo.toml +++ b/lampada/Cargo.toml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [package] name = "lampada" version = "0.1.0" diff --git a/lampada/README.md b/lampada/README.md index dc5f016..68bf418 100644 --- a/lampada/README.md +++ b/lampada/README.md @@ -1,3 +1,9 @@ +<!-- +SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> + +SPDX-License-Identifier: AGPL-3.0-or-later +--> + # lampada a core xmpp client that graciously manages streams, delegating logic to an implementor of a trait. diff --git a/lampada/src/connection/mod.rs b/lampada/src/connection/mod.rs index 3a3187f..485b93d 100644 --- a/lampada/src/connection/mod.rs +++ b/lampada/src/connection/mod.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + // TODO: consider if this needs to be handled by a supervisor or could be handled by luz directly use std::{ @@ -7,7 +11,7 @@ use std::{ time::Duration, }; -use jid::JID; +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}; @@ -121,12 +125,11 @@ where 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; @@ -169,12 +172,11 @@ where 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; @@ -214,11 +216,10 @@ where 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; @@ -305,8 +306,7 @@ impl SupervisorHandle { pub fn new<Lgc>( streams: BoundJabberStream, on_crash: oneshot::Sender<()>, - jid: JID, - server: JID, + jid: FullJID, password: Arc<String>, logic: Lgc, ) -> (WriteHandle, Self) @@ -327,7 +327,6 @@ impl SupervisorHandle { let connected = Connected { jid, write_handle: write_handle.clone(), - server, }; let supervisor_sender = SupervisorSender { diff --git a/lampada/src/connection/read.rs b/lampada/src/connection/read.rs index 591a2cb..ebcf66a 100644 --- a/lampada/src/connection/read.rs +++ b/lampada/src/connection/read.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{ collections::HashMap, marker::PhantomData, diff --git a/lampada/src/connection/write.rs b/lampada/src/connection/write.rs index b982eea..a047674 100644 --- a/lampada/src/connection/write.rs +++ b/lampada/src/connection/write.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::ops::{Deref, DerefMut}; use luz::jabber_stream::bound_stream::BoundJabberWriter; diff --git a/lampada/src/error.rs b/lampada/src/error.rs index f29d0cc..9ca5f12 100644 --- a/lampada/src/error.rs +++ b/lampada/src/error.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::sync::Arc; use stanza::client::Stanza; @@ -24,7 +28,7 @@ pub enum ConnectionError { #[error("disconnected")] Disconnected, #[error("invalid server jid: {0}")] - InvalidServerJID(#[from] jid::ParseError), + InvalidServerJID(#[from] jid::JIDError), } #[derive(Debug, Error, Clone)] diff --git a/lampada/src/lib.rs b/lampada/src/lib.rs index 6b6cbe8..2b71a9d 100644 --- a/lampada/src/lib.rs +++ b/lampada/src/lib.rs @@ -1,5 +1,9 @@ #![feature(where_clause_attrs)] +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{ collections::HashMap, ops::{Deref, DerefMut}, @@ -12,6 +16,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}, @@ -36,24 +41,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 @@ -227,34 +226,17 @@ where .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.clone(), - )) - .await; - sender.send(Err(ConnectionError::InvalidServerJID(e))); - 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(), ); @@ -262,18 +244,16 @@ where let shutdown_recv = shutdown_recv.fuse(); self.connection_supervisor_shutdown = shutdown_recv; - let resource = jid.resourcepart.clone().expect("client somehow connected without binding"); let connected = Connected { - jid, + 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(resource)); + sender.send(Ok(full_jid.resourcepart)); } Err(e) => { tracing::error!("error: {}", e); diff --git a/luz/Cargo.toml b/luz/Cargo.toml index e9cccd9..a758629 100644 --- a/luz/Cargo.toml +++ b/luz/Cargo.toml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [package] name = "luz" authors = ["cel <cel@bunny.garden>"] diff --git a/luz/src/client.rs b/luz/src/client.rs index ab0aa6d..eb7fcfd 100644 --- a/luz/src/client.rs +++ b/luz/src/client.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + #[cfg(not(target_arch = "wasm32"))] mod tcp; #[cfg(target_arch = "wasm32")] diff --git a/luz/src/client/tcp.rs b/luz/src/client/tcp.rs index 4e35ef0..9f35e0f 100644 --- a/luz/src/client/tcp.rs +++ b/luz/src/client/tcp.rs @@ -1,3 +1,8 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use jid::FullJID; use rsasl::config::SASLConfig; use stanza::{ sasl::Mechanisms, @@ -10,22 +15,25 @@ use crate::{ }; pub async fn connect_and_login( - jid: &mut JID, + jid: &JID, + // jid: &mut JID, password: impl AsRef<str>, - server: &mut String, -) -> Result<BoundJabberStream> { + // 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), server).await?, + JabberStream::start_stream(Connection::Unencrypted(tcp_stream), &mut server) + .await?, ) } Connecting::InsecureStreamStarted(jabber_stream) => { @@ -46,8 +54,9 @@ pub async fn connect_and_login( )) } Connecting::ConnectionEstablished(connection) => { - conn_state = - Connecting::StreamStarted(JabberStream::start_stream(connection, server).await?) + conn_state = Connecting::StreamStarted( + JabberStream::start_stream(connection, &mut server).await?, + ) } Connecting::StreamStarted(jabber_stream) => { conn_state = Connecting::GotFeatures(jabber_stream.get_features().await?) @@ -68,7 +77,7 @@ pub async fn connect_and_login( ) } Connecting::Bind(jabber_stream) => { - return Ok(jabber_stream.bind(jid).await?.to_bound_jabber()); + return Ok(jabber_stream.bind(jid).await?); } } } diff --git a/luz/src/client/ws.rs b/luz/src/client/ws.rs index 13c3cdf..f7cb55b 100644 --- a/luz/src/client/ws.rs +++ b/luz/src/client/ws.rs @@ -1,3 +1,8 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use jid::FullJID; use rsasl::config::SASLConfig; use stanza::{ sasl::Mechanisms, @@ -9,22 +14,22 @@ use crate::{ }; pub async fn connect_and_login( - jid: &mut JID, + jid: &JID, password: impl AsRef<str>, - server: &mut String, -) -> Result<BoundJabberStream> { +) -> 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, server).await?) + Connecting::StreamStarted(JabberStream::start_stream(ws, &mut server).await?) } Connecting::StreamStarted(jabber_stream) => { conn_state = Connecting::GotFeatures(jabber_stream.get_features().await?) @@ -45,7 +50,7 @@ pub async fn connect_and_login( ) } Connecting::Bind(jabber_stream) => { - return Ok(jabber_stream.bind(jid).await?.to_bound_jabber()); + return Ok(jabber_stream.bind(jid).await?); } } } diff --git a/luz/src/connection.rs b/luz/src/connection.rs index d0bdadc..98dccc5 100644 --- a/luz/src/connection.rs +++ b/luz/src/connection.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + #[cfg(not(target_arch = "wasm32"))] mod tcp; #[cfg(target_arch = "wasm32")] diff --git a/luz/src/connection/tcp.rs b/luz/src/connection/tcp.rs index a9e81c3..95a5c38 100644 --- a/luz/src/connection/tcp.rs +++ b/luz/src/connection/tcp.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::net::{IpAddr, SocketAddr}; use std::pin::pin; use std::str; @@ -96,7 +100,7 @@ impl Connection { // } pub async fn connect_user(jid: impl AsRef<str>) -> Result<Self> { - let jid: JID = JID::from_str(jid.as_ref())?; + 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 } diff --git a/luz/src/connection/ws.rs b/luz/src/connection/ws.rs index e64a96e..100ceea 100644 --- a/luz/src/connection/ws.rs +++ b/luz/src/connection/ws.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use js_sys::Error; use peanuts::{ReadableString, Reader}; use stanza::xep_0156::XRD; diff --git a/luz/src/error.rs b/luz/src/error.rs index fcb32a0..60cf2a0 100644 --- a/luz/src/error.rs +++ b/luz/src/error.rs @@ -1,7 +1,11 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + 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; @@ -36,7 +40,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}")] diff --git a/luz/src/jabber_stream.rs b/luz/src/jabber_stream.rs index f77e6a9..131ca42 100644 --- a/luz/src/jabber_stream.rs +++ b/luz/src/jabber_stream.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + pub mod bound_stream; #[cfg(not(target_arch = "wasm32"))] mod tcp; @@ -7,7 +11,8 @@ mod ws; use std::str::{self, FromStr}; use std::sync::Arc; -use jid::JID; +use bound_stream::BoundJabberStream; +use jid::{FullJID, JID}; use peanuts::IntoElement; #[cfg(target_arch = "wasm32")] use peanuts::WebSocketOnMessageRead; @@ -147,9 +152,9 @@ impl JabberStream { } #[instrument] - pub async fn bind(mut self, jid: &mut JID) -> Result<Self> { + 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 { + if let Some(resource) = &jid.resourcepart() { let iq = Iq { from: None, id: iq_id.clone(), @@ -176,8 +181,7 @@ impl JabberStream { })), errors: _, } if id == iq_id => { - *jid = new_jid; - return Ok(self); + return Ok((self.to_bound_jabber(), new_jid)); } Iq { from: _, @@ -219,8 +223,7 @@ impl JabberStream { })), errors: _, } if id == iq_id => { - *jid = new_jid; - return Ok(self); + return Ok((self.to_bound_jabber(), new_jid)); } Iq { from: _, @@ -257,7 +260,11 @@ impl JabberStream { id: None, lang: None, version: Some("1.0".to_string()), - to: Some(JID::from_str(server.as_ref())?), + to: Some( + JID::from_str(server.as_ref()) + .map_err(|e| Error::JID(e.into()))? + .try_into()?, + ), }; writer.write(&open).await?; @@ -290,7 +297,9 @@ impl JabberStream { // 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(), ); diff --git a/luz/src/jabber_stream/bound_stream.rs b/luz/src/jabber_stream/bound_stream.rs index 74ced14..b665434 100644 --- a/luz/src/jabber_stream/bound_stream.rs +++ b/luz/src/jabber_stream/bound_stream.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::ops::{Deref, DerefMut}; use super::{JabberReader, JabberStream, JabberWriter}; diff --git a/luz/src/jabber_stream/tcp.rs b/luz/src/jabber_stream/tcp.rs index 550c308..ea808d9 100644 --- a/luz/src/jabber_stream/tcp.rs +++ b/luz/src/jabber_stream/tcp.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::Loggable; use peanuts::{Reader, Writer}; use tokio::io::{ReadHalf, WriteHalf}; diff --git a/luz/src/jabber_stream/ws.rs b/luz/src/jabber_stream/ws.rs index 72801e6..e0e63c4 100644 --- a/luz/src/jabber_stream/ws.rs +++ b/luz/src/jabber_stream/ws.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::WebSocketOnMessageRead; use peanuts::{Reader, Writer}; use stanza::rfc_7395::Close; diff --git a/luz/src/lib.rs b/luz/src/lib.rs index 8855ca7..09eb679 100644 --- a/luz/src/lib.rs +++ b/luz/src/lib.rs @@ -1,4 +1,9 @@ #![allow(unused_must_use)] + +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + // #![feature(let_chains)] // TODO: logging (dropped errors) diff --git a/stanza/Cargo.toml b/stanza/Cargo.toml index 884584a..9bbe3f3 100644 --- a/stanza/Cargo.toml +++ b/stanza/Cargo.toml @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +# +# SPDX-License-Identifier: AGPL-3.0-or-later + [package] name = "stanza" version = "0.1.0" @@ -24,5 +28,8 @@ xep_0156 = ["dep:chrono"] xep_0172 = [] xep_0199 = [] xep_0203 = ["dep:chrono"] +xep_0280 = ["xep_0297"] +xep_0297 = ["xep_0203"] xep_0300 = [] +xep_0334 = [] xep_0390 = ["xep_0300"] diff --git a/stanza/src/bind.rs b/stanza/src/bind.rs index 3ce2246..c04651c 100644 --- a/stanza/src/bind.rs +++ b/stanza/src/bind.rs @@ -1,4 +1,8 @@ -use jid::JID; +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use jid::FullJID; use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-bind"; @@ -54,7 +58,7 @@ 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::DeserializeResult<Self> { diff --git a/stanza/src/client/error.rs b/stanza/src/client/error.rs index 9cc85a9..7dac178 100644 --- a/stanza/src/client/error.rs +++ b/stanza/src/client/error.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::fmt::Display; use std::str::FromStr; diff --git a/stanza/src/client/iq.rs b/stanza/src/client/iq.rs index 478530a..be2a3f1 100644 --- a/stanza/src/client/iq.rs +++ b/stanza/src/client/iq.rs @@ -1,8 +1,14 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use jid::JID; use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS}; +#[cfg(feature = "xep_0280")] +use crate::xep_0280::{self, Disable, Enable}; use crate::{ bind::{self, Bind}, client::error::Error, @@ -53,6 +59,10 @@ pub enum Query { Ping(Ping), #[cfg(feature = "rfc_6121")] Roster(roster::Query), + #[cfg(feature = "xep_0280")] + CarbonsEnable(Enable), + #[cfg(feature = "xep_0280")] + CarbonsDisable(Disable), Unsupported, } @@ -80,6 +90,14 @@ impl FromElement for Query { (Some(xep_0060::owner::XMLNS), "pubsub") => Ok(Query::PubsubOwner( xep_0060::owner::Pubsub::from_element(element)?, )), + #[cfg(feature = "xep_0280")] + (Some(xep_0280::XMLNS), "enable") => { + Ok(Query::CarbonsEnable(Enable::from_element(element)?)) + } + #[cfg(feature = "xep_0280")] + (Some(xep_0280::XMLNS), "disable") => { + Ok(Query::CarbonsDisable(Disable::from_element(element)?)) + } _ => Ok(Query::Unsupported), } } @@ -103,6 +121,10 @@ impl IntoElement for Query { Query::Pubsub(pubsub) => pubsub.builder(), #[cfg(feature = "xep_0060")] Query::PubsubOwner(pubsub) => pubsub.builder(), + #[cfg(feature = "xep_0280")] + Query::CarbonsEnable(enable) => enable.builder(), + #[cfg(feature = "xep_0280")] + Query::CarbonsDisable(disable) => disable.builder(), } } } diff --git a/stanza/src/client/message.rs b/stanza/src/client/message.rs index 41761d2..a489201 100644 --- a/stanza/src/client/message.rs +++ b/stanza/src/client/message.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use jid::JID; @@ -11,6 +15,12 @@ use crate::xep_0131::Headers; use crate::xep_0172::Nick; #[cfg(feature = "xep_0203")] use crate::xep_0203::Delay; +#[cfg(feature = "xep_0280")] +use crate::xep_0280::{Private, Received, Sent}; +#[cfg(feature = "xep_0297")] +use crate::xep_0297::Forwarded; +#[cfg(feature = "xep_0334")] +use crate::xep_0334::{NoCopy, NoPermanentStore, NoStore, Store}; use super::XMLNS; @@ -34,6 +44,22 @@ pub struct Message { pub nick: Option<Nick>, #[cfg(feature = "xep_0060")] pub event: Option<Event>, + #[cfg(feature = "xep_0297")] + pub forwarded: Option<Forwarded>, + #[cfg(feature = "xep_0280")] + pub sent: Option<Sent>, + #[cfg(feature = "xep_0280")] + pub received: Option<Received>, + #[cfg(feature = "xep_0280")] + pub private: Option<Private>, + #[cfg(feature = "xep_0334")] + pub no_permanent_store: Option<NoPermanentStore>, + #[cfg(feature = "xep_0334")] + pub no_store: Option<NoStore>, + #[cfg(feature = "xep_0334")] + pub no_copy: Option<NoCopy>, + #[cfg(feature = "xep_0334")] + pub store: Option<Store>, } impl FromElement for Message { @@ -63,6 +89,30 @@ impl FromElement for Message { #[cfg(feature = "xep_0060")] let event = element.child_opt()?; + #[cfg(feature = "xep_0297")] + let forwarded = element.child_opt()?; + + #[cfg(feature = "xep_0280")] + let sent = element.child_opt()?; + + #[cfg(feature = "xep_0280")] + let received = element.child_opt()?; + + #[cfg(feature = "xep_0280")] + let private = element.child_opt()?; + + #[cfg(feature = "xep_0334")] + let no_permanent_store = element.child_opt()?; + + #[cfg(feature = "xep_0334")] + let no_store = element.child_opt()?; + + #[cfg(feature = "xep_0334")] + let no_copy = element.child_opt()?; + + #[cfg(feature = "xep_0334")] + let store = element.child_opt()?; + Ok(Message { from, id, @@ -80,6 +130,22 @@ impl FromElement for Message { nick, #[cfg(feature = "xep_0060")] event, + #[cfg(feature = "xep_0297")] + forwarded, + #[cfg(feature = "xep_0280")] + sent, + #[cfg(feature = "xep_0280")] + received, + #[cfg(feature = "xep_0280")] + private, + #[cfg(feature = "xep_0334")] + no_permanent_store, + #[cfg(feature = "xep_0334")] + no_store, + #[cfg(feature = "xep_0334")] + no_copy, + #[cfg(feature = "xep_0334")] + store, }) } } @@ -114,6 +180,30 @@ 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()); + + #[cfg(feature = "xep_0280")] + let builder = builder.push_child_opt(self.sent.clone()); + + #[cfg(feature = "xep_0280")] + let builder = builder.push_child_opt(self.received.clone()); + + #[cfg(feature = "xep_0280")] + let builder = builder.push_child_opt(self.private.clone()); + + #[cfg(feature = "xep_0334")] + let builder = builder.push_child_opt(self.no_permanent_store); + + #[cfg(feature = "xep_0334")] + let builder = builder.push_child_opt(self.no_store); + + #[cfg(feature = "xep_0334")] + let builder = builder.push_child_opt(self.no_copy); + + #[cfg(feature = "xep_0334")] + let builder = builder.push_child_opt(self.store); + builder } } diff --git a/stanza/src/client/mod.rs b/stanza/src/client/mod.rs index aca4fad..00ad3ed 100644 --- a/stanza/src/client/mod.rs +++ b/stanza/src/client/mod.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Content, ContentBuilder, DeserializeError, FromContent, FromElement, IntoContent}; use iq::Iq; diff --git a/stanza/src/client/presence.rs b/stanza/src/client/presence.rs index b0a0bc0..02de229 100644 --- a/stanza/src/client/presence.rs +++ b/stanza/src/client/presence.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use jid::JID; diff --git a/stanza/src/lib.rs b/stanza/src/lib.rs index 8f8d430..8cc3755 100644 --- a/stanza/src/lib.rs +++ b/stanza/src/lib.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::declaration::VersionInfo; pub mod bind; @@ -33,8 +37,14 @@ pub mod xep_0172; pub mod xep_0199; #[cfg(feature = "xep_0203")] pub mod xep_0203; +#[cfg(feature = "xep_0280")] +pub mod xep_0280; +#[cfg(feature = "xep_0297")] +pub mod xep_0297; #[cfg(feature = "xep_0300")] pub mod xep_0300; +#[cfg(feature = "xep_0334")] +pub mod xep_0334; #[cfg(feature = "xep_0390")] pub mod xep_0390; diff --git a/stanza/src/rfc_7395.rs b/stanza/src/rfc_7395.rs index 64d9f70..c632116 100644 --- a/stanza/src/rfc_7395.rs +++ b/stanza/src/rfc_7395.rs @@ -1,12 +1,16 @@ -use jid::JID; +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +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<JID>, - pub to: Option<JID>, + pub from: Option<BareJID>, + pub to: Option<BareJID>, pub id: Option<String>, pub version: Option<String>, pub lang: Option<String>, @@ -46,8 +50,8 @@ impl IntoElement for Open { #[derive(Debug, Default)] pub struct Close { - pub from: Option<JID>, - pub to: Option<JID>, + pub from: Option<BareJID>, + pub to: Option<BareJID>, pub id: Option<String>, pub version: Option<String>, pub lang: Option<String>, diff --git a/stanza/src/roster.rs b/stanza/src/roster.rs index 14f65ef..fe67ad1 100644 --- a/stanza/src/roster.rs +++ b/stanza/src/roster.rs @@ -1,6 +1,10 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; -use jid::JID; +use jid::BareJID; use peanuts::{DeserializeError, Element, FromElement, IntoElement}; pub const XMLNS: &str = "jabber:iq:roster"; @@ -38,7 +42,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 diff --git a/stanza/src/sasl.rs b/stanza/src/sasl.rs index 58aab84..2935923 100644 --- a/stanza/src/sasl.rs +++ b/stanza/src/sasl.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{fmt::Display, ops::Deref}; use peanuts::{DeserializeError, Element, FromElement, IntoElement}; diff --git a/stanza/src/stanza_error.rs b/stanza/src/stanza_error.rs index 8fb862f..bb0c24f 100644 --- a/stanza/src/stanza_error.rs +++ b/stanza/src/stanza_error.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + // https://datatracker.ietf.org/doc/html/rfc6120#appendix-A.8 use peanuts::{Element, FromElement, IntoElement, XML_NS}; diff --git a/stanza/src/starttls.rs b/stanza/src/starttls.rs index 730c044..92ae315 100644 --- a/stanza/src/starttls.rs +++ b/stanza/src/starttls.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "urn:ietf:params:xml:ns:xmpp-tls"; diff --git a/stanza/src/stream.rs b/stanza/src/stream.rs index 5be235a..f8aef33 100644 --- a/stanza/src/stream.rs +++ b/stanza/src/stream.rs @@ -1,6 +1,10 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::fmt::Display; -use jid::JID; +use jid::BareJID; use peanuts::{Element, ElementBuilder, FromElement, IntoElement}; use thiserror::Error; @@ -18,8 +22,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 @@ -64,8 +68,8 @@ impl IntoElement for Stream { 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>, @@ -81,7 +85,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), diff --git a/stanza/src/stream_error.rs b/stanza/src/stream_error.rs index 19ad1ae..e068cbf 100644 --- a/stanza/src/stream_error.rs +++ b/stanza/src/stream_error.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS}; use thiserror::Error; diff --git a/stanza/src/xep_0004.rs b/stanza/src/xep_0004.rs index f6ff7a0..b7b4878 100644 --- a/stanza/src/xep_0004.rs +++ b/stanza/src/xep_0004.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use peanuts::{DeserializeError, Element, FromElement, IntoElement}; diff --git a/stanza/src/xep_0030/info.rs b/stanza/src/xep_0030/info.rs index 0344ccb..69c795d 100644 --- a/stanza/src/xep_0030/info.rs +++ b/stanza/src/xep_0030/info.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{DeserializeError, Element, FromElement, IntoElement, XML_NS}; #[cfg(feature = "xep_0128")] diff --git a/stanza/src/xep_0030/items.rs b/stanza/src/xep_0030/items.rs index 7707eac..4096707 100644 --- a/stanza/src/xep_0030/items.rs +++ b/stanza/src/xep_0030/items.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use jid::JID; use peanuts::{Element, FromElement, IntoElement}; diff --git a/stanza/src/xep_0030/mod.rs b/stanza/src/xep_0030/mod.rs index 914c17b..0faaf04 100644 --- a/stanza/src/xep_0030/mod.rs +++ b/stanza/src/xep_0030/mod.rs @@ -1,2 +1,6 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + pub mod info; pub mod items; diff --git a/stanza/src/xep_0059.rs b/stanza/src/xep_0059.rs index 6490ad1..84f84ff 100644 --- a/stanza/src/xep_0059.rs +++ b/stanza/src/xep_0059.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "http://jabber.org/protocol/rsm"; diff --git a/stanza/src/xep_0060/errors.rs b/stanza/src/xep_0060/errors.rs index 6c6c530..a52ea85 100644 --- a/stanza/src/xep_0060/errors.rs +++ b/stanza/src/xep_0060/errors.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{fmt::Display, str::FromStr}; use peanuts::{DeserializeError, Element, FromElement, IntoElement}; diff --git a/stanza/src/xep_0060/event.rs b/stanza/src/xep_0060/event.rs index 3cb124b..f3cae8b 100644 --- a/stanza/src/xep_0060/event.rs +++ b/stanza/src/xep_0060/event.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use chrono::{DateTime, Utc}; diff --git a/stanza/src/xep_0060/mod.rs b/stanza/src/xep_0060/mod.rs index 566310f..ac8a849 100644 --- a/stanza/src/xep_0060/mod.rs +++ b/stanza/src/xep_0060/mod.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + pub mod errors; pub mod event; pub mod owner; diff --git a/stanza/src/xep_0060/owner.rs b/stanza/src/xep_0060/owner.rs index 0617712..3b6c6f6 100644 --- a/stanza/src/xep_0060/owner.rs +++ b/stanza/src/xep_0060/owner.rs @@ -1,6 +1,10 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; -use jid::JID; +use jid::{BareJID, JID}; use peanuts::{DeserializeError, Element, FromElement, IntoElement}; use crate::xep_0004::X; @@ -85,7 +89,7 @@ impl IntoElement for Affiliations { #[derive(Clone, Debug)] pub struct Affiliation { affiliation: AffiliationType, - jid: JID, + jid: BareJID, } impl FromElement for Affiliation { diff --git a/stanza/src/xep_0060/pubsub.rs b/stanza/src/xep_0060/pubsub.rs index 0416b78..94277b9 100644 --- a/stanza/src/xep_0060/pubsub.rs +++ b/stanza/src/xep_0060/pubsub.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::str::FromStr; use jid::JID; diff --git a/stanza/src/xep_0084/data.rs b/stanza/src/xep_0084/data.rs index 4b3223f..d147550 100644 --- a/stanza/src/xep_0084/data.rs +++ b/stanza/src/xep_0084/data.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "urn:xmpp:avatar:data"; diff --git a/stanza/src/xep_0084/metadata.rs b/stanza/src/xep_0084/metadata.rs index e4edb2f..b9d3e60 100644 --- a/stanza/src/xep_0084/metadata.rs +++ b/stanza/src/xep_0084/metadata.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "urn:xmpp:avatar:metadata"; diff --git a/stanza/src/xep_0084/mod.rs b/stanza/src/xep_0084/mod.rs index be7d5d7..1e80c9a 100644 --- a/stanza/src/xep_0084/mod.rs +++ b/stanza/src/xep_0084/mod.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + pub use data::Data; pub use metadata::Info; pub use metadata::Metadata; diff --git a/stanza/src/xep_0115.rs b/stanza/src/xep_0115.rs index 1c9cd6f..c983f2b 100644 --- a/stanza/src/xep_0115.rs +++ b/stanza/src/xep_0115.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "http://jabber.org/protocol/caps"; diff --git a/stanza/src/xep_0131.rs b/stanza/src/xep_0131.rs index 68e6e96..8d296b3 100644 --- a/stanza/src/xep_0131.rs +++ b/stanza/src/xep_0131.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "http://jabber.org/protocol/disco#info"; diff --git a/stanza/src/xep_0156.rs b/stanza/src/xep_0156.rs index bf6eac5..8b3d07c 100644 --- a/stanza/src/xep_0156.rs +++ b/stanza/src/xep_0156.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use chrono::{DateTime, Utc}; use peanuts::{Element, FromElement, IntoElement, XML_NS}; diff --git a/stanza/src/xep_0172.rs b/stanza/src/xep_0172.rs index 54846b8..8374bab 100644 --- a/stanza/src/xep_0172.rs +++ b/stanza/src/xep_0172.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "http://jabber.org/protocol/nick"; diff --git a/stanza/src/xep_0199.rs b/stanza/src/xep_0199.rs index 2ab3a86..17e9fd4 100644 --- a/stanza/src/xep_0199.rs +++ b/stanza/src/xep_0199.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use peanuts::{Element, FromElement, IntoElement}; pub const XMLNS: &str = "urn:xmpp:ping"; diff --git a/stanza/src/xep_0203.rs b/stanza/src/xep_0203.rs index 41ff196..0f4b298 100644 --- a/stanza/src/xep_0203.rs +++ b/stanza/src/xep_0203.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use chrono::{DateTime, Utc}; use jid::JID; use peanuts::{Element, FromElement, IntoElement}; diff --git a/stanza/src/xep_0280.rs b/stanza/src/xep_0280.rs new file mode 100644 index 0000000..74d2897 --- /dev/null +++ b/stanza/src/xep_0280.rs @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use peanuts::{Element, FromElement, IntoElement}; + +use crate::xep_0297::Forwarded; + +pub const XMLNS: &str = "urn:xmpp:carbons:2"; + +#[derive(Clone, Debug)] +pub struct Disable; + +impl FromElement for Disable { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("disable")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for Disable { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("disable", Some(XMLNS)) + } +} + +#[derive(Clone, Debug)] +pub struct Enable; + +impl FromElement for Enable { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("enable")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for Enable { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("enable", Some(XMLNS)) + } +} + +#[derive(Clone, Debug)] +pub struct Private; + +impl FromElement for Private { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("private")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for Private { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("private", Some(XMLNS)) + } +} + +#[derive(Clone, Debug)] +pub struct Received { + forwarded: Forwarded, +} + +impl FromElement for Received { + fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("received")?; + element.check_namespace(XMLNS)?; + + let forwarded = element.pop_child_one()?; + + Ok(Self { forwarded }) + } +} + +impl IntoElement for Received { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("received", Some(XMLNS)).push_child(self.forwarded.clone()) + } +} + +#[derive(Clone, Debug)] +pub struct Sent { + forwarded: Forwarded, +} + +impl FromElement for Sent { + fn from_element(mut element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("sent")?; + element.check_namespace(XMLNS)?; + + let forwarded = element.pop_child_one()?; + + Ok(Self { forwarded }) + } +} + +impl IntoElement for Sent { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("sent", Some(XMLNS)).push_child(self.forwarded.clone()) + } +} diff --git a/stanza/src/xep_0297.rs b/stanza/src/xep_0297.rs new file mode 100644 index 0000000..d686e49 --- /dev/null +++ b/stanza/src/xep_0297.rs @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +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>>, +} + +// TODO: raw stanza source option +pub enum ForwardedStanza { + Parsed(Box<Stanza>), + Raw(String), +} + +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 f522f1c..5a2a88b 100644 --- a/stanza/src/xep_0300.rs +++ b/stanza/src/xep_0300.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use std::{convert::Infallible, str::FromStr}; use peanuts::{Element, FromElement, IntoElement}; diff --git a/stanza/src/xep_0334.rs b/stanza/src/xep_0334.rs new file mode 100644 index 0000000..a13e125 --- /dev/null +++ b/stanza/src/xep_0334.rs @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +use peanuts::{Element, FromElement, IntoElement}; + +pub const XMLNS: &str = "urn:xmpp:hints"; + +#[derive(Clone, Copy, Debug)] +pub struct NoPermanentStore; + +impl FromElement for NoPermanentStore { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("no-permanent-store")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for NoPermanentStore { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("no-permanent-store", Some(XMLNS)) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct NoStore; + +impl FromElement for NoStore { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("no-store")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for NoStore { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("no-store", Some(XMLNS)) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct NoCopy; + +impl FromElement for NoCopy { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("no-copy")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for NoCopy { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("no-copy", Some(XMLNS)) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Store; + +impl FromElement for Store { + fn from_element(element: Element) -> peanuts::DeserializeResult<Self> { + element.check_name("store")?; + element.check_namespace(XMLNS)?; + + element.no_more_content()?; + + Ok(Self) + } +} + +impl IntoElement for Store { + fn builder(&self) -> peanuts::ElementBuilder { + Element::builder("store", Some(XMLNS)) + } +} diff --git a/stanza/src/xep_0390.rs b/stanza/src/xep_0390.rs index 1a079c2..248ff9a 100644 --- a/stanza/src/xep_0390.rs +++ b/stanza/src/xep_0390.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2025 cel <cel@bunny.garden> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + use crate::xep_0300::Hash; use peanuts::{Element, FromElement, IntoElement}; |
