updated to 22.0.1

This commit is contained in:
Fr4nz D13trich 2025-10-04 10:56:01 +02:00
parent 9fc8a043ba
commit 44a570528b
243 changed files with 14828 additions and 3056 deletions

View file

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

117
LICENSES/GPL-2.0-only.txt Normal file
View file

@ -0,0 +1,117 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
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 this service 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.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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.
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 convey 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 an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

View file

@ -13,9 +13,9 @@ import com.github.spotbugs.snom.Effort
import com.github.spotbugs.snom.SpotBugsTask import com.github.spotbugs.snom.SpotBugsTask
plugins { plugins {
id "org.jetbrains.kotlin.plugin.compose" version "2.2.0" id "org.jetbrains.kotlin.plugin.compose" version "2.2.10"
id "org.jetbrains.kotlin.kapt" id "org.jetbrains.kotlin.kapt"
id 'com.google.devtools.ksp' version '2.2.0-2.0.2' id 'com.google.devtools.ksp' version '2.2.10-2.0.2'
} }
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
@ -28,22 +28,22 @@ apply plugin: "org.jlleitschuh.gradle.ktlint"
apply plugin: 'kotlinx-serialization' apply plugin: 'kotlinx-serialization'
android { android {
compileSdk 35 compileSdkVersion 35
namespace 'com.nextcloud.talk' namespace = 'com.nextcloud.talk'
defaultConfig { defaultConfig {
minSdkVersion 26 minSdkVersion 26
targetSdkVersion 35 targetSdkVersion 35
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
// mayor.minor.hotfix.increment (for increment: 01-50=Alpha / 51-89=RC / 90-99=stable) // mayor.minor.hotfix.increment (for increment: 01-50=Alpha / 51-89=RC / 90-99=stable)
// xx .xxx .xx .xx // xx .xxx .xx .xx
versionCode 210020090 versionCode 220000190
versionName "21.2.0" versionName "22.0.1"
flavorDimensions "default" flavorDimensions "default"
renderscriptTargetApi 19 renderscriptTargetApi = 19
renderscriptSupportModeEnabled true renderscriptSupportModeEnabled true
productFlavors { productFlavors {
@ -65,7 +65,7 @@ android {
} }
// Enabling multidex support. // Enabling multidex support.
multiDexEnabled true multiDexEnabled = true
vectorDrawables.useSupportLibrary = true vectorDrawables.useSupportLibrary = true
@ -82,6 +82,11 @@ android {
} }
} }
sourceSets {
// Adds exported schema location as test app assets.
getByName("androidTest").assets.srcDir("$projectDir/schemas")
}
testInstrumentationRunnerArgument "TEST_SERVER_URL", "${NC_TEST_SERVER_BASEURL}" testInstrumentationRunnerArgument "TEST_SERVER_URL", "${NC_TEST_SERVER_BASEURL}"
testInstrumentationRunnerArgument "TEST_SERVER_USERNAME", "${NC_TEST_SERVER_USERNAME}" testInstrumentationRunnerArgument "TEST_SERVER_USERNAME", "${NC_TEST_SERVER_USERNAME}"
testInstrumentationRunnerArgument "TEST_SERVER_PASSWORD", "${NC_TEST_SERVER_PASSWORD}" testInstrumentationRunnerArgument "TEST_SERVER_PASSWORD", "${NC_TEST_SERVER_PASSWORD}"
@ -95,6 +100,7 @@ android {
unitTests.all { unitTests.all {
useJUnitPlatform() useJUnitPlatform()
} }
unitTests.returnDefaultValues = true
} }
buildTypes { buildTypes {
@ -129,7 +135,7 @@ android {
} }
buildFeatures { buildFeatures {
viewBinding true viewBinding = true
buildConfig = true buildConfig = true
compose = true compose = true
} }
@ -139,10 +145,10 @@ android {
} }
lint { lint {
abortOnError false abortOnError = false
disable 'MissingTranslation','PrivateResource' disable 'MissingTranslation','PrivateResource'
htmlOutput file("$project.buildDir/reports/lint/lint.html") htmlOutput = layout.buildDirectory.file("reports/lint/lint.html").get().asFile
htmlReport true htmlReport = true
} }
} }
kapt { kapt {
@ -152,10 +158,10 @@ kapt {
ext { ext {
androidxCameraVersion = "1.4.2" androidxCameraVersion = "1.4.2"
coilKtVersion = "2.7.0" coilKtVersion = "2.7.0"
daggerVersion = "2.56.2" daggerVersion = "2.57.1"
emojiVersion = "1.5.0" emojiVersion = "1.5.0"
fidoVersion = "4.1.0-patch2" fidoVersion = "4.1.0-patch2"
lifecycleVersion = '2.9.1' lifecycleVersion = '2.9.3'
okhttpVersion = "4.12.0" okhttpVersion = "4.12.0"
markwonVersion = "4.6.2" markwonVersion = "4.6.2"
materialDialogsVersion = "3.3.0" materialDialogsVersion = "3.3.0"
@ -163,10 +169,10 @@ ext {
prismVersion = "2.0.0" prismVersion = "2.0.0"
retrofit2Version = "3.0.0" retrofit2Version = "3.0.0"
roomVersion = "2.7.2" roomVersion = "2.7.2"
workVersion = "2.10.2" workVersion = "2.10.3"
espressoVersion = "3.6.1" espressoVersion = "3.7.0"
androidxTestVersion = "1.5.0" androidxTestVersion = "1.5.0"
media3_version = "1.7.1" media3_version = "1.8.0"
coroutines_version = "1.10.2" coroutines_version = "1.10.2"
mockitoKotlinVersion = "6.0.0" mockitoKotlinVersion = "6.0.0"
} }
@ -179,22 +185,24 @@ configurations.configureEach {
} }
dependencies { dependencies {
implementation "androidx.room:room-testing-android:${roomVersion}"
implementation 'androidx.compose.foundation:foundation-layout:1.9.0'
spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0' spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0'
spotbugsPlugins 'com.mebigfatguy.fb-contrib:fb-contrib:7.6.11' spotbugsPlugins 'com.mebigfatguy.fb-contrib:fb-contrib:7.6.14'
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.8") detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.8")
implementation("androidx.compose.runtime:runtime:1.8.3") implementation("androidx.compose.runtime:runtime:1.9.0")
implementation 'androidx.preference:preference-ktx:1.2.1' implementation 'androidx.preference:preference-ktx:1.2.1'
implementation 'androidx.datastore:datastore-core:1.1.7' implementation 'androidx.datastore:datastore-core:1.1.7'
implementation 'androidx.datastore:datastore-preferences:1.1.7' implementation 'androidx.datastore:datastore-preferences:1.1.7'
implementation 'androidx.test.ext:junit-ktx:1.2.1' implementation 'androidx.test.ext:junit-ktx:1.3.0'
implementation fileTree(include: ['*'], dir: 'libs') implementation fileTree(include: ['*'], dir: 'libs')
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0" implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0"
implementation 'androidx.appcompat:appcompat:1.7.1' implementation 'androidx.appcompat:appcompat:1.7.1'
implementation 'com.google.android.material:material:1.12.0' implementation 'com.google.android.material:material:1.13.0'
implementation 'androidx.constraintlayout:constraintlayout:2.2.1' implementation 'androidx.constraintlayout:constraintlayout:2.2.1'
implementation "com.vanniktech:emoji-google:0.21.0" implementation "com.vanniktech:emoji-google:0.21.0"
implementation "androidx.emoji2:emoji2:${emojiVersion}" implementation "androidx.emoji2:emoji2:${emojiVersion}"
@ -210,6 +218,7 @@ dependencies {
exclude group: 'org.ogce', module: 'xpp3' // Android comes with its own XmlPullParser exclude group: 'org.ogce', module: 'xpp3' // Android comes with its own XmlPullParser
}) })
implementation 'org.conscrypt:conscrypt-android:2.5.3' implementation 'org.conscrypt:conscrypt-android:2.5.3'
implementation "com.github.nextcloud-deps:qrcodescanner:0.1.2.4" // "com.github.blikoon:QRCodeScanner:0.1.2"
implementation "androidx.camera:camera-core:${androidxCameraVersion}" implementation "androidx.camera:camera-core:${androidxCameraVersion}"
implementation "androidx.camera:camera-camera2:${androidxCameraVersion}" implementation "androidx.camera:camera-camera2:${androidxCameraVersion}"
@ -236,7 +245,7 @@ dependencies {
implementation "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}" implementation "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}"
implementation 'com.bluelinelabs:logansquare:1.3.7' implementation 'com.bluelinelabs:logansquare:1.3.7'
implementation 'com.fasterxml.jackson.core:jackson-core:2.19.1' implementation 'com.fasterxml.jackson.core:jackson-core:2.20.0'
kapt 'com.bluelinelabs:logansquare-compiler:1.3.7' kapt 'com.bluelinelabs:logansquare-compiler:1.3.7'
implementation "com.squareup.retrofit2:retrofit:${retrofit2Version}" implementation "com.squareup.retrofit2:retrofit:${retrofit2Version}"
@ -251,7 +260,7 @@ dependencies {
compileOnly 'javax.annotation:javax.annotation-api:1.3.2' compileOnly 'javax.annotation:javax.annotation-api:1.3.2'
implementation 'org.greenrobot:eventbus:3.3.1' implementation 'org.greenrobot:eventbus:3.3.1'
implementation 'net.zetetic:sqlcipher-android:4.9.0' implementation 'net.zetetic:sqlcipher-android:4.10.0'
implementation "androidx.room:room-runtime:${roomVersion}" implementation "androidx.room:room-runtime:${roomVersion}"
implementation "androidx.room:room-rxjava2:${roomVersion}" implementation "androidx.room:room-rxjava2:${roomVersion}"
@ -261,7 +270,7 @@ dependencies {
implementation "org.parceler:parceler-api:$parcelerVersion" implementation "org.parceler:parceler-api:$parcelerVersion"
implementation 'com.github.ddB0515.FlexibleAdapter:flexible-adapter:5.1.1' implementation 'com.github.ddB0515.FlexibleAdapter:flexible-adapter:5.1.1'
implementation 'com.github.ddB0515.FlexibleAdapter:flexible-adapter-ui:5.1.1' implementation 'com.github.ddB0515.FlexibleAdapter:flexible-adapter-ui:5.1.1'
implementation 'org.apache.commons:commons-lang3:3.17.0' implementation 'org.apache.commons:commons-lang3:3.18.0'
implementation 'com.github.wooplr:Spotlight:1.3' implementation 'com.github.wooplr:Spotlight:1.3'
implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation 'com.google.code.findbugs:jsr305:3.0.2'
implementation 'com.github.nextcloud-deps:ChatKit:0.4.2' implementation 'com.github.nextcloud-deps:ChatKit:0.4.2'
@ -303,14 +312,14 @@ dependencies {
implementation 'androidx.core:core-ktx:1.16.0' implementation 'androidx.core:core-ktx:1.16.0'
implementation 'androidx.activity:activity-ktx:1.10.1' implementation 'androidx.activity:activity-ktx:1.10.1'
implementation 'com.github.nextcloud.android-common:ui:0.27.0' implementation 'com.github.nextcloud.android-common:ui:0.28.0'
implementation 'com.github.nextcloud-deps:android-talk-webrtc:132.6834.0' implementation 'com.github.nextcloud-deps:android-talk-webrtc:132.6834.0'
gplayImplementation 'com.google.android.gms:play-services-base:18.6.0' gplayImplementation 'com.google.android.gms:play-services-base:18.6.0'
gplayImplementation "com.google.firebase:firebase-messaging:24.1.2" gplayImplementation "com.google.firebase:firebase-messaging:24.1.2"
//compose //compose
implementation(platform("androidx.compose:compose-bom:2025.06.01")) implementation(platform("androidx.compose:compose-bom:2025.08.01"))
implementation("androidx.compose.ui:ui") implementation("androidx.compose.ui:ui")
implementation 'androidx.compose.material3:material3:1.3.2' implementation 'androidx.compose.material3:material3:1.3.2'
implementation("androidx.compose.ui:ui-tooling-preview") implementation("androidx.compose.ui:ui-tooling-preview")
@ -318,18 +327,19 @@ dependencies {
debugImplementation("androidx.compose.ui:ui-tooling") debugImplementation("androidx.compose.ui:ui-tooling")
//tests //tests
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.8.3") testRuntimeOnly 'org.junit.platform:junit-platform-launcher:1.13.4'
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.9.0")
debugImplementation("androidx.compose.ui:ui-test-manifest") debugImplementation("androidx.compose.ui:ui-test-manifest")
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.18.0' testImplementation 'org.mockito:mockito-core:5.19.0'
testImplementation 'androidx.arch.core:core-testing:2.2.0' testImplementation 'androidx.arch.core:core-testing:2.2.0'
androidTestImplementation "androidx.test:core:1.6.1" androidTestImplementation "androidx.test:core:1.7.0"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2" androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2"
androidTestImplementation 'androidx.test:core-ktx:1.6.1' androidTestImplementation 'androidx.test:core-ktx:1.7.0'
androidTestImplementation 'org.mockito:mockito-android:5.18.0' androidTestImplementation 'org.mockito:mockito-android:5.19.0'
androidTestImplementation "androidx.work:work-testing:${workVersion}" androidTestImplementation "androidx.work:work-testing:${workVersion}"
// Espresso core // Espresso core
androidTestImplementation ("androidx.test.espresso:espresso-core:$espressoVersion", { androidTestImplementation ("androidx.test.espresso:espresso-core:$espressoVersion", {
@ -343,11 +353,15 @@ dependencies {
androidTestImplementation('com.android.support.test.espresso:espresso-intents:3.0.2') androidTestImplementation('com.android.support.test.espresso:espresso-intents:3.0.2')
androidTestImplementation(platform("androidx.compose:compose-bom:2025.06.01")) androidTestImplementation(platform("androidx.compose:compose-bom:2025.08.01"))
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion" testImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version" testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version"
testImplementation 'org.junit.vintage:junit-vintage-engine:5.13.3' testImplementation 'org.junit.vintage:junit-vintage-engine:5.13.4' // DO NOT REMOVE
testImplementation "androidx.room:room-testing:${roomVersion}"
testImplementation("com.squareup.okhttp3:mockwebserver:$okhttpVersion")
testImplementation("com.google.dagger:hilt-android-testing:2.57.1")
testImplementation("org.robolectric:robolectric:4.16")
} }
tasks.register('installGitHooks', Copy) { tasks.register('installGitHooks', Copy) {
@ -371,14 +385,14 @@ tasks.withType(SpotBugsTask).configureEach { task ->
dependsOn "compile${variantNameCap}Sources" dependsOn "compile${variantNameCap}Sources"
excludeFilter = file("${project.rootDir}/spotbugs-filter.xml") excludeFilter = file("${project.rootDir}/spotbugs-filter.xml")
classes = fileTree("$project.buildDir/intermediates/javac/${variantName}/compile${variantNameCap}JavaWithJavac/classes/") classes = fileTree(layout.buildDirectory.get().asFile.toString()+"/intermediates/javac/${variantName}/compile${variantNameCap}JavaWithJavac/classes/")
reports { reports {
xml { xml {
required = true required = true
} }
html { html {
required = true required = true
outputLocation = file("$project.buildDir/reports/spotbugs/spotbugs.html") outputLocation = layout.buildDirectory.file("reports/spotbugs/spotbugs.html")
stylesheet = 'fancy.xsl' stylesheet = 'fancy.xsl'
} }
} }

View file

@ -1,709 +1,146 @@
{ {
"formatVersion": 1, "formatVersion": 1,
"database": { "database": {
"version": 10, "version": 10,
"identityHash": "c07a2543aa583e08e7b3208f44fcc7ac", "identityHash": "1b2dab0ea495c45c9c9ee6e64ba74039",
"entities": [ "entities": [
{ {
"tableName": "User", "tableName": "User",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userId` TEXT, `username` TEXT, `baseUrl` TEXT, `token` TEXT, `displayName` TEXT, `pushConfigurationState` TEXT, `capabilities` TEXT, `serverVersion` TEXT DEFAULT '', `clientCertificate` TEXT, `externalSignalingServer` TEXT, `current` INTEGER NOT NULL, `scheduledForDeletion` INTEGER NOT NULL)", "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userId` TEXT, `username` TEXT, `baseUrl` TEXT, `token` TEXT, `displayName` TEXT, `pushConfigurationState` TEXT, `capabilities` TEXT, `serverVersion` TEXT DEFAULT '', `clientCertificate` TEXT, `externalSignalingServer` TEXT, `current` INTEGER NOT NULL, `scheduledForDeletion` INTEGER NOT NULL)",
"fields": [ "fields": [
{ {
"fieldPath": "id", "fieldPath": "id",
"columnName": "id", "columnName": "id",
"affinity": "INTEGER", "affinity": "INTEGER",
"notNull": true "notNull": true
}, },
{ {
"fieldPath": "userId", "fieldPath": "userId",
"columnName": "userId", "columnName": "userId",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "username", "fieldPath": "username",
"columnName": "username", "columnName": "username",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "baseUrl", "fieldPath": "baseUrl",
"columnName": "baseUrl", "columnName": "baseUrl",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "token", "fieldPath": "token",
"columnName": "token", "columnName": "token",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "displayName", "fieldPath": "displayName",
"columnName": "displayName", "columnName": "displayName",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "pushConfigurationState", "fieldPath": "pushConfigurationState",
"columnName": "pushConfigurationState", "columnName": "pushConfigurationState",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "capabilities", "fieldPath": "capabilities",
"columnName": "capabilities", "columnName": "capabilities",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "serverVersion", "fieldPath": "serverVersion",
"columnName": "serverVersion", "columnName": "serverVersion",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false, "notNull": false,
"defaultValue": "''" "defaultValue": "''"
}, },
{ {
"fieldPath": "clientCertificate", "fieldPath": "clientCertificate",
"columnName": "clientCertificate", "columnName": "clientCertificate",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "externalSignalingServer", "fieldPath": "externalSignalingServer",
"columnName": "externalSignalingServer", "columnName": "externalSignalingServer",
"affinity": "TEXT", "affinity": "TEXT",
"notNull": false "notNull": false
}, },
{ {
"fieldPath": "current", "fieldPath": "current",
"columnName": "current", "columnName": "current",
"affinity": "INTEGER", "affinity": "INTEGER",
"notNull": true "notNull": true
}, },
{ {
"fieldPath": "scheduledForDeletion", "fieldPath": "scheduledForDeletion",
"columnName": "scheduledForDeletion", "columnName": "scheduledForDeletion",
"affinity": "INTEGER", "affinity": "INTEGER",
"notNull": true "notNull": true
} }
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "ArbitraryStorage",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountIdentifier` INTEGER NOT NULL, `key` TEXT NOT NULL, `object` TEXT, `value` TEXT, PRIMARY KEY(`accountIdentifier`, `key`))",
"fields": [
{
"fieldPath": "accountIdentifier",
"columnName": "accountIdentifier",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "storageObject",
"columnName": "object",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"accountIdentifier",
"key"
]
},
"indices": [],
"foreignKeys": []
}
], ],
"primaryKey": { "views": [],
"autoGenerate": true, "setupQueries": [
"columnNames": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"id" "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '1b2dab0ea495c45c9c9ee6e64ba74039')"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "ArbitraryStorage",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountIdentifier` INTEGER NOT NULL, `key` TEXT NOT NULL, `object` TEXT, `value` TEXT, PRIMARY KEY(`accountIdentifier`, `key`))",
"fields": [
{
"fieldPath": "accountIdentifier",
"columnName": "accountIdentifier",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "storageObject",
"columnName": "object",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"accountIdentifier",
"key"
]
},
"indices": [],
"foreignKeys": []
},
{
"tableName": "Conversations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT, `name` TEXT, `displayName` TEXT, `description` TEXT, `type` TEXT, `lastPing` INTEGER NOT NULL, `participantType` TEXT, `hasPassword` INTEGER NOT NULL, `sessionId` TEXT, `actorId` TEXT, `actorType` TEXT, `isFavorite` INTEGER NOT NULL, `lastActivity` INTEGER NOT NULL, `unreadMessages` INTEGER NOT NULL, `unreadMention` INTEGER NOT NULL, `lastMessageJson` TEXT, `objectType` TEXT, `notificationLevel` TEXT, `readOnly` TEXT, `lobbyState` TEXT, `lobbyTimer` INTEGER, `lastReadMessage` INTEGER NOT NULL, `lastCommonReadMessage` INTEGER NOT NULL, `hasCall` INTEGER NOT NULL, `callFlag` INTEGER NOT NULL, `canStartCall` INTEGER NOT NULL, `canLeaveConversation` INTEGER, `canDeleteConversation` INTEGER, `unreadMentionDirect` INTEGER, `notificationCalls` INTEGER, `permissions` INTEGER NOT NULL, `messageExpiration` INTEGER NOT NULL, `status` TEXT, `statusIcon` TEXT, `statusMessage` TEXT, `statusClearAt` INTEGER, `callRecording` INTEGER NOT NULL, `avatarVersion` TEXT, `isCustomAvatar` INTEGER, `callStartTime` INTEGER, `recordingConsent` INTEGER NOT NULL, `remoteServer` TEXT, `remoteToken` TEXT, PRIMARY KEY(`internalId`), FOREIGN KEY(`accountId`) REFERENCES `User`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastPing",
"columnName": "lastPing",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "participantType",
"columnName": "participantType",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "hasPassword",
"columnName": "hasPassword",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "sessionId",
"columnName": "sessionId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "favorite",
"columnName": "isFavorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastActivity",
"columnName": "lastActivity",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMessages",
"columnName": "unreadMessages",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMention",
"columnName": "unreadMention",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastMessageJson",
"columnName": "lastMessageJson",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "objectType",
"columnName": "objectType",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "notificationLevel",
"columnName": "notificationLevel",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "conversationReadOnlyState",
"columnName": "readOnly",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lobbyState",
"columnName": "lobbyState",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lobbyTimer",
"columnName": "lobbyTimer",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastReadMessage",
"columnName": "lastReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastCommonReadMessage",
"columnName": "lastCommonReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasCall",
"columnName": "hasCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callFlag",
"columnName": "callFlag",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canStartCall",
"columnName": "canStartCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canLeaveConversation",
"columnName": "canLeaveConversation",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "canDeleteConversation",
"columnName": "canDeleteConversation",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "unreadMentionDirect",
"columnName": "unreadMentionDirect",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "notificationCalls",
"columnName": "notificationCalls",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "permissions",
"columnName": "permissions",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageExpiration",
"columnName": "messageExpiration",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "statusIcon",
"columnName": "statusIcon",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "statusMessage",
"columnName": "statusMessage",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "statusClearAt",
"columnName": "statusClearAt",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "callRecording",
"columnName": "callRecording",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "avatarVersion",
"columnName": "avatarVersion",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "hasCustomAvatar",
"columnName": "isCustomAvatar",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "callStartTime",
"columnName": "callStartTime",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "recordingConsentRequired",
"columnName": "recordingConsent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "remoteServer",
"columnName": "remoteServer",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "remoteToken",
"columnName": "remoteToken",
"affinity": "TEXT",
"notNull": false
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_Conversations_accountId",
"unique": false,
"columnNames": [
"accountId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_Conversations_accountId` ON `${TABLE_NAME}` (`accountId`)"
}
],
"foreignKeys": [
{
"table": "User",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"accountId"
],
"referencedColumns": [
"id"
]
}
] ]
}, }
{
"tableName": "ChatMessages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER, `token` TEXT, `id` INTEGER NOT NULL, `internalConversationId` TEXT, `actorType` TEXT, `actorId` TEXT, `actorDisplayName` TEXT, `timestamp` INTEGER NOT NULL, `systemMessage` TEXT, `messageType` TEXT, `isReplyable` INTEGER NOT NULL, `message` TEXT, `messageParameters` TEXT, `expirationTimestamp` INTEGER NOT NULL, `parent` INTEGER, `reactions` TEXT, `reactionsSelf` TEXT, `markdown` INTEGER, `lastEditActorType` TEXT, `lastEditActorId` TEXT, `lastEditActorDisplayName` TEXT, `lastEditTimestamp` INTEGER, `deleted` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "actorDisplayName",
"columnName": "actorDisplayName",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "systemMessageType",
"columnName": "systemMessage",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "messageType",
"columnName": "messageType",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "replyable",
"columnName": "isReplyable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "messageParameters",
"columnName": "messageParameters",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "expirationTimestamp",
"columnName": "expirationTimestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "parentMessageId",
"columnName": "parent",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "reactions",
"columnName": "reactions",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "reactionsSelf",
"columnName": "reactionsSelf",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "renderMarkdown",
"columnName": "markdown",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "lastEditActorType",
"columnName": "lastEditActorType",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastEditActorId",
"columnName": "lastEditActorId",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastEditActorDisplayName",
"columnName": "lastEditActorDisplayName",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastEditTimestamp",
"columnName": "lastEditTimestamp",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "deleted",
"columnName": "deleted",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_ChatMessages_internalId",
"unique": true,
"columnNames": [
"internalId"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_ChatMessages_internalId` ON `${TABLE_NAME}` (`internalId`)"
},
{
"name": "index_ChatMessages_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessages_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
},
{
"tableName": "ChatBlocks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `internalConversationId` TEXT NOT NULL, `accountId` INTEGER, `token` TEXT, `oldestMessageId` INTEGER NOT NULL, `newestMessageId` INTEGER NOT NULL, `hasHistory` INTEGER NOT NULL, FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "oldestMessageId",
"columnName": "oldestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "newestMessageId",
"columnName": "newestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasHistory",
"columnName": "hasHistory",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'c07a2543aa583e08e7b3208f44fcc7ac')"
]
}
} }

View file

@ -0,0 +1,746 @@
{
"formatVersion": 1,
"database": {
"version": 18,
"identityHash": "c5e3716925065d7419fb23efabf6691f",
"entities": [
{
"tableName": "User",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userId` TEXT, `username` TEXT, `baseUrl` TEXT, `token` TEXT, `displayName` TEXT, `pushConfigurationState` TEXT, `capabilities` TEXT, `serverVersion` TEXT DEFAULT '', `clientCertificate` TEXT, `externalSignalingServer` TEXT, `current` INTEGER NOT NULL, `scheduledForDeletion` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "userId",
"columnName": "userId",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "baseUrl",
"columnName": "baseUrl",
"affinity": "TEXT"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT"
},
{
"fieldPath": "pushConfigurationState",
"columnName": "pushConfigurationState",
"affinity": "TEXT"
},
{
"fieldPath": "capabilities",
"columnName": "capabilities",
"affinity": "TEXT"
},
{
"fieldPath": "serverVersion",
"columnName": "serverVersion",
"affinity": "TEXT",
"defaultValue": "''"
},
{
"fieldPath": "clientCertificate",
"columnName": "clientCertificate",
"affinity": "TEXT"
},
{
"fieldPath": "externalSignalingServer",
"columnName": "externalSignalingServer",
"affinity": "TEXT"
},
{
"fieldPath": "current",
"columnName": "current",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "scheduledForDeletion",
"columnName": "scheduledForDeletion",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "ArbitraryStorage",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountIdentifier` INTEGER NOT NULL, `key` TEXT NOT NULL, `object` TEXT, `value` TEXT, PRIMARY KEY(`accountIdentifier`, `key`))",
"fields": [
{
"fieldPath": "accountIdentifier",
"columnName": "accountIdentifier",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "storageObject",
"columnName": "object",
"affinity": "TEXT"
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"accountIdentifier",
"key"
]
}
},
{
"tableName": "Conversations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `displayName` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `avatarVersion` TEXT NOT NULL, `callFlag` INTEGER NOT NULL, `callRecording` INTEGER NOT NULL, `callStartTime` INTEGER NOT NULL, `canDeleteConversation` INTEGER NOT NULL, `canLeaveConversation` INTEGER NOT NULL, `canStartCall` INTEGER NOT NULL, `description` TEXT NOT NULL, `hasCall` INTEGER NOT NULL, `hasPassword` INTEGER NOT NULL, `isCustomAvatar` INTEGER NOT NULL, `isFavorite` INTEGER NOT NULL, `lastActivity` INTEGER NOT NULL, `lastCommonReadMessage` INTEGER NOT NULL, `lastMessage` TEXT, `lastPing` INTEGER NOT NULL, `lastReadMessage` INTEGER NOT NULL, `lobbyState` TEXT NOT NULL, `lobbyTimer` INTEGER NOT NULL, `messageExpiration` INTEGER NOT NULL, `name` TEXT NOT NULL, `notificationCalls` INTEGER NOT NULL, `notificationLevel` TEXT NOT NULL, `objectType` TEXT NOT NULL, `objectId` TEXT NOT NULL, `participantType` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `readOnly` TEXT NOT NULL, `recordingConsent` INTEGER NOT NULL, `remoteServer` TEXT, `remoteToken` TEXT, `sessionId` TEXT NOT NULL, `status` TEXT, `statusClearAt` INTEGER, `statusIcon` TEXT, `statusMessage` TEXT, `type` TEXT NOT NULL, `unreadMention` INTEGER NOT NULL, `unreadMentionDirect` INTEGER NOT NULL, `unreadMessages` INTEGER NOT NULL, `hasArchived` INTEGER NOT NULL, `hasSensitive` INTEGER NOT NULL, `hasImportant` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`accountId`) REFERENCES `User`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "avatarVersion",
"columnName": "avatarVersion",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "callFlag",
"columnName": "callFlag",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callRecording",
"columnName": "callRecording",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callStartTime",
"columnName": "callStartTime",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canDeleteConversation",
"columnName": "canDeleteConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canLeaveConversation",
"columnName": "canLeaveConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canStartCall",
"columnName": "canStartCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hasCall",
"columnName": "hasCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasPassword",
"columnName": "hasPassword",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasCustomAvatar",
"columnName": "isCustomAvatar",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "isFavorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastActivity",
"columnName": "lastActivity",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastCommonReadMessage",
"columnName": "lastCommonReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastMessage",
"columnName": "lastMessage",
"affinity": "TEXT"
},
{
"fieldPath": "lastPing",
"columnName": "lastPing",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastReadMessage",
"columnName": "lastReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lobbyState",
"columnName": "lobbyState",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "lobbyTimer",
"columnName": "lobbyTimer",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageExpiration",
"columnName": "messageExpiration",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notificationCalls",
"columnName": "notificationCalls",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "notificationLevel",
"columnName": "notificationLevel",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectType",
"columnName": "objectType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectId",
"columnName": "objectId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "participantType",
"columnName": "participantType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "permissions",
"columnName": "permissions",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "conversationReadOnlyState",
"columnName": "readOnly",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "recordingConsentRequired",
"columnName": "recordingConsent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "remoteServer",
"columnName": "remoteServer",
"affinity": "TEXT"
},
{
"fieldPath": "remoteToken",
"columnName": "remoteToken",
"affinity": "TEXT"
},
{
"fieldPath": "sessionId",
"columnName": "sessionId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT"
},
{
"fieldPath": "statusClearAt",
"columnName": "statusClearAt",
"affinity": "INTEGER"
},
{
"fieldPath": "statusIcon",
"columnName": "statusIcon",
"affinity": "TEXT"
},
{
"fieldPath": "statusMessage",
"columnName": "statusMessage",
"affinity": "TEXT"
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "unreadMention",
"columnName": "unreadMention",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMentionDirect",
"columnName": "unreadMentionDirect",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMessages",
"columnName": "unreadMessages",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasArchived",
"columnName": "hasArchived",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasSensitive",
"columnName": "hasSensitive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasImportant",
"columnName": "hasImportant",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_Conversations_accountId",
"unique": false,
"columnNames": [
"accountId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_Conversations_accountId` ON `${TABLE_NAME}` (`accountId`)"
}
],
"foreignKeys": [
{
"table": "User",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"accountId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "ChatMessages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `id` INTEGER NOT NULL, `internalConversationId` TEXT NOT NULL, `threadId` INTEGER, `isThread` INTEGER NOT NULL, `actorDisplayName` TEXT NOT NULL, `message` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `deleted` INTEGER NOT NULL, `expirationTimestamp` INTEGER NOT NULL, `isReplyable` INTEGER NOT NULL, `isTemporary` INTEGER NOT NULL, `lastEditActorDisplayName` TEXT, `lastEditActorId` TEXT, `lastEditActorType` TEXT, `lastEditTimestamp` INTEGER, `markdown` INTEGER, `messageParameters` TEXT, `messageType` TEXT NOT NULL, `parent` INTEGER, `reactions` TEXT, `reactionsSelf` TEXT, `referenceId` TEXT, `sendStatus` TEXT, `silent` INTEGER NOT NULL, `systemMessage` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "isThread",
"columnName": "isThread",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "actorDisplayName",
"columnName": "actorDisplayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "deleted",
"columnName": "deleted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "expirationTimestamp",
"columnName": "expirationTimestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "replyable",
"columnName": "isReplyable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTemporary",
"columnName": "isTemporary",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastEditActorDisplayName",
"columnName": "lastEditActorDisplayName",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorId",
"columnName": "lastEditActorId",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorType",
"columnName": "lastEditActorType",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditTimestamp",
"columnName": "lastEditTimestamp",
"affinity": "INTEGER"
},
{
"fieldPath": "renderMarkdown",
"columnName": "markdown",
"affinity": "INTEGER"
},
{
"fieldPath": "messageParameters",
"columnName": "messageParameters",
"affinity": "TEXT"
},
{
"fieldPath": "messageType",
"columnName": "messageType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentMessageId",
"columnName": "parent",
"affinity": "INTEGER"
},
{
"fieldPath": "reactions",
"columnName": "reactions",
"affinity": "TEXT"
},
{
"fieldPath": "reactionsSelf",
"columnName": "reactionsSelf",
"affinity": "TEXT"
},
{
"fieldPath": "referenceId",
"columnName": "referenceId",
"affinity": "TEXT"
},
{
"fieldPath": "sendStatus",
"columnName": "sendStatus",
"affinity": "TEXT"
},
{
"fieldPath": "silent",
"columnName": "silent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "systemMessageType",
"columnName": "systemMessage",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_ChatMessages_internalId",
"unique": true,
"columnNames": [
"internalId"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_ChatMessages_internalId` ON `${TABLE_NAME}` (`internalId`)"
},
{
"name": "index_ChatMessages_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessages_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
},
{
"tableName": "ChatBlocks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `internalConversationId` TEXT NOT NULL, `accountId` INTEGER, `token` TEXT, `threadId` INTEGER, `oldestMessageId` INTEGER NOT NULL, `newestMessageId` INTEGER NOT NULL, `hasHistory` INTEGER NOT NULL, FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "oldestMessageId",
"columnName": "oldestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "newestMessageId",
"columnName": "newestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasHistory",
"columnName": "hasHistory",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_ChatBlocks_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatBlocks_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'c5e3716925065d7419fb23efabf6691f')"
]
}
}

View file

@ -0,0 +1,746 @@
{
"formatVersion": 1,
"database": {
"version": 19,
"identityHash": "c5e3716925065d7419fb23efabf6691f",
"entities": [
{
"tableName": "User",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userId` TEXT, `username` TEXT, `baseUrl` TEXT, `token` TEXT, `displayName` TEXT, `pushConfigurationState` TEXT, `capabilities` TEXT, `serverVersion` TEXT DEFAULT '', `clientCertificate` TEXT, `externalSignalingServer` TEXT, `current` INTEGER NOT NULL, `scheduledForDeletion` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "userId",
"columnName": "userId",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "baseUrl",
"columnName": "baseUrl",
"affinity": "TEXT"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT"
},
{
"fieldPath": "pushConfigurationState",
"columnName": "pushConfigurationState",
"affinity": "TEXT"
},
{
"fieldPath": "capabilities",
"columnName": "capabilities",
"affinity": "TEXT"
},
{
"fieldPath": "serverVersion",
"columnName": "serverVersion",
"affinity": "TEXT",
"defaultValue": "''"
},
{
"fieldPath": "clientCertificate",
"columnName": "clientCertificate",
"affinity": "TEXT"
},
{
"fieldPath": "externalSignalingServer",
"columnName": "externalSignalingServer",
"affinity": "TEXT"
},
{
"fieldPath": "current",
"columnName": "current",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "scheduledForDeletion",
"columnName": "scheduledForDeletion",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "ArbitraryStorage",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountIdentifier` INTEGER NOT NULL, `key` TEXT NOT NULL, `object` TEXT, `value` TEXT, PRIMARY KEY(`accountIdentifier`, `key`))",
"fields": [
{
"fieldPath": "accountIdentifier",
"columnName": "accountIdentifier",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "storageObject",
"columnName": "object",
"affinity": "TEXT"
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"accountIdentifier",
"key"
]
}
},
{
"tableName": "Conversations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `displayName` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `avatarVersion` TEXT NOT NULL, `callFlag` INTEGER NOT NULL, `callRecording` INTEGER NOT NULL, `callStartTime` INTEGER NOT NULL, `canDeleteConversation` INTEGER NOT NULL, `canLeaveConversation` INTEGER NOT NULL, `canStartCall` INTEGER NOT NULL, `description` TEXT NOT NULL, `hasCall` INTEGER NOT NULL, `hasPassword` INTEGER NOT NULL, `isCustomAvatar` INTEGER NOT NULL, `isFavorite` INTEGER NOT NULL, `lastActivity` INTEGER NOT NULL, `lastCommonReadMessage` INTEGER NOT NULL, `lastMessage` TEXT, `lastPing` INTEGER NOT NULL, `lastReadMessage` INTEGER NOT NULL, `lobbyState` TEXT NOT NULL, `lobbyTimer` INTEGER NOT NULL, `messageExpiration` INTEGER NOT NULL, `name` TEXT NOT NULL, `notificationCalls` INTEGER NOT NULL, `notificationLevel` TEXT NOT NULL, `objectType` TEXT NOT NULL, `objectId` TEXT NOT NULL, `participantType` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `readOnly` TEXT NOT NULL, `recordingConsent` INTEGER NOT NULL, `remoteServer` TEXT, `remoteToken` TEXT, `sessionId` TEXT NOT NULL, `status` TEXT, `statusClearAt` INTEGER, `statusIcon` TEXT, `statusMessage` TEXT, `type` TEXT NOT NULL, `unreadMention` INTEGER NOT NULL, `unreadMentionDirect` INTEGER NOT NULL, `unreadMessages` INTEGER NOT NULL, `hasArchived` INTEGER NOT NULL, `hasSensitive` INTEGER NOT NULL, `hasImportant` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`accountId`) REFERENCES `User`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "avatarVersion",
"columnName": "avatarVersion",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "callFlag",
"columnName": "callFlag",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callRecording",
"columnName": "callRecording",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callStartTime",
"columnName": "callStartTime",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canDeleteConversation",
"columnName": "canDeleteConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canLeaveConversation",
"columnName": "canLeaveConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canStartCall",
"columnName": "canStartCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hasCall",
"columnName": "hasCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasPassword",
"columnName": "hasPassword",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasCustomAvatar",
"columnName": "isCustomAvatar",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "isFavorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastActivity",
"columnName": "lastActivity",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastCommonReadMessage",
"columnName": "lastCommonReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastMessage",
"columnName": "lastMessage",
"affinity": "TEXT"
},
{
"fieldPath": "lastPing",
"columnName": "lastPing",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastReadMessage",
"columnName": "lastReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lobbyState",
"columnName": "lobbyState",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "lobbyTimer",
"columnName": "lobbyTimer",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageExpiration",
"columnName": "messageExpiration",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notificationCalls",
"columnName": "notificationCalls",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "notificationLevel",
"columnName": "notificationLevel",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectType",
"columnName": "objectType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectId",
"columnName": "objectId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "participantType",
"columnName": "participantType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "permissions",
"columnName": "permissions",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "conversationReadOnlyState",
"columnName": "readOnly",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "recordingConsentRequired",
"columnName": "recordingConsent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "remoteServer",
"columnName": "remoteServer",
"affinity": "TEXT"
},
{
"fieldPath": "remoteToken",
"columnName": "remoteToken",
"affinity": "TEXT"
},
{
"fieldPath": "sessionId",
"columnName": "sessionId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT"
},
{
"fieldPath": "statusClearAt",
"columnName": "statusClearAt",
"affinity": "INTEGER"
},
{
"fieldPath": "statusIcon",
"columnName": "statusIcon",
"affinity": "TEXT"
},
{
"fieldPath": "statusMessage",
"columnName": "statusMessage",
"affinity": "TEXT"
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "unreadMention",
"columnName": "unreadMention",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMentionDirect",
"columnName": "unreadMentionDirect",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMessages",
"columnName": "unreadMessages",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasArchived",
"columnName": "hasArchived",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasSensitive",
"columnName": "hasSensitive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasImportant",
"columnName": "hasImportant",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_Conversations_accountId",
"unique": false,
"columnNames": [
"accountId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_Conversations_accountId` ON `${TABLE_NAME}` (`accountId`)"
}
],
"foreignKeys": [
{
"table": "User",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"accountId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "ChatMessages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `id` INTEGER NOT NULL, `internalConversationId` TEXT NOT NULL, `threadId` INTEGER, `isThread` INTEGER NOT NULL, `actorDisplayName` TEXT NOT NULL, `message` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `deleted` INTEGER NOT NULL, `expirationTimestamp` INTEGER NOT NULL, `isReplyable` INTEGER NOT NULL, `isTemporary` INTEGER NOT NULL, `lastEditActorDisplayName` TEXT, `lastEditActorId` TEXT, `lastEditActorType` TEXT, `lastEditTimestamp` INTEGER, `markdown` INTEGER, `messageParameters` TEXT, `messageType` TEXT NOT NULL, `parent` INTEGER, `reactions` TEXT, `reactionsSelf` TEXT, `referenceId` TEXT, `sendStatus` TEXT, `silent` INTEGER NOT NULL, `systemMessage` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "isThread",
"columnName": "isThread",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "actorDisplayName",
"columnName": "actorDisplayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "deleted",
"columnName": "deleted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "expirationTimestamp",
"columnName": "expirationTimestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "replyable",
"columnName": "isReplyable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTemporary",
"columnName": "isTemporary",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastEditActorDisplayName",
"columnName": "lastEditActorDisplayName",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorId",
"columnName": "lastEditActorId",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorType",
"columnName": "lastEditActorType",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditTimestamp",
"columnName": "lastEditTimestamp",
"affinity": "INTEGER"
},
{
"fieldPath": "renderMarkdown",
"columnName": "markdown",
"affinity": "INTEGER"
},
{
"fieldPath": "messageParameters",
"columnName": "messageParameters",
"affinity": "TEXT"
},
{
"fieldPath": "messageType",
"columnName": "messageType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentMessageId",
"columnName": "parent",
"affinity": "INTEGER"
},
{
"fieldPath": "reactions",
"columnName": "reactions",
"affinity": "TEXT"
},
{
"fieldPath": "reactionsSelf",
"columnName": "reactionsSelf",
"affinity": "TEXT"
},
{
"fieldPath": "referenceId",
"columnName": "referenceId",
"affinity": "TEXT"
},
{
"fieldPath": "sendStatus",
"columnName": "sendStatus",
"affinity": "TEXT"
},
{
"fieldPath": "silent",
"columnName": "silent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "systemMessageType",
"columnName": "systemMessage",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_ChatMessages_internalId",
"unique": true,
"columnNames": [
"internalId"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_ChatMessages_internalId` ON `${TABLE_NAME}` (`internalId`)"
},
{
"name": "index_ChatMessages_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessages_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
},
{
"tableName": "ChatBlocks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `internalConversationId` TEXT NOT NULL, `accountId` INTEGER, `token` TEXT, `threadId` INTEGER, `oldestMessageId` INTEGER NOT NULL, `newestMessageId` INTEGER NOT NULL, `hasHistory` INTEGER NOT NULL, FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "oldestMessageId",
"columnName": "oldestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "newestMessageId",
"columnName": "newestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasHistory",
"columnName": "hasHistory",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_ChatBlocks_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatBlocks_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'c5e3716925065d7419fb23efabf6691f')"
]
}
}

View file

@ -0,0 +1,751 @@
{
"formatVersion": 1,
"database": {
"version": 20,
"identityHash": "7330dad871a0b42e36931ffe8c7d4bcf",
"entities": [
{
"tableName": "User",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userId` TEXT, `username` TEXT, `baseUrl` TEXT, `token` TEXT, `displayName` TEXT, `pushConfigurationState` TEXT, `capabilities` TEXT, `serverVersion` TEXT DEFAULT '', `clientCertificate` TEXT, `externalSignalingServer` TEXT, `current` INTEGER NOT NULL, `scheduledForDeletion` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "userId",
"columnName": "userId",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "baseUrl",
"columnName": "baseUrl",
"affinity": "TEXT"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT"
},
{
"fieldPath": "pushConfigurationState",
"columnName": "pushConfigurationState",
"affinity": "TEXT"
},
{
"fieldPath": "capabilities",
"columnName": "capabilities",
"affinity": "TEXT"
},
{
"fieldPath": "serverVersion",
"columnName": "serverVersion",
"affinity": "TEXT",
"defaultValue": "''"
},
{
"fieldPath": "clientCertificate",
"columnName": "clientCertificate",
"affinity": "TEXT"
},
{
"fieldPath": "externalSignalingServer",
"columnName": "externalSignalingServer",
"affinity": "TEXT"
},
{
"fieldPath": "current",
"columnName": "current",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "scheduledForDeletion",
"columnName": "scheduledForDeletion",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "ArbitraryStorage",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountIdentifier` INTEGER NOT NULL, `key` TEXT NOT NULL, `object` TEXT, `value` TEXT, PRIMARY KEY(`accountIdentifier`, `key`))",
"fields": [
{
"fieldPath": "accountIdentifier",
"columnName": "accountIdentifier",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "storageObject",
"columnName": "object",
"affinity": "TEXT"
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"accountIdentifier",
"key"
]
}
},
{
"tableName": "Conversations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `displayName` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `avatarVersion` TEXT NOT NULL, `callFlag` INTEGER NOT NULL, `callRecording` INTEGER NOT NULL, `callStartTime` INTEGER NOT NULL, `canDeleteConversation` INTEGER NOT NULL, `canLeaveConversation` INTEGER NOT NULL, `canStartCall` INTEGER NOT NULL, `description` TEXT NOT NULL, `hasCall` INTEGER NOT NULL, `hasPassword` INTEGER NOT NULL, `isCustomAvatar` INTEGER NOT NULL, `isFavorite` INTEGER NOT NULL, `lastActivity` INTEGER NOT NULL, `lastCommonReadMessage` INTEGER NOT NULL, `lastMessage` TEXT, `lastPing` INTEGER NOT NULL, `lastReadMessage` INTEGER NOT NULL, `lobbyState` TEXT NOT NULL, `lobbyTimer` INTEGER NOT NULL, `messageExpiration` INTEGER NOT NULL, `name` TEXT NOT NULL, `notificationCalls` INTEGER NOT NULL, `notificationLevel` TEXT NOT NULL, `objectType` TEXT NOT NULL, `objectId` TEXT NOT NULL, `participantType` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `readOnly` TEXT NOT NULL, `recordingConsent` INTEGER NOT NULL, `remoteServer` TEXT, `remoteToken` TEXT, `sessionId` TEXT NOT NULL, `status` TEXT, `statusClearAt` INTEGER, `statusIcon` TEXT, `statusMessage` TEXT, `type` TEXT NOT NULL, `unreadMention` INTEGER NOT NULL, `unreadMentionDirect` INTEGER NOT NULL, `unreadMessages` INTEGER NOT NULL, `hasArchived` INTEGER NOT NULL, `hasSensitive` INTEGER NOT NULL, `hasImportant` INTEGER NOT NULL, `messageDraft` TEXT, PRIMARY KEY(`internalId`), FOREIGN KEY(`accountId`) REFERENCES `User`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "avatarVersion",
"columnName": "avatarVersion",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "callFlag",
"columnName": "callFlag",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callRecording",
"columnName": "callRecording",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callStartTime",
"columnName": "callStartTime",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canDeleteConversation",
"columnName": "canDeleteConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canLeaveConversation",
"columnName": "canLeaveConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canStartCall",
"columnName": "canStartCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hasCall",
"columnName": "hasCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasPassword",
"columnName": "hasPassword",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasCustomAvatar",
"columnName": "isCustomAvatar",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "isFavorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastActivity",
"columnName": "lastActivity",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastCommonReadMessage",
"columnName": "lastCommonReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastMessage",
"columnName": "lastMessage",
"affinity": "TEXT"
},
{
"fieldPath": "lastPing",
"columnName": "lastPing",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastReadMessage",
"columnName": "lastReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lobbyState",
"columnName": "lobbyState",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "lobbyTimer",
"columnName": "lobbyTimer",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageExpiration",
"columnName": "messageExpiration",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notificationCalls",
"columnName": "notificationCalls",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "notificationLevel",
"columnName": "notificationLevel",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectType",
"columnName": "objectType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectId",
"columnName": "objectId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "participantType",
"columnName": "participantType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "permissions",
"columnName": "permissions",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "conversationReadOnlyState",
"columnName": "readOnly",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "recordingConsentRequired",
"columnName": "recordingConsent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "remoteServer",
"columnName": "remoteServer",
"affinity": "TEXT"
},
{
"fieldPath": "remoteToken",
"columnName": "remoteToken",
"affinity": "TEXT"
},
{
"fieldPath": "sessionId",
"columnName": "sessionId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT"
},
{
"fieldPath": "statusClearAt",
"columnName": "statusClearAt",
"affinity": "INTEGER"
},
{
"fieldPath": "statusIcon",
"columnName": "statusIcon",
"affinity": "TEXT"
},
{
"fieldPath": "statusMessage",
"columnName": "statusMessage",
"affinity": "TEXT"
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "unreadMention",
"columnName": "unreadMention",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMentionDirect",
"columnName": "unreadMentionDirect",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMessages",
"columnName": "unreadMessages",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasArchived",
"columnName": "hasArchived",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasSensitive",
"columnName": "hasSensitive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasImportant",
"columnName": "hasImportant",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageDraft",
"columnName": "messageDraft",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_Conversations_accountId",
"unique": false,
"columnNames": [
"accountId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_Conversations_accountId` ON `${TABLE_NAME}` (`accountId`)"
}
],
"foreignKeys": [
{
"table": "User",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"accountId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "ChatMessages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `id` INTEGER NOT NULL, `internalConversationId` TEXT NOT NULL, `threadId` INTEGER, `isThread` INTEGER NOT NULL, `actorDisplayName` TEXT NOT NULL, `message` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `deleted` INTEGER NOT NULL, `expirationTimestamp` INTEGER NOT NULL, `isReplyable` INTEGER NOT NULL, `isTemporary` INTEGER NOT NULL, `lastEditActorDisplayName` TEXT, `lastEditActorId` TEXT, `lastEditActorType` TEXT, `lastEditTimestamp` INTEGER, `markdown` INTEGER, `messageParameters` TEXT, `messageType` TEXT NOT NULL, `parent` INTEGER, `reactions` TEXT, `reactionsSelf` TEXT, `referenceId` TEXT, `sendStatus` TEXT, `silent` INTEGER NOT NULL, `systemMessage` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "isThread",
"columnName": "isThread",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "actorDisplayName",
"columnName": "actorDisplayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "deleted",
"columnName": "deleted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "expirationTimestamp",
"columnName": "expirationTimestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "replyable",
"columnName": "isReplyable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTemporary",
"columnName": "isTemporary",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastEditActorDisplayName",
"columnName": "lastEditActorDisplayName",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorId",
"columnName": "lastEditActorId",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorType",
"columnName": "lastEditActorType",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditTimestamp",
"columnName": "lastEditTimestamp",
"affinity": "INTEGER"
},
{
"fieldPath": "renderMarkdown",
"columnName": "markdown",
"affinity": "INTEGER"
},
{
"fieldPath": "messageParameters",
"columnName": "messageParameters",
"affinity": "TEXT"
},
{
"fieldPath": "messageType",
"columnName": "messageType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentMessageId",
"columnName": "parent",
"affinity": "INTEGER"
},
{
"fieldPath": "reactions",
"columnName": "reactions",
"affinity": "TEXT"
},
{
"fieldPath": "reactionsSelf",
"columnName": "reactionsSelf",
"affinity": "TEXT"
},
{
"fieldPath": "referenceId",
"columnName": "referenceId",
"affinity": "TEXT"
},
{
"fieldPath": "sendStatus",
"columnName": "sendStatus",
"affinity": "TEXT"
},
{
"fieldPath": "silent",
"columnName": "silent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "systemMessageType",
"columnName": "systemMessage",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_ChatMessages_internalId",
"unique": true,
"columnNames": [
"internalId"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_ChatMessages_internalId` ON `${TABLE_NAME}` (`internalId`)"
},
{
"name": "index_ChatMessages_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessages_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
},
{
"tableName": "ChatBlocks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `internalConversationId` TEXT NOT NULL, `accountId` INTEGER, `token` TEXT, `threadId` INTEGER, `oldestMessageId` INTEGER NOT NULL, `newestMessageId` INTEGER NOT NULL, `hasHistory` INTEGER NOT NULL, FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "oldestMessageId",
"columnName": "oldestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "newestMessageId",
"columnName": "newestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasHistory",
"columnName": "hasHistory",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_ChatBlocks_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatBlocks_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7330dad871a0b42e36931ffe8c7d4bcf')"
]
}
}

View file

@ -0,0 +1,761 @@
{
"formatVersion": 1,
"database": {
"version": 21,
"identityHash": "8077a29304b3d28882e4b37fb10d0081",
"entities": [
{
"tableName": "User",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `userId` TEXT, `username` TEXT, `baseUrl` TEXT, `token` TEXT, `displayName` TEXT, `pushConfigurationState` TEXT, `capabilities` TEXT, `serverVersion` TEXT DEFAULT '', `clientCertificate` TEXT, `externalSignalingServer` TEXT, `current` INTEGER NOT NULL, `scheduledForDeletion` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "userId",
"columnName": "userId",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "baseUrl",
"columnName": "baseUrl",
"affinity": "TEXT"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT"
},
{
"fieldPath": "pushConfigurationState",
"columnName": "pushConfigurationState",
"affinity": "TEXT"
},
{
"fieldPath": "capabilities",
"columnName": "capabilities",
"affinity": "TEXT"
},
{
"fieldPath": "serverVersion",
"columnName": "serverVersion",
"affinity": "TEXT",
"defaultValue": "''"
},
{
"fieldPath": "clientCertificate",
"columnName": "clientCertificate",
"affinity": "TEXT"
},
{
"fieldPath": "externalSignalingServer",
"columnName": "externalSignalingServer",
"affinity": "TEXT"
},
{
"fieldPath": "current",
"columnName": "current",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "scheduledForDeletion",
"columnName": "scheduledForDeletion",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "ArbitraryStorage",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountIdentifier` INTEGER NOT NULL, `key` TEXT NOT NULL, `object` TEXT, `value` TEXT, PRIMARY KEY(`accountIdentifier`, `key`))",
"fields": [
{
"fieldPath": "accountIdentifier",
"columnName": "accountIdentifier",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "key",
"columnName": "key",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "storageObject",
"columnName": "object",
"affinity": "TEXT"
},
{
"fieldPath": "value",
"columnName": "value",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"accountIdentifier",
"key"
]
}
},
{
"tableName": "Conversations",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `displayName` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `avatarVersion` TEXT NOT NULL, `callFlag` INTEGER NOT NULL, `callRecording` INTEGER NOT NULL, `callStartTime` INTEGER NOT NULL, `canDeleteConversation` INTEGER NOT NULL, `canLeaveConversation` INTEGER NOT NULL, `canStartCall` INTEGER NOT NULL, `description` TEXT NOT NULL, `hasCall` INTEGER NOT NULL, `hasPassword` INTEGER NOT NULL, `isCustomAvatar` INTEGER NOT NULL, `isFavorite` INTEGER NOT NULL, `lastActivity` INTEGER NOT NULL, `lastCommonReadMessage` INTEGER NOT NULL, `lastMessage` TEXT, `lastPing` INTEGER NOT NULL, `lastReadMessage` INTEGER NOT NULL, `lobbyState` TEXT NOT NULL, `lobbyTimer` INTEGER NOT NULL, `messageExpiration` INTEGER NOT NULL, `name` TEXT NOT NULL, `notificationCalls` INTEGER NOT NULL, `notificationLevel` TEXT NOT NULL, `objectType` TEXT NOT NULL, `objectId` TEXT NOT NULL, `participantType` TEXT NOT NULL, `permissions` INTEGER NOT NULL, `readOnly` TEXT NOT NULL, `recordingConsent` INTEGER NOT NULL, `remoteServer` TEXT, `remoteToken` TEXT, `sessionId` TEXT NOT NULL, `status` TEXT, `statusClearAt` INTEGER, `statusIcon` TEXT, `statusMessage` TEXT, `type` TEXT NOT NULL, `unreadMention` INTEGER NOT NULL, `unreadMentionDirect` INTEGER NOT NULL, `unreadMessages` INTEGER NOT NULL, `hasArchived` INTEGER NOT NULL, `hasSensitive` INTEGER NOT NULL, `hasImportant` INTEGER NOT NULL, `messageDraft` TEXT, PRIMARY KEY(`internalId`), FOREIGN KEY(`accountId`) REFERENCES `User`(`id`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "displayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "avatarVersion",
"columnName": "avatarVersion",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "callFlag",
"columnName": "callFlag",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callRecording",
"columnName": "callRecording",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "callStartTime",
"columnName": "callStartTime",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canDeleteConversation",
"columnName": "canDeleteConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canLeaveConversation",
"columnName": "canLeaveConversation",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "canStartCall",
"columnName": "canStartCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "hasCall",
"columnName": "hasCall",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasPassword",
"columnName": "hasPassword",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasCustomAvatar",
"columnName": "isCustomAvatar",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "favorite",
"columnName": "isFavorite",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastActivity",
"columnName": "lastActivity",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastCommonReadMessage",
"columnName": "lastCommonReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastMessage",
"columnName": "lastMessage",
"affinity": "TEXT"
},
{
"fieldPath": "lastPing",
"columnName": "lastPing",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastReadMessage",
"columnName": "lastReadMessage",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lobbyState",
"columnName": "lobbyState",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "lobbyTimer",
"columnName": "lobbyTimer",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageExpiration",
"columnName": "messageExpiration",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "notificationCalls",
"columnName": "notificationCalls",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "notificationLevel",
"columnName": "notificationLevel",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectType",
"columnName": "objectType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "objectId",
"columnName": "objectId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "participantType",
"columnName": "participantType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "permissions",
"columnName": "permissions",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "conversationReadOnlyState",
"columnName": "readOnly",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "recordingConsentRequired",
"columnName": "recordingConsent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "remoteServer",
"columnName": "remoteServer",
"affinity": "TEXT"
},
{
"fieldPath": "remoteToken",
"columnName": "remoteToken",
"affinity": "TEXT"
},
{
"fieldPath": "sessionId",
"columnName": "sessionId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT"
},
{
"fieldPath": "statusClearAt",
"columnName": "statusClearAt",
"affinity": "INTEGER"
},
{
"fieldPath": "statusIcon",
"columnName": "statusIcon",
"affinity": "TEXT"
},
{
"fieldPath": "statusMessage",
"columnName": "statusMessage",
"affinity": "TEXT"
},
{
"fieldPath": "type",
"columnName": "type",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "unreadMention",
"columnName": "unreadMention",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMentionDirect",
"columnName": "unreadMentionDirect",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "unreadMessages",
"columnName": "unreadMessages",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasArchived",
"columnName": "hasArchived",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasSensitive",
"columnName": "hasSensitive",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasImportant",
"columnName": "hasImportant",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "messageDraft",
"columnName": "messageDraft",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_Conversations_accountId",
"unique": false,
"columnNames": [
"accountId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_Conversations_accountId` ON `${TABLE_NAME}` (`accountId`)"
}
],
"foreignKeys": [
{
"table": "User",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"accountId"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "ChatMessages",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`internalId` TEXT NOT NULL, `accountId` INTEGER NOT NULL, `token` TEXT NOT NULL, `id` INTEGER NOT NULL, `internalConversationId` TEXT NOT NULL, `threadId` INTEGER, `isThread` INTEGER NOT NULL, `actorDisplayName` TEXT NOT NULL, `message` TEXT NOT NULL, `actorId` TEXT NOT NULL, `actorType` TEXT NOT NULL, `deleted` INTEGER NOT NULL, `expirationTimestamp` INTEGER NOT NULL, `isReplyable` INTEGER NOT NULL, `isTemporary` INTEGER NOT NULL, `lastEditActorDisplayName` TEXT, `lastEditActorId` TEXT, `lastEditActorType` TEXT, `lastEditTimestamp` INTEGER, `markdown` INTEGER, `messageParameters` TEXT, `messageType` TEXT NOT NULL, `parent` INTEGER, `reactions` TEXT, `reactionsSelf` TEXT, `referenceId` TEXT, `sendStatus` TEXT, `silent` INTEGER NOT NULL, `systemMessage` TEXT NOT NULL, `threadTitle` TEXT, `threadReplies` INTEGER, `timestamp` INTEGER NOT NULL, PRIMARY KEY(`internalId`), FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "internalId",
"columnName": "internalId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "isThread",
"columnName": "isThread",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "actorDisplayName",
"columnName": "actorDisplayName",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorId",
"columnName": "actorId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "actorType",
"columnName": "actorType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "deleted",
"columnName": "deleted",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "expirationTimestamp",
"columnName": "expirationTimestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "replyable",
"columnName": "isReplyable",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "isTemporary",
"columnName": "isTemporary",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "lastEditActorDisplayName",
"columnName": "lastEditActorDisplayName",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorId",
"columnName": "lastEditActorId",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditActorType",
"columnName": "lastEditActorType",
"affinity": "TEXT"
},
{
"fieldPath": "lastEditTimestamp",
"columnName": "lastEditTimestamp",
"affinity": "INTEGER"
},
{
"fieldPath": "renderMarkdown",
"columnName": "markdown",
"affinity": "INTEGER"
},
{
"fieldPath": "messageParameters",
"columnName": "messageParameters",
"affinity": "TEXT"
},
{
"fieldPath": "messageType",
"columnName": "messageType",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "parentMessageId",
"columnName": "parent",
"affinity": "INTEGER"
},
{
"fieldPath": "reactions",
"columnName": "reactions",
"affinity": "TEXT"
},
{
"fieldPath": "reactionsSelf",
"columnName": "reactionsSelf",
"affinity": "TEXT"
},
{
"fieldPath": "referenceId",
"columnName": "referenceId",
"affinity": "TEXT"
},
{
"fieldPath": "sendStatus",
"columnName": "sendStatus",
"affinity": "TEXT"
},
{
"fieldPath": "silent",
"columnName": "silent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "systemMessageType",
"columnName": "systemMessage",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "threadTitle",
"columnName": "threadTitle",
"affinity": "TEXT"
},
{
"fieldPath": "threadReplies",
"columnName": "threadReplies",
"affinity": "INTEGER"
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"internalId"
]
},
"indices": [
{
"name": "index_ChatMessages_internalId",
"unique": true,
"columnNames": [
"internalId"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_ChatMessages_internalId` ON `${TABLE_NAME}` (`internalId`)"
},
{
"name": "index_ChatMessages_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatMessages_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
},
{
"tableName": "ChatBlocks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `internalConversationId` TEXT NOT NULL, `accountId` INTEGER, `token` TEXT, `threadId` INTEGER, `oldestMessageId` INTEGER NOT NULL, `newestMessageId` INTEGER NOT NULL, `hasHistory` INTEGER NOT NULL, FOREIGN KEY(`internalConversationId`) REFERENCES `Conversations`(`internalId`) ON UPDATE CASCADE ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "internalConversationId",
"columnName": "internalConversationId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "accountId",
"affinity": "INTEGER"
},
{
"fieldPath": "token",
"columnName": "token",
"affinity": "TEXT"
},
{
"fieldPath": "threadId",
"columnName": "threadId",
"affinity": "INTEGER"
},
{
"fieldPath": "oldestMessageId",
"columnName": "oldestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "newestMessageId",
"columnName": "newestMessageId",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hasHistory",
"columnName": "hasHistory",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_ChatBlocks_internalConversationId",
"unique": false,
"columnNames": [
"internalConversationId"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_ChatBlocks_internalConversationId` ON `${TABLE_NAME}` (`internalConversationId`)"
}
],
"foreignKeys": [
{
"table": "Conversations",
"onDelete": "CASCADE",
"onUpdate": "CASCADE",
"columns": [
"internalConversationId"
],
"referencedColumns": [
"internalId"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8077a29304b3d28882e4b37fb10d0081')"
]
}
}

View file

@ -25,6 +25,9 @@ import org.junit.Assert.assertEquals
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import java.lang.Boolean
import kotlin.Long
import kotlin.String
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class ChatBlocksDaoTest { class ChatBlocksDaoTest {
@ -50,12 +53,82 @@ class ChatBlocksDaoTest {
fun closeDb() = db.close() fun closeDb() = db.close()
@Test @Test
fun testGetConnectedChatBlocks() = fun testGetChatBlocksContainingMessageId() =
runTest { runTest {
usersDao.saveUser(createUserEntity("account1", "Account 1")) val user = createUserEntity("account1", "Account 1")
usersDao.saveUser(user)
val account1 = usersDao.getUserWithUserId("account1").blockingGet() val account1 = usersDao.getUserWithUserId("account1").blockingGet()
conversationsDao.upsertConversations( conversationsDao.upsertConversations(
accountId = user.id,
listOf(
createConversationEntity(
accountId = account1.id,
"abc",
roomName = "Conversation One"
),
createConversationEntity(
accountId = account1.id,
"def",
roomName = "Conversation Two"
)
)
)
val conversation1 = conversationsDao.getConversationsForUser(account1.id).first()[0]
val chatBlock1 = ChatBlockEntity(
internalConversationId = conversation1.internalId,
accountId = conversation1.accountId,
token = conversation1.token,
threadId = 123,
oldestMessageId = 50,
newestMessageId = 60,
hasHistory = true
)
val chatBlock2 = ChatBlockEntity(
internalConversationId = conversation1.internalId,
accountId = conversation1.accountId,
token = conversation1.token,
threadId = 123,
oldestMessageId = 10,
newestMessageId = 20,
hasHistory = true
)
val chatBlock3 = ChatBlockEntity(
internalConversationId = conversation1.internalId,
accountId = conversation1.accountId,
token = conversation1.token,
threadId = null,
oldestMessageId = 50,
newestMessageId = 60,
hasHistory = true
)
chatBlocksDao.upsertChatBlock(chatBlock1)
chatBlocksDao.upsertChatBlock(chatBlock2)
chatBlocksDao.upsertChatBlock(chatBlock3)
val chatBlocksOfThread = chatBlocksDao.getChatBlocksContainingMessageId(
internalConversationId = conversation1.internalId,
threadId = 123,
messageId = 55
)
assertEquals(1, chatBlocksOfThread.first().size)
}
@Test
fun testGetConnectedChatBlocks() =
runTest {
val user = createUserEntity("account1", "Account 1")
usersDao.saveUser(user)
val account1 = usersDao.getUserWithUserId("account1").blockingGet()
conversationsDao.upsertConversations(
account1.id,
listOf( listOf(
createConversationEntity( createConversationEntity(
accountId = account1.id, accountId = account1.id,
@ -77,6 +150,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 50, oldestMessageId = 50,
newestMessageId = 60, newestMessageId = 60,
hasHistory = true hasHistory = true
@ -86,6 +160,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 10, oldestMessageId = 10,
newestMessageId = 20, newestMessageId = 20,
hasHistory = true hasHistory = true
@ -95,6 +170,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 45, oldestMessageId = 45,
newestMessageId = 55, newestMessageId = 55,
hasHistory = true hasHistory = true
@ -104,6 +180,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 52, oldestMessageId = 52,
newestMessageId = 58, newestMessageId = 58,
hasHistory = true hasHistory = true
@ -113,6 +190,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 1, oldestMessageId = 1,
newestMessageId = 99, newestMessageId = 99,
hasHistory = true hasHistory = true
@ -122,6 +200,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 59, oldestMessageId = 59,
newestMessageId = 70, newestMessageId = 70,
hasHistory = true hasHistory = true
@ -131,6 +210,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation1.internalId, internalConversationId = conversation1.internalId,
accountId = conversation1.accountId, accountId = conversation1.accountId,
token = conversation1.token, token = conversation1.token,
threadId = null,
oldestMessageId = 80, oldestMessageId = 80,
newestMessageId = 90, newestMessageId = 90,
hasHistory = true hasHistory = true
@ -140,6 +220,7 @@ class ChatBlocksDaoTest {
internalConversationId = conversation2.internalId, internalConversationId = conversation2.internalId,
accountId = conversation2.accountId, accountId = conversation2.accountId,
token = conversation2.token, token = conversation2.token,
threadId = null,
oldestMessageId = 53, oldestMessageId = 53,
newestMessageId = 57, newestMessageId = 57,
hasHistory = true hasHistory = true
@ -156,14 +237,94 @@ class ChatBlocksDaoTest {
chatBlocksDao.upsertChatBlock(chatBlockWithinButOtherConversation) chatBlocksDao.upsertChatBlock(chatBlockWithinButOtherConversation)
val results = chatBlocksDao.getConnectedChatBlocks( val results = chatBlocksDao.getConnectedChatBlocks(
conversation1.internalId, internalConversationId = conversation1.internalId,
searchedChatBlock.oldestMessageId, threadId = null,
searchedChatBlock.newestMessageId oldestMessageId = searchedChatBlock.oldestMessageId,
newestMessageId = searchedChatBlock.newestMessageId
) )
assertEquals(5, results.first().size) assertEquals(5, results.first().size)
} }
@Test
fun testGetConnectedChatBlocksWithThreadsScenario() =
runTest {
val user = createUserEntity("account1", "Account 1")
usersDao.saveUser(user)
val account1 = usersDao.getUserWithUserId("account1").blockingGet()
conversationsDao.upsertConversations(
account1.id,
listOf(
createConversationEntity(
accountId = account1.id,
"abc",
roomName = "Conversation One"
),
createConversationEntity(
accountId = account1.id,
"def",
roomName = "Conversation Two"
)
)
)
val conversation1 = conversationsDao.getConversationsForUser(account1.id).first()[0]
val searchedChatBlock = ChatBlockEntity(
internalConversationId = conversation1.internalId,
accountId = conversation1.accountId,
token = conversation1.token,
threadId = 123,
oldestMessageId = 50,
newestMessageId = 60,
hasHistory = true
)
val chatBlockOverlap1 = ChatBlockEntity(
internalConversationId = conversation1.internalId,
accountId = conversation1.accountId,
token = conversation1.token,
threadId = null,
oldestMessageId = 45,
newestMessageId = 55,
hasHistory = true
)
val chatBlockOverlap2 = ChatBlockEntity(
internalConversationId = conversation1.internalId,
accountId = conversation1.accountId,
token = conversation1.token,
threadId = 123,
oldestMessageId = 59,
newestMessageId = 70,
hasHistory = true
)
chatBlocksDao.upsertChatBlock(searchedChatBlock)
chatBlocksDao.upsertChatBlock(chatBlockOverlap1)
chatBlocksDao.upsertChatBlock(chatBlockOverlap2)
val resultsForThreadIdNull = chatBlocksDao.getConnectedChatBlocks(
internalConversationId = conversation1.internalId,
threadId = null,
oldestMessageId = searchedChatBlock.oldestMessageId,
newestMessageId = searchedChatBlock.newestMessageId
)
assertEquals(1, resultsForThreadIdNull.first().size)
val resultsForThreadId123 = chatBlocksDao.getConnectedChatBlocks(
internalConversationId = conversation1.internalId,
threadId = 123,
oldestMessageId = searchedChatBlock.oldestMessageId,
newestMessageId = searchedChatBlock.newestMessageId
)
assertEquals(2, resultsForThreadId123.first().size)
}
private fun createUserEntity(userId: String, userName: String) = private fun createUserEntity(userId: String, userName: String) =
UserEntity( UserEntity(
userId = userId, userId = userId,
@ -176,8 +337,8 @@ class ChatBlocksDaoTest {
serverVersion = null, serverVersion = null,
clientCertificate = null, clientCertificate = null,
externalSignalingServer = null, externalSignalingServer = null,
current = java.lang.Boolean.FALSE, current = Boolean.FALSE,
scheduledForDeletion = java.lang.Boolean.FALSE scheduledForDeletion = Boolean.FALSE
) )
private fun createConversationEntity(accountId: Long, token: String, roomName: String) = private fun createConversationEntity(accountId: Long, token: String, roomName: String) =

View file

@ -66,6 +66,7 @@ class ChatMessagesDaoTest {
// Problem: lets say we want to update the conv list -> We don#t know the primary keys! // Problem: lets say we want to update the conv list -> We don#t know the primary keys!
// with account@token that would be easier! // with account@token that would be easier!
conversationsDao.upsertConversations( conversationsDao.upsertConversations(
account1.id,
listOf( listOf(
createConversationEntity( createConversationEntity(
accountId = account1.id, accountId = account1.id,
@ -140,7 +141,11 @@ class ChatMessagesDaoTest {
assertEquals("are", conv1chatMessage3.message) assertEquals("are", conv1chatMessage3.message)
val chatMessagesConv1Since = val chatMessagesConv1Since =
chatMessagesDao.getMessagesForConversationSince(conversation1.internalId, conv1chatMessage3.id) chatMessagesDao.getMessagesForConversationSince(
conversation1.internalId,
conv1chatMessage3.id,
null
)
assertEquals(3, chatMessagesConv1Since.first().size) assertEquals(3, chatMessagesConv1Since.first().size)
assertEquals("are", chatMessagesConv1Since.first()[0].message) assertEquals("are", chatMessagesConv1Since.first()[0].message)
assertEquals("some", chatMessagesConv1Since.first()[1].message) assertEquals("some", chatMessagesConv1Since.first()[1].message)
@ -150,7 +155,8 @@ class ChatMessagesDaoTest {
chatMessagesDao.getMessagesForConversationBeforeAndEqual( chatMessagesDao.getMessagesForConversationBeforeAndEqual(
conversation1.internalId, conversation1.internalId,
conv1chatMessage3.id, conv1chatMessage3.id,
3 3,
null
) )
assertEquals(3, chatMessagesConv1To.first().size) assertEquals(3, chatMessagesConv1To.first().size)
assertEquals("hello", chatMessagesConv1To.first()[2].message) assertEquals("hello", chatMessagesConv1To.first()[2].message)

View file

@ -0,0 +1,114 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@email.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.data.database.migrations
import androidx.room.Room
import androidx.room.testing.MigrationTestHelper
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.nextcloud.talk.data.source.local.Migrations
import com.nextcloud.talk.data.source.local.TalkDatabase
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
@RunWith(AndroidJUnit4::class)
class MigrationsTest {
companion object {
private const val TEST_DB = "migration-test"
private const val INIT_VERSION = 10 // last version before update to offline first
private val TAG = MigrationsTest::class.java.simpleName
}
@get:Rule
val helper: MigrationTestHelper = MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
TalkDatabase::class.java
)
@Test
@Throws(IOException::class)
@Suppress("SpreadOperator")
fun migrateAll() {
helper.createDatabase(TEST_DB, INIT_VERSION).apply {
close()
}
Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().targetContext,
TalkDatabase::class.java,
TEST_DB
).addMigrations(*TalkDatabase.MIGRATIONS).build().apply {
openHelper.writableDatabase.close()
}
}
@Test
@Throws(IOException::class)
fun migrate10To11() {
helper.createDatabase(TEST_DB, 10).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 11, true, Migrations.MIGRATION_10_11)
}
@Test
@Throws(IOException::class)
fun migrate11To12() {
helper.createDatabase(TEST_DB, 11).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 12, true, Migrations.MIGRATION_11_12)
}
@Test
@Throws(IOException::class)
fun migrate12To13() {
helper.createDatabase(TEST_DB, 12).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 13, true, Migrations.MIGRATION_12_13)
}
@Test
@Throws(IOException::class)
fun migrate13To14() {
helper.createDatabase(TEST_DB, 13).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 14, true, Migrations.MIGRATION_13_14)
}
@Test
@Throws(IOException::class)
fun migrate14To15() {
helper.createDatabase(TEST_DB, 14).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 15, true, Migrations.MIGRATION_14_15)
}
@Test
@Throws(IOException::class)
fun migrate15To16() {
helper.createDatabase(TEST_DB, 15).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 16, true, Migrations.MIGRATION_15_16)
}
@Test
@Throws(IOException::class)
fun migrate17To19() {
helper.createDatabase(TEST_DB, 17).apply {
close()
}
helper.runMigrationsAndValidate(TEST_DB, 19, true, Migrations.MIGRATION_17_19)
}
}

View file

@ -0,0 +1,68 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.utils
import android.graphics.Color
import org.junit.Assert
import org.junit.Test
class ColorGeneratorTest {
@Test
fun testUsernameToColor() {
usernameToColorHexHelper("", "#0082c9")
usernameToColorHexHelper(",", "#1e78c1")
usernameToColorHexHelper(".", "#c98879")
usernameToColorHexHelper("admin", "#d09e6d")
usernameToColorHexHelper("123e4567-e89b-12d3-a456-426614174000", "#bc5c91")
usernameToColorHexHelper("Akeel Robertson", "#9750a4")
usernameToColorHexHelper("Brayden Truong", "#d09e6d")
usernameToColorHexHelper("Daphne Roy", "#9750a4")
usernameToColorHexHelper("Ellena Wright Frederic Conway", "#c37285")
usernameToColorHexHelper("Gianluca Hills", "#d6b461")
usernameToColorHexHelper("Haseeb Stephens", "#d6b461")
usernameToColorHexHelper("Idris Mac", "#9750a4")
usernameToColorHexHelper("Kristi Fisher", "#0082c9")
usernameToColorHexHelper("Lillian Wall", "#bc5c91")
usernameToColorHexHelper("Lorelai Taylor", "#ddcb55")
usernameToColorHexHelper("Madina Knight", "#9750a4")
usernameToColorHexHelper("Meeting", "#c98879")
usernameToColorHexHelper("Private Circle", "#c37285")
usernameToColorHexHelper("Rae Hope", "#795aab")
usernameToColorHexHelper("Santiago Singleton", "#bc5c91")
usernameToColorHexHelper("Sid Combs", "#d09e6d")
usernameToColorHexHelper("TestCircle", "#499aa2")
usernameToColorHexHelper("Tom Mörtel", "#248eb5")
usernameToColorHexHelper("Vivienne Jacobs", "#1e78c1")
usernameToColorHexHelper("Zaki Cortes", "#6ea68f")
usernameToColorHexHelper("a user", "#5b64b3")
usernameToColorHexHelper("admin@cloud.example.com", "#9750a4")
usernameToColorHexHelper("another user", "#ddcb55")
usernameToColorHexHelper("asd", "#248eb5")
usernameToColorHexHelper("bar", "#0082c9")
usernameToColorHexHelper("foo", "#d09e6d")
usernameToColorHexHelper("wasd", "#b6469d")
usernameToColorHexHelper("مرحبا بالعالم", "#c98879")
usernameToColorHexHelper("🙈", "#b6469d")
}
private fun usernameToColorHexHelper(username: String, expectedHexColor: String) {
val userColorInt = ColorGenerator.usernameToColor(username) // returns Int
val userHexColor = intToHex(userColorInt)
Assert.assertEquals(expectedHexColor.lowercase(), userHexColor.lowercase())
}
private fun intToHex(colorInt: Int): String {
val r = Color.red(colorInt)
val g = Color.green(colorInt)
val b = Color.blue(colorInt)
return String.format("#%02x%02x%02x", r, g, b)
}
}

View file

@ -258,6 +258,10 @@
android:name=".lock.LockedActivity" android:name=".lock.LockedActivity"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity
android:name=".threadsoverview.ThreadsOverviewActivity"
android:theme="@style/AppTheme" />
<receiver <receiver
android:name=".receivers.PackageReplacedReceiver" android:name=".receivers.PackageReplacedReceiver"
android:exported="false"> android:exported="false">

View file

@ -8,6 +8,7 @@
*/ */
package com.nextcloud.talk.account package com.nextcloud.talk.account
import android.Manifest
import android.accounts.Account import android.accounts.Account
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Intent import android.content.Intent
@ -21,8 +22,13 @@ import android.view.View
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.widget.TextView import android.widget.TextView
import androidx.activity.OnBackPressedCallback import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.core.os.bundleOf
import autodagger.AutoInjector import autodagger.AutoInjector
import com.blikoon.qrcodescanner.QrCodeActivity
import com.github.dhaval2404.imagepicker.util.PermissionUtil
import com.google.android.material.snackbar.Snackbar
import com.nextcloud.talk.R import com.nextcloud.talk.R
import com.nextcloud.talk.activities.BaseActivity import com.nextcloud.talk.activities.BaseActivity
import com.nextcloud.talk.api.NcApi import com.nextcloud.talk.api.NcApi
@ -47,6 +53,7 @@ import io.reactivex.schedulers.Schedulers
import java.security.cert.CertificateException import java.security.cert.CertificateException
import javax.inject.Inject import javax.inject.Inject
@Suppress("TooManyFunctions")
@AutoInjector(NextcloudTalkApplication::class) @AutoInjector(NextcloudTalkApplication::class)
class ServerSelectionActivity : BaseActivity() { class ServerSelectionActivity : BaseActivity() {
@ -120,6 +127,8 @@ class ServerSelectionActivity : BaseActivity() {
} }
binding.certTextView.setOnClickListener { onCertClick() } binding.certTextView.setOnClickListener { onCertClick() }
binding.scanQr.setOnClickListener { onScan() }
if (ApplicationWideMessageHolder.getInstance().messageType != null) { if (ApplicationWideMessageHolder.getInstance().messageType != null) {
if (ApplicationWideMessageHolder.getInstance().messageType if (ApplicationWideMessageHolder.getInstance().messageType
== ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK == ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK
@ -390,6 +399,52 @@ class ServerSelectionActivity : BaseActivity() {
} }
} }
private val requestCameraPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// Permission was granted
startQRScanner()
}
}
fun onScan() {
if (PermissionUtil.isPermissionGranted(this, Manifest.permission.CAMERA)) {
startQRScanner()
} else {
requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
private fun startQRScanner() {
val intent = Intent(this, QrCodeActivity::class.java)
qrScanResultLauncher.launch(intent)
}
private val qrScanResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
val data = result.data
if (data == null) {
return@registerForActivityResult
}
val resultData = data.getStringExtra(QR_URI)
if (resultData == null || !resultData.startsWith("nc")) {
Snackbar.make(binding.root, getString(R.string.qr_code_error), Snackbar.LENGTH_SHORT).show()
return@registerForActivityResult
}
val intent = Intent(this, WebViewLoginActivity::class.java)
val bundle = bundleOf().apply {
putString(BundleKeys.KEY_FROM_QR, resultData)
}
intent.putExtras(bundle)
startActivity(intent)
}
}
public override fun onDestroy() { public override fun onDestroy() {
super.onDestroy() super.onDestroy()
dispose() dispose()
@ -408,5 +463,6 @@ class ServerSelectionActivity : BaseActivity() {
companion object { companion object {
private val TAG = ServerSelectionActivity::class.java.simpleName private val TAG = ServerSelectionActivity::class.java.simpleName
const val MIN_SERVER_MAJOR_VERSION = 13 const val MIN_SERVER_MAJOR_VERSION = 13
private const val QR_URI = "com.blikoon.qrcodescanner.got_qr_scan_relult"
} }
} }

View file

@ -1,9 +1,7 @@
/* /*
* Nextcloud Talk - Android Client * Nextcloud Talk - Android Client
* *
* SPDX-FileCopyrightText: 2023 Marcel Hibbe <dev@mhibbe.de> * SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-FileCopyrightText: 2022 Andy Scherzinger <info@andy-scherzinger.de>
* SPDX-FileCopyrightText: 2017 Mario Danic <mario@lovelyhq.com>
* SPDX-License-Identifier: GPL-3.0-or-later * SPDX-License-Identifier: GPL-3.0-or-later
*/ */
package com.nextcloud.talk.account package com.nextcloud.talk.account
@ -63,6 +61,7 @@ import java.security.cert.X509Certificate
import java.util.Locale import java.util.Locale
import javax.inject.Inject import javax.inject.Inject
@Suppress("ReturnCount", "LongMethod")
@AutoInjector(NextcloudTalkApplication::class) @AutoInjector(NextcloudTalkApplication::class)
class WebViewLoginActivity : BaseActivity() { class WebViewLoginActivity : BaseActivity() {
@ -115,10 +114,9 @@ class WebViewLoginActivity : BaseActivity() {
setContentView(binding.root) setContentView(binding.root)
actionBar?.hide() actionBar?.hide()
initSystemBars() initSystemBars()
assembledPrefix = resources!!.getString(R.string.nc_talk_login_scheme) + PROTOCOL_SUFFIX + "login/"
onBackPressedDispatcher.addCallback(this, onBackPressedCallback) onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
handleIntent() handleIntent()
setupWebView()
} }
private fun handleIntent() { private fun handleIntent() {
@ -133,11 +131,18 @@ class WebViewLoginActivity : BaseActivity() {
if (extras.containsKey(BundleKeys.KEY_PASSWORD)) { if (extras.containsKey(BundleKeys.KEY_PASSWORD)) {
password = extras.getString(BundleKeys.KEY_PASSWORD) password = extras.getString(BundleKeys.KEY_PASSWORD)
} }
if (extras.containsKey(BundleKeys.KEY_FROM_QR)) {
extras.getString(BundleKeys.KEY_FROM_QR)?.let {
parseAndLoginFromWebView(it)
}
} else {
setupWebView()
}
} }
@SuppressLint("SetJavaScriptEnabled") @SuppressLint("SetJavaScriptEnabled")
private fun setupWebView() { private fun setupWebView() {
assembledPrefix = resources!!.getString(R.string.nc_talk_login_scheme) + PROTOCOL_SUFFIX + "login/"
binding.webview.settings.allowFileAccess = false binding.webview.settings.allowFileAccess = false
binding.webview.settings.allowFileAccessFromFileURLs = false binding.webview.settings.allowFileAccessFromFileURLs = false
binding.webview.settings.javaScriptEnabled = true binding.webview.settings.javaScriptEnabled = true
@ -289,22 +294,18 @@ class WebViewLoginActivity : BaseActivity() {
} }
@SuppressLint("DiscouragedPrivateApi") @SuppressLint("DiscouragedPrivateApi")
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "WebViewClientOnReceivedSslError")
override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) { override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
try { try {
val sslCertificate = error.certificate val sslCertificate = error.certificate
val f: Field = sslCertificate.javaClass.getDeclaredField("mX509Certificate") val f: Field = sslCertificate.javaClass.getDeclaredField("mX509Certificate")
f.isAccessible = true f.isAccessible = true
val cert = f[sslCertificate] as X509Certificate val cert = f[sslCertificate] as X509Certificate
if (cert == null) { try {
handler.cancel() trustManager.checkServerTrusted(arrayOf(cert), "generic")
} else { handler.proceed()
try { } catch (exception: CertificateException) {
trustManager.checkServerTrusted(arrayOf(cert), "generic") eventBus.post(CertificateEvent(cert, trustManager, handler))
handler.proceed()
} catch (exception: CertificateException) {
eventBus.post(CertificateEvent(cert, trustManager, handler))
}
} }
} catch (exception: Exception) { } catch (exception: Exception) {
handler.cancel() handler.cancel()
@ -332,12 +333,16 @@ class WebViewLoginActivity : BaseActivity() {
dispose() dispose()
cookieManager.cookieStore.removeAll() cookieManager.cookieStore.removeAll()
if (userManager.checkIfUserIsScheduledForDeletion(loginData.username!!, baseUrl!!).blockingGet()) { if (userManager.checkIfUserIsScheduledForDeletion(loginData.username!!, loginData.serverUrl!!)
.blockingGet()
) {
Log.e(TAG, "Tried to add already existing user who is scheduled for deletion.") Log.e(TAG, "Tried to add already existing user who is scheduled for deletion.")
Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_LONG).show() Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_LONG).show()
// however the user is not yet deleted, just start AccountRemovalWorker again to make sure to delete it. // however the user is not yet deleted, just start AccountRemovalWorker again to make sure to delete it.
startAccountRemovalWorkerAndRestartApp() startAccountRemovalWorkerAndRestartApp()
} else if (userManager.checkIfUserExists(loginData.username!!, baseUrl!!).blockingGet()) { } else if (userManager.checkIfUserExists(loginData.username!!, loginData.serverUrl!!)
.blockingGet()
) {
if (reauthorizeAccount) { if (reauthorizeAccount) {
updateUserAndRestartApp(loginData) updateUserAndRestartApp(loginData)
} else { } else {
@ -347,6 +352,9 @@ class WebViewLoginActivity : BaseActivity() {
} else { } else {
startAccountVerification(loginData) startAccountVerification(loginData)
} }
} else {
Log.e(TAG, "Login Data was null")
restartApp()
} }
} }
@ -356,9 +364,9 @@ class WebViewLoginActivity : BaseActivity() {
bundle.putString(KEY_TOKEN, loginData.token) bundle.putString(KEY_TOKEN, loginData.token)
bundle.putString(KEY_BASE_URL, loginData.serverUrl) bundle.putString(KEY_BASE_URL, loginData.serverUrl)
var protocol = "" var protocol = ""
if (baseUrl!!.startsWith("http://")) { if (loginData.serverUrl!!.startsWith("http://")) {
protocol = "http://" protocol = "http://"
} else if (baseUrl!!.startsWith("https://")) { } else if (loginData.serverUrl!!.startsWith("https://")) {
protocol = "https://" protocol = "https://"
} }
if (!TextUtils.isEmpty(protocol)) { if (!TextUtils.isEmpty(protocol)) {
@ -416,17 +424,17 @@ class WebViewLoginActivity : BaseActivity() {
return null return null
} }
for (value in values) { for (value in values) {
if (value.startsWith("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) { if (value.startsWith("user$LOGIN_URL_DATA_KEY_VALUE_SEPARATOR")) {
loginData.username = URLDecoder.decode( loginData.username = URLDecoder.decode(
value.substring(("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length) value.substring(("user$LOGIN_URL_DATA_KEY_VALUE_SEPARATOR").length)
) )
} else if (value.startsWith("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) { } else if (value.startsWith("password$LOGIN_URL_DATA_KEY_VALUE_SEPARATOR")) {
loginData.token = URLDecoder.decode( loginData.token = URLDecoder.decode(
value.substring(("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length) value.substring(("password$LOGIN_URL_DATA_KEY_VALUE_SEPARATOR").length)
) )
} else if (value.startsWith("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) { } else if (value.startsWith("server$LOGIN_URL_DATA_KEY_VALUE_SEPARATOR")) {
loginData.serverUrl = URLDecoder.decode( loginData.serverUrl = URLDecoder.decode(
value.substring(("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length) value.substring(("server$LOGIN_URL_DATA_KEY_VALUE_SEPARATOR").length)
) )
} else { } else {
return null return null

View file

@ -0,0 +1,161 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.account.data
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.nextcloud.talk.account.data.io.LocalLoginDataSource
import com.nextcloud.talk.account.data.model.LoginCompletion
import com.nextcloud.talk.account.data.model.LoginResponse
import com.nextcloud.talk.account.data.network.NetworkLoginDataSource
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_BASE_URL
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ORIGINAL_PROTOCOL
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_TOKEN
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_USERNAME
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.net.URLDecoder
@Suppress("TooManyFunctions", "ReturnCount")
class LoginRepository(val network: NetworkLoginDataSource, val local: LocalLoginDataSource) {
companion object {
val TAG: String = LoginRepository::class.java.simpleName
private const val INTERVAL = 250L
private const val HTTP_OK = 200
private const val USER_KEY = "user:"
private const val SERVER_KEY = "server:"
private const val PASS_KEY = "password:"
private const val PREFIX = "nc://login/"
private const val MAX_ARGS = 3
}
private var shouldReauthorizeUser = false
private var shouldLoop = true
suspend fun pollLogin(response: LoginResponse): LoginCompletion? =
withContext(Dispatchers.IO) {
while (shouldLoop) {
val loginData = network.performLoginFlowV2(response)
if (loginData == null) {
break
}
if (loginData.status == HTTP_OK) {
return@withContext loginData
}
delay(INTERVAL) // No response yet, retry
}
return@withContext null
}
/**
* Entry point for QR scanner
*
*/
fun startLoginFlowFromQR(dataString: String, reAuth: Boolean = false): LoginCompletion? {
shouldReauthorizeUser = reAuth
if (!dataString.startsWith(PREFIX)) {
Log.e(TAG, "Invalid login URL detected")
return null
}
val data = dataString.removePrefix(PREFIX)
val values = data.split('&')
if (values.size !in 1..MAX_ARGS) {
Log.e(TAG, "Illegal number of login URL elements detected: ${values.size}")
return null
}
var server = ""
var loginName = ""
var appPassword = ""
values.forEach { value ->
when {
value.startsWith(USER_KEY) -> {
loginName = URLDecoder.decode(value.removePrefix(USER_KEY), "UTF-8")
}
value.startsWith(PASS_KEY) -> {
appPassword = URLDecoder.decode(value.removePrefix(PASS_KEY), "UTF-8")
}
value.startsWith(SERVER_KEY) -> {
server = URLDecoder.decode(value.removePrefix(SERVER_KEY), "UTF-8")
}
}
}
return if (server.isNotEmpty() && loginName.isNotEmpty() && appPassword.isNotEmpty()) {
LoginCompletion(HTTP_OK, server, loginName, appPassword)
} else {
null
}
}
/**
* Entry point to the login process
*/
suspend fun startLoginFlow(baseUrl: String, reAuth: Boolean = false): LoginResponse? =
withContext(Dispatchers.IO) {
shouldReauthorizeUser = reAuth
val response = network.anonymouslyPostLoginRequest(baseUrl)
return@withContext response
}
/**
* Ends normal login process by canceling the polling
*/
fun cancelLoginFlow() {
shouldLoop = false
}
/**
* Returns bundle if user is not scheduled for deletion or doesn't already exist, null otherwise
*/
fun parseAndLogin(loginData: LoginCompletion): Bundle? {
if (local.checkIfUserIsScheduledForDeletion(loginData)) {
// however the user is not yet deleted, just start AccountRemovalWorker again to make sure to delete it.
local.startAccountRemovalWorker()
return null
} else if (local.checkIfUserExists(loginData)) {
if (shouldReauthorizeUser) {
local.updateUser(loginData)
} else {
Log.w(TAG, "Tried to add an account that account already exists. Skipped user creation.")
}
return null
} else {
return startAccountVerification(loginData)
}
}
private fun startAccountVerification(loginData: LoginCompletion): Bundle {
val bundle = Bundle()
bundle.putString(KEY_USERNAME, loginData.loginName)
bundle.putString(KEY_TOKEN, loginData.appPassword)
bundle.putString(KEY_BASE_URL, loginData.server)
var protocol = ""
if (loginData.server.startsWith("http://")) {
protocol = "http://"
} else if (loginData.server.startsWith("https://")) {
protocol = "https://"
}
if (!TextUtils.isEmpty(protocol)) {
bundle.putString(KEY_ORIGINAL_PROTOCOL, protocol)
}
return bundle
}
}

View file

@ -0,0 +1,45 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.account.data.io
import android.content.Context
import androidx.lifecycle.LiveData
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import com.nextcloud.talk.account.data.model.LoginCompletion
import com.nextcloud.talk.jobs.AccountRemovalWorker
import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.preferences.AppPreferences
// local datasource for communicating with room through account manager
// crucial for making sure the login process interacts with the db as expected.
class LocalLoginDataSource(val userManager: UserManager, val appPreferences: AppPreferences, val context: Context) {
fun updateUser(loginData: LoginCompletion) {
val currentUser = userManager.currentUser.blockingGet()
if (currentUser != null) {
currentUser.clientCertificate = appPreferences.temporaryClientCertAlias
currentUser.token = loginData.appPassword
userManager.updateOrCreateUser(currentUser)
}
}
fun startAccountRemovalWorker(): LiveData<WorkInfo?> {
val accountRemovalWork = OneTimeWorkRequest.Builder(AccountRemovalWorker::class.java).build()
WorkManager.getInstance(context).enqueue(accountRemovalWork)
return WorkManager.getInstance(context).getWorkInfoByIdLiveData(accountRemovalWork.id)
}
fun checkIfUserIsScheduledForDeletion(data: LoginCompletion): Boolean =
userManager.checkIfUserIsScheduledForDeletion(data.loginName, data.server).blockingGet()
fun checkIfUserExists(data: LoginCompletion): Boolean =
userManager.checkIfUserExists(data.loginName, data.server).blockingGet()
}

View file

@ -0,0 +1,12 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.account.data.model
data class LoginResponse(val token: String, val pollUrl: String, val loginUrl: String)
data class LoginCompletion(val status: Int, val server: String, val loginName: String, val appPassword: String)

View file

@ -0,0 +1,122 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.account.data.network
import android.util.Log
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.nextcloud.talk.account.data.model.LoginCompletion
import com.nextcloud.talk.account.data.model.LoginResponse
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.io.IOException
import javax.net.ssl.SSLHandshakeException
// This class handles the network and polling logic in isolation, which makes it easier to test
// Login and Authentication is critical, thus it needs to be working properly.
class NetworkLoginDataSource(val okHttpClient: OkHttpClient) {
companion object {
val TAG: String = NetworkLoginDataSource::class.java.simpleName
}
fun anonymouslyPostLoginRequest(baseUrl: String): LoginResponse? {
val url = "$baseUrl/index.php/login/v2"
var result: LoginResponse? = null
runCatching {
val response = getResponseOfAnonymouslyPostLoginRequest(url)
val jsonObject: JsonObject = JsonParser.parseString(response).asJsonObject
val loginUrl: String = getLoginUrl(jsonObject)
val token = jsonObject.getAsJsonObject("poll").get("token").asString
val pollUrl = jsonObject.getAsJsonObject("poll").get("endpoint").asString
result = LoginResponse(token, pollUrl, loginUrl)
}.getOrElse { e ->
when (e) {
is SSLHandshakeException,
is NullPointerException,
is IOException -> {
Log.e(TAG, "Error caught at anonymouslyPostLoginRequest: $e")
}
else -> throw e
}
}
return result
}
private fun getResponseOfAnonymouslyPostLoginRequest(url: String): String? {
val request = Request.Builder()
.url(url)
.post(FormBody.Builder().build())
.addHeader("Clear-Site-Data", "cookies")
.build()
okHttpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw IOException("Unexpected code $response")
}
return response.body?.string()
}
}
private fun getLoginUrl(response: JsonObject): String {
var result: String? = response.get("login").asString
if (result == null) {
result = ""
}
return result
}
fun performLoginFlowV2(response: LoginResponse): LoginCompletion? {
val requestBody: RequestBody = FormBody.Builder()
.add("token", response.token)
.build()
val request = Request.Builder()
.url(response.pollUrl)
.post(requestBody)
.build()
var result: LoginCompletion? = null
runCatching {
okHttpClient.newCall(request).execute()
.use { response ->
val status: Int = response.code
val responseBody = response.body?.string()
result = if (response.isSuccessful && responseBody?.isNotEmpty() == true) {
val jsonObject = JsonParser.parseString(responseBody).asJsonObject
val server: String = jsonObject.get("server").asString
val loginName: String = jsonObject.get("loginName").asString
val appPassword: String = jsonObject.get("appPassword").asString
LoginCompletion(status, server, loginName, appPassword)
} else {
LoginCompletion(status, "", "", "")
}
}
}.getOrElse { e ->
when (e) {
is NullPointerException,
is SSLHandshakeException,
is IllegalStateException,
is IOException -> {
Log.e(TAG, "Error caught at performLoginFlowV2: $e")
}
else -> throw e
}
}
return result
}
}

View file

@ -0,0 +1,92 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.account.viewmodels
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nextcloud.talk.account.data.LoginRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
class BrowserLoginActivityViewModel @Inject constructor(val repository: LoginRepository) : ViewModel() {
companion object {
private val TAG = BrowserLoginActivityViewModel::class.java.simpleName
}
sealed class InitialLoginViewState {
data object None : InitialLoginViewState()
data class InitialLoginRequestSuccess(val loginUrl: String) : InitialLoginViewState()
data object InitialLoginRequestError : InitialLoginViewState()
}
private val _initialLoginRequestState = MutableStateFlow<InitialLoginViewState>(InitialLoginViewState.None)
val initialLoginRequestState: StateFlow<InitialLoginViewState> = _initialLoginRequestState
sealed class PostLoginViewState {
data object None : PostLoginViewState()
data object PostLoginRestartApp : PostLoginViewState()
data object PostLoginError : PostLoginViewState()
data class PostLoginContinue(val data: Bundle) : PostLoginViewState()
}
private val _postLoginState = MutableStateFlow<PostLoginViewState>(PostLoginViewState.None)
val postLoginState: StateFlow<PostLoginViewState> = _postLoginState
fun loginNormally(baseUrl: String, reAuth: Boolean = false) {
viewModelScope.launch {
val response = repository.startLoginFlow(baseUrl, reAuth)
if (response == null) {
_initialLoginRequestState.value = InitialLoginViewState.InitialLoginRequestError
return@launch
}
_initialLoginRequestState.value =
InitialLoginViewState.InitialLoginRequestSuccess(response.loginUrl)
val loginCompletionResponse = repository.pollLogin(response)
if (loginCompletionResponse == null) {
_postLoginState.value = PostLoginViewState.PostLoginError
return@launch
}
val bundle = repository.parseAndLogin(loginCompletionResponse)
if (bundle == null) {
_postLoginState.value = PostLoginViewState.PostLoginRestartApp
return@launch
}
_postLoginState.value = PostLoginViewState.PostLoginContinue(bundle)
}
}
fun loginWithQR(dataString: String, reAuth: Boolean = false) {
viewModelScope.launch {
val loginCompletionResponse = repository.startLoginFlowFromQR(dataString, reAuth)
if (loginCompletionResponse == null) {
_postLoginState.value = PostLoginViewState.PostLoginError
return@launch
}
val bundle = repository.parseAndLogin(loginCompletionResponse)
if (bundle == null) {
_postLoginState.value = PostLoginViewState.PostLoginRestartApp
return@launch
}
_postLoginState.value = PostLoginViewState.PostLoginContinue(bundle)
}
}
fun cancelLogin() = repository.cancelLoginFlow()
}

View file

@ -17,7 +17,6 @@ import android.text.TextUtils
import android.util.Log import android.util.Log
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager import android.view.WindowManager
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.webkit.SslErrorHandler import android.webkit.SslErrorHandler
@ -25,6 +24,8 @@ import android.widget.EditText
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import autodagger.AutoInjector import autodagger.AutoInjector
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.nextcloud.talk.R import com.nextcloud.talk.R
@ -119,18 +120,23 @@ open class BaseActivity : AppCompatActivity() {
* May be aligned with android-common lib in the future: .../ui/util/extensions/AppCompatActivityExtensions.kt * May be aligned with android-common lib in the future: .../ui/util/extensions/AppCompatActivityExtensions.kt
*/ */
fun initSystemBars() { fun initSystemBars() {
window.decorView.setOnApplyWindowInsetsListener { view, insets -> val decorView = window.decorView
decorView.setOnApplyWindowInsetsListener { view, insets ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
val statusBarHeight = insets.getInsets(WindowInsets.Type.statusBars()).top val systemBars = insets.getInsets(
view.setPadding(0, statusBarHeight, 0, 0) WindowInsetsCompat.Type.systemBars() or
WindowInsetsCompat.Type.displayCutout()
)
val color = ResourcesCompat.getColor(resources, R.color.bg_default, context.theme) val color = ResourcesCompat.getColor(resources, R.color.bg_default, context.theme)
view.setBackgroundColor(color) view.setBackgroundColor(color)
view.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
} else { } else {
colorizeStatusBar() colorizeStatusBar()
colorizeNavigationBar() colorizeNavigationBar()
} }
insets insets
} }
ViewCompat.requestApplyInsets(decorView)
} }
open fun colorizeStatusBar() { open fun colorizeStatusBar() {

View file

@ -10,7 +10,6 @@
package com.nextcloud.talk.activities package com.nextcloud.talk.activities
import android.app.KeyguardManager import android.app.KeyguardManager
import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.provider.ContactsContract import android.provider.ContactsContract
@ -93,7 +92,7 @@ class MainActivity :
} }
fun lockScreenIfConditionsApply() { fun lockScreenIfConditionsApply() {
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
if (keyguardManager.isKeyguardSecure && appPreferences.isScreenLocked) { if (keyguardManager.isKeyguardSecure && appPreferences.isScreenLocked) {
if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.screenLockTimeout)) { if (!SecurityUtils.checkIfWeAreAuthenticated(appPreferences.screenLockTimeout)) {
val lockIntent = Intent(context, LockedActivity::class.java) val lockIntent = Intent(context, LockedActivity::class.java)

View file

@ -22,6 +22,7 @@ import android.view.View
import android.widget.RelativeLayout import android.widget.RelativeLayout
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat import androidx.core.content.res.ResourcesCompat
import coil.dispose
import com.nextcloud.talk.R import com.nextcloud.talk.R
import com.nextcloud.talk.adapters.items.ConversationItem.ConversationItemViewHolder import com.nextcloud.talk.adapters.items.ConversationItem.ConversationItemViewHolder
import com.nextcloud.talk.application.NextcloudTalkApplication.Companion.sharedApplication import com.nextcloud.talk.application.NextcloudTalkApplication.Companion.sharedApplication
@ -182,7 +183,9 @@ class ConversationItem(
} }
private fun showAvatar(holder: ConversationItemViewHolder) { private fun showAvatar(holder: ConversationItemViewHolder) {
holder.binding.dialogAvatar.dispose()
holder.binding.dialogAvatar.visibility = View.VISIBLE holder.binding.dialogAvatar.visibility = View.VISIBLE
var shouldLoadAvatar = shouldLoadAvatar(holder) var shouldLoadAvatar = shouldLoadAvatar(holder)
if (ConversationEnums.ConversationType.ROOM_SYSTEM == model.type) { if (ConversationEnums.ConversationType.ROOM_SYSTEM == model.type) {
holder.binding.dialogAvatar.loadSystemAvatar() holder.binding.dialogAvatar.loadSystemAvatar()

View file

@ -221,6 +221,10 @@ class MentionAutocompleteItem(
if (statusMessage.isNullOrEmpty()) { if (statusMessage.isNullOrEmpty()) {
holder.binding.conversationInfoStatusMessage.setText(R.string.dnd) holder.binding.conversationInfoStatusMessage.setText(R.string.dnd)
} }
} else if (status != null && status == StatusType.BUSY.string) {
if (statusMessage.isNullOrEmpty()) {
holder.binding.conversationInfoStatusMessage.setText(R.string.busy)
}
} else if (status != null && status == StatusType.AWAY.string) { } else if (status != null && status == StatusType.AWAY.string) {
if (statusMessage.isNullOrEmpty()) { if (statusMessage.isNullOrEmpty()) {
holder.binding.conversationInfoStatusMessage.setText(R.string.away) holder.binding.conversationInfoStatusMessage.setText(R.string.away)

View file

@ -276,6 +276,10 @@ class ParticipantItem(
if (model.statusMessage == null || model.statusMessage!!.isEmpty()) { if (model.statusMessage == null || model.statusMessage!!.isEmpty()) {
holder.binding.conversationInfoStatusMessage.setText(R.string.dnd) holder.binding.conversationInfoStatusMessage.setText(R.string.dnd)
} }
} else if (model.status != null && model.status == StatusType.BUSY.string) {
if (model.statusMessage == null || model.statusMessage!!.isEmpty()) {
holder.binding.conversationInfoStatusMessage.setText(R.string.busy)
}
} else if (model.status != null && model.status == StatusType.AWAY.string) { } else if (model.status != null && model.status == StatusType.AWAY.string) {
if (model.statusMessage == null || model.statusMessage!!.isEmpty()) { if (model.statusMessage == null || model.statusMessage!!.isEmpty()) {
holder.binding.conversationInfoStatusMessage.setText(R.string.away) holder.binding.conversationInfoStatusMessage.setText(R.string.away)

View file

@ -22,21 +22,21 @@ interface AdjustableMessageHolderInterface {
val binding: ViewBinding val binding: ViewBinding
fun adjustIfNoteToSelf(viewHolder: AdjustableMessageHolderInterface, currentConversation: ConversationModel?) { fun adjustIfNoteToSelf(currentConversation: ConversationModel?) {
if (currentConversation?.type == ConversationType.NOTE_TO_SELF) { if (currentConversation?.type == ConversationType.NOTE_TO_SELF) {
when (viewHolder.binding.javaClass) { when (this.binding.javaClass) {
ItemCustomOutcomingTextMessageBinding::class.java -> ItemCustomOutcomingTextMessageBinding::class.java ->
(viewHolder.binding as ItemCustomOutcomingTextMessageBinding).bubble (this.binding as ItemCustomOutcomingTextMessageBinding).bubble
ItemCustomOutcomingDeckCardMessageBinding::class.java -> ItemCustomOutcomingDeckCardMessageBinding::class.java ->
(viewHolder.binding as ItemCustomOutcomingDeckCardMessageBinding).bubble (this.binding as ItemCustomOutcomingDeckCardMessageBinding).bubble
ItemCustomOutcomingLinkPreviewMessageBinding::class.java -> ItemCustomOutcomingLinkPreviewMessageBinding::class.java ->
(viewHolder.binding as ItemCustomOutcomingLinkPreviewMessageBinding).bubble (this.binding as ItemCustomOutcomingLinkPreviewMessageBinding).bubble
ItemCustomOutcomingPollMessageBinding::class.java -> ItemCustomOutcomingPollMessageBinding::class.java ->
(viewHolder.binding as ItemCustomOutcomingPollMessageBinding).bubble (this.binding as ItemCustomOutcomingPollMessageBinding).bubble
ItemCustomOutcomingVoiceMessageBinding::class.java -> ItemCustomOutcomingVoiceMessageBinding::class.java ->
(viewHolder.binding as ItemCustomOutcomingVoiceMessageBinding).bubble (this.binding as ItemCustomOutcomingVoiceMessageBinding).bubble
ItemCustomOutcomingLocationMessageBinding::class.java -> ItemCustomOutcomingLocationMessageBinding::class.java ->
(viewHolder.binding as ItemCustomOutcomingLocationMessageBinding).bubble (this.binding as ItemCustomOutcomingLocationMessageBinding).bubble
else -> null else -> null
}?.let { }?.let {
RelativeLayout.LayoutParams(binding.root.layoutParams).apply { RelativeLayout.LayoutParams(binding.root.layoutParams).apply {

View file

@ -12,4 +12,5 @@ interface CommonMessageInterface {
fun onLongClickReactions(chatMessage: ChatMessage) fun onLongClickReactions(chatMessage: ChatMessage)
fun onClickReaction(chatMessage: ChatMessage, emoji: String) fun onClickReaction(chatMessage: ChatMessage, emoji: String)
fun onOpenMessageActionsDialog(chatMessage: ChatMessage) fun onOpenMessageActionsDialog(chatMessage: ChatMessage)
fun openThread(chatMessage: ChatMessage)
} }

View file

@ -182,7 +182,7 @@ class IncomingDeckCardViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted) viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted)
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -229,10 +229,18 @@ class IncomingDeckCardViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView binding.messageQuote.quotedChatMessageView
) )
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -110,6 +110,19 @@ class IncomingLinkPreviewMessageViewHolder(incomingView: View, payload: Any) :
itemView.setTag(R.string.replyable_message_view_tag, message.replyable) itemView.setTag(R.string.replyable_message_view_tag, message.replyable)
val chatActivity = commonMessageInterface as ChatActivity
val showThreadButton = chatActivity.conversationThreadId == null && message.isThread
if (showThreadButton) {
binding.reactions.threadButton.visibility = View.VISIBLE
binding.reactions.threadButton.setContent {
ThreadButtonComposable(
onButtonClick = { openThread(message) }
)
}
} else {
binding.reactions.threadButton.visibility = View.GONE
}
Reaction().showReactions( Reaction().showReactions(
message, message,
::clickOnReaction, ::clickOnReaction,
@ -129,6 +142,10 @@ class IncomingLinkPreviewMessageViewHolder(incomingView: View, payload: Any) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
private fun setAvatarAndAuthorOnMessageItem(message: ChatMessage) { private fun setAvatarAndAuthorOnMessageItem(message: ChatMessage) {
val actorName = message.actorDisplayName val actorName = message.actorDisplayName
if (!actorName.isNullOrBlank()) { if (!actorName.isNullOrBlank()) {
@ -157,7 +174,7 @@ class IncomingLinkPreviewMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted) viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted)
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -204,10 +221,18 @@ class IncomingLinkPreviewMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView binding.messageQuote.quotedChatMessageView
) )
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -142,7 +142,7 @@ class IncomingLocationMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted) viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted)
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -189,10 +189,18 @@ class IncomingLocationMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView binding.messageQuote.quotedChatMessageView
) )
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -81,6 +81,15 @@ class IncomingPollMessageViewHolder(incomingView: View, payload: Any) :
setPollPreview(message) setPollPreview(message)
val chatActivity = commonMessageInterface as ChatActivity
Thread().showThreadPreview(
chatActivity,
message,
threadBinding = binding.threadTitleWrapper,
reactionsBinding = binding.reactions,
openThread = { openThread(message) }
)
Reaction().showReactions( Reaction().showReactions(
message, message,
::clickOnReaction, ::clickOnReaction,
@ -100,6 +109,10 @@ class IncomingPollMessageViewHolder(incomingView: View, payload: Any) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
private fun setPollPreview(message: ChatMessage) { private fun setPollPreview(message: ChatMessage) {
var pollId: String? = null var pollId: String? = null
var pollName: String? = null var pollName: String? = null
@ -164,7 +177,7 @@ class IncomingPollMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted) viewThemeUtils.talk.themeIncomingMessageBubble(bubble, message.isGrouped, message.isDeleted)
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -211,9 +224,17 @@ class IncomingPollMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView binding.messageQuote.quotedChatMessageView
) )
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -17,6 +17,7 @@ import android.widget.ProgressBar;
import com.google.android.material.card.MaterialCardView; import com.google.android.material.card.MaterialCardView;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.databinding.ItemCustomIncomingPreviewMessageBinding; import com.nextcloud.talk.databinding.ItemCustomIncomingPreviewMessageBinding;
import com.nextcloud.talk.databinding.ItemThreadTitleBinding;
import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding; import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding;
import com.nextcloud.talk.chat.data.model.ChatMessage; import com.nextcloud.talk.chat.data.model.ChatMessage;
import com.nextcloud.talk.utils.TextMatchers; import com.nextcloud.talk.utils.TextMatchers;
@ -138,4 +139,7 @@ public class IncomingPreviewMessageViewHolder extends PreviewMessageViewHolder {
@Override @Override
public ReactionsInsideMessageBinding getReactionsBinding(){ return binding.reactions; } public ReactionsInsideMessageBinding getReactionsBinding(){ return binding.reactions; }
@Override
public ItemThreadTitleBinding getThreadsBinding(){ return binding.threadTitleWrapper; }
} }

View file

@ -146,6 +146,9 @@ class IncomingTextMessageViewHolder(itemView: View, payload: Any) :
} }
binding.messageText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) binding.messageText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
binding.messageText.text = processedMessageText binding.messageText.text = processedMessageText
// just for debugging:
// binding.messageText.text =
// SpannableStringBuilder(processedMessageText).append(" (" + message.jsonMessageId + ")")
} else { } else {
binding.messageText.visibility = View.GONE binding.messageText.visibility = View.GONE
binding.checkboxContainer.visibility = View.VISIBLE binding.checkboxContainer.visibility = View.VISIBLE
@ -159,16 +162,35 @@ class IncomingTextMessageViewHolder(itemView: View, payload: Any) :
binding.messageTime.text = dateUtils.getLocalTimeStringFromTimestamp(message.timestamp) binding.messageTime.text = dateUtils.getLocalTimeStringFromTimestamp(message.timestamp)
} }
viewThemeUtils.platform.colorTextView(binding.messageTime, ColorRole.ON_SURFACE_VARIANT) viewThemeUtils.platform.colorTextView(binding.messageTime, ColorRole.ON_SURFACE_VARIANT)
// parent message handling // parent message handling
if (!message.isDeleted && message.parentMessageId != null) { val chatActivity = commonMessageInterface as ChatActivity
processParentMessage(message) binding.messageQuote.quotedChatMessageView.visibility =
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE if (!message.isDeleted &&
} else { message.parentMessageId != null &&
binding.messageQuote.quotedChatMessageView.visibility = View.GONE message.parentMessageId != chatActivity.conversationThreadId
) {
processParentMessage(message)
View.VISIBLE
} else {
View.GONE
}
binding.messageQuote.quotedChatMessageView.setOnLongClickListener { l: View? ->
commonMessageInterface.onOpenMessageActionsDialog(message)
true
} }
itemView.setTag(R.string.replyable_message_view_tag, message.replyable) itemView.setTag(R.string.replyable_message_view_tag, message.replyable)
Thread().showThreadPreview(
chatActivity,
message,
threadBinding = binding.threadTitleWrapper,
reactionsBinding = binding.reactions,
openThread = { openThread(message) }
)
Reaction().showReactions( Reaction().showReactions(
message, message,
::clickOnReaction, ::clickOnReaction,
@ -291,6 +313,10 @@ class IncomingTextMessageViewHolder(itemView: View, payload: Any) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
private fun setAvatarAndAuthorOnMessageItem(message: ChatMessage) { private fun setAvatarAndAuthorOnMessageItem(message: ChatMessage) {
val actorName = message.actorDisplayName val actorName = message.actorDisplayName
if (!actorName.isNullOrBlank()) { if (!actorName.isNullOrBlank()) {
@ -369,7 +395,7 @@ class IncomingTextMessageViewHolder(itemView: View, payload: Any) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView, binding.messageQuote.quotedChatMessageView,
R.color.high_emphasis_text R.color.high_emphasis_text
) )

View file

@ -304,7 +304,7 @@ class IncomingVoiceMessageViewHolder(incomingView: View, payload: Any) :
) )
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -351,10 +351,20 @@ class IncomingVoiceMessageViewHolder(incomingView: View, payload: Any) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView binding.messageQuote.quotedChatMessageView
) )
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE
binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -10,8 +10,10 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.util.Log import android.util.Log
import android.view.View import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import coil.load import coil.load
import com.nextcloud.talk.R
import com.nextcloud.talk.api.NcApi import com.nextcloud.talk.api.NcApi
import com.nextcloud.talk.chat.data.model.ChatMessage import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.databinding.ReferenceInsideMessageBinding import com.nextcloud.talk.databinding.ReferenceInsideMessageBinding
@ -74,12 +76,18 @@ class LinkPreview {
} }
val referenceThumbUrl = reference.openGraphObject?.thumb val referenceThumbUrl = reference.openGraphObject?.thumb
var backgroundId = R.drawable.link_text_background
if (!referenceThumbUrl.isNullOrEmpty()) { if (!referenceThumbUrl.isNullOrEmpty()) {
binding.referenceThumbImage.visibility = View.VISIBLE binding.referenceThumbImage.visibility = View.VISIBLE
binding.referenceThumbImage.load(referenceThumbUrl) binding.referenceThumbImage.load(referenceThumbUrl)
} else { } else {
backgroundId = R.drawable.link_text_no_preview_background
binding.referenceThumbImage.visibility = View.GONE binding.referenceThumbImage.visibility = View.GONE
} }
binding.referenceMetadataContainer.background = ContextCompat.getDrawable(
binding.referenceMetadataContainer.context,
backgroundId
)
binding.referenceWrapper.setOnClickListener { binding.referenceWrapper.setOnClickListener {
val browserIntent = Intent(Intent.ACTION_VIEW, referenceLink!!.toUri()) val browserIntent = Intent(Intent.ACTION_VIEW, referenceLink!!.toUri())
@ -95,7 +103,6 @@ class LinkPreview {
binding.referenceDescription.visibility = View.GONE binding.referenceDescription.visibility = View.GONE
binding.referenceLink.visibility = View.GONE binding.referenceLink.visibility = View.GONE
binding.referenceThumbImage.visibility = View.GONE binding.referenceThumbImage.visibility = View.GONE
binding.referenceIndentedSideBar.visibility = View.GONE
} }
override fun onComplete() { override fun onComplete() {

View file

@ -170,7 +170,7 @@ class OutcomingDeckCardViewHolder(outcomingView: View) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -217,10 +217,18 @@ class OutcomingDeckCardViewHolder(outcomingView: View) :
viewThemeUtils.talk.themeParentMessage( viewThemeUtils.talk.themeParentMessage(
parentChatMessage, parentChatMessage,
message, message,
binding.messageQuote.quoteColoredView binding.messageQuote.quotedChatMessageView
) )
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -127,6 +127,19 @@ class OutcomingLinkPreviewMessageViewHolder(outcomingView: View, payload: Any) :
itemView.setTag(R.string.replyable_message_view_tag, message.replyable) itemView.setTag(R.string.replyable_message_view_tag, message.replyable)
val chatActivity = commonMessageInterface as ChatActivity
val showThreadButton = chatActivity.conversationThreadId == null && message.isThread
if (showThreadButton) {
binding.reactions.threadButton.visibility = View.VISIBLE
binding.reactions.threadButton.setContent {
ThreadButtonComposable(
onButtonClick = { openThread(message) }
)
}
} else {
binding.reactions.threadButton.visibility = View.GONE
}
Reaction().showReactions( Reaction().showReactions(
message, message,
::clickOnReaction, ::clickOnReaction,
@ -146,7 +159,11 @@ class OutcomingLinkPreviewMessageViewHolder(outcomingView: View, payload: Any) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
@Suppress("Detekt.TooGenericExceptionCaught") private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
@Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -188,9 +205,21 @@ class OutcomingLinkPreviewMessageViewHolder(outcomingView: View, payload: Any) :
) )
viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage) viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage)
viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor) viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor)
viewThemeUtils.talk.colorOutgoingQuoteBackground(binding.messageQuote.quoteColoredView) viewThemeUtils.talk.themeParentMessage(
parentChatMessage,
message,
binding.messageQuote.quotedChatMessageView
)
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -196,7 +196,7 @@ class OutcomingLocationMessageViewHolder(incomingView: View) :
}) })
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -238,9 +238,21 @@ class OutcomingLocationMessageViewHolder(incomingView: View) :
) )
viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage) viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage)
viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor) viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor)
viewThemeUtils.talk.colorOutgoingQuoteBackground(binding.messageQuote.quoteColoredView) viewThemeUtils.talk.themeParentMessage(
parentChatMessage,
message,
binding.messageQuote.quotedChatMessageView
)
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -39,9 +39,10 @@ import javax.inject.Inject
@AutoInjector(NextcloudTalkApplication::class) @AutoInjector(NextcloudTalkApplication::class)
class OutcomingPollMessageViewHolder(outcomingView: View, payload: Any) : class OutcomingPollMessageViewHolder(outcomingView: View, payload: Any) :
MessageHolders.OutcomingTextMessageViewHolder<ChatMessage>(outcomingView, payload) { MessageHolders.OutcomingTextMessageViewHolder<ChatMessage>(outcomingView, payload),
AdjustableMessageHolderInterface {
private val binding: ItemCustomOutcomingPollMessageBinding = ItemCustomOutcomingPollMessageBinding.bind(itemView) override val binding: ItemCustomOutcomingPollMessageBinding = ItemCustomOutcomingPollMessageBinding.bind(itemView)
@Inject @Inject
lateinit var context: Context lateinit var context: Context
@ -103,6 +104,15 @@ class OutcomingPollMessageViewHolder(outcomingView: View, payload: Any) :
setPollPreview(message) setPollPreview(message)
val chatActivity = commonMessageInterface as ChatActivity
Thread().showThreadPreview(
chatActivity,
message,
threadBinding = binding.threadTitleWrapper,
reactionsBinding = binding.reactions,
openThread = { openThread(message) }
)
Reaction().showReactions( Reaction().showReactions(
message, message,
::clickOnReaction, ::clickOnReaction,
@ -122,6 +132,10 @@ class OutcomingPollMessageViewHolder(outcomingView: View, payload: Any) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
private fun setPollPreview(message: ChatMessage) { private fun setPollPreview(message: ChatMessage) {
var pollId: String? = null var pollId: String? = null
var pollName: String? = null var pollName: String? = null
@ -158,7 +172,7 @@ class OutcomingPollMessageViewHolder(outcomingView: View, payload: Any) :
} }
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -200,9 +214,21 @@ class OutcomingPollMessageViewHolder(outcomingView: View, payload: Any) :
) )
viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage) viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage)
viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor) viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor)
viewThemeUtils.talk.colorOutgoingQuoteBackground(binding.messageQuote.quoteColoredView) viewThemeUtils.talk.themeParentMessage(
parentChatMessage,
message,
binding.messageQuote.quotedChatMessageView
)
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -16,6 +16,7 @@ import android.widget.ProgressBar;
import com.google.android.material.card.MaterialCardView; import com.google.android.material.card.MaterialCardView;
import com.nextcloud.talk.R; import com.nextcloud.talk.R;
import com.nextcloud.talk.databinding.ItemCustomOutcomingPreviewMessageBinding; import com.nextcloud.talk.databinding.ItemCustomOutcomingPreviewMessageBinding;
import com.nextcloud.talk.databinding.ItemThreadTitleBinding;
import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding; import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding;
import com.nextcloud.talk.chat.data.model.ChatMessage; import com.nextcloud.talk.chat.data.model.ChatMessage;
import com.nextcloud.talk.utils.TextMatchers; import com.nextcloud.talk.utils.TextMatchers;
@ -133,6 +134,9 @@ public class OutcomingPreviewMessageViewHolder extends PreviewMessageViewHolder
@Override @Override
public ReactionsInsideMessageBinding getReactionsBinding() { return binding.reactions; } public ReactionsInsideMessageBinding getReactionsBinding() { return binding.reactions; }
@Override
public ItemThreadTitleBinding getThreadsBinding(){ return binding.threadTitleWrapper; }
@NonNull @NonNull
@Override @Override
public EmojiTextView getMessageCaption() { return binding.messageCaption; } public EmojiTextView getMessageCaption() { return binding.messageCaption; }

View file

@ -160,6 +160,9 @@ class OutcomingTextMessageViewHolder(itemView: View) :
binding.messageTime.layoutParams = layoutParams binding.messageTime.layoutParams = layoutParams
viewThemeUtils.platform.colorTextView(binding.messageText, ColorRole.ON_SURFACE_VARIANT) viewThemeUtils.platform.colorTextView(binding.messageText, ColorRole.ON_SURFACE_VARIANT)
binding.messageText.text = processedMessageText binding.messageText.text = processedMessageText
// just for debugging:
// binding.messageText.text =
// SpannableStringBuilder(processedMessageText).append(" (" + message.jsonMessageId + ")")
} else { } else {
binding.messageText.visibility = View.GONE binding.messageText.visibility = View.GONE
binding.checkboxContainer.visibility = View.VISIBLE binding.checkboxContainer.visibility = View.VISIBLE
@ -174,12 +177,23 @@ class OutcomingTextMessageViewHolder(itemView: View) :
} }
viewThemeUtils.platform.colorTextView(binding.messageTime, ColorRole.ON_SURFACE_VARIANT) viewThemeUtils.platform.colorTextView(binding.messageTime, ColorRole.ON_SURFACE_VARIANT)
setBubbleOnChatMessage(message) setBubbleOnChatMessage(message)
// parent message handling // parent message handling
if (!message.isDeleted && message.parentMessageId != null) { val chatActivity = commonMessageInterface as ChatActivity
processParentMessage(message) binding.messageQuote.quotedChatMessageView.visibility =
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE if (!message.isDeleted &&
} else { message.parentMessageId != null &&
binding.messageQuote.quotedChatMessageView.visibility = View.GONE message.parentMessageId != chatActivity.conversationThreadId
) {
processParentMessage(message)
View.VISIBLE
} else {
View.GONE
}
binding.messageQuote.quotedChatMessageView.setOnLongClickListener { l: View? ->
commonMessageInterface.onOpenMessageActionsDialog(message)
true
} }
binding.checkMark.visibility = View.INVISIBLE binding.checkMark.visibility = View.INVISIBLE
@ -195,8 +209,6 @@ class OutcomingTextMessageViewHolder(itemView: View) :
updateStatus(R.drawable.ic_check, context.resources?.getString(R.string.nc_message_sent)) updateStatus(R.drawable.ic_check, context.resources?.getString(R.string.nc_message_sent))
} }
val chatActivity = commonMessageInterface as ChatActivity
chatActivity.lifecycleScope.launch { chatActivity.lifecycleScope.launch {
if (message.isTemporary && !networkMonitor.isOnline.value) { if (message.isTemporary && !networkMonitor.isOnline.value) {
updateStatus( updateStatus(
@ -208,6 +220,14 @@ class OutcomingTextMessageViewHolder(itemView: View) :
itemView.setTag(R.string.replyable_message_view_tag, message.replyable) itemView.setTag(R.string.replyable_message_view_tag, message.replyable)
Thread().showThreadPreview(
chatActivity,
message,
threadBinding = binding.threadTitleWrapper,
reactionsBinding = binding.reactions,
openThread = { openThread(message) }
)
Reaction().showReactions( Reaction().showReactions(
message, message,
::clickOnReaction, ::clickOnReaction,
@ -345,6 +365,10 @@ class OutcomingTextMessageViewHolder(itemView: View) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught")
private fun processParentMessage(message: ChatMessage) { private fun processParentMessage(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
@ -389,7 +413,11 @@ class OutcomingTextMessageViewHolder(itemView: View) :
viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage) viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage)
viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor) viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor)
viewThemeUtils.talk.colorOutgoingQuoteBackground(binding.messageQuote.quoteColoredView) viewThemeUtils.talk.themeParentMessage(
parentChatMessage,
message,
binding.messageQuote.quotedChatMessageView
)
binding.messageQuote.quotedChatMessageView.setOnClickListener { binding.messageQuote.quotedChatMessageView.setOnClickListener {
chatActivity.jumpToQuotedMessage(parentChatMessage) chatActivity.jumpToQuotedMessage(parentChatMessage)

View file

@ -307,7 +307,7 @@ class OutcomingVoiceMessageViewHolder(outcomingView: View) :
binding.progressBar.visibility = View.VISIBLE binding.progressBar.visibility = View.VISIBLE
} }
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught", "Detekt.LongMethod")
private fun setParentMessageDataOnMessageItem(message: ChatMessage) { private fun setParentMessageDataOnMessageItem(message: ChatMessage) {
if (message.parentMessageId != null && !message.isDeleted) { if (message.parentMessageId != null && !message.isDeleted) {
CoroutineScope(Dispatchers.Main).launch { CoroutineScope(Dispatchers.Main).launch {
@ -349,9 +349,21 @@ class OutcomingVoiceMessageViewHolder(outcomingView: View) :
) )
viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage) viewThemeUtils.talk.colorOutgoingQuoteText(binding.messageQuote.quotedMessage)
viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor) viewThemeUtils.talk.colorOutgoingQuoteAuthorText(binding.messageQuote.quotedMessageAuthor)
viewThemeUtils.talk.colorOutgoingQuoteBackground(binding.messageQuote.quoteColoredView) viewThemeUtils.talk.themeParentMessage(
parentChatMessage,
message,
binding.messageQuote.quotedChatMessageView
)
binding.messageQuote.quotedChatMessageView.visibility = View.VISIBLE binding.messageQuote.quotedChatMessageView.visibility =
if (!message.isDeleted &&
message.parentMessageId != null &&
message.parentMessageId != chatActivity.conversationThreadId
) {
View.VISIBLE
} else {
View.GONE
}
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Error when processing parent message in view holder", e) Log.d(TAG, "Error when processing parent message in view holder", e)
} }

View file

@ -28,8 +28,10 @@ import com.nextcloud.android.common.ui.theme.utils.ColorRole
import com.nextcloud.talk.R import com.nextcloud.talk.R
import com.nextcloud.talk.application.NextcloudTalkApplication import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.application.NextcloudTalkApplication.Companion.sharedApplication import com.nextcloud.talk.application.NextcloudTalkApplication.Companion.sharedApplication
import com.nextcloud.talk.chat.ChatActivity
import com.nextcloud.talk.chat.data.model.ChatMessage import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.data.user.model.User import com.nextcloud.talk.data.user.model.User
import com.nextcloud.talk.databinding.ItemThreadTitleBinding
import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding
import com.nextcloud.talk.extensions.loadChangelogBotAvatar import com.nextcloud.talk.extensions.loadChangelogBotAvatar
import com.nextcloud.talk.extensions.loadFederatedUserAvatar import com.nextcloud.talk.extensions.loadFederatedUserAvatar
@ -78,6 +80,7 @@ abstract class PreviewMessageViewHolder(itemView: View?, payload: Any?) :
var okHttpClient: OkHttpClient? = null var okHttpClient: OkHttpClient? = null
open var progressBar: ProgressBar? = null open var progressBar: ProgressBar? = null
open var reactionsBinding: ReactionsInsideMessageBinding? = null open var reactionsBinding: ReactionsInsideMessageBinding? = null
open var threadsBinding: ItemThreadTitleBinding? = null
var fileViewerUtils: FileViewerUtils? = null var fileViewerUtils: FileViewerUtils? = null
var clickView: View? = null var clickView: View? = null
@ -150,6 +153,16 @@ abstract class PreviewMessageViewHolder(itemView: View?, payload: Any?) :
messageText.text = "" messageText.text = ""
} }
itemView.setTag(R.string.replyable_message_view_tag, message.replyable) itemView.setTag(R.string.replyable_message_view_tag, message.replyable)
val chatActivity = commonMessageInterface as ChatActivity
Thread().showThreadPreview(
chatActivity,
message,
threadBinding = threadsBinding!!,
reactionsBinding = reactionsBinding!!,
openThread = { openThread(message) }
)
val paddingSide = DisplayUtils.convertDpToPixel(HORIZONTAL_REACTION_PADDING, context!!).toInt() val paddingSide = DisplayUtils.convertDpToPixel(HORIZONTAL_REACTION_PADDING, context!!).toInt()
Reaction().showReactions( Reaction().showReactions(
message, message,
@ -203,6 +216,10 @@ abstract class PreviewMessageViewHolder(itemView: View?, payload: Any?) :
commonMessageInterface.onClickReaction(chatMessage, emoji) commonMessageInterface.onClickReaction(chatMessage, emoji)
} }
private fun openThread(chatMessage: ChatMessage) {
commonMessageInterface.openThread(chatMessage)
}
override fun getPayloadForImageLoader(message: ChatMessage?): Any? { override fun getPayloadForImageLoader(message: ChatMessage?): Any? {
if (message!!.selectedIndividualHashMap!!.containsKey(KEY_CONTACT_NAME)) { if (message!!.selectedIndividualHashMap!!.containsKey(KEY_CONTACT_NAME)) {
previewContainer.visibility = View.GONE previewContainer.visibility = View.GONE

View file

@ -14,6 +14,7 @@ import android.text.SpannableString
import android.text.TextPaint import android.text.TextPaint
import android.text.method.LinkMovementMethod import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan import android.text.style.ClickableSpan
import android.util.TypedValue
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
@ -76,6 +77,10 @@ class SystemMessageViewHolder(itemView: View) :
R.drawable.shape_grouped_incoming_message R.drawable.shape_grouped_incoming_message
) )
ViewCompat.setBackground(background, bubbleDrawable) ViewCompat.setBackground(background, bubbleDrawable)
binding.messageText.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
resources.getDimension(R.dimen.chat_system_message_text_size)
)
var messageString: Spannable = SpannableString(message.text) var messageString: Spannable = SpannableString(message.text)
if (message.messageParameters != null && message.messageParameters!!.size > 0) { if (message.messageParameters != null && message.messageParameters!!.size > 0) {
for (key in message.messageParameters!!.keys) { for (key in message.messageParameters!!.keys) {
@ -89,7 +94,13 @@ class SystemMessageViewHolder(itemView: View) :
} else { } else {
individualMap["name"] individualMap["name"]
} }
messageString = DisplayUtils.searchAndColor(messageString, searchText!!, mentionColor) messageString =
DisplayUtils.searchAndColor(
messageString,
searchText!!,
mentionColor,
resources.getDimensionPixelSize(R.dimen.chat_system_message_text_size)
)
if (individualMap["link"] != null) { if (individualMap["link"] != null) {
val displayName = individualMap["name"] ?: "" val displayName = individualMap["name"] ?: ""
val link = (user.baseUrl + individualMap["link"]) val link = (user.baseUrl + individualMap["link"])

View file

@ -39,19 +39,19 @@ public class TalkMessagesListAdapter<M extends IMessage> extends MessagesListAda
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
} else if (holder instanceof OutcomingTextMessageViewHolder holderInstance) { } else if (holder instanceof OutcomingTextMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
holderInstance.adjustIfNoteToSelf(holderInstance, chatActivity.getCurrentConversation()); holderInstance.adjustIfNoteToSelf(chatActivity.getCurrentConversation());
} else if (holder instanceof IncomingLocationMessageViewHolder holderInstance) { } else if (holder instanceof IncomingLocationMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
} else if (holder instanceof OutcomingLocationMessageViewHolder holderInstance) { } else if (holder instanceof OutcomingLocationMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
holderInstance.adjustIfNoteToSelf(holderInstance, chatActivity.getCurrentConversation()); holderInstance.adjustIfNoteToSelf(chatActivity.getCurrentConversation());
} else if (holder instanceof IncomingLinkPreviewMessageViewHolder holderInstance) { } else if (holder instanceof IncomingLinkPreviewMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
} else if (holder instanceof OutcomingLinkPreviewMessageViewHolder holderInstance) { } else if (holder instanceof OutcomingLinkPreviewMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
holderInstance.adjustIfNoteToSelf(holderInstance, chatActivity.getCurrentConversation()); holderInstance.adjustIfNoteToSelf(chatActivity.getCurrentConversation());
} else if (holder instanceof IncomingVoiceMessageViewHolder holderInstance) { } else if (holder instanceof IncomingVoiceMessageViewHolder holderInstance) {
holderInstance.assignVoiceMessageInterface(chatActivity); holderInstance.assignVoiceMessageInterface(chatActivity);
@ -59,7 +59,7 @@ public class TalkMessagesListAdapter<M extends IMessage> extends MessagesListAda
} else if (holder instanceof OutcomingVoiceMessageViewHolder holderInstance) { } else if (holder instanceof OutcomingVoiceMessageViewHolder holderInstance) {
holderInstance.assignVoiceMessageInterface(chatActivity); holderInstance.assignVoiceMessageInterface(chatActivity);
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
holderInstance.adjustIfNoteToSelf(holderInstance, chatActivity.getCurrentConversation()); holderInstance.adjustIfNoteToSelf(chatActivity.getCurrentConversation());
} else if (holder instanceof PreviewMessageViewHolder holderInstance) { } else if (holder instanceof PreviewMessageViewHolder holderInstance) {
holderInstance.assignPreviewMessageInterface(chatActivity); holderInstance.assignPreviewMessageInterface(chatActivity);
@ -72,7 +72,13 @@ public class TalkMessagesListAdapter<M extends IMessage> extends MessagesListAda
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
} else if (holder instanceof OutcomingDeckCardViewHolder holderInstance) { } else if (holder instanceof OutcomingDeckCardViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity); holderInstance.assignCommonMessageInterface(chatActivity);
holderInstance.adjustIfNoteToSelf(holderInstance, chatActivity.getCurrentConversation()); holderInstance.adjustIfNoteToSelf(chatActivity.getCurrentConversation());
} else if (holder instanceof IncomingPollMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity);
} else if (holder instanceof OutcomingPollMessageViewHolder holderInstance) {
holderInstance.assignCommonMessageInterface(chatActivity);
holderInstance.adjustIfNoteToSelf(chatActivity.getCurrentConversation());
} }
super.onBindViewHolder(holder, position); super.onBindViewHolder(holder, position);

View file

@ -0,0 +1,45 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2022 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.adapters.messages
import android.view.View
import com.nextcloud.talk.R
import com.nextcloud.talk.chat.ChatActivity
import com.nextcloud.talk.databinding.ReactionsInsideMessageBinding
import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.databinding.ItemThreadTitleBinding
class Thread {
fun showThreadPreview(
chatActivity: ChatActivity,
message: ChatMessage,
threadBinding: ItemThreadTitleBinding,
reactionsBinding: ReactionsInsideMessageBinding,
openThread: (message: ChatMessage) -> Unit
) {
val isFirstMessageOfThreadInNormalChat = chatActivity.conversationThreadId == null && message.isThread
if (isFirstMessageOfThreadInNormalChat) {
threadBinding.threadTitleLayout.visibility = View.VISIBLE
threadBinding.threadTitleLayout.findViewById<androidx.emoji2.widget.EmojiTextView>(R.id.threadTitle).text =
message.threadTitle
reactionsBinding.threadButton.visibility = View.VISIBLE
reactionsBinding.threadButton.setContent {
ThreadButtonComposable(
message.threadReplies ?: 0,
onButtonClick = { openThread(message) }
)
}
} else {
threadBinding.threadTitleLayout.visibility = View.GONE
reactionsBinding.threadButton.visibility = View.GONE
}
}
}

View file

@ -0,0 +1,88 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.adapters.messages
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.nextcloud.talk.R
@Composable
fun ThreadButtonComposable(replyAmount: Int = 0, onButtonClick: () -> Unit = {}) {
val replyAmountText = if (replyAmount == 0) {
stringResource(R.string.thread_reply)
} else {
pluralStringResource(
R.plurals.thread_replies,
replyAmount,
replyAmount
)
}
OutlinedButton(
onClick = onButtonClick,
modifier = Modifier
.padding(8.dp)
.height(24.dp),
shape = RoundedCornerShape(9.dp),
border = BorderStroke(1.dp, colorResource(R.color.grey_600)),
contentPadding = PaddingValues(0.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = Color.Transparent,
contentColor = colorResource(R.color.grey_600)
)
) {
Icon(
painter = painterResource(R.drawable.ic_reply),
contentDescription = stringResource(R.string.open_thread),
modifier = Modifier
.size(20.dp)
.padding(start = 5.dp, end = 2.dp),
tint = colorResource(R.color.grey_600)
)
Text(
text = replyAmountText,
modifier = Modifier
.padding(end = 5.dp)
)
}
}
@Preview
@Composable
fun ThreadButtonPreviewMultipleReplies() {
ThreadButtonComposable(2)
}
@Preview
@Composable
fun ThreadButtonPreviewOneReply() {
ThreadButtonComposable(1)
}
@Preview
@Composable
fun ThreadButtonPreviewZeroReplies() {
ThreadButtonComposable(0)
}

View file

@ -19,6 +19,8 @@ import com.nextcloud.talk.models.json.participants.TalkBan
import com.nextcloud.talk.models.json.participants.TalkBanOverall import com.nextcloud.talk.models.json.participants.TalkBanOverall
import com.nextcloud.talk.models.json.profile.ProfileOverall import com.nextcloud.talk.models.json.profile.ProfileOverall
import com.nextcloud.talk.models.json.testNotification.TestNotificationOverall import com.nextcloud.talk.models.json.testNotification.TestNotificationOverall
import com.nextcloud.talk.models.json.threads.ThreadOverall
import com.nextcloud.talk.models.json.threads.ThreadsOverall
import com.nextcloud.talk.models.json.userAbsence.UserAbsenceOverall import com.nextcloud.talk.models.json.userAbsence.UserAbsenceOverall
import okhttp3.MultipartBody import okhttp3.MultipartBody
import okhttp3.RequestBody import okhttp3.RequestBody
@ -146,7 +148,8 @@ interface NcApiCoroutines {
@Field("actorDisplayName") actorDisplayName: String, @Field("actorDisplayName") actorDisplayName: String,
@Field("replyTo") replyTo: Int, @Field("replyTo") replyTo: Int,
@Field("silent") sendWithoutNotification: Boolean, @Field("silent") sendWithoutNotification: Boolean,
@Field("referenceId") referenceId: String @Field("referenceId") referenceId: String,
@Field("threadTitle") threadTitle: String?
): ChatOverallSingleMessage ): ChatOverallSingleMessage
@FormUrlEncoded @FormUrlEncoded
@ -274,7 +277,8 @@ interface NcApiCoroutines {
suspend fun getContextOfChatMessage( suspend fun getContextOfChatMessage(
@Header("Authorization") authorization: String, @Header("Authorization") authorization: String,
@Url url: String, @Url url: String,
@Query("limit") limit: Int @Query("limit") limit: Int,
@Query("threadId") threadId: Int?
): ChatOverall ): ChatOverall
@GET @GET
@ -285,4 +289,22 @@ interface NcApiCoroutines {
@DELETE @DELETE
suspend fun unbindRoom(@Header("Authorization") authorization: String, @Url url: String): GenericOverall suspend fun unbindRoom(@Header("Authorization") authorization: String, @Url url: String): GenericOverall
@GET
suspend fun getThreads(
@Header("Authorization") authorization: String,
@Url url: String,
@Query("limit") limit: Int?
): ThreadsOverall
@GET
suspend fun getThread(@Header("Authorization") authorization: String, @Url url: String): ThreadOverall
@FormUrlEncoded
@POST
suspend fun setThreadNotificationLevel(
@Header("Authorization") authorization: String,
@Url url: String,
@Field("level") level: Int
): ThreadOverall
} }

View file

@ -50,7 +50,7 @@ fun ParticipantTile(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
isVoiceOnlyCall: Boolean isVoiceOnlyCall: Boolean
) { ) {
val colorInt = ColorGenerator.shared.usernameToColor(participantUiState.nick) val colorInt = ColorGenerator.usernameToColor(participantUiState.nick)
BoxWithConstraints( BoxWithConstraints(
modifier = modifier modifier = modifier

View file

@ -24,12 +24,14 @@ import android.content.pm.PackageManager
import android.content.res.AssetFileDescriptor import android.content.res.AssetFileDescriptor
import android.database.Cursor import android.database.Cursor
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import android.location.LocationManager
import android.net.Uri import android.net.Uri
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.provider.ContactsContract import android.provider.ContactsContract
import android.provider.MediaStore import android.provider.MediaStore
import android.provider.Settings
import android.text.SpannableStringBuilder import android.text.SpannableStringBuilder
import android.text.TextUtils import android.text.TextUtils
import android.util.Log import android.util.Log
@ -38,6 +40,7 @@ import android.view.Menu
import android.view.MenuItem import android.view.MenuItem
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.AbsListView import android.widget.AbsListView
import android.widget.FrameLayout import android.widget.FrameLayout
@ -56,7 +59,13 @@ import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.view.ContextThemeWrapper import androidx.appcompat.view.ContextThemeWrapper
import androidx.cardview.widget.CardView import androidx.cardview.widget.CardView
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.ComposeView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import androidx.core.content.PermissionChecker import androidx.core.content.PermissionChecker
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
@ -126,6 +135,8 @@ import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.chat.data.model.ChatMessage import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.chat.viewmodels.ChatViewModel import com.nextcloud.talk.chat.viewmodels.ChatViewModel
import com.nextcloud.talk.chat.viewmodels.MessageInputViewModel import com.nextcloud.talk.chat.viewmodels.MessageInputViewModel
import com.nextcloud.talk.contextchat.ContextChatView
import com.nextcloud.talk.contextchat.ContextChatViewModel
import com.nextcloud.talk.conversationinfo.ConversationInfoActivity import com.nextcloud.talk.conversationinfo.ConversationInfoActivity
import com.nextcloud.talk.conversationinfo.viewmodel.ConversationInfoViewModel import com.nextcloud.talk.conversationinfo.viewmodel.ConversationInfoViewModel
import com.nextcloud.talk.conversationlist.ConversationsListActivity import com.nextcloud.talk.conversationlist.ConversationsListActivity
@ -148,17 +159,18 @@ import com.nextcloud.talk.models.json.chat.ReadStatus
import com.nextcloud.talk.models.json.conversations.ConversationEnums import com.nextcloud.talk.models.json.conversations.ConversationEnums
import com.nextcloud.talk.models.json.participants.Participant import com.nextcloud.talk.models.json.participants.Participant
import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall import com.nextcloud.talk.models.json.signaling.settings.SignalingSettingsOverall
import com.nextcloud.talk.models.json.threads.ThreadInfo
import com.nextcloud.talk.polls.ui.PollCreateDialogFragment import com.nextcloud.talk.polls.ui.PollCreateDialogFragment
import com.nextcloud.talk.remotefilebrowser.activities.RemoteFileBrowserActivity import com.nextcloud.talk.remotefilebrowser.activities.RemoteFileBrowserActivity
import com.nextcloud.talk.shareditems.activities.SharedItemsActivity import com.nextcloud.talk.shareditems.activities.SharedItemsActivity
import com.nextcloud.talk.signaling.SignalingMessageReceiver import com.nextcloud.talk.signaling.SignalingMessageReceiver
import com.nextcloud.talk.signaling.SignalingMessageSender import com.nextcloud.talk.signaling.SignalingMessageSender
import com.nextcloud.talk.threadsoverview.ThreadsOverviewActivity
import com.nextcloud.talk.translate.ui.TranslateActivity import com.nextcloud.talk.translate.ui.TranslateActivity
import com.nextcloud.talk.ui.PlaybackSpeed import com.nextcloud.talk.ui.PlaybackSpeed
import com.nextcloud.talk.ui.PlaybackSpeedControl import com.nextcloud.talk.ui.PlaybackSpeedControl
import com.nextcloud.talk.ui.StatusDrawable import com.nextcloud.talk.ui.StatusDrawable
import com.nextcloud.talk.ui.bottom.sheet.ProfileBottomSheet import com.nextcloud.talk.ui.bottom.sheet.ProfileBottomSheet
import com.nextcloud.talk.ui.dialog.ContextChatCompose
import com.nextcloud.talk.ui.dialog.DateTimeCompose import com.nextcloud.talk.ui.dialog.DateTimeCompose
import com.nextcloud.talk.ui.dialog.FileAttachmentPreviewFragment import com.nextcloud.talk.ui.dialog.FileAttachmentPreviewFragment
import com.nextcloud.talk.ui.dialog.MessageActionsDialog import com.nextcloud.talk.ui.dialog.MessageActionsDialog
@ -193,10 +205,12 @@ import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_FILE_PATHS
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_INTERNAL_USER_ID import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_INTERNAL_USER_ID
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_IS_BREAKOUT_ROOM import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_IS_BREAKOUT_ROOM
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_IS_MODERATOR import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_IS_MODERATOR
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_OPENED_VIA_NOTIFICATION
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_RECORDING_STATE import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_RECORDING_STATE
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ROOM_TOKEN import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ROOM_TOKEN
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_START_CALL_AFTER_ROOM_SWITCH import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_START_CALL_AFTER_ROOM_SWITCH
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SWITCH_TO_ROOM import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SWITCH_TO_ROOM
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_THREAD_ID
import com.nextcloud.talk.utils.permissions.PlatformPermissionUtil import com.nextcloud.talk.utils.permissions.PlatformPermissionUtil
import com.nextcloud.talk.utils.rx.DisposableSet import com.nextcloud.talk.utils.rx.DisposableSet
import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder import com.nextcloud.talk.utils.singletons.ApplicationWideCurrentRoomHolder
@ -275,10 +289,14 @@ class ChatActivity :
lateinit var chatViewModel: ChatViewModel lateinit var chatViewModel: ChatViewModel
lateinit var conversationInfoViewModel: ConversationInfoViewModel lateinit var conversationInfoViewModel: ConversationInfoViewModel
lateinit var contextChatViewModel: ContextChatViewModel
lateinit var messageInputViewModel: MessageInputViewModel lateinit var messageInputViewModel: MessageInputViewModel
private var chatMenu: Menu? = null private var chatMenu: Menu? = null
private var overflowMenuHostView: ComposeView? = null
private var isThreadMenuExpanded by mutableStateOf(false)
private val startSelectContactForResult = registerForActivityResult( private val startSelectContactForResult = registerForActivityResult(
ActivityResultContracts ActivityResultContracts
.StartActivityForResult() .StartActivityForResult()
@ -308,28 +326,27 @@ class ChatActivity :
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
executeIfResultOk(it) { intent -> executeIfResultOk(it) { intent ->
runBlocking { runBlocking {
val id = intent?.getStringExtra(MessageSearchActivity.RESULT_KEY_MESSAGE_ID) val messageId = intent?.getStringExtra(MessageSearchActivity.RESULT_KEY_MESSAGE_ID)
id?.let { val threadId = intent?.getStringExtra(MessageSearchActivity.RESULT_KEY_THREAD_ID)
startContextChatWindowForMessage(id) messageId?.let {
startContextChatWindowForMessage(messageId, threadId)
} }
} }
} }
} }
private fun startContextChatWindowForMessage(id: String?) { private fun startContextChatWindowForMessage(messageId: String?, threadId: String?) {
binding.genericComposeView.apply { binding.genericComposeView.apply {
val shouldDismiss = mutableStateOf(false)
setContent { setContent {
val bundle = bundleOf() contextChatViewModel.getContextForChatMessages(
bundle.putString(BundleKeys.KEY_CREDENTIALS, credentials!!) credentials = credentials!!,
bundle.putString(BundleKeys.KEY_BASE_URL, conversationUser!!.baseUrl) baseUrl = conversationUser!!.baseUrl!!,
bundle.putString(KEY_ROOM_TOKEN, roomToken) token = roomToken,
bundle.putString(BundleKeys.KEY_MESSAGE_ID, id) threadId = threadId,
bundle.putString( messageId = messageId!!,
KEY_CONVERSATION_NAME, title = currentConversation!!.displayName
currentConversation!!.displayName
) )
ContextChatCompose(bundle).GetDialogView(shouldDismiss, context) ContextChatView(context, contextChatViewModel)
} }
} }
Log.d(TAG, "Should open something else") Log.d(TAG, "Should open something else")
@ -350,6 +367,9 @@ class ChatActivity :
var sessionIdAfterRoomJoined: String? = null var sessionIdAfterRoomJoined: String? = null
lateinit var roomToken: String lateinit var roomToken: String
var conversationThreadId: Long? = null
var openedViaNotification: Boolean = false
var conversationThreadInfo: ThreadInfo? = null
var conversationUser: User? = null var conversationUser: User? = null
lateinit var spreedCapabilities: SpreedCapability lateinit var spreedCapabilities: SpreedCapability
var chatApiVersion: Int = 1 var chatApiVersion: Int = 1
@ -391,8 +411,13 @@ class ChatActivity :
private val onBackPressedCallback = object : OnBackPressedCallback(true) { private val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() { override fun handleOnBackPressed() {
val intent = Intent(this@ChatActivity, ConversationsListActivity::class.java) if (!openedViaNotification && isChatThread()) {
startActivity(intent) isEnabled = false
onBackPressedDispatcher.onBackPressed()
} else {
val intent = Intent(this@ChatActivity, ConversationsListActivity::class.java)
startActivity(intent)
}
} }
} }
@ -461,18 +486,20 @@ class ChatActivity :
setContentView(binding.root) setContentView(binding.root)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.chat_container)) { view, insets -> ViewCompat.setOnApplyWindowInsetsListener(binding.chatContainer) { view, insets ->
val statusBarInsets = insets.getInsets(WindowInsetsCompat.Type.statusBars()) val systemBarInsets = insets.getInsets(
val navBarInsets = insets.getInsets(WindowInsetsCompat.Type.navigationBars()) WindowInsetsCompat.Type.systemBars() or
WindowInsetsCompat.Type.displayCutout()
)
val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime()) val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime())
val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime()) val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
val bottomPadding = if (isKeyboardVisible) imeInsets.bottom else navBarInsets.bottom val bottomPadding = if (isKeyboardVisible) imeInsets.bottom else systemBarInsets.bottom
view.setPadding( view.setPadding(
view.paddingLeft, systemBarInsets.left,
statusBarInsets.top, systemBarInsets.top,
view.paddingRight, systemBarInsets.right,
bottomPadding bottomPadding
) )
WindowInsetsCompat.CONSUMED WindowInsetsCompat.CONSUMED
@ -489,14 +516,27 @@ class ChatActivity :
conversationInfoViewModel = ViewModelProvider(this, viewModelFactory)[ConversationInfoViewModel::class.java] conversationInfoViewModel = ViewModelProvider(this, viewModelFactory)[ConversationInfoViewModel::class.java]
contextChatViewModel = ViewModelProvider(this, viewModelFactory)[ContextChatViewModel::class.java]
val urlForChatting = ApiUtils.getUrlForChat(chatApiVersion, conversationUser?.baseUrl, roomToken) val urlForChatting = ApiUtils.getUrlForChat(chatApiVersion, conversationUser?.baseUrl, roomToken)
val credentials = ApiUtils.getCredentials(conversationUser!!.username, conversationUser!!.token) val credentials = ApiUtils.getCredentials(conversationUser!!.username, conversationUser!!.token)
chatViewModel.initData( chatViewModel.initData(
credentials!!, credentials!!,
urlForChatting, urlForChatting,
roomToken roomToken,
conversationThreadId
) )
conversationThreadId?.let {
val threadUrl = ApiUtils.getUrlForThread(
version = 1,
baseUrl = conversationUser!!.baseUrl,
token = roomToken,
threadId = it.toInt()
)
chatViewModel.getThread(credentials, threadUrl)
}
messageInputFragment = getMessageInputFragment() messageInputFragment = getMessageInputFragment()
messageInputViewModel = ViewModelProvider(this, viewModelFactory)[MessageInputViewModel::class.java] messageInputViewModel = ViewModelProvider(this, viewModelFactory)[MessageInputViewModel::class.java]
messageInputViewModel.setData(chatViewModel.getChatRepository()) messageInputViewModel.setData(chatViewModel.getChatRepository())
@ -521,6 +561,7 @@ class ChatActivity :
return MessageInputFragment().apply { return MessageInputFragment().apply {
arguments = Bundle().apply { arguments = Bundle().apply {
putString(CONVERSATION_INTERNAL_ID, internalId) putString(CONVERSATION_INTERNAL_ID, internalId)
putString(BundleKeys.KEY_SHARED_TEXT, sharedText)
} }
} }
} }
@ -549,6 +590,14 @@ class ChatActivity :
roomToken = extras?.getString(KEY_ROOM_TOKEN).orEmpty() roomToken = extras?.getString(KEY_ROOM_TOKEN).orEmpty()
conversationThreadId = if (extras?.containsKey(KEY_THREAD_ID) == true) {
extras.getLong(KEY_THREAD_ID)
} else {
null
}
openedViaNotification = extras?.getBoolean(KEY_OPENED_VIA_NOTIFICATION) ?: false
sharedText = extras?.getString(BundleKeys.KEY_SHARED_TEXT).orEmpty() sharedText = extras?.getString(BundleKeys.KEY_SHARED_TEXT).orEmpty()
Log.d(TAG, " roomToken = $roomToken") Log.d(TAG, " roomToken = $roomToken")
@ -671,7 +720,8 @@ class ChatActivity :
joinRoomWithPassword() joinRoomWithPassword()
if (conversationUser?.userId != "?" && if (conversationUser?.userId != "?" &&
hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.MENTION_FLAG) hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.MENTION_FLAG) &&
!isChatThread()
) { ) {
binding.chatToolbar.setOnClickListener { _ -> showConversationInfoScreen() } binding.chatToolbar.setOnClickListener { _ -> showConversationInfoScreen() }
} }
@ -937,6 +987,7 @@ class ChatActivity :
var chatMessageList = triple.third var chatMessageList = triple.third
chatMessageList = handleSystemMessages(chatMessageList) chatMessageList = handleSystemMessages(chatMessageList)
chatMessageList = handleThreadMessages(chatMessageList)
if (chatMessageList.isEmpty()) { if (chatMessageList.isEmpty()) {
return@onEach return@onEach
} }
@ -1107,6 +1158,11 @@ class ChatActivity :
chatViewModel.getVoiceRecordingInProgress.observe(this) { voiceRecordingInProgress -> chatViewModel.getVoiceRecordingInProgress.observe(this) { voiceRecordingInProgress ->
VibrationUtils.vibrateShort(context) VibrationUtils.vibrateShort(context)
if (voiceRecordingInProgress) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
binding.voiceRecordingLock.visibility = if ( binding.voiceRecordingLock.visibility = if (
voiceRecordingInProgress && voiceRecordingInProgress &&
chatViewModel.getVoiceRecordingLocked.value != true chatViewModel.getVoiceRecordingLocked.value != true
@ -1133,6 +1189,7 @@ class ChatActivity :
chatMenu?.removeItem(R.id.conversation_event) chatMenu?.removeItem(R.id.conversation_event)
} }
is ChatViewModel.UnbindRoomUiState.Error -> { is ChatViewModel.UnbindRoomUiState.Error -> {
Snackbar.make( Snackbar.make(
binding.root, binding.root,
@ -1140,7 +1197,8 @@ class ChatActivity :
Snackbar.LENGTH_LONG Snackbar.LENGTH_LONG
).show() ).show()
} }
else -> { }
else -> {}
} }
} }
@ -1234,6 +1292,25 @@ class ChatActivity :
} }
} }
} }
this.lifecycleScope.launch {
chatViewModel.threadRetrieveState.collect { uiState ->
when (uiState) {
ChatViewModel.ThreadRetrieveUiState.None -> {
}
is ChatViewModel.ThreadRetrieveUiState.Error -> {
Log.e(TAG, "Error when retrieving thread", uiState.exception)
Snackbar.make(binding.root, R.string.nc_common_error_sorry, Snackbar.LENGTH_LONG).show()
}
is ChatViewModel.ThreadRetrieveUiState.Success -> {
conversationThreadInfo = uiState.thread
invalidateOptionsMenu()
}
}
}
}
} }
private fun removeUnreadMessagesMarker() { private fun removeUnreadMessagesMarker() {
@ -1503,6 +1580,7 @@ class ChatActivity :
} while (true && pos >= 0) } while (true && pos >= 0)
} }
@Suppress("LongMethod")
private fun initMessageHolders(): MessageHolders { private fun initMessageHolders(): MessageHolders {
val messageHolders = MessageHolders() val messageHolders = MessageHolders()
val profileBottomSheet = ProfileBottomSheet(ncApi, conversationUser!!, viewThemeUtils) val profileBottomSheet = ProfileBottomSheet(ncApi, conversationUser!!, viewThemeUtils)
@ -2271,11 +2349,26 @@ class ChatActivity :
BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID,
File(file.absolutePath) File(file.absolutePath)
) )
uploadFile(shareUri.toString(), false) uploadFile(
fileUri = shareUri.toString(),
isVoiceMessage = false,
caption = "",
roomToken = roomToken,
replyToMessageId = getReplyToMessageId(),
displayName = currentConversation?.displayName ?: ""
)
} }
cursor?.close() cursor?.close()
} }
fun getReplyToMessageId(): Int {
var replyMessageId = messageInputViewModel.getReplyChatMessage.value?.id?.toInt()
if (replyMessageId == null || replyMessageId == 0) {
replyMessageId = conversationThreadInfo?.thread?.id ?: 0
}
return replyMessageId
}
@Throws(IllegalStateException::class) @Throws(IllegalStateException::class)
private fun onPickCameraResult(intent: Intent?) { private fun onPickCameraResult(intent: Intent?) {
try { try {
@ -2447,35 +2540,27 @@ class ChatActivity :
private fun uploadFiles(files: MutableList<String>, caption: String = "") { private fun uploadFiles(files: MutableList<String>, caption: String = "") {
for (i in 0 until files.size) { for (i in 0 until files.size) {
if (i == files.size - 1) { if (i == files.size - 1) {
uploadFile(files[i], false, caption) uploadFile(
fileUri = files[i],
isVoiceMessage = false,
caption = caption,
roomToken = roomToken,
replyToMessageId = getReplyToMessageId(),
displayName = currentConversation?.displayName!!
)
} else { } else {
uploadFile(files[i], false) uploadFile(
fileUri = files[i],
isVoiceMessage = false,
caption = "",
roomToken = roomToken,
replyToMessageId = getReplyToMessageId(),
displayName = currentConversation?.displayName!!
)
} }
} }
} }
private fun uploadFile(fileUri: String, isVoiceMessage: Boolean, caption: String = "", token: String = "") {
var metaData = ""
var room = ""
if (!participantPermissions.hasChatPermission()) {
Log.w(TAG, "uploading file(s) is forbidden because of missing attendee permissions")
return
}
if (isVoiceMessage) {
metaData = VOICE_MESSAGE_META_DATA
}
if (caption != "") {
metaData = "{\"caption\":\"$caption\"}"
}
if (token == "") room = roomToken else room = token
chatViewModel.uploadFile(fileUri, room, currentConversation?.displayName!!, metaData)
}
fun showGalleryPicker() { fun showGalleryPicker() {
pickMultipleMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageAndVideo)) pickMultipleMedia.launch(PickVisualMediaRequest(PickVisualMedia.ImageAndVideo))
} }
@ -2516,10 +2601,67 @@ class ChatActivity :
fun showShareLocationScreen() { fun showShareLocationScreen() {
Log.d(TAG, "showShareLocationScreen") Log.d(TAG, "showShareLocationScreen")
val intent = Intent(this, LocationPickerActivity::class.java) val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
intent.putExtra(KEY_ROOM_TOKEN, roomToken) val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
intent.putExtra(BundleKeys.KEY_CHAT_API_VERSION, chatApiVersion)
startActivity(intent) if (!isGpsEnabled) {
showLocationServicesDisabledDialog()
} else if (!permissionUtil.isLocationPermissionGranted()) {
showLocationPermissionDeniedDialog()
}
if (permissionUtil.isLocationPermissionGranted() && isGpsEnabled) {
val intent = Intent(this, LocationPickerActivity::class.java)
intent.putExtra(KEY_ROOM_TOKEN, roomToken)
intent.putExtra(BundleKeys.KEY_CHAT_API_VERSION, chatApiVersion)
startActivity(intent)
}
}
private fun showLocationServicesDisabledDialog() {
val title = resources.getString(R.string.location_services_disabled)
val explanation = resources.getString(R.string.location_services_disabled_msg)
val positive = resources.getString(R.string.nc_permissions_settings)
val cancel = resources.getString(R.string.nc_cancel)
val dialogBuilder = MaterialAlertDialogBuilder(this)
.setTitle(title)
.setMessage(explanation)
.setPositiveButton(positive) { _, _ ->
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
.setNegativeButton(cancel, null)
viewThemeUtils.dialog.colorMaterialAlertDialogBackground(this, dialogBuilder)
val dialog = dialogBuilder.show()
viewThemeUtils.platform.colorTextButtons(
dialog.getButton(AlertDialog.BUTTON_POSITIVE),
dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
)
}
private fun showLocationPermissionDeniedDialog() {
val title = resources.getString(R.string.location_permission_denied)
val explanation = resources.getString(R.string.location_permission_denied_msg)
val positive = resources.getString(R.string.nc_permissions_settings)
val cancel = resources.getString(R.string.nc_cancel)
val dialogBuilder = MaterialAlertDialogBuilder(this)
.setTitle(title)
.setMessage(explanation)
.setPositiveButton(positive) { _, _ ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
}
startActivity(intent)
}
.setNegativeButton(cancel, null)
viewThemeUtils.dialog.colorMaterialAlertDialogBackground(this, dialogBuilder)
val dialog = dialogBuilder.show()
viewThemeUtils.platform.colorTextButtons(
dialog.getButton(AlertDialog.BUTTON_POSITIVE),
dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
)
} }
private fun showConversationInfoScreen() { private fun showConversationInfoScreen() {
@ -2587,6 +2729,7 @@ class ChatActivity :
if (mentionAutocomplete != null && mentionAutocomplete!!.isPopupShowing) { if (mentionAutocomplete != null && mentionAutocomplete!!.isPopupShowing) {
mentionAutocomplete?.dismissPopup() mentionAutocomplete?.dismissPopup()
} }
adapter = null
} }
private fun isActivityNotChangingConfigurations(): Boolean = !isChangingConfigurations private fun isActivityNotChangingConfigurations(): Boolean = !isChangingConfigurations
@ -2600,7 +2743,9 @@ class ChatActivity :
viewThemeUtils.platform.colorTextView(title, ColorRole.ON_SURFACE) viewThemeUtils.platform.colorTextView(title, ColorRole.ON_SURFACE)
title.text = title.text =
if (currentConversation?.displayName != null) { if (isChatThread()) {
conversationThreadInfo?.thread?.title
} else if (currentConversation?.displayName != null) {
try { try {
EmojiCompat.get().process(currentConversation?.displayName as CharSequence).toString() EmojiCompat.get().process(currentConversation?.displayName as CharSequence).toString()
} catch (e: java.lang.IllegalStateException) { } catch (e: java.lang.IllegalStateException) {
@ -2611,7 +2756,16 @@ class ChatActivity :
"" ""
} }
if (currentConversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL) { if (isChatThread()) {
val replyAmount = conversationThreadInfo?.thread?.numReplies ?: 0
val repliesAmountTitle = resources.getQuantityString(
R.plurals.thread_replies,
replyAmount,
replyAmount
)
statusMessageViewContents(repliesAmountTitle)
} else if (currentConversation?.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL) {
var statusMessage = "" var statusMessage = ""
if (currentConversation?.statusIcon != null) { if (currentConversation?.statusIcon != null) {
statusMessage += currentConversation?.statusIcon statusMessage += currentConversation?.statusIcon
@ -3101,11 +3255,21 @@ class ChatActivity :
} }
val searchItem = menu.findItem(R.id.conversation_search) val searchItem = menu.findItem(R.id.conversation_search)
searchItem.isVisible = CapabilitiesUtil.isUnifiedSearchAvailable(spreedCapabilities) && searchItem.isVisible = CapabilitiesUtil.isUnifiedSearchAvailable(spreedCapabilities) &&
currentConversation!!.remoteServer.isNullOrEmpty() currentConversation!!.remoteServer.isNullOrEmpty() &&
!isChatThread()
if (CapabilitiesUtil.isAbleToCall(spreedCapabilities)) { val sharedItemsItem = menu.findItem(R.id.shared_items)
sharedItemsItem.isVisible = !isChatThread()
val conversationInfoItem = menu.findItem(R.id.conversation_info)
conversationInfoItem.isVisible = !isChatThread()
val showThreadsItem = menu.findItem(R.id.show_threads)
showThreadsItem.isVisible = !isChatThread() &&
hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.THREADS)
if (CapabilitiesUtil.isAbleToCall(spreedCapabilities) && !isChatThread()) {
conversationVoiceCallMenuItem = menu.findItem(R.id.conversation_voice_call) conversationVoiceCallMenuItem = menu.findItem(R.id.conversation_voice_call)
conversationVideoMenuItem = menu.findItem(R.id.conversation_video_call) conversationVideoMenuItem = menu.findItem(R.id.conversation_video_call)
@ -3136,10 +3300,24 @@ class ChatActivity :
menu.removeItem(R.id.conversation_video_call) menu.removeItem(R.id.conversation_video_call)
menu.removeItem(R.id.conversation_voice_call) menu.removeItem(R.id.conversation_voice_call)
} }
handleThreadNotificationIcon(menu.findItem(R.id.thread_notifications))
} }
return true return true
} }
private fun handleThreadNotificationIcon(threadNotificationItem: MenuItem) {
threadNotificationItem.isVisible = isChatThread() &&
hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.THREADS)
val threadNotificationIcon = when (conversationThreadInfo?.attendee?.notificationLevel) {
1 -> R.drawable.outline_notifications_active_24
3 -> R.drawable.ic_baseline_notifications_off_24
else -> R.drawable.baseline_notifications_24
}
threadNotificationItem.icon = ContextCompat.getDrawable(context, threadNotificationIcon)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) { when (item.itemId) {
R.id.conversation_video_call -> { R.id.conversation_video_call -> {
@ -3169,15 +3347,105 @@ class ChatActivity :
R.id.conversation_event -> { R.id.conversation_event -> {
val anchorView = findViewById<View>(R.id.conversation_event) val anchorView = findViewById<View>(R.id.conversation_event)
showPopupWindow(anchorView) showConversationEventMenu(anchorView)
true
}
R.id.show_threads -> {
openThreadsOverview()
true
}
R.id.thread_notifications -> {
showThreadNotificationMenu()
true true
} }
else -> super.onOptionsItemSelected(item) else -> super.onOptionsItemSelected(item)
} }
@Suppress("Detekt.LongMethod")
private fun showThreadNotificationMenu() {
fun setThreadNotificationLevel(level: Int) {
val threadNotificationUrl = ApiUtils.getUrlForThreadNotificationLevel(
version = 1,
baseUrl = conversationUser!!.baseUrl,
token = roomToken,
threadId = conversationThreadId!!.toInt()
)
chatViewModel.setThreadNotificationLevel(credentials!!, threadNotificationUrl, level)
}
if (overflowMenuHostView == null) {
val threadNotificationsAnchor: View? = findViewById(R.id.thread_notifications)
val colorScheme = viewThemeUtils.getColorScheme(this)
overflowMenuHostView = ComposeView(this).apply {
setContent {
MaterialTheme(
colorScheme = colorScheme
) {
val items = listOf(
MenuItemData(
title = context.resources.getString(R.string.notifications_default),
subtitle = context.resources.getString(
R.string.notifications_default_description
),
icon = R.drawable.baseline_notifications_24,
onClick = {
setThreadNotificationLevel(0)
}
),
MenuItemData(
title = context.resources.getString(R.string.notification_all_messages),
subtitle = null,
icon = R.drawable.outline_notifications_active_24,
onClick = {
setThreadNotificationLevel(1)
}
),
MenuItemData(
title = context.resources.getString(R.string.notification_mention_only),
subtitle = null,
icon = R.drawable.baseline_notifications_24,
onClick = {
setThreadNotificationLevel(2)
}
),
MenuItemData(
title = context.resources.getString(R.string.notification_off),
subtitle = null,
icon = R.drawable.ic_baseline_notifications_off_24,
onClick = {
setThreadNotificationLevel(3)
}
)
)
OverflowMenu(
anchor = threadNotificationsAnchor,
expanded = isThreadMenuExpanded,
items = items,
onDismiss = { isThreadMenuExpanded = false }
)
}
}
}
addContentView(
overflowMenuHostView,
CoordinatorLayout.LayoutParams(
CoordinatorLayout.LayoutParams.MATCH_PARENT,
CoordinatorLayout.LayoutParams.MATCH_PARENT
)
)
}
isThreadMenuExpanded = true
}
@SuppressLint("InflateParams") @SuppressLint("InflateParams")
private fun showPopupWindow(anchorView: View) { private fun showConversationEventMenu(anchorView: View) {
val popupView = layoutInflater.inflate(R.layout.item_event_schedule, null) val popupView = layoutInflater.inflate(R.layout.item_event_schedule, null)
val subtitleTextView = popupView.findViewById<TextView>(R.id.meetingTime) val subtitleTextView = popupView.findViewById<TextView>(R.id.meetingTime)
@ -3366,7 +3634,7 @@ class ChatActivity :
} }
private fun handleSystemMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> { private fun handleSystemMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> {
val chatMessageMap = chatMessageList.map { it.id to it }.toMap().toMutableMap() val chatMessageMap = chatMessageList.associateBy { it.id }.toMutableMap()
val chatMessageIterator = chatMessageMap.iterator() val chatMessageIterator = chatMessageMap.iterator()
while (chatMessageIterator.hasNext()) { while (chatMessageIterator.hasNext()) {
@ -3375,7 +3643,8 @@ class ChatActivity :
if (isInfoMessageAboutDeletion(currentMessage) || if (isInfoMessageAboutDeletion(currentMessage) ||
isReactionsMessage(currentMessage) || isReactionsMessage(currentMessage) ||
isPollVotedMessage(currentMessage) || isPollVotedMessage(currentMessage) ||
isEditMessage(currentMessage) isEditMessage(currentMessage) ||
isThreadCreatedMessage(currentMessage)
) { ) {
chatMessageIterator.remove() chatMessageIterator.remove()
} }
@ -3384,29 +3653,56 @@ class ChatActivity :
} }
private fun handleExpandableSystemMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> { private fun handleExpandableSystemMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> {
val chatMessageMap = chatMessageList.map { it.id to it }.toMap().toMutableMap() val chatMessageMap = chatMessageList.associateBy { it.id }.toMutableMap()
val chatMessageIterator = chatMessageMap.iterator() val chatMessageIterator = chatMessageMap.iterator()
while (chatMessageIterator.hasNext()) { while (chatMessageIterator.hasNext()) {
val currentMessage = chatMessageIterator.next() val currentMessage = chatMessageIterator.next()
chatMessageMap[currentMessage.value.previousMessageId.toString()]?.let { previousMessage ->
val previousMessage = chatMessageMap[currentMessage.value.previousMessageId.toString()] if (isSystemMessage(currentMessage.value) &&
if (isSystemMessage(currentMessage.value) && previousMessage.systemMessageType == currentMessage.value.systemMessageType &&
previousMessage?.systemMessageType == currentMessage.value.systemMessageType isSameDayMessages(previousMessage, currentMessage.value)
) { ) {
previousMessage?.expandableParent = true groupSystemMessages(previousMessage, currentMessage.value)
currentMessage.value.expandableParent = false
if (currentMessage.value.lastItemOfExpandableGroup == 0) {
currentMessage.value.lastItemOfExpandableGroup = currentMessage.value.jsonMessageId
} }
previousMessage?.lastItemOfExpandableGroup = currentMessage.value.lastItemOfExpandableGroup
previousMessage?.expandableChildrenAmount = currentMessage.value.expandableChildrenAmount + 1
} }
} }
return chatMessageMap.values.toList() return chatMessageMap.values.toList()
} }
private fun groupSystemMessages(previousMessage: ChatMessage, currentMessage: ChatMessage) {
previousMessage.expandableParent = true
currentMessage.expandableParent = false
if (currentMessage.lastItemOfExpandableGroup == 0) {
currentMessage.lastItemOfExpandableGroup = currentMessage.jsonMessageId
}
previousMessage.lastItemOfExpandableGroup = currentMessage.lastItemOfExpandableGroup
previousMessage.expandableChildrenAmount = currentMessage.expandableChildrenAmount + 1
}
private fun handleThreadMessages(chatMessageList: List<ChatMessage>): List<ChatMessage> {
fun isThreadChildMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
currentMessage.value.isThread &&
currentMessage.value.threadId?.toInt() != currentMessage.value.jsonMessageId
val chatMessageMap = chatMessageList.associateBy { it.id }.toMutableMap()
if (conversationThreadId == null) {
val chatMessageIterator = chatMessageMap.iterator()
while (chatMessageIterator.hasNext()) {
val currentMessage = chatMessageIterator.next()
if (isThreadChildMessage(currentMessage)) {
chatMessageIterator.remove()
}
}
}
return chatMessageMap.values.toList()
}
private fun isInfoMessageAboutDeletion(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean = private fun isInfoMessageAboutDeletion(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
currentMessage.value.parentMessageId != null && currentMessage.value.parentMessageId != null &&
currentMessage.value.systemMessageType == ChatMessage currentMessage.value.systemMessageType == ChatMessage
@ -3417,6 +3713,9 @@ class ChatActivity :
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_DELETED || currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_DELETED ||
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_REVOKED currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.REACTION_REVOKED
private fun isThreadCreatedMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
currentMessage.value.systemMessageType == ChatMessage.SystemMessageType.THREAD_CREATED
private fun isEditMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean = private fun isEditMessage(currentMessage: MutableMap.MutableEntry<String, ChatMessage>): Boolean =
currentMessage.value.parentMessageId != null && currentMessage.value.parentMessageId != null &&
currentMessage.value.systemMessageType == ChatMessage currentMessage.value.systemMessageType == ChatMessage
@ -3489,6 +3788,10 @@ class ChatActivity :
} }
} }
override fun openThread(chatMessage: ChatMessage) {
openThread(chatMessage.jsonMessageId.toLong())
}
override fun onLongClickReactions(chatMessage: ChatMessage) { override fun onLongClickReactions(chatMessage: ChatMessage) {
ShowReactionsDialog( ShowReactionsDialog(
this, this,
@ -3761,7 +4064,14 @@ class ChatActivity :
val type = message.getCalculateMessageType() val type = message.getCalculateMessageType()
when (type) { when (type) {
ChatMessage.MessageType.VOICE_MESSAGE -> { ChatMessage.MessageType.VOICE_MESSAGE -> {
uploadFile(shareUri.toString(), true, token = roomToken) uploadFile(
shareUri.toString(),
true,
roomToken = roomToken,
caption = "",
replyToMessageId = getReplyToMessageId(),
displayName = currentConversation?.displayName ?: ""
)
showSnackBar(roomToken) showSnackBar(roomToken)
} }
@ -3770,12 +4080,26 @@ class ChatActivity :
if (null != shareUri) { if (null != shareUri) {
try { try {
context.contentResolver.openInputStream(shareUri)?.close() context.contentResolver.openInputStream(shareUri)?.close()
uploadFile(shareUri.toString(), false, caption!!, roomToken) uploadFile(
fileUri = shareUri.toString(),
isVoiceMessage = false,
caption = caption!!,
roomToken = roomToken,
replyToMessageId = getReplyToMessageId(),
displayName = currentConversation?.displayName ?: ""
)
showSnackBar(roomToken) showSnackBar(roomToken)
} catch (e: java.lang.Exception) { } catch (e: Exception) {
Log.w(TAG, "File corresponding to the uri does not exist $shareUri") Log.w(TAG, "File corresponding to the uri does not exist $shareUri", e)
downloadFileToCache(message, false) { downloadFileToCache(message, false) {
uploadFile(shareUri.toString(), false, caption!!, roomToken) uploadFile(
fileUri = shareUri.toString(),
isVoiceMessage = false,
caption = caption!!,
roomToken = roomToken,
replyToMessageId = getReplyToMessageId(),
displayName = currentConversation?.displayName ?: ""
)
showSnackBar(roomToken) showSnackBar(roomToken)
} }
} }
@ -4097,6 +4421,10 @@ class ChatActivity :
pollVoteDialog.show(supportFragmentManager, TAG) pollVoteDialog.show(supportFragmentManager, TAG)
} }
fun createThread() {
messageInputViewModel.startThreadCreation()
}
fun jumpToQuotedMessage(parentMessage: ChatMessage) { fun jumpToQuotedMessage(parentMessage: ChatMessage) {
var foundMessage = false var foundMessage = false
for (position in 0 until (adapter!!.items.size)) { for (position in 0 until (adapter!!.items.size)) {
@ -4109,10 +4437,38 @@ class ChatActivity :
} }
if (!foundMessage) { if (!foundMessage) {
Log.d(TAG, "quoted message with id " + parentMessage.id + " was not found in adapter") Log.d(TAG, "quoted message with id " + parentMessage.id + " was not found in adapter")
startContextChatWindowForMessage(parentMessage.id) startContextChatWindowForMessage(parentMessage.id, conversationThreadId.toString())
} }
} }
private fun isChatThread(): Boolean = conversationThreadId != null && conversationThreadId!! > 0
fun openThread(messageId: Long) {
val bundle = Bundle()
bundle.putString(KEY_ROOM_TOKEN, roomToken)
bundle.putLong(KEY_THREAD_ID, messageId)
val chatIntent = Intent(context, ChatActivity::class.java)
chatIntent.putExtras(bundle)
startActivity(chatIntent)
}
fun openThreadsOverview() {
val threadsUrl = ApiUtils.getUrlForRecentThreads(
version = 1,
baseUrl = conversationUser!!.baseUrl,
token = roomToken
)
val bundle = Bundle()
bundle.putString(KEY_ROOM_TOKEN, roomToken)
bundle.putString(ThreadsOverviewActivity.KEY_APPBAR_TITLE, getString(R.string.recent_threads))
bundle.putString(ThreadsOverviewActivity.KEY_THREADS_SOURCE_URL, threadsUrl)
val threadsOverviewIntent = Intent(context, ThreadsOverviewActivity::class.java)
threadsOverviewIntent.putExtras(bundle)
startActivity(threadsOverviewIntent)
}
override fun joinAudioCall() { override fun joinAudioCall() {
startACall(true, false) startACall(true, false)
} }
@ -4158,6 +4514,37 @@ class ChatActivity :
) )
} }
fun uploadFile(
fileUri: String,
isVoiceMessage: Boolean,
caption: String = "",
roomToken: String = "",
replyToMessageId: Int? = null,
displayName: String
) {
chatViewModel.uploadFile(
fileUri,
isVoiceMessage,
caption,
roomToken,
replyToMessageId,
displayName
)
cancelReply()
}
fun cancelReply() {
messageInputViewModel.reply(null)
chatViewModel.messageDraft.quotedMessageText = null
chatViewModel.messageDraft.quotedDisplayName = null
chatViewModel.messageDraft.quotedImageUrl = null
chatViewModel.messageDraft.quotedJsonId = null
}
fun cancelCreateThread() {
chatViewModel.clearThreadTitle()
}
companion object { companion object {
val TAG = ChatActivity::class.simpleName val TAG = ChatActivity::class.simpleName
private const val CONTENT_TYPE_CALL_STARTED: Byte = 1 private const val CONTENT_TYPE_CALL_STARTED: Byte = 1
@ -4177,7 +4564,6 @@ class ChatActivity :
private const val REQUEST_RECORD_AUDIO_PERMISSION = 222 private const val REQUEST_RECORD_AUDIO_PERMISSION = 222
private const val REQUEST_READ_CONTACT_PERMISSION = 234 private const val REQUEST_READ_CONTACT_PERMISSION = 234
private const val REQUEST_CAMERA_PERMISSION = 223 private const val REQUEST_CAMERA_PERMISSION = 223
private const val VOICE_MESSAGE_META_DATA = "{\"messageType\":\"voice-message\"}"
private const val FILE_DATE_PATTERN = "yyyy-MM-dd HH-mm-ss" private const val FILE_DATE_PATTERN = "yyyy-MM-dd HH-mm-ss"
private const val VIDEO_SUFFIX = ".mp4" private const val VIDEO_SUFFIX = ".mp4"
private const val FULLY_OPAQUE_INT: Int = 255 private const val FULLY_OPAQUE_INT: Int = 255

View file

@ -35,7 +35,6 @@ import android.widget.LinearLayout
import android.widget.PopupMenu import android.widget.PopupMenu
import android.widget.RelativeLayout import android.widget.RelativeLayout
import android.widget.SeekBar import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.view.ContextThemeWrapper import androidx.appcompat.view.ContextThemeWrapper
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
@ -61,6 +60,7 @@ import com.nextcloud.talk.application.NextcloudTalkApplication.Companion.sharedA
import com.nextcloud.talk.callbacks.MentionAutocompleteCallback import com.nextcloud.talk.callbacks.MentionAutocompleteCallback
import com.nextcloud.talk.chat.data.model.ChatMessage import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.chat.viewmodels.ChatViewModel import com.nextcloud.talk.chat.viewmodels.ChatViewModel
import com.nextcloud.talk.chat.viewmodels.MessageInputViewModel
import com.nextcloud.talk.data.network.NetworkMonitor import com.nextcloud.talk.data.network.NetworkMonitor
import com.nextcloud.talk.databinding.FragmentMessageInputBinding import com.nextcloud.talk.databinding.FragmentMessageInputBinding
import com.nextcloud.talk.jobs.UploadAndShareFilesWorker import com.nextcloud.talk.jobs.UploadAndShareFilesWorker
@ -75,45 +75,28 @@ import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.CapabilitiesUtil import com.nextcloud.talk.utils.CapabilitiesUtil
import com.nextcloud.talk.utils.CharPolicy import com.nextcloud.talk.utils.CharPolicy
import com.nextcloud.talk.utils.EmojiTextInputEditText
import com.nextcloud.talk.utils.ImageEmojiEditText import com.nextcloud.talk.utils.ImageEmojiEditText
import com.nextcloud.talk.utils.SpreedFeatures import com.nextcloud.talk.utils.SpreedFeatures
import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew
import com.nextcloud.talk.utils.message.MessageUtils import com.nextcloud.talk.utils.message.MessageUtils
import com.nextcloud.talk.utils.text.Spans import com.nextcloud.talk.utils.text.Spans
import com.otaliastudios.autocomplete.Autocomplete import com.otaliastudios.autocomplete.Autocomplete
import com.stfalcon.chatkit.commons.models.IMessage
import com.vanniktech.emoji.EmojiPopup import com.vanniktech.emoji.EmojiPopup
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Objects import java.util.Objects
import javax.inject.Inject import javax.inject.Inject
@Suppress("LongParameterList", "TooManyFunctions") @Suppress("LongParameterList", "TooManyFunctions", "LargeClass", "LongMethod")
@AutoInjector(NextcloudTalkApplication::class) @AutoInjector(NextcloudTalkApplication::class)
class MessageInputFragment : Fragment() { class MessageInputFragment : Fragment() {
companion object {
fun newInstance() = MessageInputFragment()
private val TAG: String = MessageInputFragment::class.java.simpleName
private const val TYPING_DURATION_TO_SEND_NEXT_TYPING_MESSAGE = 10000L
private const val TYPING_INTERVAL_TO_SEND_NEXT_TYPING_MESSAGE = 1000L
private const val TYPING_STARTED_SIGNALING_MESSAGE_TYPE = "startedTyping"
private const val TYPING_STOPPED_SIGNALING_MESSAGE_TYPE = "stoppedTyping"
const val VOICE_MESSAGE_META_DATA = "{\"messageType\":\"voice-message\"}"
private const val QUOTED_MESSAGE_IMAGE_MAX_HEIGHT = 96f
private const val MENTION_AUTO_COMPLETE_ELEVATION = 6f
private const val MINIMUM_VOICE_RECORD_DURATION: Int = 1000
private const val ANIMATION_DURATION: Long = 750
private const val VOICE_RECORD_CANCEL_SLIDER_X: Int = -150
private const val VOICE_RECORD_LOCK_THRESHOLD: Float = 100f
private const val INCREMENT = 8f
private const val CURSOR_KEY = "_cursor"
private const val CONNECTION_ESTABLISHED_ANIM_DURATION: Long = 3000
private const val FULLY_OPAQUE: Float = 1.0f
private const val FULLY_TRANSPARENT: Float = 0.0f
}
@Inject @Inject
lateinit var viewThemeUtils: ViewThemeUtils lateinit var viewThemeUtils: ViewThemeUtils
@ -144,6 +127,12 @@ class MessageInputFragment : Fragment() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
sharedApplication!!.componentApplication.inject(this) sharedApplication!!.componentApplication.inject(this)
conversationInternalId = arguments?.getString(ChatActivity.CONVERSATION_INTERNAL_ID).orEmpty() conversationInternalId = arguments?.getString(ChatActivity.CONVERSATION_INTERNAL_ID).orEmpty()
chatActivity = requireActivity() as ChatActivity
val sharedText = arguments?.getString(BundleKeys.KEY_SHARED_TEXT).orEmpty()
if (sharedText.isNotEmpty()) {
chatActivity.chatViewModel.messageDraft.messageText = sharedText
chatActivity.chatViewModel.saveMessageDraft()
}
if (conversationInternalId.isEmpty()) { if (conversationInternalId.isEmpty()) {
Log.e(TAG, "internalId for conversation passed to MessageInputFragment is empty") Log.e(TAG, "internalId for conversation passed to MessageInputFragment is empty")
} }
@ -151,45 +140,75 @@ class MessageInputFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentMessageInputBinding.inflate(inflater) binding = FragmentMessageInputBinding.inflate(inflater)
chatActivity = requireActivity() as ChatActivity
themeMessageInputView() themeMessageInputView()
initMessageInputView() initMessageInputView()
initSmileyKeyboardToggler() initSmileyKeyboardToggler()
setupMentionAutocomplete() setupMentionAutocomplete()
initVoiceRecordButton() initVoiceRecordButton()
initThreadHandling()
restoreState() restoreState()
return binding.root return binding.root
} }
override fun onPause() {
super.onPause()
saveState()
}
override fun onDestroyView() { override fun onDestroyView() {
super.onDestroyView() super.onDestroyView()
if (mentionAutocomplete != null && mentionAutocomplete!!.isPopupShowing) { if (mentionAutocomplete != null && mentionAutocomplete!!.isPopupShowing) {
mentionAutocomplete?.dismissPopup() mentionAutocomplete?.dismissPopup()
} }
clearEditUI() clearEditUI()
cancelReply()
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
initObservers() initObservers()
binding.fragmentCreateThreadView.createThreadView.findViewById<EmojiTextInputEditText>(
R.id
.createThreadInput
).doAfterTextChanged { text ->
val threadTitle = text.toString()
chatActivity.chatViewModel.messageDraft.threadTitle = threadTitle
}
} }
private fun initObservers() { private fun initObservers() {
Log.d(TAG, "LifeCyclerOwner is: ${viewLifecycleOwner.lifecycle}") Log.d(TAG, "LifeCyclerOwner is: ${viewLifecycleOwner.lifecycle}")
chatActivity.messageInputViewModel.getReplyChatMessage.observe(viewLifecycleOwner) { message -> chatActivity.messageInputViewModel.getReplyChatMessage.observe(viewLifecycleOwner) { message ->
message?.let { replyToMessage(message) } message?.let {
chatActivity.chatViewModel.messageDraft.quotedMessageText = message.text
chatActivity.chatViewModel.messageDraft.quotedDisplayName = message.actorDisplayName
chatActivity.chatViewModel.messageDraft.quotedImageUrl = message.imageUrl
chatActivity.chatViewModel.messageDraft.quotedJsonId = message.jsonMessageId
replyToMessage(
message.text,
message.actorDisplayName,
message.imageUrl
)
} ?: clearReplyUi()
} }
chatActivity.messageInputViewModel.getEditChatMessage.observe(viewLifecycleOwner) { message -> chatActivity.messageInputViewModel.getEditChatMessage.observe(viewLifecycleOwner) { message ->
message?.let { setEditUI(it as ChatMessage) } message?.let { setEditUI(it as ChatMessage) }
} }
chatActivity.messageInputViewModel.createThreadViewState.observe(viewLifecycleOwner) { state ->
when (state) {
is MessageInputViewModel.CreateThreadStartState ->
binding.fragmentCreateThreadView.createThreadView.visibility = View.GONE
is MessageInputViewModel.CreateThreadEditState -> {
binding.fragmentCreateThreadView.createThreadView.visibility = View.VISIBLE
binding.fragmentCreateThreadView.createThreadView
.findViewById<EmojiTextInputEditText>(R.id.createThreadInput)?.setText(
chatActivity.chatViewModel.messageDraft.threadTitle
)
}
else -> {}
}
initVoiceRecordButton()
}
chatActivity.chatViewModel.leaveRoomViewState.observe(viewLifecycleOwner) { state -> chatActivity.chatViewModel.leaveRoomViewState.observe(viewLifecycleOwner) { state ->
when (state) { when (state) {
is ChatViewModel.LeaveRoomSuccessState -> sendStopTypingMessage() is ChatViewModel.LeaveRoomSuccessState -> sendStopTypingMessage()
@ -299,33 +318,29 @@ class MessageInputFragment : Fragment() {
} }
private fun restoreState() { private fun restoreState() {
if (binding.fragmentMessageInputView.inputEditText.text.isEmpty()) { CoroutineScope(Dispatchers.IO).launch {
requireContext().getSharedPreferences(chatActivity.localClassName, AppCompatActivity.MODE_PRIVATE).apply { chatActivity.chatViewModel.updateMessageDraft()
val text = getString(chatActivity.roomToken, "")
val cursor = getInt(chatActivity.roomToken + CURSOR_KEY, 0)
binding.fragmentMessageInputView.messageInput.setText(text)
binding.fragmentMessageInputView.messageInput.setSelection(cursor)
}
}
}
private fun saveState() { withContext(Dispatchers.Main) {
val text = binding.fragmentMessageInputView.messageInput.text.toString() val draft = chatActivity.chatViewModel.messageDraft
val cursor = binding.fragmentMessageInputView.messageInput.selectionStart binding.fragmentMessageInputView.messageInput.setText(draft.messageText)
val previous = requireContext().getSharedPreferences( binding.fragmentMessageInputView.messageInput.setSelection(draft.messageCursor)
chatActivity.localClassName,
AppCompatActivity
.MODE_PRIVATE
).getString(chatActivity.roomToken, "null")
if (text != previous) { if (draft.threadTitle?.isNotEmpty() == true) {
requireContext().getSharedPreferences( chatActivity.messageInputViewModel.startThreadCreation()
chatActivity.localClassName, }
AppCompatActivity.MODE_PRIVATE
).edit().apply { if (draft.messageText != "") {
putString(chatActivity.roomToken, text) binding.fragmentMessageInputView.messageInput.requestFocus()
putInt(chatActivity.roomToken + CURSOR_KEY, cursor) }
apply()
if (isInReplyState()) {
replyToMessage(
chatActivity.chatViewModel.messageDraft.quotedMessageText,
chatActivity.chatViewModel.messageDraft.quotedDisplayName,
chatActivity.chatViewModel.messageDraft.quotedImageUrl
)
}
} }
} }
} }
@ -388,7 +403,11 @@ class MessageInputFragment : Fragment() {
} }
override fun afterTextChanged(s: Editable) { override fun afterTextChanged(s: Editable) {
// unused atm val cursor = binding.fragmentMessageInputView.messageInput.selectionStart
val text = binding.fragmentMessageInputView.messageInput.text.toString()
chatActivity.chatViewModel.messageDraft.messageCursor = cursor
chatActivity.chatViewModel.messageDraft.messageText = text
handleButtonsVisibility()
} }
}) })
@ -396,11 +415,14 @@ class MessageInputFragment : Fragment() {
// See: https://developer.android.com/guide/topics/text/image-keyboard // See: https://developer.android.com/guide/topics/text/image-keyboard
(binding.fragmentMessageInputView.inputEditText as ImageEmojiEditText).onCommitContentListener = { (binding.fragmentMessageInputView.inputEditText as ImageEmojiEditText).onCommitContentListener = {
uploadFile(it.toString(), false) chatActivity.chatViewModel.uploadFile(
} fileUri = it.toString(),
isVoiceMessage = false,
if (chatActivity.sharedText.isNotEmpty()) { caption = "",
binding.fragmentMessageInputView.inputEditText?.setText(chatActivity.sharedText) roomToken = chatActivity.roomToken,
replyToMessageId = chatActivity.getReplyToMessageId(),
displayName = chatActivity.currentConversation?.displayName!!
)
} }
binding.fragmentMessageInputView.setAttachmentsListener { binding.fragmentMessageInputView.setAttachmentsListener {
@ -439,6 +461,9 @@ class MessageInputFragment : Fragment() {
binding.fragmentEditView.clearEdit.setOnClickListener { binding.fragmentEditView.clearEdit.setOnClickListener {
clearEditUI() clearEditUI()
} }
binding.fragmentCreateThreadView.abortCreateThread.setOnClickListener {
cancelCreateThread()
}
if (CapabilitiesUtil.hasSpreedFeatureCapability(chatActivity.spreedCapabilities, SpreedFeatures.SILENT_SEND)) { if (CapabilitiesUtil.hasSpreedFeatureCapability(chatActivity.spreedCapabilities, SpreedFeatures.SILENT_SEND)) {
binding.fragmentMessageInputView.button?.setOnLongClickListener { binding.fragmentMessageInputView.button?.setOnLongClickListener {
@ -466,6 +491,10 @@ class MessageInputFragment : Fragment() {
binding.fragmentCallStarted.callStartedSecondaryText.visibility = if (collapsed) View.VISIBLE else View.GONE binding.fragmentCallStarted.callStartedSecondaryText.visibility = if (collapsed) View.VISIBLE else View.GONE
setDropDown(collapsed) setDropDown(collapsed)
} }
binding.fragmentMessageInputView.findViewById<ImageButton>(R.id.cancelReplyButton)?.setOnClickListener {
cancelReply()
}
} }
private fun setDropDown(collapsed: Boolean) { private fun setDropDown(collapsed: Boolean) {
@ -480,32 +509,7 @@ class MessageInputFragment : Fragment() {
@Suppress("ClickableViewAccessibility", "CyclomaticComplexMethod", "LongMethod") @Suppress("ClickableViewAccessibility", "CyclomaticComplexMethod", "LongMethod")
private fun initVoiceRecordButton() { private fun initVoiceRecordButton() {
if (binding.fragmentMessageInputView.messageInput.text.isNullOrBlank()) { handleButtonsVisibility()
binding.fragmentMessageInputView.messageSendButton.visibility = View.GONE
binding.fragmentMessageInputView.recordAudioButton.visibility = View.VISIBLE
} else {
binding.fragmentMessageInputView.messageSendButton.visibility = View.VISIBLE
binding.fragmentMessageInputView.recordAudioButton.visibility = View.GONE
}
binding.fragmentMessageInputView.inputEditText.doAfterTextChanged {
binding.fragmentMessageInputView.recordAudioButton.visibility =
if (binding.fragmentMessageInputView.inputEditText.text.isEmpty() &&
chatActivity.messageInputViewModel.getEditChatMessage.value == null
) {
View.VISIBLE
} else {
View.GONE
}
binding.fragmentMessageInputView.messageSendButton.visibility =
if (binding.fragmentMessageInputView.inputEditText.text.isEmpty() ||
binding.fragmentEditView.editMessageView.isVisible
) {
View.GONE
} else {
View.VISIBLE
}
}
var prevDx = 0f var prevDx = 0f
var voiceRecordStartTime = 0L var voiceRecordStartTime = 0L
@ -568,9 +572,9 @@ class MessageInputFragment : Fragment() {
return@setOnTouchListener false return@setOnTouchListener false
} else { } else {
chatActivity.chatViewModel.stopAndSendAudioRecording( chatActivity.chatViewModel.stopAndSendAudioRecording(
chatActivity.roomToken, roomToken = chatActivity.roomToken,
chatActivity.currentConversation!!.displayName, replyToMessageId = chatActivity.getReplyToMessageId(),
VOICE_MESSAGE_META_DATA displayName = chatActivity.currentConversation!!.displayName
) )
} }
resetSlider() resetSlider()
@ -615,7 +619,67 @@ class MessageInputFragment : Fragment() {
} }
} }
} }
v?.onTouchEvent(event) ?: true v?.onTouchEvent(event) != false
}
}
private fun initThreadHandling() {
binding.fragmentMessageInputView.submitThreadButton.setOnClickListener {
submitMessage(false)
}
binding.fragmentCreateThreadView.createThreadInput.doAfterTextChanged {
handleButtonsVisibility()
}
}
private fun handleButtonsVisibility() {
fun View.setVisible(isVisible: Boolean) {
visibility = if (isVisible) View.VISIBLE else View.GONE
}
val isEditModeActive = binding.fragmentEditView.editMessageView.isVisible
val isThreadCreateModeActive = binding.fragmentCreateThreadView.createThreadView.isVisible
val inputContainsText = binding.fragmentMessageInputView.messageInput.text.isNotEmpty()
val threadTitleContainsText = binding.fragmentCreateThreadView.createThreadInput.text?.isNotEmpty() ?: false
binding.fragmentMessageInputView.apply {
when {
isEditModeActive -> {
messageSendButton.setVisible(false)
recordAudioButton.setVisible(false)
submitThreadButton.setVisible(false)
attachmentButton.setVisible(true)
}
isThreadCreateModeActive -> {
messageSendButton.setVisible(false)
recordAudioButton.setVisible(false)
attachmentButton.setVisible(false)
submitThreadButton.setVisible(true)
if (inputContainsText && threadTitleContainsText) {
submitThreadButton.isEnabled = true
submitThreadButton.alpha = FULLY_OPAQUE
} else {
submitThreadButton.isEnabled = false
submitThreadButton.alpha = OPACITY_DISABLED
}
}
inputContainsText -> {
recordAudioButton.setVisible(false)
submitThreadButton.setVisible(false)
messageSendButton.setVisible(true)
attachmentButton.setVisible(true)
}
else -> {
messageSendButton.setVisible(false)
submitThreadButton.setVisible(false)
recordAudioButton.setVisible(true)
attachmentButton.setVisible(true)
}
}
} }
} }
@ -717,52 +781,45 @@ class MessageInputFragment : Fragment() {
} }
} }
private fun replyToMessage(message: IMessage?) { private fun replyToMessage(quotedMessageText: String?, quotedActorDisplayName: String?, quotedImageUrl: String?) {
Log.d(TAG, "Reply") Log.d(TAG, "Reply")
val chatMessage = message as ChatMessage? val view = binding.fragmentMessageInputView
chatMessage?.let { view.findViewById<ImageButton>(R.id.cancelReplyButton)?.visibility =
val view = binding.fragmentMessageInputView View.VISIBLE
view.findViewById<ImageButton>(R.id.attachmentButton)?.visibility =
View.GONE
view.findViewById<ImageButton>(R.id.cancelReplyButton)?.visibility =
View.VISIBLE
val quotedMessage = view.findViewById<EmojiTextView>(R.id.quotedMessage) val quotedMessage = view.findViewById<EmojiTextView>(R.id.quotedMessage)
quotedMessage?.maxLines = 2 quotedMessage?.maxLines = 2
quotedMessage?.ellipsize = TextUtils.TruncateAt.END quotedMessage?.ellipsize = TextUtils.TruncateAt.END
quotedMessage?.text = it.text quotedMessage?.text = quotedMessageText
view.findViewById<EmojiTextView>(R.id.quotedMessageAuthor)?.text = view.findViewById<EmojiTextView>(R.id.quotedMessageAuthor)?.text =
it.actorDisplayName ?: requireContext().getText(R.string.nc_nick_guest) quotedActorDisplayName ?: requireContext().getText(R.string.nc_nick_guest)
chatActivity.conversationUser?.let { chatActivity.conversationUser?.let {
val quotedMessageImage = view.findViewById<ImageView>(R.id.quotedMessageImage) val quotedMessageImage = view.findViewById<ImageView>(R.id.quotedMessageImage)
chatMessage.imageUrl?.let { previewImageUrl -> quotedImageUrl?.let { previewImageUrl ->
quotedMessageImage?.visibility = View.VISIBLE quotedMessageImage?.visibility = View.VISIBLE
val px = TypedValue.applyDimension( val px = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TypedValue.COMPLEX_UNIT_DIP,
QUOTED_MESSAGE_IMAGE_MAX_HEIGHT, QUOTED_MESSAGE_IMAGE_MAX_HEIGHT,
resources.displayMetrics resources.displayMetrics
) )
quotedMessageImage?.maxHeight = px.toInt() quotedMessageImage?.maxHeight = px.toInt()
val layoutParams = quotedMessageImage?.layoutParams as FlexboxLayout.LayoutParams val layoutParams = quotedMessageImage?.layoutParams as FlexboxLayout.LayoutParams
layoutParams.flexGrow = 0f layoutParams.flexGrow = 0f
quotedMessageImage.layoutParams = layoutParams quotedMessageImage.layoutParams = layoutParams
quotedMessageImage.load(previewImageUrl) { quotedMessageImage.load(previewImageUrl) {
addHeader("Authorization", chatActivity.credentials!!) addHeader("Authorization", chatActivity.credentials!!)
}
} ?: run {
view.findViewById<ImageView>(R.id.quotedMessageImage)?.visibility = View.GONE
} }
} ?: run {
view.findViewById<ImageView>(R.id.quotedMessageImage)?.visibility = View.GONE
} }
val quotedChatMessageView =
view.findViewById<RelativeLayout>(R.id.quotedChatMessageView)
quotedChatMessageView?.tag = message?.jsonMessageId
quotedChatMessageView?.visibility = View.VISIBLE
} }
val quotedChatMessageView = view.findViewById<RelativeLayout>(R.id.quotedChatMessageView)
quotedChatMessageView?.visibility = View.VISIBLE
} }
fun updateOwnTypingStatus(typedText: CharSequence) { fun updateOwnTypingStatus(typedText: CharSequence) {
@ -829,58 +886,34 @@ class MessageInputFragment : Fragment() {
private fun isTypingStatusEnabled(): Boolean = private fun isTypingStatusEnabled(): Boolean =
!CapabilitiesUtil.isTypingStatusPrivate(chatActivity.conversationUser!!) !CapabilitiesUtil.isTypingStatusPrivate(chatActivity.conversationUser!!)
private fun uploadFile(fileUri: String, isVoiceMessage: Boolean, caption: String = "", token: String = "") {
var metaData = ""
val room: String
if (!chatActivity.participantPermissions.hasChatPermission()) {
Log.w(ChatActivity.TAG, "uploading file(s) is forbidden because of missing attendee permissions")
return
}
if (isVoiceMessage) {
metaData = VOICE_MESSAGE_META_DATA
}
if (caption != "") {
metaData = "{\"caption\":\"$caption\"}"
}
if (token == "") room = chatActivity.roomToken else room = token
chatActivity.chatViewModel.uploadFile(fileUri, room, chatActivity.currentConversation!!.displayName, metaData)
}
private fun submitMessage(sendWithoutNotification: Boolean) { private fun submitMessage(sendWithoutNotification: Boolean) {
if (binding.fragmentMessageInputView.inputEditText != null) { if (binding.fragmentMessageInputView.inputEditText != null) {
val editable = binding.fragmentMessageInputView.inputEditText!!.editableText val editable = binding.fragmentMessageInputView.inputEditText!!.editableText
replaceMentionChipSpans(editable) replaceMentionChipSpans(editable)
binding.fragmentMessageInputView.inputEditText?.setText("") binding.fragmentMessageInputView.inputEditText?.setText("")
sendStopTypingMessage() sendStopTypingMessage()
val replyMessageId = binding.fragmentMessageInputView
.findViewById<RelativeLayout>(R.id.quotedChatMessageView)?.tag as Int? ?: 0
sendMessage( sendMessage(
editable.toString(), editable.toString(),
replyMessageId,
sendWithoutNotification sendWithoutNotification
) )
cancelReply() cancelReply()
cancelCreateThread()
} }
} }
private fun sendMessage(message: String, replyTo: Int?, sendWithoutNotification: Boolean) { private fun sendMessage(message: String, sendWithoutNotification: Boolean) {
chatActivity.messageInputViewModel.sendChatMessage( chatActivity.messageInputViewModel.sendChatMessage(
chatActivity.conversationUser!!.getCredentials(), credentials = chatActivity.conversationUser!!.getCredentials(),
ApiUtils.getUrlForChat( url = ApiUtils.getUrlForChat(
chatActivity.chatApiVersion, chatActivity.chatApiVersion,
chatActivity.conversationUser!!.baseUrl!!, chatActivity.conversationUser!!.baseUrl!!,
chatActivity.roomToken chatActivity.roomToken
), ),
message, message = message,
chatActivity.conversationUser!!.displayName ?: "", displayName = chatActivity.conversationUser!!.displayName ?: "",
replyTo ?: 0, replyTo = chatActivity.getReplyToMessageId(),
sendWithoutNotification sendWithoutNotification = sendWithoutNotification,
threadTitle = chatActivity.chatViewModel.messageDraft.threadTitle
) )
} }
@ -964,6 +997,7 @@ class MessageInputFragment : Fragment() {
binding.fragmentMessageInputView.inputEditText.setSelection(end) binding.fragmentMessageInputView.inputEditText.setSelection(end)
binding.fragmentMessageInputView.messageSendButton.visibility = View.GONE binding.fragmentMessageInputView.messageSendButton.visibility = View.GONE
binding.fragmentMessageInputView.recordAudioButton.visibility = View.GONE binding.fragmentMessageInputView.recordAudioButton.visibility = View.GONE
binding.fragmentMessageInputView.submitThreadButton.visibility = View.GONE
binding.fragmentMessageInputView.editMessageButton.visibility = View.VISIBLE binding.fragmentMessageInputView.editMessageButton.visibility = View.VISIBLE
binding.fragmentEditView.editMessageView.visibility = View.VISIBLE binding.fragmentEditView.editMessageView.visibility = View.VISIBLE
binding.fragmentMessageInputView.attachmentButton.visibility = View.GONE binding.fragmentMessageInputView.attachmentButton.visibility = View.GONE
@ -975,15 +1009,12 @@ class MessageInputFragment : Fragment() {
binding.fragmentEditView.editMessageView.visibility = View.GONE binding.fragmentEditView.editMessageView.visibility = View.GONE
binding.fragmentMessageInputView.attachmentButton.visibility = View.VISIBLE binding.fragmentMessageInputView.attachmentButton.visibility = View.VISIBLE
chatActivity.messageInputViewModel.edit(null) chatActivity.messageInputViewModel.edit(null)
handleButtonsVisibility()
} }
private fun themeMessageInputView() { private fun themeMessageInputView() {
binding.fragmentMessageInputView.button?.let { viewThemeUtils.platform.colorImageView(it, ColorRole.PRIMARY) } binding.fragmentMessageInputView.button?.let { viewThemeUtils.platform.colorImageView(it, ColorRole.PRIMARY) }
binding.fragmentMessageInputView.findViewById<ImageButton>(R.id.cancelReplyButton)?.setOnClickListener {
cancelReply()
}
binding.fragmentMessageInputView.findViewById<ImageButton>(R.id.cancelReplyButton)?.let { binding.fragmentMessageInputView.findViewById<ImageButton>(R.id.cancelReplyButton)?.let {
viewThemeUtils.platform viewThemeUtils.platform
.themeImageButton(it) .themeImageButton(it)
@ -1021,6 +1052,9 @@ class MessageInputFragment : Fragment() {
binding.fragmentEditView.clearEdit.let { binding.fragmentEditView.clearEdit.let {
viewThemeUtils.platform.colorImageView(it, ColorRole.PRIMARY) viewThemeUtils.platform.colorImageView(it, ColorRole.PRIMARY)
} }
binding.fragmentCreateThreadView.abortCreateThread.let {
viewThemeUtils.platform.colorImageView(it, ColorRole.PRIMARY)
}
binding.fragmentCallStarted.callStartedBackground.apply { binding.fragmentCallStarted.callStartedBackground.apply {
viewThemeUtils.talk.themeOutgoingMessageBubble(this, grouped = true, false) viewThemeUtils.talk.themeOutgoingMessageBubble(this, grouped = true, false)
@ -1037,14 +1071,56 @@ class MessageInputFragment : Fragment() {
binding.fragmentCallStarted.callStartedCloseBtn.apply { binding.fragmentCallStarted.callStartedCloseBtn.apply {
viewThemeUtils.platform.colorImageView(this, ColorRole.PRIMARY) viewThemeUtils.platform.colorImageView(this, ColorRole.PRIMARY)
} }
binding.fragmentMessageInputView.submitThreadButton.apply {
viewThemeUtils.platform.colorImageView(this, ColorRole.SECONDARY)
}
binding.fragmentCreateThreadView.createThreadInput.apply {
viewThemeUtils.platform.colorEditText(this)
}
}
private fun cancelCreateThread() {
chatActivity.cancelCreateThread()
chatActivity.messageInputViewModel.stopThreadCreation()
binding.fragmentCreateThreadView.createThreadView.visibility = View.GONE
} }
private fun cancelReply() { private fun cancelReply() {
val quote = binding.fragmentMessageInputView chatActivity.cancelReply()
.findViewById<RelativeLayout>(R.id.quotedChatMessageView) clearReplyUi()
}
private fun clearReplyUi() {
val quote = binding.fragmentMessageInputView.findViewById<RelativeLayout>(R.id.quotedChatMessageView)
quote.visibility = View.GONE quote.visibility = View.GONE
quote.tag = null
binding.fragmentMessageInputView.findViewById<ImageButton>(R.id.attachmentButton)?.visibility = View.VISIBLE binding.fragmentMessageInputView.findViewById<ImageButton>(R.id.attachmentButton)?.visibility = View.VISIBLE
chatActivity.messageInputViewModel.reply(null) }
private fun isInReplyState(): Boolean {
val jsonId = chatActivity.chatViewModel.messageDraft.quotedJsonId
return jsonId != null
}
companion object {
fun newInstance() = MessageInputFragment()
private val TAG: String = MessageInputFragment::class.java.simpleName
private const val TYPING_DURATION_TO_SEND_NEXT_TYPING_MESSAGE = 10000L
private const val TYPING_INTERVAL_TO_SEND_NEXT_TYPING_MESSAGE = 1000L
private const val TYPING_STARTED_SIGNALING_MESSAGE_TYPE = "startedTyping"
private const val TYPING_STOPPED_SIGNALING_MESSAGE_TYPE = "stoppedTyping"
private const val QUOTED_MESSAGE_IMAGE_MAX_HEIGHT = 96f
private const val MENTION_AUTO_COMPLETE_ELEVATION = 6f
private const val MINIMUM_VOICE_RECORD_DURATION: Int = 1000
private const val ANIMATION_DURATION: Long = 750
private const val VOICE_RECORD_CANCEL_SLIDER_X: Int = -150
private const val VOICE_RECORD_LOCK_THRESHOLD: Float = 100f
private const val INCREMENT = 8f
private const val CURSOR_KEY = "_cursor"
private const val CONNECTION_ESTABLISHED_ANIM_DURATION: Long = 3000
private const val FULLY_OPAQUE: Float = 1.0f
private const val FULLY_TRANSPARENT: Float = 0.0f
private const val OPACITY_DISABLED = 0.7f
} }
} }

View file

@ -114,9 +114,9 @@ class MessageInputVoiceRecordingFragment : Fragment() {
binding.sendVoiceRecording.setOnClickListener { binding.sendVoiceRecording.setOnClickListener {
chatActivity.chatViewModel.stopAndSendAudioRecording( chatActivity.chatViewModel.stopAndSendAudioRecording(
chatActivity.roomToken, roomToken = chatActivity.roomToken,
chatActivity.currentConversation!!.displayName, replyToMessageId = chatActivity.getReplyToMessageId(),
MessageInputFragment.VOICE_MESSAGE_META_DATA displayName = chatActivity.currentConversation!!.displayName
) )
clear() clear()
} }

View file

@ -0,0 +1,160 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.chat
import android.view.View
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import com.nextcloud.talk.R
data class MenuItemData(val title: String, val subtitle: String? = null, val icon: Int? = null, val onClick: () -> Unit)
@Composable
fun OverflowMenu(anchor: View?, expanded: Boolean, items: List<MenuItemData>, onDismiss: () -> Unit) {
if (!expanded) return
val rect = anchor?.boundsInWindow()
val xOffset = rect?.left ?: 0
val yOffset = rect?.bottom ?: 0
Popup(
onDismissRequest = onDismiss,
offset = IntOffset(xOffset, yOffset)
) {
Column(
modifier = Modifier
.width(IntrinsicSize.Max)
.background(
color = colorResource(id = R.color.bg_default),
shape = RoundedCornerShape(1.dp)
)
.shadow(
elevation = 1.dp,
shape = RoundedCornerShape(1.dp),
clip = false
)
) {
items.forEach { item ->
DynamicMenuItem(
item.copy(
onClick = {
item.onClick()
onDismiss()
}
)
)
}
}
}
}
@Composable
fun DynamicMenuItem(item: MenuItemData) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clickable(
onClick = item.onClick,
interactionSource = remember { MutableInteractionSource() }
)
.padding(horizontal = 12.dp, vertical = 12.dp)
) {
item.icon?.let { icon ->
Icon(
painter = painterResource(icon),
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface
)
Spacer(Modifier.width(8.dp))
}
Column {
Text(item.title, color = MaterialTheme.colorScheme.onSurface)
item.subtitle?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
private fun View.boundsInWindow(): android.graphics.Rect {
val location = IntArray(2)
getLocationOnScreen(location)
return android.graphics.Rect(
location[0],
location[1],
location[0] + width,
location[1] + height
)
}
@Preview
@Composable
fun OverflowMenuPreview() {
val items = listOf(
MenuItemData(
title = "first item title",
subtitle = "first item subtitle",
icon = R.drawable.baseline_notifications_24,
onClick = {}
),
MenuItemData(
title = "second item title",
subtitle = null,
icon = R.drawable.outline_notifications_active_24,
onClick = {}
),
MenuItemData(
title = "third item title",
subtitle = null,
icon = R.drawable.baseline_notifications_24,
onClick = {}
),
MenuItemData(
title = "fourth item title",
subtitle = null,
icon = R.drawable.baseline_notifications_24,
onClick = {}
)
)
OverflowMenu(
anchor = null,
expanded = true,
items = items,
onDismiss = { }
)
}

View file

@ -1,7 +1,7 @@
/* /*
* Nextcloud Talk - Android Client * Nextcloud Talk - Android Client
* *
* SPDX-FileCopyrightText: 2024 Your Name <your@email.com> * SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later * SPDX-License-Identifier: GPL-3.0-or-later
*/ */
@ -44,7 +44,7 @@ interface ChatMessageRepository : LifecycleAwareManager {
val removeMessageFlow: Flow<ChatMessage> val removeMessageFlow: Flow<ChatMessage>
fun initData(credentials: String, urlForChatting: String, roomToken: String) fun initData(credentials: String, urlForChatting: String, roomToken: String, threadId: Long?)
fun updateConversation(conversationModel: ConversationModel) fun updateConversation(conversationModel: ConversationModel)
@ -76,6 +76,8 @@ interface ChatMessageRepository : LifecycleAwareManager {
*/ */
suspend fun getMessage(messageId: Long, bundle: Bundle): Flow<ChatMessage> suspend fun getMessage(messageId: Long, bundle: Bundle): Flow<ChatMessage>
suspend fun getNumberOfThreadReplies(threadId: Long): Int
@Suppress("LongParameterList") @Suppress("LongParameterList")
suspend fun sendChatMessage( suspend fun sendChatMessage(
credentials: String, credentials: String,
@ -84,7 +86,8 @@ interface ChatMessageRepository : LifecycleAwareManager {
displayName: String, displayName: String,
replyTo: Int, replyTo: Int,
sendWithoutNotification: Boolean, sendWithoutNotification: Boolean,
referenceId: String referenceId: String,
threadTitle: String?
): Flow<Result<ChatMessage?>> ): Flow<Result<ChatMessage?>>
@Suppress("LongParameterList") @Suppress("LongParameterList")

View file

@ -45,6 +45,14 @@ data class ChatMessage(
var token: String? = null, var token: String? = null,
var threadId: Long? = null,
var isThread: Boolean = false,
var threadTitle: String? = null,
var threadReplies: Int? = 0,
// guests or users // guests or users
var actorType: String? = null, var actorType: String? = null,
@ -424,7 +432,8 @@ data class ChatMessage(
AVATAR_REMOVED, AVATAR_REMOVED,
FEDERATED_USER_ADDED, FEDERATED_USER_ADDED,
FEDERATED_USER_REMOVED, FEDERATED_USER_REMOVED,
PHONE_ADDED PHONE_ADDED,
THREAD_CREATED
} }
companion object { companion object {

View file

@ -59,7 +59,8 @@ interface ChatNetworkDataSource {
displayName: String, displayName: String,
replyTo: Int, replyTo: Int,
sendWithoutNotification: Boolean, sendWithoutNotification: Boolean,
referenceId: String referenceId: String,
threadTitle: String?
): ChatOverallSingleMessage ): ChatOverallSingleMessage
fun pullChatMessages(credentials: String, url: String, fieldMap: HashMap<String, Int>): Observable<Response<*>> fun pullChatMessages(credentials: String, url: String, fieldMap: HashMap<String, Int>): Observable<Response<*>>
@ -73,7 +74,8 @@ interface ChatNetworkDataSource {
baseUrl: String, baseUrl: String,
token: String, token: String,
messageId: String, messageId: String,
limit: Int limit: Int,
threadId: Int?
): List<ChatMessageJson> ): List<ChatMessageJson>
suspend fun getOpenGraph(credentials: String, baseUrl: String, extractedLinkToPreview: String): Reference? suspend fun getOpenGraph(credentials: String, baseUrl: String, extractedLinkToPreview: String): Reference?
suspend fun unbindRoom(credentials: String, baseUrl: String, roomToken: String): GenericOverall suspend fun unbindRoom(credentials: String, baseUrl: String, roomToken: String): GenericOverall

View file

@ -119,11 +119,13 @@ class OfflineFirstChatRepository @Inject constructor(
private lateinit var conversationModel: ConversationModel private lateinit var conversationModel: ConversationModel
private lateinit var credentials: String private lateinit var credentials: String
private lateinit var urlForChatting: String private lateinit var urlForChatting: String
private var threadId: Long? = null
override fun initData(credentials: String, urlForChatting: String, roomToken: String) { override fun initData(credentials: String, urlForChatting: String, roomToken: String, threadId: Long?) {
internalConversationId = currentUser.id.toString() + "@" + roomToken internalConversationId = currentUser.id.toString() + "@" + roomToken
this.credentials = credentials this.credentials = credentials
this.urlForChatting = urlForChatting this.urlForChatting = urlForChatting
this.threadId = threadId
} }
override fun updateConversation(conversationModel: ConversationModel) { override fun updateConversation(conversationModel: ConversationModel) {
@ -143,7 +145,7 @@ class OfflineFirstChatRepository @Inject constructor(
Log.d(TAG, "conversationModel.internalId: " + conversationModel.internalId) Log.d(TAG, "conversationModel.internalId: " + conversationModel.internalId)
Log.d(TAG, "conversationModel.lastReadMessage:" + conversationModel.lastReadMessage) Log.d(TAG, "conversationModel.lastReadMessage:" + conversationModel.lastReadMessage)
var newestMessageIdFromDb = chatDao.getNewestMessageId(internalConversationId) var newestMessageIdFromDb = chatBlocksDao.getNewestMessageIdFromChatBlocks(internalConversationId, threadId)
Log.d(TAG, "newestMessageIdFromDb: $newestMessageIdFromDb") Log.d(TAG, "newestMessageIdFromDb: $newestMessageIdFromDb")
val weAlreadyHaveSomeOfflineMessages = newestMessageIdFromDb > 0 val weAlreadyHaveSomeOfflineMessages = newestMessageIdFromDb > 0
@ -189,7 +191,7 @@ class OfflineFirstChatRepository @Inject constructor(
Log.e(TAG, "initial loading of messages failed") Log.e(TAG, "initial loading of messages failed")
} }
newestMessageIdFromDb = chatDao.getNewestMessageId(internalConversationId) newestMessageIdFromDb = chatBlocksDao.getNewestMessageIdFromChatBlocks(internalConversationId, threadId)
Log.d(TAG, "newestMessageIdFromDb after sync: $newestMessageIdFromDb") Log.d(TAG, "newestMessageIdFromDb after sync: $newestMessageIdFromDb")
} }
@ -203,9 +205,9 @@ class OfflineFirstChatRepository @Inject constructor(
val limit = getCappedMessagesAmountOfChatBlock(newestMessageIdFromDb) val limit = getCappedMessagesAmountOfChatBlock(newestMessageIdFromDb)
val list = getMessagesBeforeAndEqual( val list = getMessagesBeforeAndEqual(
newestMessageIdFromDb, messageId = newestMessageIdFromDb,
internalConversationId, internalConversationId = internalConversationId,
limit messageLimit = limit
) )
if (list.isNotEmpty()) { if (list.isNotEmpty()) {
handleNewAndTempMessages( handleNewAndTempMessages(
@ -234,7 +236,8 @@ class OfflineFirstChatRepository @Inject constructor(
val amountBetween = chatDao.getCountBetweenMessageIds( val amountBetween = chatDao.getCountBetweenMessageIds(
internalConversationId, internalConversationId,
messageId, messageId,
chatBlock.oldestMessageId chatBlock.oldestMessageId,
threadId
) )
Log.d(TAG, "amount of messages between newestMessageId and oldest message of same ChatBlock:$amountBetween") Log.d(TAG, "amount of messages between newestMessageId and oldest message of same ChatBlock:$amountBetween")
@ -284,7 +287,7 @@ class OfflineFirstChatRepository @Inject constructor(
) )
withNetworkParams.putSerializable(BundleKeys.KEY_FIELD_MAP, fieldMap) withNetworkParams.putSerializable(BundleKeys.KEY_FIELD_MAP, fieldMap)
val loadFromServer = hasToLoadPreviousMessagesFromServer(beforeMessageId) val loadFromServer = hasToLoadPreviousMessagesFromServer(beforeMessageId, DEFAULT_MESSAGES_LIMIT)
if (loadFromServer) { if (loadFromServer) {
Log.d(TAG, "Starting online request for loadMoreMessages") Log.d(TAG, "Starting online request for loadMoreMessages")
@ -346,7 +349,10 @@ class OfflineFirstChatRepository @Inject constructor(
updateUiForLastCommonRead() updateUiForLastCommonRead()
val newestMessage = chatDao.getNewestMessageId(internalConversationId).toInt() val newestMessage = chatBlocksDao.getNewestMessageIdFromChatBlocks(
internalConversationId,
threadId
).toInt()
// update field map vars for next cycle // update field map vars for next cycle
fieldMap = getFieldMap( fieldMap = getFieldMap(
@ -409,7 +415,7 @@ class OfflineFirstChatRepository @Inject constructor(
_messageFlow.emit(triple) _messageFlow.emit(triple)
} }
private suspend fun hasToLoadPreviousMessagesFromServer(beforeMessageId: Long): Boolean { private suspend fun hasToLoadPreviousMessagesFromServer(beforeMessageId: Long, amountToCheck: Int): Boolean {
val loadFromServer: Boolean val loadFromServer: Boolean
val blockForMessage = getBlockOfMessage(beforeMessageId.toInt()) val blockForMessage = getBlockOfMessage(beforeMessageId.toInt())
@ -421,26 +427,25 @@ class OfflineFirstChatRepository @Inject constructor(
Log.d(TAG, "The last chatBlock is reached so we won't request server for older messages") Log.d(TAG, "The last chatBlock is reached so we won't request server for older messages")
loadFromServer = false loadFromServer = false
} else { } else {
// we know that beforeMessageId and blockForMessage.oldestMessageId are in the same block.
// As we want the last DEFAULT_MESSAGES_LIMIT entries before beforeMessageId, we calculate if these
// messages are DEFAULT_MESSAGES_LIMIT entries apart from each other
val amountBetween = chatDao.getCountBetweenMessageIds( val amountBetween = chatDao.getCountBetweenMessageIds(
internalConversationId, internalConversationId,
beforeMessageId, beforeMessageId,
blockForMessage.oldestMessageId blockForMessage.oldestMessageId,
threadId
) )
loadFromServer = amountBetween < DEFAULT_MESSAGES_LIMIT loadFromServer = amountBetween < amountToCheck
Log.d( Log.d(
TAG, TAG,
"Amount between messageId " + beforeMessageId + " and " + blockForMessage.oldestMessageId + "Amount between messageId " + beforeMessageId + " and " + blockForMessage.oldestMessageId +
" is: " + amountBetween + " so 'loadFromServer' is " + loadFromServer " is: " + amountBetween + " and $amountToCheck were needed, so 'loadFromServer' is " +
loadFromServer
) )
} }
return loadFromServer return loadFromServer
} }
@Suppress("LongParameterList")
private fun getFieldMap( private fun getFieldMap(
lookIntoFuture: Boolean, lookIntoFuture: Boolean,
timeout: Int, timeout: Int,
@ -461,17 +466,23 @@ class OfflineFirstChatRepository @Inject constructor(
fieldMap["lastCommonReadId"] = it fieldMap["lastCommonReadId"] = it
} }
threadId?.let { fieldMap["threadId"] = it.toInt() }
fieldMap["timeout"] = timeout fieldMap["timeout"] = timeout
fieldMap["limit"] = limit fieldMap["limit"] = limit
fieldMap["lookIntoFuture"] = if (lookIntoFuture) 1 else 0 fieldMap["lookIntoFuture"] = if (lookIntoFuture) 1 else 0
fieldMap["setReadMarker"] = if (setReadMarker) 1 else 0 fieldMap["setReadMarker"] = if (setReadMarker) 1 else 0
return fieldMap return fieldMap
} }
override suspend fun getNumberOfThreadReplies(threadId: Long): Int =
chatDao.getNumberOfThreadReplies(internalConversationId, threadId)
override suspend fun getMessage(messageId: Long, bundle: Bundle): Flow<ChatMessage> { override suspend fun getMessage(messageId: Long, bundle: Bundle): Flow<ChatMessage> {
Log.d(TAG, "Get message with id $messageId") Log.d(TAG, "Get message with id $messageId")
val loadFromServer = hasToLoadPreviousMessagesFromServer(messageId) val loadFromServer = hasToLoadPreviousMessagesFromServer(messageId, 1)
if (loadFromServer) { if (loadFromServer) {
val fieldMap = getFieldMap( val fieldMap = getFieldMap(
@ -487,8 +498,10 @@ class OfflineFirstChatRepository @Inject constructor(
Log.d(TAG, "Starting online request for single message (e.g. a reply)") Log.d(TAG, "Starting online request for single message (e.g. a reply)")
sync(bundle) sync(bundle)
} }
return chatDao.getChatMessageForConversation(internalConversationId, messageId) return chatDao.getChatMessageForConversation(
.map(ChatMessageEntity::asModel) internalConversationId,
messageId
).map(ChatMessageEntity::asModel)
} }
@Suppress("UNCHECKED_CAST", "MagicNumber", "Detekt.TooGenericExceptionCaught") @Suppress("UNCHECKED_CAST", "MagicNumber", "Detekt.TooGenericExceptionCaught")
@ -652,11 +665,12 @@ class OfflineFirstChatRepository @Inject constructor(
internalConversationId = internalConversationId, internalConversationId = internalConversationId,
accountId = conversationModel.accountId, accountId = conversationModel.accountId,
token = conversationModel.token, token = conversationModel.token,
threadId = threadId,
oldestMessageId = oldestMessageIdForNewChatBlock, oldestMessageId = oldestMessageIdForNewChatBlock,
newestMessageId = newestMessageIdForNewChatBlock, newestMessageId = newestMessageIdForNewChatBlock,
hasHistory = hasHistory hasHistory = hasHistory
) )
chatBlocksDao.upsertChatBlock(newChatBlock) chatBlocksDao.upsertChatBlock(newChatBlock) // crash when no conversation thread exists!
updateBlocks(newChatBlock) updateBlocks(newChatBlock)
return chatMessagesFromSyncToProcess return chatMessagesFromSyncToProcess
@ -713,7 +727,11 @@ class OfflineFirstChatRepository @Inject constructor(
var blockContainingQueriedMessage: ChatBlockEntity? = null var blockContainingQueriedMessage: ChatBlockEntity? = null
if (queriedMessageId != null) { if (queriedMessageId != null) {
val blocksContainingQueriedMessage = val blocksContainingQueriedMessage =
chatBlocksDao.getChatBlocksContainingMessageId(internalConversationId, queriedMessageId.toLong()) chatBlocksDao.getChatBlocksContainingMessageId(
internalConversationId = internalConversationId,
threadId = threadId,
messageId = queriedMessageId.toLong()
)
val chatBlocks = blocksContainingQueriedMessage.first() val chatBlocks = blocksContainingQueriedMessage.first()
if (chatBlocks.size > 1) { if (chatBlocks.size > 1) {
@ -732,9 +750,10 @@ class OfflineFirstChatRepository @Inject constructor(
private suspend fun updateBlocks(chatBlock: ChatBlockEntity): ChatBlockEntity? { private suspend fun updateBlocks(chatBlock: ChatBlockEntity): ChatBlockEntity? {
val connectedChatBlocks = val connectedChatBlocks =
chatBlocksDao.getConnectedChatBlocks( chatBlocksDao.getConnectedChatBlocks(
internalConversationId, internalConversationId = internalConversationId,
chatBlock.oldestMessageId, threadId = threadId,
chatBlock.newestMessageId oldestMessageId = chatBlock.oldestMessageId,
newestMessageId = chatBlock.newestMessageId
).first() ).first()
return if (connectedChatBlocks.size == 1) { return if (connectedChatBlocks.size == 1) {
@ -761,6 +780,7 @@ class OfflineFirstChatRepository @Inject constructor(
internalConversationId = internalConversationId, internalConversationId = internalConversationId,
accountId = conversationModel.accountId, accountId = conversationModel.accountId,
token = conversationModel.token, token = conversationModel.token,
threadId = threadId,
oldestMessageId = oldestIdFromDbChatBlocks, oldestMessageId = oldestIdFromDbChatBlocks,
newestMessageId = newestIdFromDbChatBlocks, newestMessageId = newestIdFromDbChatBlocks,
hasHistory = hasHistory hasHistory = hasHistory
@ -784,7 +804,8 @@ class OfflineFirstChatRepository @Inject constructor(
chatDao.getMessagesForConversationBeforeAndEqual( chatDao.getMessagesForConversationBeforeAndEqual(
internalConversationId, internalConversationId,
messageId, messageId,
messageLimit messageLimit,
threadId
).map { ).map {
it.map(ChatMessageEntity::asModel) it.map(ChatMessageEntity::asModel)
}.first() }.first()
@ -798,7 +819,8 @@ class OfflineFirstChatRepository @Inject constructor(
chatDao.getMessagesForConversationBefore( chatDao.getMessagesForConversationBefore(
internalConversationId, internalConversationId,
messageId, messageId,
messageLimit messageLimit,
threadId
).map { ).map {
it.map(ChatMessageEntity::asModel) it.map(ChatMessageEntity::asModel)
}.first() }.first()
@ -838,7 +860,8 @@ class OfflineFirstChatRepository @Inject constructor(
displayName: String, displayName: String,
replyTo: Int, replyTo: Int,
sendWithoutNotification: Boolean, sendWithoutNotification: Boolean,
referenceId: String referenceId: String,
threadTitle: String?
): Flow<Result<ChatMessage?>> { ): Flow<Result<ChatMessage?>> {
if (!networkMonitor.isOnline.value) { if (!networkMonitor.isOnline.value) {
return flow { return flow {
@ -854,14 +877,16 @@ class OfflineFirstChatRepository @Inject constructor(
displayName, displayName,
replyTo, replyTo,
sendWithoutNotification, sendWithoutNotification,
referenceId referenceId,
threadTitle
) )
val chatMessageModel = response.ocs?.data?.asModel() val chatMessageModel = response.ocs?.data?.asModel()
val sentMessage = chatDao.getTempMessageForConversation( val sentMessage = chatDao.getTempMessageForConversation(
internalConversationId, internalConversationId,
referenceId referenceId,
threadId
).firstOrNull() ).firstOrNull()
sentMessage?.let { sentMessage?.let {
@ -877,7 +902,8 @@ class OfflineFirstChatRepository @Inject constructor(
val failedMessage = chatDao.getTempMessageForConversation( val failedMessage = chatDao.getTempMessageForConversation(
internalConversationId, internalConversationId,
referenceId referenceId,
threadId
).firstOrNull() ).firstOrNull()
failedMessage?.let { failedMessage?.let {
it.sendStatus = SendStatus.FAILED it.sendStatus = SendStatus.FAILED
@ -900,7 +926,11 @@ class OfflineFirstChatRepository @Inject constructor(
sendWithoutNotification: Boolean, sendWithoutNotification: Boolean,
referenceId: String referenceId: String
): Flow<Result<ChatMessage?>> { ): Flow<Result<ChatMessage?>> {
val messageToResend = chatDao.getTempMessageForConversation(internalConversationId, referenceId).firstOrNull() val messageToResend = chatDao.getTempMessageForConversation(
internalConversationId,
referenceId,
threadId
).firstOrNull()
return if (messageToResend != null) { return if (messageToResend != null) {
messageToResend.sendStatus = SendStatus.PENDING messageToResend.sendStatus = SendStatus.PENDING
chatDao.updateChatMessage(messageToResend) chatDao.updateChatMessage(messageToResend)
@ -909,13 +939,14 @@ class OfflineFirstChatRepository @Inject constructor(
_updateMessageFlow.emit(messageToResendModel) _updateMessageFlow.emit(messageToResendModel)
sendChatMessage( sendChatMessage(
credentials, credentials = credentials,
url, url = url,
message, message = message,
displayName, displayName = displayName,
replyTo, replyTo = replyTo,
sendWithoutNotification, sendWithoutNotification = sendWithoutNotification,
referenceId referenceId = referenceId,
threadTitle = null
) )
} else { } else {
flow { flow {
@ -949,8 +980,7 @@ class OfflineFirstChatRepository @Inject constructor(
try { try {
val messageToEdit = chatDao.getChatMessageForConversation( val messageToEdit = chatDao.getChatMessageForConversation(
internalConversationId, internalConversationId,
message.jsonMessageId message.jsonMessageId.toLong()
.toLong()
).first() ).first()
messageToEdit.message = editedMessageText messageToEdit.message = editedMessageText
chatDao.upsertChatMessage(messageToEdit) chatDao.upsertChatMessage(messageToEdit)
@ -964,7 +994,7 @@ class OfflineFirstChatRepository @Inject constructor(
} }
override suspend fun sendUnsentChatMessages(credentials: String, url: String) { override suspend fun sendUnsentChatMessages(credentials: String, url: String) {
val tempMessages = chatDao.getTempUnsentMessagesForConversation(internalConversationId).first() val tempMessages = chatDao.getTempUnsentMessagesForConversation(internalConversationId, threadId).first()
tempMessages.sortedBy { it.internalId }.onEach { tempMessages.sortedBy { it.internalId }.onEach {
sendChatMessage( sendChatMessage(
credentials, credentials,
@ -973,7 +1003,8 @@ class OfflineFirstChatRepository @Inject constructor(
it.actorDisplayName, it.actorDisplayName,
it.parentMessageId?.toIntOrZero() ?: 0, it.parentMessageId?.toIntOrZero() ?: 0,
it.silent, it.silent,
it.referenceId.orEmpty() it.referenceId.orEmpty(),
null
).collect { result -> ).collect { result ->
if (result.isSuccess) { if (result.isSuccess) {
Log.d(TAG, "Sent temp message") Log.d(TAG, "Sent temp message")
@ -1042,6 +1073,7 @@ class OfflineFirstChatRepository @Inject constructor(
internalId = "$internalConversationId@_temp_$currentTimeMillies", internalId = "$internalConversationId@_temp_$currentTimeMillies",
internalConversationId = internalConversationId, internalConversationId = internalConversationId,
id = currentTimeWithoutYear.toLong(), id = currentTimeWithoutYear.toLong(),
threadId = threadId,
message = message, message = message,
deleted = false, deleted = false,
token = conversationModel.token, token = conversationModel.token,

View file

@ -144,7 +144,8 @@ class RetrofitChatNetwork(private val ncApi: NcApi, private val ncApiCoroutines:
displayName: String, displayName: String,
replyTo: Int, replyTo: Int,
sendWithoutNotification: Boolean, sendWithoutNotification: Boolean,
referenceId: String referenceId: String,
threadTitle: String?
): ChatOverallSingleMessage = ): ChatOverallSingleMessage =
ncApiCoroutines.sendChatMessage( ncApiCoroutines.sendChatMessage(
credentials, credentials,
@ -153,7 +154,8 @@ class RetrofitChatNetwork(private val ncApi: NcApi, private val ncApiCoroutines:
displayName, displayName,
replyTo, replyTo,
sendWithoutNotification, sendWithoutNotification,
referenceId referenceId,
threadTitle
) )
override fun pullChatMessages( override fun pullChatMessages(
@ -196,10 +198,11 @@ class RetrofitChatNetwork(private val ncApi: NcApi, private val ncApiCoroutines:
baseUrl: String, baseUrl: String,
token: String, token: String,
messageId: String, messageId: String,
limit: Int limit: Int,
threadId: Int?
): List<ChatMessageJson> { ): List<ChatMessageJson> {
val url = ApiUtils.getUrlForChatMessageContext(baseUrl, token, messageId) val url = ApiUtils.getUrlForChatMessageContext(baseUrl, token, messageId)
return ncApiCoroutines.getContextOfChatMessage(credentials, url, limit).ocs?.data ?: listOf() return ncApiCoroutines.getContextOfChatMessage(credentials, url, limit, threadId).ocs?.data ?: listOf()
} }
override suspend fun getOpenGraph( override suspend fun getOpenGraph(

View file

@ -17,6 +17,8 @@ import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.nextcloud.talk.arbitrarystorage.ArbitraryStorageManager
import com.nextcloud.talk.chat.data.ChatMessageRepository import com.nextcloud.talk.chat.data.ChatMessageRepository
import com.nextcloud.talk.chat.data.io.AudioFocusRequestManager import com.nextcloud.talk.chat.data.io.AudioFocusRequestManager
import com.nextcloud.talk.chat.data.io.MediaPlayerManager import com.nextcloud.talk.chat.data.io.MediaPlayerManager
@ -24,22 +26,27 @@ import com.nextcloud.talk.chat.data.io.MediaRecorderManager
import com.nextcloud.talk.chat.data.model.ChatMessage import com.nextcloud.talk.chat.data.model.ChatMessage
import com.nextcloud.talk.chat.data.network.ChatNetworkDataSource import com.nextcloud.talk.chat.data.network.ChatNetworkDataSource
import com.nextcloud.talk.conversationlist.data.OfflineConversationsRepository import com.nextcloud.talk.conversationlist.data.OfflineConversationsRepository
import com.nextcloud.talk.conversationlist.viewmodels.ConversationsListViewModel.Companion.FOLLOWED_THREADS_EXIST
import com.nextcloud.talk.data.user.model.User import com.nextcloud.talk.data.user.model.User
import com.nextcloud.talk.extensions.toIntOrZero import com.nextcloud.talk.extensions.toIntOrZero
import com.nextcloud.talk.jobs.UploadAndShareFilesWorker import com.nextcloud.talk.jobs.UploadAndShareFilesWorker
import com.nextcloud.talk.models.MessageDraft
import com.nextcloud.talk.models.domain.ConversationModel import com.nextcloud.talk.models.domain.ConversationModel
import com.nextcloud.talk.models.domain.ReactionAddedModel import com.nextcloud.talk.models.domain.ReactionAddedModel
import com.nextcloud.talk.models.domain.ReactionDeletedModel import com.nextcloud.talk.models.domain.ReactionDeletedModel
import com.nextcloud.talk.models.json.capabilities.SpreedCapability import com.nextcloud.talk.models.json.capabilities.SpreedCapability
import com.nextcloud.talk.models.json.chat.ChatMessageJson
import com.nextcloud.talk.models.json.chat.ChatOverallSingleMessage import com.nextcloud.talk.models.json.chat.ChatOverallSingleMessage
import com.nextcloud.talk.models.json.conversations.RoomOverall import com.nextcloud.talk.models.json.conversations.RoomOverall
import com.nextcloud.talk.models.json.generic.GenericOverall import com.nextcloud.talk.models.json.generic.GenericOverall
import com.nextcloud.talk.models.json.opengraph.Reference import com.nextcloud.talk.models.json.opengraph.Reference
import com.nextcloud.talk.models.json.reminder.Reminder import com.nextcloud.talk.models.json.reminder.Reminder
import com.nextcloud.talk.models.json.threads.ThreadInfo
import com.nextcloud.talk.models.json.userAbsence.UserAbsenceData import com.nextcloud.talk.models.json.userAbsence.UserAbsenceData
import com.nextcloud.talk.repositories.reactions.ReactionsRepository import com.nextcloud.talk.repositories.reactions.ReactionsRepository
import com.nextcloud.talk.threadsoverview.data.ThreadsRepository
import com.nextcloud.talk.ui.PlaybackSpeed import com.nextcloud.talk.ui.PlaybackSpeed
import com.nextcloud.talk.utils.ParticipantPermissions
import com.nextcloud.talk.utils.UserIdUtils
import com.nextcloud.talk.utils.bundle.BundleKeys import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew
import com.nextcloud.talk.utils.preferences.AppPreferences import com.nextcloud.talk.utils.preferences.AppPreferences
@ -51,6 +58,8 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
@ -65,6 +74,7 @@ class ChatViewModel @Inject constructor(
private val appPreferences: AppPreferences, private val appPreferences: AppPreferences,
private val chatNetworkDataSource: ChatNetworkDataSource, private val chatNetworkDataSource: ChatNetworkDataSource,
private val chatRepository: ChatMessageRepository, private val chatRepository: ChatMessageRepository,
private val threadsRepository: ThreadsRepository,
private val conversationRepository: OfflineConversationsRepository, private val conversationRepository: OfflineConversationsRepository,
private val reactionsRepository: ReactionsRepository, private val reactionsRepository: ReactionsRepository,
private val mediaRecorderManager: MediaRecorderManager, private val mediaRecorderManager: MediaRecorderManager,
@ -73,6 +83,9 @@ class ChatViewModel @Inject constructor(
) : ViewModel(), ) : ViewModel(),
DefaultLifecycleObserver { DefaultLifecycleObserver {
@Inject
lateinit var arbitraryStorageManager: ArbitraryStorageManager
enum class LifeCycleFlag { enum class LifeCycleFlag {
PAUSED, PAUSED,
RESUMED, RESUMED,
@ -84,6 +97,9 @@ class ChatViewModel @Inject constructor(
val disposableSet = mutableSetOf<Disposable>() val disposableSet = mutableSetOf<Disposable>()
var mediaPlayerDuration = mediaPlayerManager.mediaPlayerDuration var mediaPlayerDuration = mediaPlayerManager.mediaPlayerDuration
val mediaPlayerPosition = mediaPlayerManager.mediaPlayerPosition val mediaPlayerPosition = mediaPlayerManager.mediaPlayerPosition
var chatRoomToken: String = ""
var messageDraft: MessageDraft = MessageDraft()
lateinit var participantPermissions: ParticipantPermissions
fun getChatRepository(): ChatMessageRepository = chatRepository fun getChatRepository(): ChatMessageRepository = chatRepository
@ -103,6 +119,8 @@ class ChatViewModel @Inject constructor(
mediaRecorderManager.handleOnPause() mediaRecorderManager.handleOnPause()
chatRepository.handleOnPause() chatRepository.handleOnPause()
mediaPlayerManager.handleOnPause() mediaPlayerManager.handleOnPause()
saveMessageDraft()
} }
override fun onStop(owner: LifecycleOwner) { override fun onStop(owner: LifecycleOwner) {
@ -152,9 +170,8 @@ class ChatViewModel @Inject constructor(
val voiceMessagePlaybackSpeedPreferences: LiveData<Map<String, PlaybackSpeed>> val voiceMessagePlaybackSpeedPreferences: LiveData<Map<String, PlaybackSpeed>>
get() = _voiceMessagePlaybackSpeedPreferences get() = _voiceMessagePlaybackSpeedPreferences
private val _getContextChatMessages: MutableLiveData<List<ChatMessageJson>> = MutableLiveData() private val _threadRetrieveState = MutableStateFlow<ThreadRetrieveUiState>(ThreadRetrieveUiState.None)
val getContextChatMessages: LiveData<List<ChatMessageJson>> val threadRetrieveState: StateFlow<ThreadRetrieveUiState> = _threadRetrieveState
get() = _getContextChatMessages
val getOpenGraph: LiveData<Reference> val getOpenGraph: LiveData<Reference>
get() = _getOpenGraph get() = _getOpenGraph
@ -270,8 +287,9 @@ class ChatViewModel @Inject constructor(
val reactionDeletedViewState: LiveData<ViewState> val reactionDeletedViewState: LiveData<ViewState>
get() = _reactionDeletedViewState get() = _reactionDeletedViewState
fun initData(credentials: String, urlForChatting: String, roomToken: String) { fun initData(credentials: String, urlForChatting: String, roomToken: String, threadId: Long?) {
chatRepository.initData(credentials, urlForChatting, roomToken) chatRepository.initData(credentials, urlForChatting, roomToken, threadId)
chatRoomToken = roomToken
} }
fun updateConversation(currentConversation: ConversationModel) { fun updateConversation(currentConversation: ConversationModel) {
@ -293,6 +311,10 @@ class ChatViewModel @Inject constructor(
} else { } else {
_getCapabilitiesViewState.value = GetCapabilitiesUpdateState(user.capabilities!!.spreedCapability!!) _getCapabilitiesViewState.value = GetCapabilitiesUpdateState(user.capabilities!!.spreedCapability!!)
} }
participantPermissions = ParticipantPermissions(
user.capabilities!!.spreedCapability!!,
conversationModel
)
} else { } else {
chatNetworkDataSource.getCapabilities(user, token) chatNetworkDataSource.getCapabilities(user, token)
.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.io())
@ -308,6 +330,10 @@ class ChatViewModel @Inject constructor(
} else { } else {
_getCapabilitiesViewState.value = GetCapabilitiesUpdateState(spreedCapabilities) _getCapabilitiesViewState.value = GetCapabilitiesUpdateState(spreedCapabilities)
} }
participantPermissions = ParticipantPermissions(
spreedCapabilities,
conversationModel
)
} }
override fun onError(e: Throwable) { override fun onError(e: Throwable) {
@ -422,6 +448,45 @@ class ChatViewModel @Inject constructor(
}) })
} }
@Suppress("Detekt.TooGenericExceptionCaught")
fun getThread(credentials: String, url: String) {
viewModelScope.launch {
try {
val thread = threadsRepository.getThread(credentials, url)
_threadRetrieveState.value = ThreadRetrieveUiState.Success(thread.ocs?.data)
} catch (exception: Exception) {
_threadRetrieveState.value = ThreadRetrieveUiState.Error(exception)
}
}
}
@Suppress("Detekt.TooGenericExceptionCaught", "MagicNumber")
fun setThreadNotificationLevel(credentials: String, url: String, level: Int) {
fun updateFollowedThreadsIndicator(notificationLevel: Int?) {
when (notificationLevel) {
1, 2 -> {
val accountId = UserIdUtils.getIdForUser(userProvider.currentUser.blockingGet())
arbitraryStorageManager.storeStorageSetting(
accountId,
FOLLOWED_THREADS_EXIST,
true.toString(),
""
)
}
}
}
viewModelScope.launch {
try {
val thread = threadsRepository.setThreadNotificationLevel(credentials, url, level)
updateFollowedThreadsIndicator(thread.ocs?.data?.attendee?.notificationLevel)
_threadRetrieveState.value = ThreadRetrieveUiState.Success(thread.ocs?.data)
} catch (exception: Exception) {
_threadRetrieveState.value = ThreadRetrieveUiState.Error(exception)
}
}
}
fun loadMessages(withCredentials: String, withUrl: String) { fun loadMessages(withCredentials: String, withUrl: String) {
val bundle = Bundle() val bundle = Bundle()
bundle.putString(BundleKeys.KEY_CHAT_URL, withUrl) bundle.putString(BundleKeys.KEY_CHAT_URL, withUrl)
@ -633,13 +698,20 @@ class ChatViewModel @Inject constructor(
} }
} }
fun stopAndSendAudioRecording(room: String, displayName: String, metaData: String) { fun stopAndSendAudioRecording(roomToken: String = "", replyToMessageId: Int? = null, displayName: String) {
stopAudioRecording() stopAudioRecording()
if (mediaRecorderManager.mediaRecorderState != MediaRecorderManager.MediaRecorderState.ERROR) { if (mediaRecorderManager.mediaRecorderState != MediaRecorderManager.MediaRecorderState.ERROR) {
val uri = Uri.fromFile(File(mediaRecorderManager.currentVoiceRecordFile)) val uri = Uri.fromFile(File(mediaRecorderManager.currentVoiceRecordFile))
Log.d(TAG, "File uploaded") Log.d(TAG, "File uploaded")
uploadFile(uri.toString(), room, displayName, metaData) uploadFile(
fileUri = uri.toString(),
isVoiceMessage = true,
caption = "",
roomToken = roomToken,
replyToMessageId = replyToMessageId,
displayName = displayName
)
} }
} }
@ -652,7 +724,38 @@ class ChatViewModel @Inject constructor(
fun getCurrentVoiceRecordFile(): String = mediaRecorderManager.currentVoiceRecordFile fun getCurrentVoiceRecordFile(): String = mediaRecorderManager.currentVoiceRecordFile
fun uploadFile(fileUri: String, room: String, displayName: String, metaData: String) { fun uploadFile(
fileUri: String,
isVoiceMessage: Boolean,
caption: String = "",
roomToken: String = "",
replyToMessageId: Int? = null,
displayName: String
) {
val metaDataMap = mutableMapOf<String, Any>()
var room = ""
if (!participantPermissions.hasChatPermission()) {
Log.w(TAG, "uploading file(s) is forbidden because of missing attendee permissions")
return
}
if (replyToMessageId != 0) {
metaDataMap["replyTo"] = replyToMessageId.toString()
}
if (isVoiceMessage) {
metaDataMap["messageType"] = "voice-message"
}
if (caption != "") {
metaDataMap["caption"] = caption
}
val metaData = Gson().toJson(metaDataMap)
room = if (roomToken == "") chatRoomToken else roomToken
try { try {
require(fileUri.isNotEmpty()) require(fileUri.isNotEmpty())
UploadAndShareFilesWorker.upload( UploadAndShareFilesWorker.upload(
@ -699,6 +802,8 @@ class ChatViewModel @Inject constructor(
emit(message.first()) emit(message.first())
} }
suspend fun getNumberOfThreadReplies(threadId: Long): Int = chatRepository.getNumberOfThreadReplies(threadId)
fun setPlayBack(speed: PlaybackSpeed) { fun setPlayBack(speed: PlaybackSpeed) {
mediaPlayerManager.setPlayBackSpeed(speed) mediaPlayerManager.setPlayBackSpeed(speed)
CoroutineScope(Dispatchers.Default).launch { CoroutineScope(Dispatchers.Default).launch {
@ -834,26 +939,34 @@ class ChatViewModel @Inject constructor(
} }
} }
fun getContextForChatMessages(credentials: String, baseUrl: String, token: String, messageId: String, limit: Int) {
viewModelScope.launch {
val messages = chatNetworkDataSource.getContextForChatMessage(
credentials,
baseUrl,
token,
messageId,
limit
)
_getContextChatMessages.value = messages
}
}
fun getOpenGraph(credentials: String, baseUrl: String, urlToPreview: String) { fun getOpenGraph(credentials: String, baseUrl: String, urlToPreview: String) {
viewModelScope.launch { viewModelScope.launch {
_getOpenGraph.value = chatNetworkDataSource.getOpenGraph(credentials, baseUrl, urlToPreview) _getOpenGraph.value = chatNetworkDataSource.getOpenGraph(credentials, baseUrl, urlToPreview)
} }
} }
suspend fun updateMessageDraft() {
val model = conversationRepository.getLocallyStoredConversation(chatRoomToken)
model?.messageDraft?.let {
messageDraft = it
}
}
fun saveMessageDraft() {
CoroutineScope(Dispatchers.IO).launch {
val model = conversationRepository.getLocallyStoredConversation(chatRoomToken)
model?.let {
it.messageDraft = messageDraft
conversationRepository.updateConversation(it)
}
}
}
fun clearThreadTitle() {
messageDraft.threadTitle = ""
saveMessageDraft()
}
companion object { companion object {
private val TAG = ChatViewModel::class.simpleName private val TAG = ChatViewModel::class.simpleName
const val JOIN_ROOM_RETRY_COUNT: Long = 3 const val JOIN_ROOM_RETRY_COUNT: Long = 3
@ -871,4 +984,10 @@ class ChatViewModel @Inject constructor(
data class Success(val statusCode: Int) : UnbindRoomUiState() data class Success(val statusCode: Int) : UnbindRoomUiState()
data class Error(val message: String) : UnbindRoomUiState() data class Error(val message: String) : UnbindRoomUiState()
} }
sealed class ThreadRetrieveUiState {
data object None : ThreadRetrieveUiState()
data class Success(val thread: ThreadInfo?) : ThreadRetrieveUiState()
data class Error(val exception: Exception) : ThreadRetrieveUiState()
}
} }

View file

@ -90,11 +90,19 @@ class MessageInputViewModel @Inject constructor(
val getEditChatMessage: LiveData<IMessage?> val getEditChatMessage: LiveData<IMessage?>
get() = _getEditChatMessage get() = _getEditChatMessage
private val _getReplyChatMessage: MutableLiveData<IMessage?> = MutableLiveData() private val _getReplyChatMessage: MutableLiveData<ChatMessage?> = MutableLiveData()
val getReplyChatMessage: LiveData<IMessage?> val getReplyChatMessage: LiveData<ChatMessage?>
get() = _getReplyChatMessage get() = _getReplyChatMessage
object CreateThreadStartState : ViewState
class CreateThreadEditState : ViewState
private val _createThreadViewState: MutableLiveData<ViewState> = MutableLiveData(CreateThreadStartState)
val createThreadViewState: LiveData<ViewState>
get() = _createThreadViewState
sealed interface ViewState sealed interface ViewState
object SendChatMessageStartState : ViewState object SendChatMessageStartState : ViewState
class SendChatMessageSuccessState(val message: CharSequence) : ViewState class SendChatMessageSuccessState(val message: CharSequence) : ViewState
class SendChatMessageErrorState(val message: CharSequence) : ViewState class SendChatMessageErrorState(val message: CharSequence) : ViewState
@ -125,7 +133,8 @@ class MessageInputViewModel @Inject constructor(
message: String, message: String,
displayName: String, displayName: String,
replyTo: Int, replyTo: Int,
sendWithoutNotification: Boolean sendWithoutNotification: Boolean,
threadTitle: String?
) { ) {
val referenceId = SendMessageUtils().generateReferenceId() val referenceId = SendMessageUtils().generateReferenceId()
Log.d(TAG, "Random SHA-256 Hash: $referenceId") Log.d(TAG, "Random SHA-256 Hash: $referenceId")
@ -156,7 +165,8 @@ class MessageInputViewModel @Inject constructor(
displayName, displayName,
replyTo, replyTo,
sendWithoutNotification, sendWithoutNotification,
referenceId referenceId,
threadTitle
).collect { result -> ).collect { result ->
if (result.isSuccess) { if (result.isSuccess) {
Log.d(TAG, "received ref id: " + (result.getOrNull()?.referenceId ?: "none")) Log.d(TAG, "received ref id: " + (result.getOrNull()?.referenceId ?: "none"))
@ -203,7 +213,7 @@ class MessageInputViewModel @Inject constructor(
} }
} }
fun reply(message: IMessage?) { fun reply(message: ChatMessage?) {
_getReplyChatMessage.postValue(message) _getReplyChatMessage.postValue(message)
} }
@ -256,6 +266,14 @@ class MessageInputViewModel @Inject constructor(
_callStartedFlow.postValue(Pair(recent, show)) _callStartedFlow.postValue(Pair(recent, show))
} }
fun startThreadCreation() {
_createThreadViewState.postValue(CreateThreadEditState())
}
fun stopThreadCreation() {
_createThreadViewState.postValue(CreateThreadStartState)
}
companion object { companion object {
private val TAG = MessageInputViewModel::class.java.simpleName private val TAG = MessageInputViewModel::class.java.simpleName
} }

View file

@ -51,28 +51,30 @@ fun StandardAppBar(title: String, menuItems: List<Pair<String, () -> Unit>>?) {
} }
}, },
actions = { actions = {
Box { if (!menuItems.isNullOrEmpty()) {
IconButton(onClick = { expanded = true }) { Box {
Icon( IconButton(onClick = { expanded = true }) {
imageVector = Icons.Default.MoreVert, Icon(
contentDescription = stringResource(R.string.nc_common_more_options) imageVector = Icons.Default.MoreVert,
) contentDescription = stringResource(R.string.nc_common_more_options)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier.background(color = colorResource(id = R.color.bg_default))
) {
menuItems?.forEach { (label, action) ->
DropdownMenuItem(
text = { Text(label) },
onClick = {
action()
expanded = false
}
) )
} }
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier.background(color = colorResource(id = R.color.bg_default))
) {
menuItems?.forEach { (label, action) ->
DropdownMenuItem(
text = { Text(label) },
onClick = {
action()
expanded = false
}
)
}
}
} }
} }
} }

View file

@ -1,7 +1,7 @@
/* /*
* Nextcloud Talk - Android Client * Nextcloud Talk - Android Client
* *
* SPDX-FileCopyrightText: 2024 Your Name <your@email.com> * SPDX-FileCopyrightText: 2024 Sowjanya Kota <sowjanya.kch@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later * SPDX-License-Identifier: GPL-3.0-or-later
*/ */

View file

@ -10,6 +10,7 @@ package com.nextcloud.talk.contacts
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.displayCutoutPadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
@ -35,7 +36,8 @@ fun ContactsScreen(contactsViewModel: ContactsViewModel, uiState: ContactsUiStat
Scaffold( Scaffold(
modifier = Modifier modifier = Modifier
.statusBarsPadding(), .statusBarsPadding()
.displayCutoutPadding(),
topBar = { topBar = {
if (isSearchActive) { if (isSearchActive) {
ContactsSearchAppBar( ContactsSearchAppBar(
@ -64,8 +66,8 @@ fun ContactsScreen(contactsViewModel: ContactsViewModel, uiState: ContactsUiStat
content = { paddingValues -> content = { paddingValues ->
Column( Column(
Modifier Modifier
.padding(0.dp, paddingValues.calculateTopPadding(), 0.dp, 0.dp)
.background(colorResource(id = R.color.bg_default)) .background(colorResource(id = R.color.bg_default))
.padding(0.dp, paddingValues.calculateTopPadding(), 0.dp, paddingValues.calculateBottomPadding())
) { ) {
if (!isAddParticipants) { if (!isAddParticipants) {
ConversationCreationOptions() ConversationCreationOptions()

View file

@ -0,0 +1,240 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.contextchat
import android.content.Context
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.nextcloud.talk.R
import com.nextcloud.talk.data.database.mappers.asModel
import com.nextcloud.talk.models.json.chat.ChatMessageJson
import com.nextcloud.talk.ui.ComposeChatAdapter
import com.nextcloud.talk.utils.preview.ComposePreviewUtils
@Composable
fun ContextChatView(context: Context, contextViewModel: ContextChatViewModel) {
val contextChatMessagesState = contextViewModel.getContextChatMessagesState.collectAsState().value
when (contextChatMessagesState) {
ContextChatViewModel.ContextChatRetrieveUiState.None -> {}
is ContextChatViewModel.ContextChatRetrieveUiState.Success -> {
ContextChatSuccessView(
visible = true,
context = context,
contextChatRetrieveUiStateSuccess = contextChatMessagesState,
onDismiss = {
contextViewModel.clearContextChatState()
}
)
}
is ContextChatViewModel.ContextChatRetrieveUiState.Error -> {
ContextChatErrorView()
}
}
}
@Composable
fun ContextChatErrorView() {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
Icons.Filled.Info,
contentDescription = "Info Icon"
)
Text(
stringResource(R.string.nc_capabilities_failed)
)
}
}
@Composable
fun ContextChatSuccessView(
visible: Boolean,
context: Context,
contextChatRetrieveUiStateSuccess: ContextChatViewModel.ContextChatRetrieveUiState.Success,
onDismiss: () -> Unit
) {
val previewUtils = ComposePreviewUtils.getInstance(LocalContext.current)
val colorScheme = previewUtils.viewThemeUtils.getColorScheme(context)
if (visible) {
MaterialTheme(colorScheme) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(
dismissOnBackPress = true,
dismissOnClickOutside = true,
usePlatformDefaultWidth = false
)
) {
Surface {
Column(
modifier = Modifier.Companion
.fillMaxWidth()
.fillMaxHeight()
.padding(top = 16.dp)
) {
Row(
modifier = Modifier.Companion.align(Alignment.Companion.Start),
verticalAlignment = Alignment.Companion.CenterVertically
) {
IconButton(onClick = onDismiss) {
Icon(
Icons.Filled.Close,
stringResource(R.string.close),
modifier = Modifier.Companion
.size(24.dp)
)
}
Column(verticalArrangement = Arrangement.Center) {
Text(contextChatRetrieveUiStateSuccess.title ?: "", fontSize = 18.sp)
if (!contextChatRetrieveUiStateSuccess.subTitle.isNullOrEmpty()) {
Text(contextChatRetrieveUiStateSuccess.subTitle, fontSize = 12.sp)
}
}
// This code was written back then but not needed yet, but it's not deleted yet
// because it may be used soon when further migrating to Compose...
// Spacer(modifier = Modifier.weight(1f))
// val cInt = context.resources.getColor(R.color.high_emphasis_text, null)
// Icon(
// painterResource(R.drawable.ic_call_black_24dp),
// "",
// tint = Color(cInt),
// modifier = Modifier
// .padding()
// .padding(end = 16.dp)
// .alpha(HALF_ALPHA)
// )
//
// Icon(
// painterResource(R.drawable.ic_baseline_videocam_24),
// "",
// tint = Color(cInt),
// modifier = Modifier
// .padding()
// .alpha(HALF_ALPHA)
// )
//
// ComposeChatMenu(colorScheme.background, false)
}
val messages = contextChatRetrieveUiStateSuccess.messages.map(ChatMessageJson::asModel)
val messageId = contextChatRetrieveUiStateSuccess.messageId
val threadId = contextChatRetrieveUiStateSuccess.threadId
val adapter = ComposeChatAdapter(
messagesJson = contextChatRetrieveUiStateSuccess.messages,
messageId = messageId,
threadId = threadId
)
SideEffect {
adapter.addMessages(messages.toMutableList(), true)
}
adapter.GetView()
}
}
}
}
}
}
// This code was written back then but not needed yet, but it's not deleted yet
// because it may be used soon when further migrating to Compose...
@Composable
private fun ComposeChatMenu(backgroundColor: Color, enabled: Boolean = true) {
var expanded by remember { mutableStateOf(false) }
Box(
modifier = Modifier.Companion.wrapContentSize(Alignment.Companion.TopStart)
) {
IconButton(onClick = { expanded = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "More options"
)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier.Companion.background(backgroundColor)
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.nc_search)) },
onClick = {
expanded = false
},
enabled = enabled
)
HorizontalDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.nc_conversation_menu_conversation_info)) },
onClick = {
expanded = false
},
enabled = enabled
)
HorizontalDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.nc_shared_items)) },
onClick = {
expanded = false
},
enabled = enabled
)
}
}
}

View file

@ -0,0 +1,109 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.contextchat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import autodagger.AutoInjector
import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.chat.data.network.ChatNetworkDataSource
import com.nextcloud.talk.chat.viewmodels.ChatViewModel
import com.nextcloud.talk.models.json.chat.ChatMessageJson
import com.nextcloud.talk.users.UserManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@AutoInjector(NextcloudTalkApplication::class)
class ContextChatViewModel @Inject constructor(private val chatNetworkDataSource: ChatNetworkDataSource) :
ViewModel() {
@Inject
lateinit var chatViewModel: ChatViewModel
@Inject
lateinit var userManager: UserManager
var threadId: String? = null
private val _getContextChatMessagesState =
MutableStateFlow<ContextChatRetrieveUiState>(ContextChatRetrieveUiState.None)
val getContextChatMessagesState: StateFlow<ContextChatRetrieveUiState> = _getContextChatMessagesState
@Suppress("LongParameterList")
fun getContextForChatMessages(
credentials: String,
baseUrl: String,
token: String,
threadId: String?,
messageId: String,
title: String
) {
viewModelScope.launch {
val user = userManager.currentUser.blockingGet()
if (!user.hasSpreedFeatureCapability("chat-get-context") ||
!user.hasSpreedFeatureCapability("federation-v1")
) {
_getContextChatMessagesState.value = ContextChatRetrieveUiState.Error
}
var messages = chatNetworkDataSource.getContextForChatMessage(
credentials = credentials,
baseUrl = baseUrl,
token = token,
messageId = messageId,
limit = LIMIT,
threadId = threadId?.toInt()
)
if (threadId.isNullOrEmpty()) {
messages = messages.filter { !isThreadChildMessage(it) }
}
val subTitle = if (threadId?.isNotEmpty() == true) {
messages.firstOrNull()?.threadTitle
} else {
""
}
_getContextChatMessagesState.value = ContextChatRetrieveUiState.Success(
messageId = messageId,
threadId = threadId,
messages = messages,
title = title,
subTitle = subTitle
)
}
}
fun isThreadChildMessage(currentMessage: ChatMessageJson): Boolean =
currentMessage.hasThread &&
currentMessage.threadId != currentMessage.id
fun clearContextChatState() {
_getContextChatMessagesState.value = ContextChatRetrieveUiState.None
}
sealed class ContextChatRetrieveUiState {
data object None : ContextChatRetrieveUiState()
data class Success(
val messageId: String,
val threadId: String?,
val messages: List<ChatMessageJson>,
val title: String?,
val subTitle: String?
) : ContextChatRetrieveUiState()
data object Error : ContextChatRetrieveUiState()
}
companion object {
private const val LIMIT = 50
}
}

View file

@ -29,12 +29,14 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.displayCutoutPadding
import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
@ -173,6 +175,9 @@ fun ConversationCreationScreen(
ColoredStatusBar() ColoredStatusBar()
Scaffold( Scaffold(
modifier = Modifier
.statusBarsPadding()
.displayCutoutPadding(),
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text(text = stringResource(id = R.string.nc_new_conversation)) }, title = { Text(text = stringResource(id = R.string.nc_new_conversation)) },
@ -191,8 +196,8 @@ fun ConversationCreationScreen(
content = { paddingValues -> content = { paddingValues ->
Column( Column(
modifier = Modifier modifier = Modifier
.padding(0.dp, paddingValues.calculateTopPadding(), 0.dp, 0.dp)
.background(colorResource(id = R.color.bg_default)) .background(colorResource(id = R.color.bg_default))
.padding(0.dp, paddingValues.calculateTopPadding(), 0.dp, paddingValues.calculateBottomPadding())
.fillMaxSize() .fillMaxSize()
.verticalScroll(rememberScrollState()) .verticalScroll(rememberScrollState())
) { ) {

View file

@ -82,6 +82,7 @@ import com.nextcloud.talk.models.json.participants.Participant.ActorType.USERS
import com.nextcloud.talk.models.json.participants.ParticipantsOverall import com.nextcloud.talk.models.json.participants.ParticipantsOverall
import com.nextcloud.talk.repositories.conversations.ConversationsRepository import com.nextcloud.talk.repositories.conversations.ConversationsRepository
import com.nextcloud.talk.shareditems.activities.SharedItemsActivity import com.nextcloud.talk.shareditems.activities.SharedItemsActivity
import com.nextcloud.talk.threadsoverview.ThreadsOverviewActivity
import com.nextcloud.talk.ui.dialog.DialogBanListFragment import com.nextcloud.talk.ui.dialog.DialogBanListFragment
import com.nextcloud.talk.utils.ApiUtils import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.CapabilitiesUtil import com.nextcloud.talk.utils.CapabilitiesUtil
@ -601,6 +602,22 @@ class ConversationInfoActivity :
startActivity(intent) startActivity(intent)
} }
fun openThreadsOverview() {
val threadsUrl = ApiUtils.getUrlForRecentThreads(
version = 1,
baseUrl = conversationUser.baseUrl,
token = conversationToken
)
val bundle = Bundle()
bundle.putString(KEY_ROOM_TOKEN, conversationToken)
bundle.putString(ThreadsOverviewActivity.KEY_APPBAR_TITLE, getString(R.string.recent_threads))
bundle.putString(ThreadsOverviewActivity.KEY_THREADS_SOURCE_URL, threadsUrl)
val threadsOverviewIntent = Intent(context, ThreadsOverviewActivity::class.java)
threadsOverviewIntent.putExtras(bundle)
startActivity(threadsOverviewIntent)
}
private fun setupWebinaryView() { private fun setupWebinaryView() {
if (hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.WEBINARY_LOBBY) && if (hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.WEBINARY_LOBBY) &&
webinaryRoomType(conversation!!) && webinaryRoomType(conversation!!) &&
@ -1057,9 +1074,17 @@ class ConversationInfoActivity :
) { ) {
binding.sharedItemsButton.setOnClickListener { showSharedItems() } binding.sharedItemsButton.setOnClickListener { showSharedItems() }
} else { } else {
binding.sharedItemsButton.visibility = GONE
binding.sharedItems.visibility = GONE binding.sharedItems.visibility = GONE
} }
if (hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.THREADS)) {
binding.sharedItems.visibility = VISIBLE
binding.showThreadsButton.setOnClickListener { openThreadsOverview() }
} else {
binding.showThreadsButton.visibility = GONE
}
if (conversation!!.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL && if (conversation!!.type == ConversationEnums.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL &&
hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.CONVERSATION_CREATION_ALL) hasSpreedFeatureCapability(spreedCapabilities, SpreedFeatures.CONVERSATION_CREATION_ALL)
) { ) {

View file

@ -38,14 +38,12 @@ import androidx.activity.OnBackPressedCallback
import androidx.annotation.OptIn import androidx.annotation.OptIn
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.SearchView
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat import androidx.core.graphics.drawable.IconCompat
import androidx.core.graphics.drawable.toDrawable import androidx.core.graphics.drawable.toDrawable
import androidx.core.net.toUri import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.core.view.MenuItemCompat import androidx.core.view.MenuItemCompat
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
@ -111,10 +109,12 @@ import com.nextcloud.talk.models.json.converters.EnumActorTypeConverter
import com.nextcloud.talk.models.json.participants.Participant import com.nextcloud.talk.models.json.participants.Participant
import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepository import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepository
import com.nextcloud.talk.settings.SettingsActivity import com.nextcloud.talk.settings.SettingsActivity
import com.nextcloud.talk.threadsoverview.ThreadsOverviewActivity
import com.nextcloud.talk.ui.BackgroundVoiceMessageCard import com.nextcloud.talk.ui.BackgroundVoiceMessageCard
import com.nextcloud.talk.ui.dialog.ChooseAccountDialogFragment import com.nextcloud.talk.ui.dialog.ChooseAccountDialogFragment
import com.nextcloud.talk.ui.dialog.ChooseAccountShareToDialogFragment import com.nextcloud.talk.ui.dialog.ChooseAccountShareToDialogFragment
import com.nextcloud.talk.ui.dialog.ContextChatCompose import com.nextcloud.talk.contextchat.ContextChatView
import com.nextcloud.talk.contextchat.ContextChatViewModel
import com.nextcloud.talk.ui.dialog.ConversationsListBottomDialog import com.nextcloud.talk.ui.dialog.ConversationsListBottomDialog
import com.nextcloud.talk.ui.dialog.FilterConversationFragment import com.nextcloud.talk.ui.dialog.FilterConversationFragment
import com.nextcloud.talk.ui.dialog.FilterConversationFragment.Companion.ARCHIVE import com.nextcloud.talk.ui.dialog.FilterConversationFragment.Companion.ARCHIVE
@ -203,6 +203,7 @@ class ConversationsListActivity :
lateinit var contactsViewModel: ContactsViewModel lateinit var contactsViewModel: ContactsViewModel
lateinit var conversationsListViewModel: ConversationsListViewModel lateinit var conversationsListViewModel: ConversationsListViewModel
lateinit var contextChatViewModel: ContextChatViewModel
override val appBarLayoutType: AppBarLayoutType override val appBarLayoutType: AppBarLayoutType
get() = AppBarLayoutType.SEARCH_BAR get() = AppBarLayoutType.SEARCH_BAR
@ -262,14 +263,14 @@ class ConversationsListActivity :
currentUser = currentUserProvider.currentUser.blockingGet() currentUser = currentUserProvider.currentUser.blockingGet()
conversationsListViewModel = ViewModelProvider(this, viewModelFactory)[ConversationsListViewModel::class.java] conversationsListViewModel = ViewModelProvider(this, viewModelFactory)[ConversationsListViewModel::class.java]
contextChatViewModel = ViewModelProvider(this, viewModelFactory)[ContextChatViewModel::class.java]
binding = ActivityConversationsBinding.inflate(layoutInflater) binding = ActivityConversationsBinding.inflate(layoutInflater)
setupActionBar() setupActionBar()
setContentView(binding.root) setContentView(binding.root)
initSystemBars() initSystemBars()
viewThemeUtils.material.themeSearchCardView(binding.searchToolbar) viewThemeUtils.material.themeSearchCardView(binding.searchToolbar)
viewThemeUtils.material.colorMaterialButtonContent(binding.menuButton, ColorRole.ON_SURFACE) viewThemeUtils.material.colorMaterialButtonContent(binding.menuButton, ColorRole.ON_SURFACE_VARIANT)
viewThemeUtils.platform.colorTextView(binding.searchText, ColorRole.ON_SURFACE_VARIANT) viewThemeUtils.platform.colorTextView(binding.searchText, ColorRole.ON_SURFACE_VARIANT)
forwardMessage = intent.getBooleanExtra(KEY_FORWARD_MSG_FLAG, false) forwardMessage = intent.getBooleanExtra(KEY_FORWARD_MSG_FLAG, false)
@ -343,6 +344,7 @@ class ConversationsListActivity :
} }
showSearchOrToolbar() showSearchOrToolbar()
conversationsListViewModel.checkIfThreadsExist()
} }
override fun onPause() { override fun onPause() {
@ -359,7 +361,7 @@ class ConversationsListActivity :
@Suppress("MagicNumber") @Suppress("MagicNumber")
private fun addEmptyItemForEdgeToEdgeIfNecessary() { private fun addEmptyItemForEdgeToEdgeIfNecessary() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
adapter?.addScrollableFooter(SpacerItem(200)) adapter?.addScrollableFooter(SpacerItem(100))
} }
} }
@ -428,6 +430,23 @@ class ConversationsListActivity :
} }
} }
lifecycleScope.launch {
conversationsListViewModel.threadsExistState.collect { state ->
when (state) {
is ConversationsListViewModel.ThreadsExistUiState.Success -> {
binding.threadsButton.visibility = if (state.threadsExistence == true) {
View.VISIBLE
} else {
View.GONE
}
}
else -> {
binding.threadsButton.visibility = View.GONE
}
}
}
}
lifecycleScope.launch { lifecycleScope.launch {
conversationsListViewModel.getRoomsFlow conversationsListViewModel.getRoomsFlow
.onEach { list -> .onEach { list ->
@ -707,6 +726,7 @@ class ConversationsListActivity :
binding.newMentionPopupBubble.visibility = View.GONE binding.newMentionPopupBubble.visibility = View.GONE
} }
layoutManager?.scrollToPositionWithOffset(0, 0)
updateFilterConversationButtonColor() updateFilterConversationButtonColor()
} }
@ -994,7 +1014,7 @@ class ConversationsListActivity :
private fun showSearchBar() { private fun showSearchBar() {
val layoutParams = binding.searchToolbar.layoutParams as AppBarLayout.LayoutParams val layoutParams = binding.searchToolbar.layoutParams as AppBarLayout.LayoutParams
binding.searchToolbar.visibility = View.VISIBLE binding.searchToolbar.visibility = View.VISIBLE
binding.searchText.hint = getString(R.string.appbar_search_in, getString(R.string.nc_app_product_name)) binding.searchText.text = getString(R.string.appbar_search_in, getString(R.string.nc_app_product_name))
binding.conversationListToolbar.visibility = View.GONE binding.conversationListToolbar.visibility = View.GONE
// layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout // layoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout
// .LayoutParams.SCROLL_FLAG_SNAP | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); // .LayoutParams.SCROLL_FLAG_SNAP | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
@ -1304,6 +1324,13 @@ class ConversationsListActivity :
newFragment.show(supportFragmentManager, FilterConversationFragment.TAG) newFragment.show(supportFragmentManager, FilterConversationFragment.TAG)
} }
binding.threadsButton.setOnClickListener {
openFollowedThreadsOverview()
}
binding.threadsButton.let {
viewThemeUtils.platform.colorImageView(it, ColorRole.ON_SURFACE_VARIANT)
}
binding.newMentionPopupBubble.visibility = View.GONE binding.newMentionPopupBubble.visibility = View.GONE
binding.newMentionPopupBubble.setOnClickListener { binding.newMentionPopupBubble.setOnClickListener {
val layoutManager = binding.recyclerView.layoutManager as SmoothScrollLinearLayoutManager? val layoutManager = binding.recyclerView.layoutManager as SmoothScrollLinearLayoutManager?
@ -1507,15 +1534,16 @@ class ConversationsListActivity :
).model.displayName ).model.displayName
binding.genericComposeView.apply { binding.genericComposeView.apply {
val shouldDismiss = mutableStateOf(false)
setContent { setContent {
val bundle = bundleOf() contextChatViewModel.getContextForChatMessages(
bundle.putString(BundleKeys.KEY_CREDENTIALS, credentials!!) credentials = credentials!!,
bundle.putString(BundleKeys.KEY_BASE_URL, currentUser!!.baseUrl) baseUrl = currentUser!!.baseUrl!!,
bundle.putString(KEY_ROOM_TOKEN, token) token = token,
bundle.putString(BundleKeys.KEY_MESSAGE_ID, item.messageEntry.messageId) threadId = item.messageEntry.threadId,
bundle.putString(BundleKeys.KEY_CONVERSATION_NAME, conversationName) messageId = item.messageEntry.messageId!!,
ContextChatCompose(bundle).GetDialogView(shouldDismiss, context) title = item.messageEntry.title
)
ContextChatView(context, contextChatViewModel)
} }
} }
} }
@ -2205,17 +2233,32 @@ class ConversationsListActivity :
binding.filterConversationsButton.let { binding.filterConversationsButton.let {
viewThemeUtils.platform.colorImageView( viewThemeUtils.platform.colorImageView(
it, it,
ColorRole.ON_SURFACE ColorRole.ON_SURFACE_VARIANT
) )
} }
} }
} }
fun openFollowedThreadsOverview() {
val threadsUrl = ApiUtils.getUrlForSubscribedThreads(
version = 1,
baseUrl = currentUser!!.baseUrl
)
val bundle = Bundle()
bundle.putString(ThreadsOverviewActivity.KEY_APPBAR_TITLE, getString(R.string.threads))
bundle.putString(ThreadsOverviewActivity.KEY_THREADS_SOURCE_URL, threadsUrl)
val threadsOverviewIntent = Intent(context, ThreadsOverviewActivity::class.java)
threadsOverviewIntent.putExtras(bundle)
startActivity(threadsOverviewIntent)
}
companion object { companion object {
private val TAG = ConversationsListActivity::class.java.simpleName private val TAG = ConversationsListActivity::class.java.simpleName
const val UNREAD_BUBBLE_DELAY = 2500 const val UNREAD_BUBBLE_DELAY = 2500
const val BOTTOM_SHEET_DELAY: Long = 2500 const val BOTTOM_SHEET_DELAY: Long = 2500
private const val KEY_SEARCH_QUERY = "ConversationsListActivity.searchQuery" private const val KEY_SEARCH_QUERY = "ConversationsListActivity.searchQuery"
private const val CHAT_ACTIVITY_LOCAL_NAME = "com.nextcloud.talk.chat.ChatActivity"
const val SEARCH_DEBOUNCE_INTERVAL_MS = 300 const val SEARCH_DEBOUNCE_INTERVAL_MS = 300
const val SEARCH_MIN_CHARS = 1 const val SEARCH_MIN_CHARS = 1
const val HTTP_UNAUTHORIZED = 401 const val HTTP_UNAUTHORIZED = 401

View file

@ -36,4 +36,8 @@ interface OfflineConversationsRepository {
* to be handled asynchronously. * to be handled asynchronously.
*/ */
fun getRoom(roomToken: String): Job fun getRoom(roomToken: String): Job
suspend fun updateConversation(conversationModel: ConversationModel)
suspend fun getLocallyStoredConversation(roomToken: String): ConversationModel?
} }

View file

@ -98,12 +98,22 @@ class OfflineFirstConversationsRepository @Inject constructor(
runBlocking { runBlocking {
_conversationFlow.emit(model) _conversationFlow.emit(model)
val entityList = listOf(model.asEntity()) val entityList = listOf(model.asEntity())
dao.upsertConversations(entityList) dao.upsertConversations(user.id!!, entityList)
} }
} }
}) })
} }
override suspend fun updateConversation(conversationModel: ConversationModel) {
val entity = conversationModel.asEntity()
dao.updateConversation(entity)
}
override suspend fun getLocallyStoredConversation(roomToken: String): ConversationModel? {
val id = user.id!!
return getConversation(id, roomToken)
}
@Suppress("Detekt.TooGenericExceptionCaught") @Suppress("Detekt.TooGenericExceptionCaught")
private suspend fun getRoomsFromServer(): List<ConversationEntity>? { private suspend fun getRoomsFromServer(): List<ConversationEntity>? {
var conversationsFromSync: List<ConversationEntity>? = null var conversationsFromSync: List<ConversationEntity>? = null
@ -126,7 +136,7 @@ class OfflineFirstConversationsRepository @Inject constructor(
} }
deleteLeftConversations(conversationsFromSync) deleteLeftConversations(conversationsFromSync)
dao.upsertConversations(conversationsFromSync) dao.upsertConversations(user.id!!, conversationsFromSync)
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "Something went wrong when fetching conversations", e) Log.e(TAG, "Something went wrong when fetching conversations", e)
} }

View file

@ -10,21 +10,35 @@ import android.util.Log
import androidx.lifecycle.LiveData import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nextcloud.talk.arbitrarystorage.ArbitraryStorageManager
import com.nextcloud.talk.conversationlist.data.OfflineConversationsRepository import com.nextcloud.talk.conversationlist.data.OfflineConversationsRepository
import com.nextcloud.talk.data.user.model.User
import com.nextcloud.talk.invitation.data.InvitationsModel import com.nextcloud.talk.invitation.data.InvitationsModel
import com.nextcloud.talk.invitation.data.InvitationsRepository import com.nextcloud.talk.invitation.data.InvitationsRepository
import com.nextcloud.talk.threadsoverview.data.ThreadsRepository
import com.nextcloud.talk.users.UserManager import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.CapabilitiesUtil.hasSpreedFeatureCapability
import com.nextcloud.talk.utils.SpreedFeatures
import com.nextcloud.talk.utils.UserIdUtils
import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew
import io.reactivex.Observer import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
class ConversationsListViewModel @Inject constructor( class ConversationsListViewModel @Inject constructor(
private val repository: OfflineConversationsRepository, private val repository: OfflineConversationsRepository,
private val threadsRepository: ThreadsRepository,
private val currentUserProvider: CurrentUserProviderNew,
var userManager: UserManager var userManager: UserManager
) : ViewModel() { ) : ViewModel() {
@ -32,10 +46,23 @@ class ConversationsListViewModel @Inject constructor(
lateinit var invitationsRepository: InvitationsRepository lateinit var invitationsRepository: InvitationsRepository
@Inject @Inject
lateinit var currentUserProvider: CurrentUserProviderNew lateinit var arbitraryStorageManager: ArbitraryStorageManager
private val _currentUser = currentUserProvider.currentUser.blockingGet()
val currentUser: User = _currentUser
val credentials = ApiUtils.getCredentials(_currentUser.username, _currentUser.token) ?: ""
sealed interface ViewState sealed interface ViewState
sealed class ThreadsExistUiState {
data object None : ThreadsExistUiState()
data class Success(val threadsExistence: Boolean?) : ThreadsExistUiState()
data class Error(val exception: Exception) : ThreadsExistUiState()
}
private val _threadsExistState = MutableStateFlow<ThreadsExistUiState>(ThreadsExistUiState.None)
val threadsExistState: StateFlow<ThreadsExistUiState> = _threadsExistState
object GetRoomsStartState : ViewState object GetRoomsStartState : ViewState
object GetRoomsErrorState : ViewState object GetRoomsErrorState : ViewState
open class GetRoomsSuccessState(val listIsNotEmpty: Boolean) : ViewState open class GetRoomsSuccessState(val listIsNotEmpty: Boolean) : ViewState
@ -87,6 +114,79 @@ class ConversationsListViewModel @Inject constructor(
repository.getRooms() repository.getRooms()
} }
fun checkIfThreadsExist() {
val limitForFollowedThreadsExistenceCheck = 1
val accountId = UserIdUtils.getIdForUser(currentUserProvider.currentUser.blockingGet())
fun isLastCheckTooOld(lastCheckDate: Long): Boolean {
val currentTimeMillis = System.currentTimeMillis()
val differenceMillis = currentTimeMillis - lastCheckDate
val checkIntervalInMillies = TimeUnit.HOURS.toMillis(2)
return differenceMillis > checkIntervalInMillies
}
fun checkIfFollowedThreadsExist() {
val threadsUrl = ApiUtils.getUrlForSubscribedThreads(
version = 1,
baseUrl = currentUser.baseUrl
)
viewModelScope.launch {
try {
val threads =
threadsRepository.getThreads(credentials, threadsUrl, limitForFollowedThreadsExistenceCheck)
val followedThreadsExistNew = threads.ocs?.data?.isNotEmpty()
_threadsExistState.value = ThreadsExistUiState.Success(followedThreadsExistNew)
val followedThreadsExistLastCheckNew = System.currentTimeMillis()
arbitraryStorageManager.storeStorageSetting(
accountId,
FOLLOWED_THREADS_EXIST_LAST_CHECK,
followedThreadsExistLastCheckNew.toString(),
""
)
arbitraryStorageManager.storeStorageSetting(
accountId,
FOLLOWED_THREADS_EXIST,
followedThreadsExistNew.toString(),
""
)
} catch (exception: Exception) {
_threadsExistState.value = ThreadsExistUiState.Error(exception)
}
}
}
if (!hasSpreedFeatureCapability(currentUser.capabilities!!.spreedCapability!!, SpreedFeatures.THREADS)) {
_threadsExistState.value = ThreadsExistUiState.Success(false)
return
}
val followedThreadsExistOld = arbitraryStorageManager.getStorageSetting(
accountId,
FOLLOWED_THREADS_EXIST,
""
).blockingGet()?.value?.toBoolean() ?: false
val followedThreadsExistLastCheckOld = arbitraryStorageManager.getStorageSetting(
accountId,
FOLLOWED_THREADS_EXIST_LAST_CHECK,
""
).blockingGet()?.value?.toLong()
if (followedThreadsExistOld) {
Log.d(TAG, "followed threads exist for this user. No need to check again.")
_threadsExistState.value = ThreadsExistUiState.Success(true)
} else {
if (followedThreadsExistLastCheckOld == null || isLastCheckTooOld(followedThreadsExistLastCheckOld)) {
Log.d(TAG, "check if followed threads exist never happened or is too old. Checking now...")
checkIfFollowedThreadsExist()
} else {
_threadsExistState.value = ThreadsExistUiState.Success(false)
Log.d(TAG, "already checked in the last 2 hours if followed threads exist. Skip check.")
}
}
}
inner class FederatedInvitationsObserver : Observer<InvitationsModel> { inner class FederatedInvitationsObserver : Observer<InvitationsModel> {
override fun onSubscribe(d: Disposable) { override fun onSubscribe(d: Disposable) {
// unused atm // unused atm
@ -122,5 +222,7 @@ class ConversationsListViewModel @Inject constructor(
companion object { companion object {
private val TAG = ConversationsListViewModel::class.simpleName private val TAG = ConversationsListViewModel::class.simpleName
const val FOLLOWED_THREADS_EXIST_LAST_CHECK = "FOLLOWED_THREADS_EXIST_LAST_CHECK"
const val FOLLOWED_THREADS_EXIST = "FOLLOWED_THREADS_EXIST"
} }
} }

View file

@ -9,6 +9,10 @@
*/ */
package com.nextcloud.talk.dagger.modules package com.nextcloud.talk.dagger.modules
import android.content.Context
import com.nextcloud.talk.account.data.LoginRepository
import com.nextcloud.talk.account.data.io.LocalLoginDataSource
import com.nextcloud.talk.account.data.network.NetworkLoginDataSource
import com.nextcloud.talk.api.NcApi import com.nextcloud.talk.api.NcApi
import com.nextcloud.talk.api.NcApiCoroutines import com.nextcloud.talk.api.NcApiCoroutines
import com.nextcloud.talk.chat.data.ChatMessageRepository import com.nextcloud.talk.chat.data.ChatMessageRepository
@ -54,10 +58,14 @@ import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepository
import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepositoryImpl import com.nextcloud.talk.repositories.unifiedsearch.UnifiedSearchRepositoryImpl
import com.nextcloud.talk.shareditems.repositories.SharedItemsRepository import com.nextcloud.talk.shareditems.repositories.SharedItemsRepository
import com.nextcloud.talk.shareditems.repositories.SharedItemsRepositoryImpl import com.nextcloud.talk.shareditems.repositories.SharedItemsRepositoryImpl
import com.nextcloud.talk.threadsoverview.data.ThreadsRepository
import com.nextcloud.talk.threadsoverview.data.ThreadsRepositoryImpl
import com.nextcloud.talk.translate.repositories.TranslateRepository import com.nextcloud.talk.translate.repositories.TranslateRepository
import com.nextcloud.talk.translate.repositories.TranslateRepositoryImpl import com.nextcloud.talk.translate.repositories.TranslateRepositoryImpl
import com.nextcloud.talk.users.UserManager
import com.nextcloud.talk.utils.DateUtils import com.nextcloud.talk.utils.DateUtils
import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew import com.nextcloud.talk.utils.database.user.CurrentUserProviderNew
import com.nextcloud.talk.utils.preferences.AppPreferences
import dagger.Module import dagger.Module
import dagger.Provides import dagger.Provides
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
@ -184,4 +192,27 @@ class RepositoryModule {
ncApiCoroutines: NcApiCoroutines, ncApiCoroutines: NcApiCoroutines,
currentUserProviderNew: CurrentUserProviderNew currentUserProviderNew: CurrentUserProviderNew
): ConversationCreationRepository = ConversationCreationRepositoryImpl(ncApiCoroutines, currentUserProviderNew) ): ConversationCreationRepository = ConversationCreationRepositoryImpl(ncApiCoroutines, currentUserProviderNew)
@Provides
fun provideThreadsRepository(
ncApiCoroutines: NcApiCoroutines,
currentUserProviderNew: CurrentUserProviderNew
): ThreadsRepository = ThreadsRepositoryImpl(ncApiCoroutines, currentUserProviderNew)
@Provides
fun provideNetworkDataSource(okHttpClient: OkHttpClient): NetworkLoginDataSource =
NetworkLoginDataSource(okHttpClient)
@Provides
fun providesLocalDataSource(
userManager: UserManager,
appPreferences: AppPreferences,
context: Context
): LocalLoginDataSource = LocalLoginDataSource(userManager, appPreferences, context)
@Provides
fun provideLoginRepository(
networkLoginDataSource: NetworkLoginDataSource,
localLoginDataSource: LocalLoginDataSource
): LoginRepository = LoginRepository(networkLoginDataSource, localLoginDataSource)
} }

View file

@ -34,9 +34,10 @@ import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException; import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509KeyManager;
@ -48,6 +49,7 @@ import dagger.Provides;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import okhttp3.Authenticator; import okhttp3.Authenticator;
import okhttp3.Cache; import okhttp3.Cache;
import okhttp3.ConnectionSpec;
import okhttp3.Credentials; import okhttp3.Credentials;
import okhttp3.Dispatcher; import okhttp3.Dispatcher;
import okhttp3.Interceptor; import okhttp3.Interceptor;
@ -60,7 +62,6 @@ import okhttp3.internal.tls.OkHostnameVerifier;
import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module(includes = DatabaseModule.class) @Module(includes = DatabaseModule.class)
public class RestModule { public class RestModule {
@ -257,8 +258,8 @@ public class RestModule {
public static class HttpAuthenticator implements Authenticator { public static class HttpAuthenticator implements Authenticator {
private String credentials; private final String credentials;
private String authenticatorType; private final String authenticatorType;
public HttpAuthenticator(@NonNull String credentials, @NonNull String authenticatorType) { public HttpAuthenticator(@NonNull String credentials, @NonNull String authenticatorType) {
this.credentials = credentials; this.credentials = credentials;
@ -291,7 +292,7 @@ public class RestModule {
private class GetProxyRunnable implements Runnable { private class GetProxyRunnable implements Runnable {
private volatile Proxy proxy; private volatile Proxy proxy;
private AppPreferences appPreferences; private final AppPreferences appPreferences;
GetProxyRunnable(AppPreferences appPreferences) { GetProxyRunnable(AppPreferences appPreferences) {
this.appPreferences = appPreferences; this.appPreferences = appPreferences;

View file

@ -9,9 +9,11 @@ package com.nextcloud.talk.dagger.modules
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import com.nextcloud.talk.account.viewmodels.BrowserLoginActivityViewModel
import com.nextcloud.talk.chat.viewmodels.ChatViewModel import com.nextcloud.talk.chat.viewmodels.ChatViewModel
import com.nextcloud.talk.chat.viewmodels.MessageInputViewModel import com.nextcloud.talk.chat.viewmodels.MessageInputViewModel
import com.nextcloud.talk.contacts.ContactsViewModel import com.nextcloud.talk.contacts.ContactsViewModel
import com.nextcloud.talk.contextchat.ContextChatViewModel
import com.nextcloud.talk.conversationcreation.ConversationCreationViewModel import com.nextcloud.talk.conversationcreation.ConversationCreationViewModel
import com.nextcloud.talk.conversationinfo.viewmodel.ConversationInfoViewModel import com.nextcloud.talk.conversationinfo.viewmodel.ConversationInfoViewModel
import com.nextcloud.talk.conversationinfoedit.viewmodel.ConversationInfoEditViewModel import com.nextcloud.talk.conversationinfoedit.viewmodel.ConversationInfoEditViewModel
@ -27,6 +29,7 @@ import com.nextcloud.talk.polls.viewmodels.PollVoteViewModel
import com.nextcloud.talk.raisehand.viewmodel.RaiseHandViewModel import com.nextcloud.talk.raisehand.viewmodel.RaiseHandViewModel
import com.nextcloud.talk.remotefilebrowser.viewmodels.RemoteFileBrowserItemsViewModel import com.nextcloud.talk.remotefilebrowser.viewmodels.RemoteFileBrowserItemsViewModel
import com.nextcloud.talk.shareditems.viewmodels.SharedItemsViewModel import com.nextcloud.talk.shareditems.viewmodels.SharedItemsViewModel
import com.nextcloud.talk.threadsoverview.viewmodels.ThreadsOverviewViewModel
import com.nextcloud.talk.translate.viewmodels.TranslateViewModel import com.nextcloud.talk.translate.viewmodels.TranslateViewModel
import com.nextcloud.talk.viewmodels.CallRecordingViewModel import com.nextcloud.talk.viewmodels.CallRecordingViewModel
import dagger.Binds import dagger.Binds
@ -154,4 +157,19 @@ abstract class ViewModelModule {
@IntoMap @IntoMap
@ViewModelKey(DiagnoseViewModel::class) @ViewModelKey(DiagnoseViewModel::class)
abstract fun diagnoseViewModel(viewModel: DiagnoseViewModel): ViewModel abstract fun diagnoseViewModel(viewModel: DiagnoseViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(ThreadsOverviewViewModel::class)
abstract fun threadsOverviewViewModel(viewModel: ThreadsOverviewViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(BrowserLoginActivityViewModel::class)
abstract fun browserLoginActivityViewModel(viewModel: BrowserLoginActivityViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(ContextChatViewModel::class)
abstract fun contextChatViewModel(viewModel: ContextChatViewModel): ViewModel
} }

View file

@ -25,43 +25,24 @@ interface ChatBlocksDao {
SELECT * SELECT *
FROM ChatBlocks FROM ChatBlocks
WHERE internalConversationId in (:internalConversationId) WHERE internalConversationId in (:internalConversationId)
ORDER BY newestMessageId ASC AND (threadId = :threadId OR (threadId IS NULL AND :threadId IS NULL))
"""
)
fun getChatBlocks(internalConversationId: String): Flow<List<ChatBlockEntity>>
// @Query(
// """
// SELECT *
// FROM ChatBlocks
// WHERE internalConversationId in (:internalConversationId)
// AND newestMessageId >= :messageId
// ORDER BY newestMessageId ASC
// """
// )
// fun getChatBlocksThatReachMessageId(
// internalConversationId: String,
// messageId: Long
// ):
// Flow<List<ChatBlockEntity>>
@Query(
"""
SELECT *
FROM ChatBlocks
WHERE internalConversationId in (:internalConversationId)
AND oldestMessageId <= :messageId AND oldestMessageId <= :messageId
AND newestMessageId >= :messageId AND newestMessageId >= :messageId
ORDER BY newestMessageId ASC ORDER BY newestMessageId ASC
""" """
) )
fun getChatBlocksContainingMessageId(internalConversationId: String, messageId: Long): Flow<List<ChatBlockEntity?>> fun getChatBlocksContainingMessageId(
internalConversationId: String,
threadId: Long?,
messageId: Long
): Flow<List<ChatBlockEntity?>>
@Query( @Query(
""" """
SELECT * SELECT *
FROM ChatBlocks FROM ChatBlocks
WHERE internalConversationId = :internalConversationId WHERE internalConversationId = :internalConversationId
AND (threadId = :threadId OR (threadId IS NULL AND :threadId IS NULL))
AND( AND(
(oldestMessageId <= :oldestMessageId AND newestMessageId >= :oldestMessageId) (oldestMessageId <= :oldestMessageId AND newestMessageId >= :oldestMessageId)
OR OR
@ -74,20 +55,23 @@ interface ChatBlocksDao {
) )
fun getConnectedChatBlocks( fun getConnectedChatBlocks(
internalConversationId: String, internalConversationId: String,
threadId: Long?,
oldestMessageId: Long, oldestMessageId: Long,
newestMessageId: Long newestMessageId: Long
): Flow<List<ChatBlockEntity>> ): Flow<List<ChatBlockEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertChatBlock(chatBlock: ChatBlockEntity)
@Query( @Query(
""" """
DELETE FROM ChatBlocks SELECT MAX(newestMessageId) as max_items
WHERE internalConversationId LIKE :pattern FROM ChatBlocks
WHERE internalConversationId = :internalConversationId
AND (threadId = :threadId OR (threadId IS NULL AND :threadId IS NULL))
""" """
) )
fun clearChatBlocksForUser(pattern: String) fun getNewestMessageIdFromChatBlocks(internalConversationId: String, threadId: Long?): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertChatBlock(chatBlock: ChatBlockEntity)
@Query( @Query(
""" """

View file

@ -18,16 +18,6 @@ import kotlinx.coroutines.flow.Flow
@Dao @Dao
@Suppress("Detekt.TooManyFunctions") @Suppress("Detekt.TooManyFunctions")
interface ChatMessagesDao { interface ChatMessagesDao {
@Query(
"""
SELECT MAX(id) as max_items
FROM ChatMessages
WHERE internalConversationId = :internalConversationId
AND isTemporary = 0
"""
)
fun getNewestMessageId(internalConversationId: String): Long
@Query( @Query(
""" """
SELECT * SELECT *
@ -57,10 +47,14 @@ interface ChatMessagesDao {
WHERE internalConversationId = :internalConversationId WHERE internalConversationId = :internalConversationId
AND isTemporary = 1 AND isTemporary = 1
AND sendStatus != 'SENT_PENDING_ACK' AND sendStatus != 'SENT_PENDING_ACK'
AND (:threadId IS NULL OR threadId = :threadId)
ORDER BY timestamp DESC, id DESC ORDER BY timestamp DESC, id DESC
""" """
) )
fun getTempUnsentMessagesForConversation(internalConversationId: String): Flow<List<ChatMessageEntity>> fun getTempUnsentMessagesForConversation(
internalConversationId: String,
threadId: Long?
): Flow<List<ChatMessageEntity>>
@Query( @Query(
""" """
@ -69,10 +63,15 @@ interface ChatMessagesDao {
WHERE internalConversationId = :internalConversationId WHERE internalConversationId = :internalConversationId
AND referenceId = :referenceId AND referenceId = :referenceId
AND isTemporary = 1 AND isTemporary = 1
AND (:threadId IS NULL OR threadId = :threadId)
ORDER BY timestamp DESC, id DESC ORDER BY timestamp DESC, id DESC
""" """
) )
fun getTempMessageForConversation(internalConversationId: String, referenceId: String): Flow<ChatMessageEntity?> fun getTempMessageForConversation(
internalConversationId: String,
referenceId: String,
threadId: Long?
): Flow<ChatMessageEntity?>
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertChatMessages(chatMessages: List<ChatMessageEntity>) suspend fun upsertChatMessages(chatMessages: List<ChatMessageEntity>)
@ -84,7 +83,8 @@ interface ChatMessagesDao {
""" """
SELECT * SELECT *
FROM ChatMessages FROM ChatMessages
WHERE internalConversationId = :internalConversationId AND id = :messageId WHERE internalConversationId = :internalConversationId
AND id = :messageId
""" """
) )
fun getChatMessageForConversation(internalConversationId: String, messageId: Long): Flow<ChatMessageEntity> fun getChatMessageForConversation(internalConversationId: String, messageId: Long): Flow<ChatMessageEntity>
@ -126,10 +126,15 @@ interface ChatMessagesDao {
FROM ChatMessages FROM ChatMessages
WHERE internalConversationId = :internalConversationId AND id >= :messageId WHERE internalConversationId = :internalConversationId AND id >= :messageId
AND isTemporary = 0 AND isTemporary = 0
AND (:threadId IS NULL OR threadId = :threadId)
ORDER BY timestamp ASC, id ASC ORDER BY timestamp ASC, id ASC
""" """
) )
fun getMessagesForConversationSince(internalConversationId: String, messageId: Long): Flow<List<ChatMessageEntity>> fun getMessagesForConversationSince(
internalConversationId: String,
messageId: Long,
threadId: Long?
): Flow<List<ChatMessageEntity>>
@Query( @Query(
""" """
@ -138,6 +143,7 @@ interface ChatMessagesDao {
WHERE internalConversationId = :internalConversationId WHERE internalConversationId = :internalConversationId
AND isTemporary = 0 AND isTemporary = 0
AND id < :messageId AND id < :messageId
AND (:threadId IS NULL OR threadId = :threadId)
ORDER BY timestamp DESC, id DESC ORDER BY timestamp DESC, id DESC
LIMIT :limit LIMIT :limit
""" """
@ -145,7 +151,8 @@ interface ChatMessagesDao {
fun getMessagesForConversationBefore( fun getMessagesForConversationBefore(
internalConversationId: String, internalConversationId: String,
messageId: Long, messageId: Long,
limit: Int limit: Int,
threadId: Long?
): Flow<List<ChatMessageEntity>> ): Flow<List<ChatMessageEntity>>
@Query( @Query(
@ -155,6 +162,7 @@ interface ChatMessagesDao {
WHERE internalConversationId = :internalConversationId WHERE internalConversationId = :internalConversationId
AND isTemporary = 0 AND isTemporary = 0
AND id <= :messageId AND id <= :messageId
AND (:threadId IS NULL OR threadId = :threadId)
ORDER BY timestamp DESC, id DESC ORDER BY timestamp DESC, id DESC
LIMIT :limit LIMIT :limit
""" """
@ -162,7 +170,8 @@ interface ChatMessagesDao {
fun getMessagesForConversationBeforeAndEqual( fun getMessagesForConversationBeforeAndEqual(
internalConversationId: String, internalConversationId: String,
messageId: Long, messageId: Long,
limit: Int limit: Int,
threadId: Long?
): Flow<List<ChatMessageEntity>> ): Flow<List<ChatMessageEntity>>
@Query( @Query(
@ -171,10 +180,16 @@ interface ChatMessagesDao {
FROM ChatMessages FROM ChatMessages
WHERE internalConversationId = :internalConversationId WHERE internalConversationId = :internalConversationId
AND isTemporary = 0 AND isTemporary = 0
AND (:threadId IS NULL OR threadId = :threadId)
AND id BETWEEN :newestMessageId AND :oldestMessageId AND id BETWEEN :newestMessageId AND :oldestMessageId
""" """
) )
fun getCountBetweenMessageIds(internalConversationId: String, oldestMessageId: Long, newestMessageId: Long): Int fun getCountBetweenMessageIds(
internalConversationId: String,
oldestMessageId: Long,
newestMessageId: Long,
threadId: Long?
): Int
@Query( @Query(
""" """
@ -192,4 +207,18 @@ interface ChatMessagesDao {
""" """
) )
fun deleteMessagesOlderThan(internalConversationId: String, messageId: Long) fun deleteMessagesOlderThan(internalConversationId: String, messageId: Long)
@Query(
"""
SELECT COUNT(*)
FROM ChatMessages AS child
INNER JOIN ChatMessages AS parent
ON child.parent = parent.id
WHERE child.internalConversationId = :internalConversationId
AND child.isTemporary = 0
AND child.messageType = 'comment'
AND parent.threadId = :threadId
"""
)
fun getNumberOfThreadReplies(internalConversationId: String, threadId: Long): Int
} }

View file

@ -8,11 +8,14 @@
package com.nextcloud.talk.data.database.dao package com.nextcloud.talk.data.database.dao
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update import androidx.room.Update
import androidx.room.Upsert
import com.nextcloud.talk.data.database.model.ConversationEntity import com.nextcloud.talk.data.database.model.ConversationEntity
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
@Dao @Dao
interface ConversationsDao { interface ConversationsDao {
@ -22,8 +25,19 @@ interface ConversationsDao {
@Query("SELECT * FROM Conversations where accountId = :accountId AND token = :token") @Query("SELECT * FROM Conversations where accountId = :accountId AND token = :token")
fun getConversationForUser(accountId: Long, token: String): Flow<ConversationEntity?> fun getConversationForUser(accountId: Long, token: String): Flow<ConversationEntity?>
@Upsert @Transaction
fun upsertConversations(conversationEntities: List<ConversationEntity>) suspend fun upsertConversations(accountId: Long, serverItems: List<ConversationEntity>) {
serverItems.forEach { serverItem ->
val existingItem = getConversationForUser(accountId, serverItem.token).first()
if (existingItem != null) {
val mergedItem = serverItem.copy()
mergedItem.messageDraft = existingItem.messageDraft
updateConversation(mergedItem)
} else {
insertConversation(serverItem)
}
}
}
/** /**
* Deletes rows in the db matching the specified [conversationIds] * Deletes rows in the db matching the specified [conversationIds]
@ -36,9 +50,12 @@ interface ConversationsDao {
) )
fun deleteConversations(conversationIds: List<String>) fun deleteConversations(conversationIds: List<String>)
@Update @Update(onConflict = REPLACE)
fun updateConversation(conversationEntity: ConversationEntity) fun updateConversation(conversationEntity: ConversationEntity)
@Insert(onConflict = REPLACE)
fun insertConversation(conversation: ConversationEntity)
@Query( @Query(
""" """
DELETE FROM Conversations DELETE FROM Conversations

View file

@ -19,6 +19,8 @@ fun ChatMessageJson.asEntity(accountId: Long) =
accountId = accountId, accountId = accountId,
id = id, id = id,
internalConversationId = "$accountId@$token", internalConversationId = "$accountId@$token",
threadId = threadId,
isThread = hasThread,
message = message!!, message = message!!,
token = token!!, token = token!!,
actorType = actorType!!, actorType = actorType!!,
@ -40,7 +42,9 @@ fun ChatMessageJson.asEntity(accountId: Long) =
lastEditTimestamp = lastEditTimestamp, lastEditTimestamp = lastEditTimestamp,
deleted = deleted, deleted = deleted,
referenceId = referenceId, referenceId = referenceId,
silent = silent silent = silent,
threadTitle = threadTitle,
threadReplies = threadReplies
) )
fun ChatMessageEntity.asModel() = fun ChatMessageEntity.asModel() =
@ -48,6 +52,8 @@ fun ChatMessageEntity.asModel() =
jsonMessageId = id.toInt(), jsonMessageId = id.toInt(),
message = message, message = message,
token = token, token = token,
threadId = threadId,
isThread = isThread,
actorType = actorType, actorType = actorType,
actorId = actorId, actorId = actorId,
actorDisplayName = actorDisplayName, actorDisplayName = actorDisplayName,
@ -70,7 +76,9 @@ fun ChatMessageEntity.asModel() =
isTemporary = isTemporary, isTemporary = isTemporary,
sendStatus = sendStatus, sendStatus = sendStatus,
readStatus = ReadStatus.NONE, readStatus = ReadStatus.NONE,
silent = silent silent = silent,
threadTitle = threadTitle,
threadReplies = threadReplies
) )
fun ChatMessageJson.asModel() = fun ChatMessageJson.asModel() =
@ -78,6 +86,8 @@ fun ChatMessageJson.asModel() =
jsonMessageId = id.toInt(), jsonMessageId = id.toInt(),
message = message, message = message,
token = token, token = token,
threadId = threadId,
isThread = hasThread,
actorType = actorType, actorType = actorType,
actorId = actorId, actorId = actorId,
actorDisplayName = actorDisplayName, actorDisplayName = actorDisplayName,
@ -97,5 +107,7 @@ fun ChatMessageJson.asModel() =
lastEditTimestamp = lastEditTimestamp, lastEditTimestamp = lastEditTimestamp,
isDeleted = deleted, isDeleted = deleted,
referenceId = referenceId, referenceId = referenceId,
silent = silent silent = silent,
threadTitle = threadTitle,
threadReplies = threadReplies
) )

View file

@ -1,7 +1,7 @@
/* /*
* Nextcloud Talk - Android Client * Nextcloud Talk - Android Client
* *
* SPDX-FileCopyrightText: 2024 Your Name <your@email.com> * SPDX-FileCopyrightText: 2024 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later * SPDX-License-Identifier: GPL-3.0-or-later
*/ */
@ -63,7 +63,8 @@ fun ConversationModel.asEntity() =
remoteToken = remoteToken, remoteToken = remoteToken,
hasArchived = hasArchived, hasArchived = hasArchived,
hasSensitive = hasSensitive, hasSensitive = hasSensitive,
hasImportant = hasImportant hasImportant = hasImportant,
messageDraft = messageDraft
) )
fun ConversationEntity.asModel() = fun ConversationEntity.asModel() =
@ -117,7 +118,8 @@ fun ConversationEntity.asModel() =
remoteToken = remoteToken, remoteToken = remoteToken,
hasArchived = hasArchived, hasArchived = hasArchived,
hasSensitive = hasSensitive, hasSensitive = hasSensitive,
hasImportant = hasImportant hasImportant = hasImportant,
messageDraft = messageDraft
) )
fun Conversation.asEntity(accountId: Long) = fun Conversation.asEntity(accountId: Long) =

View file

@ -35,6 +35,7 @@ data class ChatBlockEntity(
@ColumnInfo(name = "internalConversationId") var internalConversationId: String, @ColumnInfo(name = "internalConversationId") var internalConversationId: String,
@ColumnInfo(name = "accountId") var accountId: Long? = null, @ColumnInfo(name = "accountId") var accountId: Long? = null,
@ColumnInfo(name = "token") var token: String?, @ColumnInfo(name = "token") var token: String?,
@ColumnInfo(name = "threadId") var threadId: Long? = null,
@ColumnInfo(name = "oldestMessageId") var oldestMessageId: Long, @ColumnInfo(name = "oldestMessageId") var oldestMessageId: Long,
@ColumnInfo(name = "newestMessageId") var newestMessageId: Long, @ColumnInfo(name = "newestMessageId") var newestMessageId: Long,
@ColumnInfo(name = "hasHistory") var hasHistory: Boolean @ColumnInfo(name = "hasHistory") var hasHistory: Boolean

View file

@ -41,7 +41,8 @@ data class ChatMessageEntity(
@ColumnInfo(name = "id") var id: Long = 0, @ColumnInfo(name = "id") var id: Long = 0,
// accountId@roomtoken // accountId@roomtoken
@ColumnInfo(name = "internalConversationId") var internalConversationId: String, @ColumnInfo(name = "internalConversationId") var internalConversationId: String,
@ColumnInfo(name = "threadId") var threadId: Long? = null,
@ColumnInfo(name = "isThread") var isThread: Boolean = false,
@ColumnInfo(name = "actorDisplayName") var actorDisplayName: String, @ColumnInfo(name = "actorDisplayName") var actorDisplayName: String,
@ColumnInfo(name = "message") var message: String, @ColumnInfo(name = "message") var message: String,
@ -67,5 +68,7 @@ data class ChatMessageEntity(
@ColumnInfo(name = "sendStatus") var sendStatus: SendStatus? = null, @ColumnInfo(name = "sendStatus") var sendStatus: SendStatus? = null,
@ColumnInfo(name = "silent") var silent: Boolean = false, @ColumnInfo(name = "silent") var silent: Boolean = false,
@ColumnInfo(name = "systemMessage") var systemMessageType: ChatMessage.SystemMessageType, @ColumnInfo(name = "systemMessage") var systemMessageType: ChatMessage.SystemMessageType,
@ColumnInfo(name = "threadTitle") var threadTitle: String? = null,
@ColumnInfo(name = "threadReplies") var threadReplies: Int? = 0,
@ColumnInfo(name = "timestamp") var timestamp: Long = 0 @ColumnInfo(name = "timestamp") var timestamp: Long = 0
) )

View file

@ -13,6 +13,7 @@ import androidx.room.ForeignKey
import androidx.room.Index import androidx.room.Index
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import com.nextcloud.talk.data.user.model.UserEntity import com.nextcloud.talk.data.user.model.UserEntity
import com.nextcloud.talk.models.MessageDraft
import com.nextcloud.talk.models.json.conversations.ConversationEnums import com.nextcloud.talk.models.json.conversations.ConversationEnums
import com.nextcloud.talk.models.json.participants.Participant import com.nextcloud.talk.models.json.participants.Participant
@ -96,7 +97,8 @@ data class ConversationEntity(
@ColumnInfo(name = "unreadMessages") var unreadMessages: Int = 0, @ColumnInfo(name = "unreadMessages") var unreadMessages: Int = 0,
@ColumnInfo(name = "hasArchived") var hasArchived: Boolean = false, @ColumnInfo(name = "hasArchived") var hasArchived: Boolean = false,
@ColumnInfo(name = "hasSensitive") var hasSensitive: Boolean = false, @ColumnInfo(name = "hasSensitive") var hasSensitive: Boolean = false,
@ColumnInfo(name = "hasImportant") var hasImportant: Boolean = false @ColumnInfo(name = "hasImportant") var hasImportant: Boolean = false,
@ColumnInfo(name = "messageDraft") var messageDraft: MessageDraft? = MessageDraft()
// missing/not needed: attendeeId // missing/not needed: attendeeId
// missing/not needed: attendeePin // missing/not needed: attendeePin
// missing/not needed: attendeePermissions // missing/not needed: attendeePermissions

View file

@ -89,6 +89,17 @@ object Migrations {
} }
} }
val MIGRATION_17_19 = object : Migration(17, 19) {
override fun migrate(db: SupportSQLiteDatabase) {
Log.i(
"Migrations",
"Migrating 17 to 19 (migration 17 to 18 had bugs in app version v22.0.0 Alpha 11 and " +
"v22.0.0 Alpha 12)"
)
migrateToMessageThreads(db)
}
}
//endregion //endregion
fun migrateToRoom(db: SupportSQLiteDatabase) { fun migrateToRoom(db: SupportSQLiteDatabase) {
@ -297,7 +308,7 @@ object Migrations {
"ADD COLUMN hasArchived INTEGER NOT NULL DEFAULT 0;" "ADD COLUMN hasArchived INTEGER NOT NULL DEFAULT 0;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "hasArchived already exists") Log.i("Migrations", "hasArchived already exists", e)
} }
} }
@ -308,7 +319,7 @@ object Migrations {
"ADD COLUMN objectId TEXT NOT NULL DEFAULT '';" "ADD COLUMN objectId TEXT NOT NULL DEFAULT '';"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column objectId to table Conversations") Log.i("Migrations", "Something went wrong when adding column objectId to table Conversations", e)
} }
} }
@ -319,7 +330,7 @@ object Migrations {
"ADD COLUMN hasSensitive INTEGER NOT NULL DEFAULT 0;" "ADD COLUMN hasSensitive INTEGER NOT NULL DEFAULT 0;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column hasSensitive to table Conversations") Log.i("Migrations", "Something went wrong when adding column hasSensitive to table Conversations", e)
} }
} }
@ -330,7 +341,43 @@ object Migrations {
"ADD COLUMN hasImportant INTEGER NOT NULL DEFAULT 0;" "ADD COLUMN hasImportant INTEGER NOT NULL DEFAULT 0;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column hasImportant to table Conversations") Log.i("Migrations", "Something went wrong when adding column hasImportant to table Conversations", e)
}
}
fun migrateToMessageThreads(db: SupportSQLiteDatabase) {
try {
db.execSQL(
"ALTER TABLE ChatBlocks " +
"ADD COLUMN threadId INTEGER;"
)
db.execSQL(
"ALTER TABLE ChatMessages " +
"ADD COLUMN threadId INTEGER;"
)
db.execSQL(
"ALTER TABLE ChatMessages " +
"ADD COLUMN isThread INTEGER NOT NULL DEFAULT 0;"
)
// Foreign key constraints are not active during migration.
// At least db.execSQL("PRAGMA foreign_keys=ON;") etc did not help.
// Because of this it is not enough to just clear the Conversations table (to have cascade deletion in
// other tables), but all related tables have to be cleared with SQL statement as well.
db.execSQL(
"DELETE FROM Conversations"
)
db.execSQL(
"DELETE FROM ChatMessages"
)
db.execSQL(
"DELETE FROM ChatBlocks"
)
} catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when migrating to messageThreads", e)
} }
} }
@ -341,7 +388,7 @@ object Migrations {
"ADD COLUMN referenceId TEXT;" "ADD COLUMN referenceId TEXT;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column referenceId to table ChatMessages") Log.i("Migrations", "Something went wrong when adding column referenceId to table ChatMessages", e)
} }
try { try {
@ -350,7 +397,7 @@ object Migrations {
"ADD COLUMN isTemporary INTEGER NOT NULL DEFAULT 0;" "ADD COLUMN isTemporary INTEGER NOT NULL DEFAULT 0;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column isTemporary to table ChatMessages") Log.i("Migrations", "Something went wrong when adding column isTemporary to table ChatMessages", e)
} }
try { try {
@ -359,7 +406,7 @@ object Migrations {
"ADD COLUMN sendingFailed INTEGER NOT NULL DEFAULT 0;" "ADD COLUMN sendingFailed INTEGER NOT NULL DEFAULT 0;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column sendingFailed to table ChatMessages") Log.i("Migrations", "Something went wrong when adding column sendingFailed to table ChatMessages", e)
} }
try { try {
@ -368,7 +415,7 @@ object Migrations {
"ADD COLUMN silent INTEGER NOT NULL DEFAULT 0;" "ADD COLUMN silent INTEGER NOT NULL DEFAULT 0;"
) )
} catch (e: SQLException) { } catch (e: SQLException) {
Log.i("Migrations", "Something went wrong when adding column silent to table ChatMessages") Log.i("Migrations", "Something went wrong when adding column silent to table ChatMessages", e)
} }
} }
} }

View file

@ -36,6 +36,7 @@ import com.nextcloud.talk.data.storage.ArbitraryStoragesDao
import com.nextcloud.talk.data.storage.model.ArbitraryStorageEntity import com.nextcloud.talk.data.storage.model.ArbitraryStorageEntity
import com.nextcloud.talk.data.user.UsersDao import com.nextcloud.talk.data.user.UsersDao
import com.nextcloud.talk.data.user.model.UserEntity import com.nextcloud.talk.data.user.model.UserEntity
import com.nextcloud.talk.models.MessageDraftConverter
import net.zetetic.database.sqlcipher.SupportOpenHelperFactory import net.zetetic.database.sqlcipher.SupportOpenHelperFactory
import java.util.Locale import java.util.Locale
@ -47,10 +48,12 @@ import java.util.Locale
ChatMessageEntity::class, ChatMessageEntity::class,
ChatBlockEntity::class ChatBlockEntity::class
], ],
version = 17, version = 21,
autoMigrations = [ autoMigrations = [
AutoMigration(from = 9, to = 10), AutoMigration(from = 9, to = 10),
AutoMigration(from = 16, to = 17, spec = AutoMigration16To17::class) AutoMigration(from = 16, to = 17, spec = AutoMigration16To17::class),
AutoMigration(from = 19, to = 20),
AutoMigration(from = 20, to = 21)
], ],
exportSchema = true exportSchema = true
) )
@ -63,8 +66,10 @@ import java.util.Locale
HashMapHashMapConverter::class, HashMapHashMapConverter::class,
LinkedHashMapConverter::class, LinkedHashMapConverter::class,
ArrayListConverter::class, ArrayListConverter::class,
SendStatusConverter::class SendStatusConverter::class,
MessageDraftConverter::class
) )
@Suppress("MagicNumber")
abstract class TalkDatabase : RoomDatabase() { abstract class TalkDatabase : RoomDatabase() {
abstract fun usersDao(): UsersDao abstract fun usersDao(): UsersDao
abstract fun conversationsDao(): ConversationsDao abstract fun conversationsDao(): ConversationsDao
@ -85,6 +90,21 @@ abstract class TalkDatabase : RoomDatabase() {
instance ?: build(context).also { instance = it } instance ?: build(context).also { instance = it }
} }
// If editing the migrations, please add a test case in MigrationsTest under androidTest/data
val MIGRATIONS = arrayOf(
Migrations.MIGRATION_6_8,
Migrations.MIGRATION_7_8,
Migrations.MIGRATION_8_9,
Migrations.MIGRATION_10_11,
Migrations.MIGRATION_11_12,
Migrations.MIGRATION_12_13,
Migrations.MIGRATION_13_14,
Migrations.MIGRATION_14_15,
Migrations.MIGRATION_15_16,
Migrations.MIGRATION_17_19
)
@Suppress("SpreadOperator")
private fun build(context: Context): TalkDatabase { private fun build(context: Context): TalkDatabase {
val passCharArray = context.getString(R.string.nc_talk_database_encryption_key).toCharArray() val passCharArray = context.getString(R.string.nc_talk_database_encryption_key).toCharArray()
val passphrase: ByteArray = getBytesFromChars(passCharArray) val passphrase: ByteArray = getBytesFromChars(passCharArray)
@ -104,17 +124,8 @@ abstract class TalkDatabase : RoomDatabase() {
.databaseBuilder(context.applicationContext, TalkDatabase::class.java, dbName) .databaseBuilder(context.applicationContext, TalkDatabase::class.java, dbName)
// comment out openHelperFactory to view the database entries in Android Studio for debugging // comment out openHelperFactory to view the database entries in Android Studio for debugging
.openHelperFactory(factory) .openHelperFactory(factory)
.addMigrations( .fallbackToDestructiveMigrationFrom(true, 18)
Migrations.MIGRATION_6_8, .addMigrations(*MIGRATIONS) // * converts migrations to vararg
Migrations.MIGRATION_7_8,
Migrations.MIGRATION_8_9,
Migrations.MIGRATION_10_11,
Migrations.MIGRATION_11_12,
Migrations.MIGRATION_12_13,
Migrations.MIGRATION_13_14,
Migrations.MIGRATION_14_15,
Migrations.MIGRATION_15_16
)
.allowMainThreadQueries() .allowMainThreadQueries()
.addCallback( .addCallback(
object : Callback() { object : Callback() {

View file

@ -19,6 +19,7 @@ import android.widget.Toast
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.displayCutoutPadding
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.statusBarsPadding
@ -114,7 +115,8 @@ class DiagnoseActivity : BaseActivity() {
ColoredStatusBar() ColoredStatusBar()
Scaffold( Scaffold(
modifier = Modifier modifier = Modifier
.statusBarsPadding(), .statusBarsPadding()
.displayCutoutPadding(),
topBar = { topBar = {
StandardAppBar( StandardAppBar(
title = stringResource(R.string.nc_settings_diagnose_title), title = stringResource(R.string.nc_settings_diagnose_title),
@ -126,8 +128,13 @@ class DiagnoseActivity : BaseActivity() {
Column( Column(
Modifier Modifier
.padding(0.dp, paddingValues.calculateTopPadding(), 0.dp, 0.dp)
.background(backgroundColor) .background(backgroundColor)
.padding(
0.dp,
paddingValues.calculateTopPadding(),
0.dp,
paddingValues.calculateBottomPadding()
)
.fillMaxSize() .fillMaxSize()
) { ) {
DiagnoseContentComposable( DiagnoseContentComposable(

View file

@ -11,9 +11,18 @@
package com.nextcloud.talk.extensions package com.nextcloud.talk.extensions
import android.content.Context import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas import android.graphics.Canvas
import android.graphics.Color import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Matrix
import android.graphics.Paint import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable import android.graphics.drawable.LayerDrawable
import android.util.Log import android.util.Log
@ -21,6 +30,7 @@ import android.widget.ImageView
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.createBitmap import androidx.core.graphics.createBitmap
import androidx.core.graphics.drawable.toBitmap
import androidx.core.graphics.drawable.toDrawable import androidx.core.graphics.drawable.toDrawable
import coil.annotation.ExperimentalCoilApi import coil.annotation.ExperimentalCoilApi
import coil.imageLoader import coil.imageLoader
@ -42,6 +52,7 @@ import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.DisplayUtils import com.nextcloud.talk.utils.DisplayUtils
import com.nextcloud.talk.utils.TextDrawable import com.nextcloud.talk.utils.TextDrawable
import java.util.Locale import java.util.Locale
import kotlin.math.min
private const val ROUNDING_PIXEL = 16f private const val ROUNDING_PIXEL = 16f
private const val TAG = "ImageViewExtensions" private const val TAG = "ImageViewExtensions"
@ -291,18 +302,12 @@ fun ImageView.loadSystemAvatar(): io.reactivex.disposables.Disposable {
) )
} }
fun ImageView.loadNoteToSelfAvatar(): io.reactivex.disposables.Disposable { fun ImageView.loadNoteToSelfAvatar() {
val layers = arrayOfNulls<Drawable>(2) val layers = arrayOfNulls<Drawable>(2)
layers[0] = ContextCompat.getDrawable(context, R.drawable.ic_launcher_background) layers[0] = ContextCompat.getDrawable(context, R.drawable.ic_launcher_background)
layers[1] = ContextCompat.getDrawable(context, R.drawable.ic_note_to_self) layers[1] = ContextCompat.getDrawable(context, R.drawable.ic_note_to_self)
val layerDrawable = LayerDrawable(layers) val layerDrawable = LayerDrawable(layers)
val data: Any = layerDrawable setImageDrawable(CircularDrawable(layerDrawable))
return DisposableWrapper(
load(data) {
transformations(CircleCropTransformation())
}
)
} }
fun ImageView.loadFirstLetterAvatar(name: String): io.reactivex.disposables.Disposable { fun ImageView.loadFirstLetterAvatar(name: String): io.reactivex.disposables.Disposable {
@ -416,3 +421,77 @@ private class DisposableWrapper(private val disposable: coil.request.Disposable)
override fun isDisposed(): Boolean = disposable.isDisposed override fun isDisposed(): Boolean = disposable.isDisposed
} }
private class CircularDrawable(private val sourceDrawable: Drawable) : Drawable() {
private val bitmap: Bitmap = drawableToBitmap(sourceDrawable)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
}
private val rect = RectF()
private var radius = 0f
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
rect.set(bounds)
radius = min(rect.width() / 2.0f, rect.height() / 2.0f)
val matrix = Matrix()
val scale: Float
var dx = 0f
var dy = 0f
if (bitmap.width * rect.height() > rect.width() * bitmap.height) {
// Taller than wide, scale to height and center horizontally
scale = rect.height() / bitmap.height.toFloat()
dx = (rect.width() - bitmap.width * scale) / 2.0f
} else {
// Wider than tall, scale to width and center vertically
scale = rect.width() / bitmap.width.toFloat()
dy = (rect.height() - bitmap.height * scale) / 2.0f
}
matrix.setScale(scale, scale)
matrix.postTranslate(dx.toInt().toFloat() + rect.left, dy.toInt().toFloat() + rect.top)
paint.shader.setLocalMatrix(matrix)
}
override fun draw(canvas: Canvas) {
canvas.drawCircle(rect.centerX(), rect.centerY(), radius, paint)
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
}
@Deprecated(
"This method is no longer used in graphics optimizations",
ReplaceWith("PixelFormat.TRANSLUCENT", "android.graphics.PixelFormat")
)
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
override fun getIntrinsicWidth(): Int = sourceDrawable.intrinsicWidth
override fun getIntrinsicHeight(): Int = sourceDrawable.intrinsicHeight
companion object {
private fun drawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
if (drawable.bitmap != null) {
return drawable.bitmap
}
}
val width = if (drawable.intrinsicWidth > 0) drawable.intrinsicWidth else 1
val height = if (drawable.intrinsicHeight > 0) drawable.intrinsicHeight else 1
return drawable.toBitmap(width, height, Bitmap.Config.ARGB_8888)
}
}
}

View file

@ -1,7 +1,7 @@
/* /*
* Nextcloud Talk - Android Client * Nextcloud Talk - Android Client
* *
* SPDX-FileCopyrightText: 2021-2023 Marcel Hibbe <dev@mhibbe.de> * SPDX-FileCopyrightText: 2021-2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-FileCopyrightText: 2022 Andy Scherzinger <info@andy-scherzinger.de> * SPDX-FileCopyrightText: 2022 Andy Scherzinger <info@andy-scherzinger.de>
* SPDX-FileCopyrightText: 2017-2018 Mario Danic <mario@lovelyhq.com> * SPDX-FileCopyrightText: 2017-2018 Mario Danic <mario@lovelyhq.com>
* SPDX-License-Identifier: GPL-3.0-or-later * SPDX-License-Identifier: GPL-3.0-or-later
@ -85,6 +85,8 @@ import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ROOM_ONE_TO_ONE
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ROOM_TOKEN import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_ROOM_TOKEN
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SHARE_RECORDING_TO_CHAT_URL import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SHARE_RECORDING_TO_CHAT_URL
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SYSTEM_NOTIFICATION_ID import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_SYSTEM_NOTIFICATION_ID
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_THREAD_ID
import com.nextcloud.talk.utils.bundle.BundleKeys.KEY_OPENED_VIA_NOTIFICATION
import com.nextcloud.talk.utils.preferences.AppPreferences import com.nextcloud.talk.utils.preferences.AppPreferences
import io.reactivex.Observable import io.reactivex.Observable
import io.reactivex.Observer import io.reactivex.Observer
@ -134,8 +136,6 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
private lateinit var signatureVerification: SignatureVerification private lateinit var signatureVerification: SignatureVerification
private var context: Context? = null private var context: Context? = null
private var conversationType: String? = "one2one" private var conversationType: String? = "one2one"
private var muteCall = false
private var importantConversation = false
private lateinit var notificationManager: NotificationManagerCompat private lateinit var notificationManager: NotificationManagerCompat
override fun doWork(): Result { override fun doWork(): Result {
@ -186,7 +186,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
private fun handleTestPushMessage() { private fun handleTestPushMessage() {
val intent = Intent(context, MainActivity::class.java) val intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK intent.flags = getIntentFlags()
showNotification(intent, null) showNotification(intent, null)
} }
@ -201,7 +201,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
private fun handleRemoteTalkSharePushMessage() { private fun handleRemoteTalkSharePushMessage() {
val mainActivityIntent = Intent(context, MainActivity::class.java) val mainActivityIntent = Intent(context, MainActivity::class.java)
mainActivityIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK mainActivityIntent.flags = getIntentFlags()
val bundle = Bundle() val bundle = Bundle()
bundle.putLong(KEY_INTERNAL_USER_ID, signatureVerification.user!!.id!!) bundle.putLong(KEY_INTERNAL_USER_ID, signatureVerification.user!!.id!!)
bundle.putBoolean(KEY_REMOTE_TALK_SHARE, true) bundle.putBoolean(KEY_REMOTE_TALK_SHARE, true)
@ -255,7 +255,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
val bundle = createBundle(conversation) val bundle = createBundle(conversation)
fullScreenIntent.putExtras(bundle) fullScreenIntent.putExtras(bundle)
fullScreenIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK fullScreenIntent.flags = getIntentFlags()
val requestCode = System.currentTimeMillis().toInt() val requestCode = System.currentTimeMillis().toInt()
@ -399,6 +399,10 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
val ncNotification = notificationOverall.ocs!!.notification val ncNotification = notificationOverall.ocs!!.notification
if (ncNotification != null) { if (ncNotification != null) {
enrichPushMessageByNcNotificationData(ncNotification) enrichPushMessageByNcNotificationData(ncNotification)
val threadId = parseThreadId(ncNotification.objectId)
threadId?.let { intent.putExtra(KEY_THREAD_ID, it) }
showNotification(intent, ncNotification) showNotification(intent, ncNotification)
} }
} }
@ -425,7 +429,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
pushMessage.timestamp = ncNotification.datetime!!.millis pushMessage.timestamp = ncNotification.datetime!!.millis
if (ncNotification.messageRichParameters != null && if (ncNotification.messageRichParameters != null &&
ncNotification.messageRichParameters!!.size > 0 ncNotification.messageRichParameters!!.isNotEmpty()
) { ) {
pushMessage.text = getParsedMessage( pushMessage.text = getParsedMessage(
ncNotification.messageRich, ncNotification.messageRich,
@ -436,11 +440,11 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
} }
val subjectRichParameters = ncNotification.subjectRichParameters val subjectRichParameters = ncNotification.subjectRichParameters
if (subjectRichParameters != null && subjectRichParameters.size > 0) { if (subjectRichParameters != null && subjectRichParameters.isNotEmpty()) {
val callHashMap = subjectRichParameters["call"] val callHashMap = subjectRichParameters["call"]
val userHashMap = subjectRichParameters["user"] val userHashMap = subjectRichParameters["user"]
val guestHashMap = subjectRichParameters["guest"] val guestHashMap = subjectRichParameters["guest"]
if (callHashMap != null && callHashMap.size > 0 && callHashMap.containsKey("name")) { if (callHashMap != null && callHashMap.isNotEmpty() && callHashMap.containsKey("name")) {
if (subjectRichParameters.containsKey("reaction")) { if (subjectRichParameters.containsKey("reaction")) {
pushMessage.subject = "" pushMessage.subject = ""
} else if (ncNotification.objectType == "chat") { } else if (ncNotification.objectType == "chat") {
@ -490,15 +494,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
else -> Log.e(TAG, "unknown pushMessage.type") else -> Log.e(TAG, "unknown pushMessage.type")
} }
// Use unique request code to make sure that a new PendingIntent gets created for each notification val pendingIntent = createUniquePendingIntent(intent)
// See https://github.com/nextcloud/talk-android/issues/2111
val requestCode = System.currentTimeMillis().toInt()
val intentFlag: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_MUTABLE
} else {
0
}
val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, intentFlag)
val uri = signatureVerification.user!!.baseUrl!!.toUri() val uri = signatureVerification.user!!.baseUrl!!.toUri()
val baseUrl = uri.host val baseUrl = uri.host
@ -530,7 +526,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
if ((TYPE_CHAT == pushMessage.type || TYPE_REMINDER == pushMessage.type) && if ((TYPE_CHAT == pushMessage.type || TYPE_REMINDER == pushMessage.type) &&
pushMessage.notificationUser != null pushMessage.notificationUser != null
) { ) {
prepareChatNotification(notificationBuilder, activeStatusBarNotification, systemNotificationId) prepareChatNotification(notificationBuilder, activeStatusBarNotification)
addReplyAction(notificationBuilder, systemNotificationId) addReplyAction(notificationBuilder, systemNotificationId)
addMarkAsReadAction(notificationBuilder, systemNotificationId) addMarkAsReadAction(notificationBuilder, systemNotificationId)
} }
@ -636,8 +632,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
private fun prepareChatNotification( private fun prepareChatNotification(
notificationBuilder: NotificationCompat.Builder, notificationBuilder: NotificationCompat.Builder,
activeStatusBarNotification: StatusBarNotification?, activeStatusBarNotification: StatusBarNotification?
systemNotificationId: Int
) { ) {
val notificationUser = pushMessage.notificationUser val notificationUser = pushMessage.notificationUser
val userType = notificationUser!!.type val userType = notificationUser!!.type
@ -838,6 +833,8 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
} }
} }
private fun parseThreadId(objectId: String?): Long? = objectId?.split("/")?.getOrNull(2)?.toLongOrNull()
private fun sendNotification(notificationId: Int, notification: Notification) { private fun sendNotification(notificationId: Int, notification: Notification) {
Log.d(TAG, "show notification with id $notificationId") Log.d(TAG, "show notification with id $notificationId")
if (ActivityCompat.checkSelfPermission( if (ActivityCompat.checkSelfPermission(
@ -947,14 +944,14 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
) )
if (isOngoingCallNotificationVisible) { if (isOngoingCallNotificationVisible) {
val notificationBuilder: NotificationCompat.Builder? val notificationBuilder = NotificationCompat.Builder(
notificationBuilder = NotificationCompat.Builder(
context!!, context!!,
NotificationUtils.NotificationChannels NotificationUtils.NotificationChannels
.NOTIFICATION_CHANNEL_MESSAGES_V4.name .NOTIFICATION_CHANNEL_MESSAGES_V4.name
) )
val intent = createMainActivityIntent()
val notification: Notification = notificationBuilder val notification: Notification = notificationBuilder
.setContentTitle( .setContentTitle(
String.format( String.format(
@ -966,7 +963,7 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
.setOngoing(false) .setOngoing(false)
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_LOW) .setPriority(NotificationCompat.PRIORITY_LOW)
.setContentIntent(getIntentToOpenConversation()) .setContentIntent(createUniquePendingIntent(intent))
.build() .build()
val notificationId: Int = SystemClock.uptimeMillis().toInt() val notificationId: Int = SystemClock.uptimeMillis().toInt()
@ -989,31 +986,29 @@ class NotificationWorker(context: Context, workerParams: WorkerParameters) : Wor
private fun createMainActivityIntent(): Intent { private fun createMainActivityIntent(): Intent {
val intent = Intent(context, MainActivity::class.java) val intent = Intent(context, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK intent.flags = getIntentFlags()
val bundle = Bundle() val bundle = Bundle()
bundle.putString(KEY_ROOM_TOKEN, pushMessage.id) bundle.putString(KEY_ROOM_TOKEN, pushMessage.id)
bundle.putLong(KEY_INTERNAL_USER_ID, signatureVerification.user!!.id!!) bundle.putLong(KEY_INTERNAL_USER_ID, signatureVerification.user!!.id!!)
bundle.putBoolean(KEY_OPENED_VIA_NOTIFICATION, true)
intent.putExtras(bundle) intent.putExtras(bundle)
return intent return intent
} }
private fun getIntentToOpenConversation(): PendingIntent? { private fun createUniquePendingIntent(intent: Intent): PendingIntent? {
val intent = Intent(context, MainActivity::class.java) // Use unique request code to make sure that a new PendingIntent gets created for each notification
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK // See https://github.com/nextcloud/talk-android/issues/2111
val bundle = Bundle()
bundle.putString(KEY_ROOM_TOKEN, pushMessage.id)
bundle.putLong(KEY_INTERNAL_USER_ID, signatureVerification.user!!.id!!)
intent.putExtras(bundle)
val requestCode = System.currentTimeMillis().toInt() val requestCode = System.currentTimeMillis().toInt()
val intentFlag: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val intentFlag: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_MUTABLE PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else { } else {
0 PendingIntent.FLAG_UPDATE_CURRENT
} }
return PendingIntent.getActivity(context, requestCode, intent, intentFlag) return PendingIntent.getActivity(context, requestCode, intent, intentFlag)
} }
private fun getIntentFlags(): Int = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
companion object { companion object {
val TAG = NotificationWorker::class.simpleName val TAG = NotificationWorker::class.simpleName
private const val TYPE_CHAT = "chat" private const val TYPE_CHAT = "chat"

View file

@ -166,6 +166,7 @@ class MessageSearchActivity : BaseActivity() {
if (state is MessageSearchViewModel.FinishedState) { if (state is MessageSearchViewModel.FinishedState) {
val resultIntent = Intent().apply { val resultIntent = Intent().apply {
putExtra(RESULT_KEY_MESSAGE_ID, state.selectedMessageId) putExtra(RESULT_KEY_MESSAGE_ID, state.selectedMessageId)
putExtra(RESULT_KEY_THREAD_ID, state.selectedThreadId)
} }
setResult(Activity.RESULT_OK, resultIntent) setResult(Activity.RESULT_OK, resultIntent)
finish() finish()
@ -244,5 +245,6 @@ class MessageSearchActivity : BaseActivity() {
companion object { companion object {
const val RESULT_KEY_MESSAGE_ID = "MessageSearchActivity.result.message" const val RESULT_KEY_MESSAGE_ID = "MessageSearchActivity.result.message"
const val RESULT_KEY_THREAD_ID = "MessageSearchActivity.result.thread"
} }
} }

View file

@ -42,7 +42,7 @@ class MessageSearchViewModel @Inject constructor(private val unifiedSearchReposi
object EmptyState : ViewState() object EmptyState : ViewState()
object ErrorState : ViewState() object ErrorState : ViewState()
class LoadedState(val results: List<SearchMessageEntry>, val hasMore: Boolean) : ViewState() class LoadedState(val results: List<SearchMessageEntry>, val hasMore: Boolean) : ViewState()
class FinishedState(val selectedMessageId: String) : ViewState() class FinishedState(val selectedMessageId: String, val selectedThreadId: String?) : ViewState()
private lateinit var messageSearchHelper: MessageSearchHelper private lateinit var messageSearchHelper: MessageSearchHelper
@ -95,7 +95,7 @@ class MessageSearchViewModel @Inject constructor(private val unifiedSearchReposi
} }
fun selectMessage(messageEntry: SearchMessageEntry) { fun selectMessage(messageEntry: SearchMessageEntry) {
_state.value = FinishedState(messageEntry.messageId!!) _state.value = FinishedState(messageEntry.messageId!!, messageEntry.threadId)
} }
companion object { companion object {

View file

@ -0,0 +1,57 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Julius Linus <juliuslinus1@gmail.com>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.models
import android.os.Parcelable
import androidx.room.TypeConverter
import com.bluelinelabs.logansquare.LoganSquare
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Serializable
@Parcelize
@JsonObject
@Serializable
data class MessageDraft(
@JsonField(name = ["messageText"])
var messageText: String = "",
@JsonField(name = ["messageCursor"])
var messageCursor: Int = 0,
@JsonField(name = ["quotedJsonId"])
var quotedJsonId: Int? = null,
@JsonField(name = ["quotedDisplayName"])
var quotedDisplayName: String? = null,
@JsonField(name = ["quotedMessageText"])
var quotedMessageText: String? = null,
@JsonField(name = ["quoteImageUrl"])
var quotedImageUrl: String? = null,
@JsonField(name = ["threadTitle"])
var threadTitle: String? = null
) : Parcelable {
constructor() : this("", 0, null, null, null, null, null)
}
class MessageDraftConverter {
@TypeConverter
fun fromMessageDraftToString(messageDraft: MessageDraft?): String =
if (messageDraft == null) {
""
} else {
LoganSquare.serialize(messageDraft)
}
@TypeConverter
fun fromStringToMessageDraft(value: String): MessageDraft? =
if (value.isBlank()) {
null
} else {
LoganSquare.parse(value, MessageDraft::class.java)
}
}

View file

@ -8,12 +8,13 @@
package com.nextcloud.talk.models.domain package com.nextcloud.talk.models.domain
import com.nextcloud.talk.data.user.model.User import com.nextcloud.talk.data.user.model.User
import com.nextcloud.talk.models.MessageDraft
import com.nextcloud.talk.models.json.chat.ChatMessageJson import com.nextcloud.talk.models.json.chat.ChatMessageJson
import com.nextcloud.talk.models.json.conversations.Conversation import com.nextcloud.talk.models.json.conversations.Conversation
import com.nextcloud.talk.models.json.conversations.ConversationEnums import com.nextcloud.talk.models.json.conversations.ConversationEnums
import com.nextcloud.talk.models.json.participants.Participant import com.nextcloud.talk.models.json.participants.Participant
class ConversationModel( data class ConversationModel(
var internalId: String, var internalId: String,
var accountId: Long, var accountId: Long,
var token: String, var token: String,
@ -65,7 +66,8 @@ class ConversationModel(
var hasImportant: Boolean = false, var hasImportant: Boolean = false,
// attributes that don't come from API. This should be changed?! // attributes that don't come from API. This should be changed?!
var password: String? = null var password: String? = null,
var messageDraft: MessageDraft? = MessageDraft()
) { ) {
companion object { companion object {

View file

@ -13,5 +13,6 @@ data class SearchMessageEntry(
val title: String, val title: String,
val messageExcerpt: String, val messageExcerpt: String,
val conversationToken: String, val conversationToken: String,
val threadId: String?,
val messageId: String? val messageId: String?
) )

View file

@ -19,6 +19,12 @@ import kotlinx.parcelize.Parcelize
data class ChatMessageJson( data class ChatMessageJson(
@JsonField(name = ["id"]) var id: Long = 0, @JsonField(name = ["id"]) var id: Long = 0,
@JsonField(name = ["token"]) var token: String? = null, @JsonField(name = ["token"]) var token: String? = null,
@JsonField(name = ["threadId"]) var threadId: Long? = null,
// Be aware that variables with "is" at the beginning will lead to the error:
// "@JsonField annotation can only be used on private fields if both getter and setter are present."
// Instead, name it with "has" at the beginning: isThread -> hasThread
@JsonField(name = ["isThread"]) var hasThread: Boolean = false,
@JsonField(name = ["actorType"]) var actorType: String? = null, @JsonField(name = ["actorType"]) var actorType: String? = null,
@JsonField(name = ["actorId"]) var actorId: String? = null, @JsonField(name = ["actorId"]) var actorId: String? = null,
@JsonField(name = ["actorDisplayName"]) var actorDisplayName: String? = null, @JsonField(name = ["actorDisplayName"]) var actorDisplayName: String? = null,
@ -44,5 +50,7 @@ data class ChatMessageJson(
@JsonField(name = ["lastEditTimestamp"]) var lastEditTimestamp: Long? = 0, @JsonField(name = ["lastEditTimestamp"]) var lastEditTimestamp: Long? = 0,
@JsonField(name = ["deleted"]) var deleted: Boolean = false, @JsonField(name = ["deleted"]) var deleted: Boolean = false,
@JsonField(name = ["referenceId"]) var referenceId: String? = null, @JsonField(name = ["referenceId"]) var referenceId: String? = null,
@JsonField(name = ["silent"]) var silent: Boolean = false @JsonField(name = ["silent"]) var silent: Boolean = false,
@JsonField(name = ["threadTitle"]) var threadTitle: String? = null,
@JsonField(name = ["threadReplies"]) var threadReplies: Int? = 0
) : Parcelable ) : Parcelable

View file

@ -1,7 +1,7 @@
/* /*
* Nextcloud Talk - Android Client * Nextcloud Talk - Android Client
* *
* SPDX-FileCopyrightText: 2024 Your Name <your@email.com> * SPDX-FileCopyrightText: 2024 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later * SPDX-License-Identifier: GPL-3.0-or-later
*/ */

View file

@ -72,6 +72,7 @@ import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.RECORDIN
import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.USER_ADDED import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.USER_ADDED
import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.USER_REMOVED import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.USER_REMOVED
import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.PHONE_ADDED import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.PHONE_ADDED
import com.nextcloud.talk.chat.data.model.ChatMessage.SystemMessageType.THREAD_CREATED
/* /*
* see https://nextcloud-talk.readthedocs.io/en/latest/chat/#system-messages * see https://nextcloud-talk.readthedocs.io/en/latest/chat/#system-messages
@ -143,6 +144,7 @@ class EnumSystemMessageTypeConverter : StringBasedTypeConverter<ChatMessage.Syst
"federated_user_added" -> FEDERATED_USER_ADDED "federated_user_added" -> FEDERATED_USER_ADDED
"federated_user_removed" -> FEDERATED_USER_REMOVED "federated_user_removed" -> FEDERATED_USER_REMOVED
"phone_added" -> PHONE_ADDED "phone_added" -> PHONE_ADDED
"thread_created" -> THREAD_CREATED
else -> DUMMY else -> DUMMY
} }
@ -212,6 +214,7 @@ class EnumSystemMessageTypeConverter : StringBasedTypeConverter<ChatMessage.Syst
FEDERATED_USER_ADDED -> "federated_user_added" FEDERATED_USER_ADDED -> "federated_user_added"
FEDERATED_USER_REMOVED -> "federated_user_removed" FEDERATED_USER_REMOVED -> "federated_user_removed"
PHONE_ADDED -> "phone_added" PHONE_ADDED -> "phone_added"
THREAD_CREATED -> "thread_created"
else -> "" else -> ""
} }
} }

View file

@ -11,5 +11,6 @@ enum class StatusType(val string: String) {
OFFLINE("offline"), OFFLINE("offline"),
DND("dnd"), DND("dnd"),
AWAY("away"), AWAY("away"),
BUSY("busy"),
INVISIBLE("invisible") INVISIBLE("invisible")
} }

View file

@ -0,0 +1,34 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.models.json.threads
import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import kotlinx.parcelize.Parcelize
@Parcelize
@JsonObject
data class Thread(
@JsonField(name = ["id"])
var id: Int = 0,
@JsonField(name = ["roomToken"])
var roomToken: String = "",
@JsonField(name = ["title"])
var title: String = "",
@JsonField(name = ["lastMessageId"])
var lastMessageId: Int = 0,
@JsonField(name = ["lastActivity"])
var lastActivity: Int = 0,
@JsonField(name = ["numReplies"])
var numReplies: Int = 0
) : Parcelable

View file

@ -0,0 +1,19 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.models.json.threads
import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import kotlinx.parcelize.Parcelize
@Parcelize
@JsonObject
data class ThreadAttendee(
@JsonField(name = ["notificationLevel"])
var notificationLevel: Int = 0
) : Parcelable

View file

@ -0,0 +1,29 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.models.json.threads
import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import com.nextcloud.talk.models.json.chat.ChatMessageJson
import kotlinx.parcelize.Parcelize
@Parcelize
@JsonObject
data class ThreadInfo(
@JsonField(name = ["thread"])
var thread: Thread? = null,
@JsonField(name = ["attendee"])
var attendee: ThreadAttendee? = null,
@JsonField(name = ["first"])
var first: ChatMessageJson? = null,
@JsonField(name = ["last"])
var last: ChatMessageJson? = null
) : Parcelable

View file

@ -0,0 +1,25 @@
/*
* Nextcloud Talk - Android Client
*
* SPDX-FileCopyrightText: 2025 Marcel Hibbe <dev@mhibbe.de>
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package com.nextcloud.talk.models.json.threads
import android.os.Parcelable
import com.bluelinelabs.logansquare.annotation.JsonField
import com.bluelinelabs.logansquare.annotation.JsonObject
import com.nextcloud.talk.models.json.generic.GenericMeta
import kotlinx.parcelize.Parcelize
@Parcelize
@JsonObject
data class ThreadOCS(
@JsonField(name = ["meta"])
var meta: GenericMeta?,
@JsonField(name = ["data"])
var data: ThreadInfo? = null
) : Parcelable {
// This constructor is added to work with the 'com.bluelinelabs.logansquare.annotation.JsonObject'
constructor() : this(null, null)
}

Some files were not shown because too many files have changed in this diff Show more