commit a66a83c0fdb9ebd945e77dc0b588997deab13e31 Author: ChronosX88 Date: Sun May 19 15:29:02 2019 +0400 [WIP] Migrating to XMPP, added XMPPConnectionService, LoginActivity diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..09b993d --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +/local.properties +/.idea +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..7ac24c7 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..cc04cd3 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. 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 +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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. 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. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + + Copyright (C) + + 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program 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, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..cbec78b --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +

+

Influence

+

+ This is a decentralized messenger for Android, which work on top of TomP2P DHT. +

+

+ + +
+ +## Table of Contents + +- [Intro](#intro) +- [Getting started](#getting-started) +- [Features](#features) +- [Useful links](#useful-links) +- [License](#license) +- [Author](#author) + +## Intro +*[Soon]* + + +## Getting started +1. Clone repo: +```bash +$ git clone https://github.com/ChronosX88/Influence-android +$ cd Influence-android +``` +2. Simply open project in Android Studio. + +(Also exists precompiled APKs - see Releases) + +[⇧ back to top](#contents) + +## Features +- 1:1 chats +- Decentralized message storage +- Username system +- Group chats [Soon] +- Encryption [Soon] +- Channels (like Telegram) [Soon] +- Profile pictures [Soon] + +[⇧ back to top](#contents) + +## Useful links + +- [TomP2P GitHub](https://github.com/tomp2p/TomP2P) + +[⇧ back to top](#contents) + +## License + +This project is licensed under the GNU GPLv3 License - see the [LICENSE](LICENSE) file for details. + +[⇧ back to top](#contents) + +## Author + +```txt +Author : ChronosX88 +Email : chronosx88@gmail.com +Github : https://github.com/ChronosX88/Influence-android.git +``` + +[![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) + +[⇧ back to top](#contents) diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..f309182 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,70 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android-extensions' +apply plugin: 'kotlin-android' + +android { + compileSdkVersion 28 + defaultConfig { + applicationId "io.github.chronosx88.influence" + minSdkVersion 19 + targetSdkVersion 28 + versionCode 1 + versionName "0.1alpha4" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + multiDexEnabled true + javaCompileOptions { + annotationProcessorOptions { + arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] + } + } + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + packagingOptions { + exclude 'META-INF/INDEX.LIST' + exclude 'META-INF/io.netty.versions.properties' + exclude 'LICENSE-EPL-1.0.txt' + exclude 'LICENSE-EDL-1.0.txt' + exclude 'META-INF/atomicfu.kotlin_module' + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation 'androidx.appcompat:appcompat:1.1.0-alpha02' + implementation "androidx.room:room-runtime:2.1.0-alpha04" + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' + annotationProcessor "androidx.room:room-compiler:2.1.0-alpha04" + implementation 'org.slf4j:slf4j-log4j12:1.7.26' + implementation('net.tomp2p:tomp2p-all:5.0-Beta8') { + exclude group: 'net.tomp2p', module: 'tomp2p-storage' + } + implementation 'com.google.android.material:material:1.1.0-alpha04' + implementation 'androidx.preference:preference:1.1.0-alpha03' + implementation 'com.google.code.gson:gson:2.8.5' + implementation 'de.hdodenhof:circleimageview:3.0.0' + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation 'com.android.support:multidex:1.0.3' + implementation "org.jetbrains.anko:anko:0.10.8" + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.0' + implementation 'com.esotericsoftware:kryo:5.0.0-RC1' + + implementation 'com.github.instacart.truetime-android:library:3.4' + implementation 'org.igniterealtime.smack:smack-core:4.3.3' + implementation 'org.igniterealtime.smack:smack-tcp:4.3.3' + implementation 'org.igniterealtime.smack:smack-android:4.3.3' + implementation 'org.igniterealtime.smack:smack-extensions:4.3.3' + +} +repositories { + mavenCentral() +} diff --git a/app/libs/je-android-5.0.104.jar b/app/libs/je-android-5.0.104.jar new file mode 100644 index 0000000..342a4aa Binary files /dev/null and b/app/libs/je-android-5.0.104.jar differ diff --git a/app/libs/trove.jar b/app/libs/trove.jar new file mode 100644 index 0000000..ac62eb3 Binary files /dev/null and b/app/libs/trove.jar differ diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/schemas/io.github.chronosx88.influence.helpers.RoomHelper/2.json b/app/schemas/io.github.chronosx88.influence.helpers.RoomHelper/2.json new file mode 100644 index 0000000..31a7610 --- /dev/null +++ b/app/schemas/io.github.chronosx88.influence.helpers.RoomHelper/2.json @@ -0,0 +1,132 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "81501115d10a6dc46002667323359631", + "entities": [ + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`messageID` TEXT NOT NULL, `type` INTEGER NOT NULL, `chatID` TEXT, `senderID` TEXT, `username` TEXT, `timestamp` INTEGER NOT NULL, `text` TEXT, `isSent` INTEGER NOT NULL, `isRead` INTEGER NOT NULL, PRIMARY KEY(`messageID`))", + "fields": [ + { + "fieldPath": "messageID", + "columnName": "messageID", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "chatID", + "columnName": "chatID", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "senderID", + "columnName": "senderID", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "isSent", + "columnName": "isSent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isRead", + "columnName": "isRead", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "messageID" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "chats", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`chatID` TEXT NOT NULL, `name` TEXT, `metadataRef` TEXT, `membersRef` TEXT, `bannedUsers` TEXT, `chunkCursor` INTEGER NOT NULL, PRIMARY KEY(`chatID`))", + "fields": [ + { + "fieldPath": "chatID", + "columnName": "chatID", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "metadataRef", + "columnName": "metadataRef", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "membersRef", + "columnName": "membersRef", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "bannedUsers", + "columnName": "bannedUsers", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "chunkCursor", + "columnName": "chunkCursor", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "chatID" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + } + ], + "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, \"81501115d10a6dc46002667323359631\")" + ] + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9f8ee82 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/LoginCredentials.java b/app/src/main/java/io/github/chronosx88/influence/LoginCredentials.java new file mode 100644 index 0000000..e96f075 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/LoginCredentials.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2019 ChronosX88 + * + * 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 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package io.github.chronosx88.influence; + +public class LoginCredentials { + String username = ""; + String password = ""; + String jabberHost = ""; +} diff --git a/app/src/main/java/io/github/chronosx88/influence/XMPPConnection.java b/app/src/main/java/io/github/chronosx88/influence/XMPPConnection.java new file mode 100644 index 0000000..6bad8f7 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/XMPPConnection.java @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2019 ChronosX88 + * + * 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 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package io.github.chronosx88.influence; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.util.Log; + +import androidx.preference.PreferenceManager; + +import org.jivesoftware.smack.ConnectionConfiguration; +import org.jivesoftware.smack.ConnectionListener; +import org.jivesoftware.smack.ReconnectionManager; +import org.jivesoftware.smack.SmackException; +import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.chat2.Chat; +import org.jivesoftware.smack.chat2.ChatManager; +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smack.tcp.XMPPTCPConnection; +import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration; +import org.jxmpp.jid.EntityBareJid; +import org.jxmpp.jid.impl.JidCreate; +import org.jxmpp.stringprep.XmppStringprepException; + +import java.io.IOException; + +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.helpers.NetworkHandler; + +public class XMPPConnection implements ConnectionListener { + private final static String LOG_TAG = "XMPPConnection"; + private LoginCredentials credentials = new LoginCredentials(); + private XMPPTCPConnection connection = null; + private SharedPreferences prefs; + private NetworkHandler networkHandler; + private BroadcastReceiver sendMessageReceiver = null; + private Context context; + + public enum ConnectionState { + CONNECTED, + AUTHENTICATED, + CONNECTING, + DISCONNECTING, + DISCONNECTED + } + + public enum SessionState { + LOGGED_IN, + LOGGED_OUT + } + + public XMPPConnection(Context context) { + String jid = prefs.getString("jid", null); + String password = prefs.getString("pass", null); + if(jid != null && password != null) { + String username = jid.split("@")[0]; + String jabberHost = jid.split("@")[1]; + credentials.username = username; + credentials.jabberHost = jabberHost; + credentials.password = password; + } + networkHandler = new NetworkHandler(context); + prefs = PreferenceManager.getDefaultSharedPreferences(context); + this.context = context; + } + + public void connect() throws XMPPException, SmackException, IOException { + if(connection == null) { + XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder() + .setXmppDomain(credentials.jabberHost) + .setHost(credentials.jabberHost) + .setResource(AppHelper.APP_NAME) + .setKeystoreType(null) + .setSecurityMode(ConnectionConfiguration.SecurityMode.required) + .setCompressionEnabled(true) + .build(); + + setupSendMessageReceiver(); + + connection = new XMPPTCPConnection(conf); + connection.addConnectionListener(this); + try { + connection.connect(); + connection.login(credentials.username, credentials.password); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + ChatManager.getInstanceFor(connection).addIncomingListener(networkHandler); + ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection); + ReconnectionManager.setEnabledPerDefault(true); + reconnectionManager.enableAutomaticReconnection(); + } + } + + public void disconnect() { + prefs.edit().putBoolean("logged_in", false).apply(); + if(connection != null) { + connection.disconnect(); + connection = null; + } + } + + @Override + public void connected(org.jivesoftware.smack.XMPPConnection connection) { + XMPPConnectionService.connectionState = ConnectionState.CONNECTED; + } + + @Override + public void authenticated(org.jivesoftware.smack.XMPPConnection connection, boolean resumed) { + XMPPConnectionService.sessionState = SessionState.LOGGED_IN; + prefs.edit().putBoolean("logged_in", true).apply(); + } + + @Override + public void connectionClosed() { + XMPPConnectionService.connectionState = ConnectionState.DISCONNECTED; + XMPPConnectionService.sessionState = SessionState.LOGGED_OUT; + prefs.edit().putBoolean("logged_in", false).apply(); + } + + @Override + public void connectionClosedOnError(Exception e) { + XMPPConnectionService.connectionState = ConnectionState.DISCONNECTED; + XMPPConnectionService.sessionState = SessionState.LOGGED_OUT; + prefs.edit().putBoolean("logged_in", false).apply(); + Log.e(LOG_TAG, "Connection closed, exception occurred"); + e.printStackTrace(); + } + + private void setupSendMessageReceiver() { + sendMessageReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + switch (action) { + case XMPPConnectionService.INTENT_SEND_MESSAGE: { + String recipientJid = intent.getStringExtra(XMPPConnectionService.MESSAGE_RECIPIENT); + String messageText = intent.getStringExtra(XMPPConnectionService.MESSAGE_BODY); + sendMessage(recipientJid, messageText); + break; + } + } + } + }; + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(XMPPConnectionService.INTENT_SEND_MESSAGE); + context.registerReceiver(sendMessageReceiver, intentFilter); + } + + private void sendMessage(String recipientJid, String messageText) { + EntityBareJid jid = null; + try { + jid = JidCreate.entityBareFrom(recipientJid); + } catch (XmppStringprepException e) { + e.printStackTrace(); + } + Chat chat = ChatManager.getInstanceFor(connection).chatWith(jid); + try { + Message message = new Message(jid, Message.Type.chat); + message.setBody(messageText); + chat.send(message); + } catch (SmackException.NotConnectedException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + public XMPPTCPConnection getConnection() { + return connection; + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/XMPPConnectionService.java b/app/src/main/java/io/github/chronosx88/influence/XMPPConnectionService.java new file mode 100644 index 0000000..5e9b00b --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/XMPPConnectionService.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2019 ChronosX88 + * + * 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 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package io.github.chronosx88.influence; + +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; + +import org.jivesoftware.smack.SmackException; +import org.jivesoftware.smack.XMPPException; + +import java.io.IOException; + +public class XMPPConnectionService extends Service { + public static final String INTENT_NEW_MESSAGE = "io.github.chronosx88.intents.new_message"; + public static final String INTENT_SEND_MESSAGE = "io.github.chronosx88.intents.send_message"; + public static final String INTENT_AUTHENTICATED = "io.github.chronosx88.intents.authenticated"; + public static final String INTENT_AUTHENTICATION_FAILED = "io.github.chronosx88.intents.authentication_failed"; + + public static final String MESSAGE_CHATID = "chat_jid"; + public static final String MESSAGE_ID = "message_id"; + public static final String MESSAGE_BODY = "message_body"; + public static final String MESSAGE_RECIPIENT = "message_recipient"; + + public static XMPPConnection.ConnectionState connectionState = XMPPConnection.ConnectionState.DISCONNECTED; + public static XMPPConnection.SessionState sessionState = XMPPConnection.SessionState.LOGGED_OUT; + + private Thread thread; + private Handler threadHandler; + private boolean isThreadAlive = false; + private XMPPConnection connection; + private Context context; + + public XMPPConnectionService(Context context) { + this.context = context; + } + + @Override + public IBinder onBind(Intent intent) { return null; } + + public void onServiceStart() { + if(!isThreadAlive) + { + isThreadAlive = true; + if(thread == null || !thread.isAlive()) { + thread = new Thread(() -> { + Looper.prepare(); + threadHandler = new Handler(); + createConnection(); + Looper.loop(); + }); + thread.start(); + } + } + } + + private void onServiceStop() { + isThreadAlive = false; + threadHandler.post(() -> { + if(connection != null) { + connection.disconnect(); + } + }); + } + + private void createConnection() { + if(connection == null) { + connection = new XMPPConnection(this); + } + try { + connection.connect(); + } catch (IOException | SmackException | XMPPException e) { + Intent intent = new Intent(INTENT_AUTHENTICATION_FAILED); + + e.printStackTrace(); + //Stop the service all together. + stopSelf(); + } + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + onServiceStart(); + return Service.START_STICKY; + } + + @Override + public void onDestroy() { + super.onDestroy(); + onServiceStop(); + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/contracts/CoreContracts.kt b/app/src/main/java/io/github/chronosx88/influence/contracts/CoreContracts.kt new file mode 100644 index 0000000..cfef030 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/contracts/CoreContracts.kt @@ -0,0 +1,89 @@ +package io.github.chronosx88.influence.contracts + +import android.content.Intent +import android.view.MenuItem + +import io.github.chronosx88.influence.helpers.ChatListAdapter +import io.github.chronosx88.influence.models.roomEntities.ChatEntity +import io.github.chronosx88.influence.models.roomEntities.MessageEntity + +interface CoreContracts { + + interface ViewWithLoadingScreen { + fun loadingScreen(state: Boolean); + } + + // -----ChatList----- + + interface IChatListLogicContract { + fun loadAllChats(): List + } + + interface IChatListPresenterContract { + fun updateChatList() + fun openChat(chatID: String) + fun onContextItemSelected(item: MenuItem) + } + + interface IChatListViewContract { + fun setRecycleAdapter(adapter: ChatListAdapter) + fun startActivity(intent: Intent) + fun updateChatList(adapter: ChatListAdapter, chats: List) + } + + // -----MainActivity----- + + interface IMainLogicContract { + fun initPeer() + fun sendStartChatMessage(username: String) + fun shutdownPeer() + } + + interface IMainPresenterContract { + fun initPeer() + fun startChatWithPeer(username: String) + fun onDestroy() + } + + interface IMainViewContract { + fun showSnackbar(message: String) + fun showProgressBar(state: Boolean) + } + + // -----ChatActivity----- + + interface IChatLogicContract { + fun sendMessage(message: MessageEntity) + fun stopTrackingForNewMsgs() + } + + interface IChatPresenterContract { + fun sendMessage(text: String) + fun updateAdapter() + fun onDestroy() + } + + interface IChatViewContract { + fun updateMessageList(message: MessageEntity) + fun updateMessageList(messages: List) + } + + // -----SettingsFragment----- + + interface ISettingsLogic { + fun checkUsernameExists(username: String) : Boolean + } + + interface ISettingsPresenter { + fun updateUsername(username: String) + } + + interface ISettingsView { + fun loadingScreen(state: Boolean) + fun showMessage(message: String) + fun refreshScreen() + } + + // -----LoginActivity----- + interface ILoginViewContract : ViewWithLoadingScreen +} diff --git a/app/src/main/java/io/github/chronosx88/influence/contracts/IItemClickListener.java b/app/src/main/java/io/github/chronosx88/influence/contracts/IItemClickListener.java new file mode 100644 index 0000000..2474dcb --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/contracts/IItemClickListener.java @@ -0,0 +1,7 @@ +package io.github.chronosx88.influence.contracts; + +import android.view.View; + +public interface IItemClickListener { + void onItemClick(View view, int position); +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/contracts/observer/INetworkObserver.java b/app/src/main/java/io/github/chronosx88/influence/contracts/observer/INetworkObserver.java new file mode 100644 index 0000000..3a2d0fe --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/contracts/observer/INetworkObserver.java @@ -0,0 +1,5 @@ +package io.github.chronosx88.influence.contracts.observer; + +public interface INetworkObserver { + void handleEvent(Object object); +} diff --git a/app/src/main/java/io/github/chronosx88/influence/contracts/observer/IObservable.java b/app/src/main/java/io/github/chronosx88/influence/contracts/observer/IObservable.java new file mode 100644 index 0000000..68a8126 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/contracts/observer/IObservable.java @@ -0,0 +1,12 @@ +package io.github.chronosx88.influence.contracts.observer; + +import com.google.gson.JsonObject; + +public interface IObservable { + void register(IObserver observer); + void register(INetworkObserver networkObserver); + void unregister(IObserver observer); + void unregister(INetworkObserver networkObserver); + void notifyUIObservers(JsonObject jsonObject); + void notifyNetworkObservers(Object object); +} diff --git a/app/src/main/java/io/github/chronosx88/influence/contracts/observer/IObserver.java b/app/src/main/java/io/github/chronosx88/influence/contracts/observer/IObserver.java new file mode 100644 index 0000000..0ffa003 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/contracts/observer/IObserver.java @@ -0,0 +1,7 @@ +package io.github.chronosx88.influence.contracts.observer; + +import com.google.gson.JsonObject; + +public interface IObserver { + void handleEvent(JsonObject object); +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/AppHelper.java b/app/src/main/java/io/github/chronosx88/influence/helpers/AppHelper.java new file mode 100644 index 0000000..ceb7ea0 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/AppHelper.java @@ -0,0 +1,65 @@ +package io.github.chronosx88.influence.helpers; + +import android.app.Application; +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; + +import net.tomp2p.dht.PeerDHT; + +import androidx.multidex.MultiDexApplication; +import androidx.room.Room; + +import com.instacart.library.truetime.TrueTime; + +import java.io.IOException; + +import io.github.chronosx88.influence.observable.MainObservable; + +/** + * Extended Application class which designed for centralized getting various objects from anywhere in the application. + */ + +public class AppHelper extends MultiDexApplication { + private static Application instance; + private static MainObservable observable; + public final static String APP_NAME = "Influence"; + + private static String jid; + private static RoomHelper chatDB; + private static SharedPreferences preferences; + + @Override + public void onCreate() { + super.onCreate(); + instance = this; + observable = new MainObservable(); + chatDB = Room.databaseBuilder(getApplicationContext(), RoomHelper.class, "chatDB") + .allowMainThreadQueries() + .build(); + preferences = PreferenceManager.getDefaultSharedPreferences(instance); + new Thread(() -> { + try { + TrueTime.build().initialize(); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + } + + public static Context getContext() { + return instance.getApplicationContext(); + } + + public static MainObservable getObservable() { return observable; } + + public static String getJid() { return jid; } + + public static void setJid(String jid1) { jid = jid1; } + + public static RoomHelper getChatDB() { return chatDB; } + + public static SharedPreferences getPreferences() { + return preferences; + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/ChatAdapter.java b/app/src/main/java/io/github/chronosx88/influence/helpers/ChatAdapter.java new file mode 100644 index 0000000..5ef7223 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/ChatAdapter.java @@ -0,0 +1,105 @@ +package io.github.chronosx88.influence.helpers; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.SortedSet; +import java.util.TimeZone; +import java.util.TreeSet; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; +import de.hdodenhof.circleimageview.CircleImageView; +import io.github.chronosx88.influence.R; +import io.github.chronosx88.influence.models.roomEntities.MessageEntity; + +public class ChatAdapter extends RecyclerView.Adapter { + private final static int RIGHT_ITEM = 0; + private final static int LEFT_ITEM = 1; + private final static int TECHNICAL_MESSAGE = 2; // TODO + + private final Context context = AppHelper.getContext(); + private ArrayList messages = new ArrayList<>(); + private static Comparator comparator = ((o1, o2) -> Long.compare(o1.timestamp, o2.timestamp)); + + @NonNull + @Override + public ChatAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + if(viewType == RIGHT_ITEM) { + return new ChatAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.message_right_item, parent, false)); + } else { + return new ChatAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.message_left_item, parent, false)); + } + } + + public void addMessage(MessageEntity message) { + if(message != null) { + for (MessageEntity messageEntity : messages) { + if(messageEntity.messageID.equals(message.messageID)) { + return; + } + } + messages.add(message); + Collections.sort(messages, comparator); + } + } + + public void addMessages(List messages) { + this.messages.addAll(messages); + Collections.sort(messages, comparator); + } + + @Override + public void onBindViewHolder(@NonNull ChatAdapter.ViewHolder holder, int position) { + // Setting message text + holder.messageText.setText(messages.get(position).text); + + // Setting message time (HOUR:MINUTE) + DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT); + dateFormat.setTimeZone(TimeZone.getDefault()); + String time = dateFormat.format(new Date(messages.get(position).timestamp)); + holder.messageTime.setText(time); + } + + @Override + public int getItemCount() { + return messages.size(); + } + + @Override + public int getItemViewType(int position) { + if(messages.get(position).senderID.equals(AppHelper.getPeerID())) { + return RIGHT_ITEM; + } else { + return LEFT_ITEM; + } + } + + class ViewHolder extends RecyclerView.ViewHolder { + TextView messageText; + CircleImageView profileImage; + TextView messageTime; + + public ViewHolder(View itemView) { + super(itemView); + messageText = itemView.findViewById(R.id.message_text); + profileImage = itemView.findViewById(R.id.profile_image); + messageTime = itemView.findViewById(R.id.message_time); + } + } + + +} diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/ChatListAdapter.java b/app/src/main/java/io/github/chronosx88/influence/helpers/ChatListAdapter.java new file mode 100644 index 0000000..4fe5f9f --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/ChatListAdapter.java @@ -0,0 +1,84 @@ +package io.github.chronosx88.influence.helpers; + +import android.view.ContextMenu; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import java.util.ArrayList; +import java.util.List; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; +import io.github.chronosx88.influence.R; +import io.github.chronosx88.influence.contracts.IItemClickListener; +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; + +public class ChatListAdapter extends RecyclerView.Adapter { + List chatList = new ArrayList<>(); + public int onClickPosition = -1; + private IItemClickListener itemClickListener; + + public ChatListAdapter(IItemClickListener itemClickListener) { + this.itemClickListener = itemClickListener; + } + + @NonNull + @Override + public ChatListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = LayoutInflater.from(parent.getContext()) + .inflate(R.layout.chat_item, parent, false); + return new ChatListViewHolder(view); + } + + public void setChatList(List entities) { + chatList.clear(); + chatList.addAll(entities); + } + + public ChatEntity getItem(int position) { + return chatList.get(position); + } + + @Override + public void onBindViewHolder(@NonNull ChatListViewHolder holder, int position) { + holder.chatName.setText(chatList.get(position).name); + holder.onLongClick(position); + } + + public ChatEntity getChatEntity(int position) { + return chatList.get(position); + } + + @Override + public int getItemCount() { + return chatList.size(); + } + + class ChatListViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener { + TextView chatName; + + public ChatListViewHolder(View itemView) { + super(itemView); + chatName = itemView.findViewById(R.id.chat_name); + itemView.setOnCreateContextMenuListener(this); + itemView.setOnClickListener((v) -> { + itemClickListener.onItemClick(v, getAdapterPosition()); + }); + } + + public void onLongClick(int position) { + itemView.setOnLongClickListener((v) -> { + onClickPosition = position; + itemView.showContextMenu(); + return true; + }); + } + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { + menu.add(0, 0, 0, "Remove chat"); + } + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/KeyPairManager.java b/app/src/main/java/io/github/chronosx88/influence/helpers/KeyPairManager.java new file mode 100644 index 0000000..2b7dc80 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/KeyPairManager.java @@ -0,0 +1,78 @@ +package io.github.chronosx88.influence.helpers; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; + +public class KeyPairManager { + private File keyPairDir; + private Serializer serializer; + + public KeyPairManager() { + this.keyPairDir = new File(AppHelper.getContext().getFilesDir().getAbsoluteFile(), "keyPairs"); + if(!this.keyPairDir.exists()) { + this.keyPairDir.mkdir(); + } + this.serializer = new Serializer<>(); + } + + public KeyPair openMainKeyPair() { + return getKeyPair("mainKeyPair"); + } + + public KeyPair getKeyPair(String keyPairName) { + keyPairName = keyPairName + ".kp"; + File keyPairFile = new File(keyPairDir, keyPairName); + if (!keyPairFile.exists()) { + return createKeyPairFile(keyPairFile); + } + return openKeyPairFile(keyPairFile); + } + + private synchronized KeyPair openKeyPairFile(File keyPairFile) { + KeyPair keyPair = null; + try { + FileInputStream inputStream = new FileInputStream(keyPairFile); + byte[] serializedKeyPair = new byte[(int) keyPairFile.length()]; + inputStream.read(serializedKeyPair); + inputStream.close(); + keyPair = serializer.deserialize(serializedKeyPair); + } catch (IOException e) { + e.printStackTrace(); + } + return keyPair; + } + + private synchronized KeyPair createKeyPairFile(File keyPairFile) { + KeyPair keyPair = null; + try { + keyPairFile.createNewFile(); + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(1024); + keyPair = keyPairGenerator.generateKeyPair(); + FileOutputStream outputStream = new FileOutputStream(keyPairFile); + outputStream.write(serializer.serialize(keyPair)); + outputStream.close(); + } catch (IOException | NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return keyPair; + } + + public synchronized void saveKeyPair(String keyPairID, KeyPair keyPair) { + File keyPairFile = new File(keyPairDir, keyPairID + ".kp"); + if(!keyPairFile.exists()) { + try { + FileOutputStream outputStream = new FileOutputStream(keyPairFile); + outputStream.write(serializer.serialize(keyPair)); + outputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/LocalDBWrapper.java b/app/src/main/java/io/github/chronosx88/influence/helpers/LocalDBWrapper.java new file mode 100644 index 0000000..1347b63 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/LocalDBWrapper.java @@ -0,0 +1,61 @@ +package io.github.chronosx88.influence.helpers; + +import android.util.Log; + +import java.util.ArrayList; +import java.util.List; + +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; +import io.github.chronosx88.influence.models.roomEntities.MessageEntity; + +public class LocalDBWrapper { + private static final String LOG_TAG = "LocalDBWrapper"; + private static RoomHelper dbInstance = AppHelper.getChatDB(); + + public static void createChatEntry(String jid, String chatName) { + dbInstance.chatDao().addChat(new ChatEntity(jid, chatName)); + } + + public static long createMessageEntry(String jid, String senderJid, long timestamp, String text, boolean isSent, boolean isRead) { + List chatEntities = AppHelper.getChatDB().chatDao().getChatByChatID(jid); + if(chatEntities.size() < 1) { + Log.e(LOG_TAG, "Failed to create message entry because chat " + jid + " doesn't exists!"); + return -1; + } + MessageEntity message = new MessageEntity(jid, senderJid, timestamp, text, isSent, isRead); + long index = dbInstance.messageDao().insertMessage(message); + return index; + } + + public static MessageEntity getMessageByID(long messageID) { + List messages = dbInstance.messageDao().getMessageByID(messageID); + if(messages.isEmpty()) { + return null; + } + return messages.get(0); + } + + public static List getMessagesByChatID(String chatID) { + List messages = dbInstance.messageDao().getMessagesByChatID(chatID); + if(messages.isEmpty()) { + return null; + } + return messages; + } + + public static ChatEntity getChatByChatID(String chatID) { + List chats = dbInstance.chatDao().getChatByChatID(chatID); + if(chats.isEmpty()) { + return null; + } + return chats.get(0); + } + + public static void updateChatEntity(ChatEntity chatEntity) { + dbInstance.chatDao().updateChat(chatEntity); + } + + public static void updateMessage(MessageEntity messageEntity) { + dbInstance.messageDao().updateMessage(messageEntity); + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/NetworkHandler.java b/app/src/main/java/io/github/chronosx88/influence/helpers/NetworkHandler.java new file mode 100644 index 0000000..9512a6f --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/NetworkHandler.java @@ -0,0 +1,35 @@ +package io.github.chronosx88.influence.helpers; + +import android.content.Context; +import android.content.Intent; + +import com.instacart.library.truetime.TrueTime; + +import org.jivesoftware.smack.chat2.Chat; +import org.jivesoftware.smack.chat2.IncomingChatMessageListener; +import org.jivesoftware.smack.packet.Message; +import org.jxmpp.jid.EntityBareJid; + +import io.github.chronosx88.influence.XMPPConnectionService; + +public class NetworkHandler implements IncomingChatMessageListener { + private final static String LOG_TAG = "NetworkHandler"; + private Context context; + + public NetworkHandler(Context context) { + this.context = context; + } + + @Override + public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) { + if(LocalDBWrapper.getChatByChatID(from.asEntityBareJidString()) == null) { + LocalDBWrapper.createChatEntry(chat.getXmppAddressOfChatPartner().asUnescapedString(), chat.getXmppAddressOfChatPartner().asBareJid().asUnescapedString()); + } + long messageID = LocalDBWrapper.createMessageEntry(chat.getXmppAddressOfChatPartner().asUnescapedString(), from.asUnescapedString(), TrueTime.now().getTime(), message.getBody(), true, false); + Intent intent = new Intent(XMPPConnectionService.INTENT_NEW_MESSAGE); + intent.setPackage(context.getPackageName()); + intent.putExtra(XMPPConnectionService.MESSAGE_CHATID, chat.getXmppAddressOfChatPartner().toString()); + intent.putExtra(XMPPConnectionService.MESSAGE_ID, messageID); + context.sendBroadcast(intent); + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/ObservableUtils.java b/app/src/main/java/io/github/chronosx88/influence/helpers/ObservableUtils.java new file mode 100644 index 0000000..c2ef9ab --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/ObservableUtils.java @@ -0,0 +1,30 @@ +package io.github.chronosx88.influence.helpers; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +public class ObservableUtils { + public static void notifyUI(int action) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", action); + AppHelper.getObservable().notifyUIObservers(jsonObject); + } + + public static void notifyUI(int action, String... additional) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", action); + JsonArray jsonArray = new JsonArray(); + for(String info : additional) { + jsonArray.add(info); + } + jsonObject.add("additional", jsonArray); + AppHelper.getObservable().notifyUIObservers(jsonObject); + } + + public static void notifyUI(int action, int additional) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", action); + jsonObject.addProperty("additional", additional); + AppHelper.getObservable().notifyUIObservers(jsonObject); + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/RoomHelper.java b/app/src/main/java/io/github/chronosx88/influence/helpers/RoomHelper.java new file mode 100644 index 0000000..d17c7a7 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/RoomHelper.java @@ -0,0 +1,17 @@ +package io.github.chronosx88.influence.helpers; + +import androidx.room.Database; +import androidx.room.RoomDatabase; +import androidx.room.TypeConverters; +import io.github.chronosx88.influence.models.daos.ChatDao; +import io.github.chronosx88.influence.models.daos.MessageDao; +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; +import io.github.chronosx88.influence.models.roomEntities.MessageEntity; + +@Database(entities = { MessageEntity.class, ChatEntity.class }, version = 2) + +@TypeConverters({RoomTypeConverter.class}) +public abstract class RoomHelper extends RoomDatabase { + public abstract ChatDao chatDao(); + public abstract MessageDao messageDao(); +} diff --git a/app/src/main/java/io/github/chronosx88/influence/helpers/RoomTypeConverter.java b/app/src/main/java/io/github/chronosx88/influence/helpers/RoomTypeConverter.java new file mode 100644 index 0000000..aa2dcdc --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/helpers/RoomTypeConverter.java @@ -0,0 +1,25 @@ +package io.github.chronosx88.influence.helpers; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.ArrayList; + +import androidx.room.TypeConverter; + +public class RoomTypeConverter { + + @TypeConverter + public static ArrayList fromString(String value) { + Type listType = new TypeToken>() {}.getType(); + return new Gson().fromJson(value, listType); + } + + @TypeConverter + public static String fromArrayList(ArrayList list) { + Gson gson = new Gson(); + return gson.toJson(list); + } + +} diff --git a/app/src/main/java/io/github/chronosx88/influence/logic/ChatListLogic.java b/app/src/main/java/io/github/chronosx88/influence/logic/ChatListLogic.java new file mode 100644 index 0000000..12eda21 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/logic/ChatListLogic.java @@ -0,0 +1,15 @@ +package io.github.chronosx88.influence.logic; + +import java.util.List; + +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; + +public class ChatListLogic implements CoreContracts.IChatListLogicContract { + + @Override + public List loadAllChats() { + return AppHelper.getChatDB().chatDao().getAllChats(); + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/logic/ChatLogic.java b/app/src/main/java/io/github/chronosx88/influence/logic/ChatLogic.java new file mode 100644 index 0000000..2d5897e --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/logic/ChatLogic.java @@ -0,0 +1,182 @@ +package io.github.chronosx88.influence.logic; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import net.tomp2p.peers.Number640; +import net.tomp2p.storage.Data; + +import java.io.IOException; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.helpers.KeyPairManager; +import io.github.chronosx88.influence.helpers.LocalDBWrapper; +import io.github.chronosx88.influence.helpers.ObservableUtils; +import io.github.chronosx88.influence.helpers.actions.NetworkActions; +import io.github.chronosx88.influence.helpers.actions.UIActions; +import io.github.chronosx88.influence.models.JoinChatMessage; +import io.github.chronosx88.influence.models.NextChunkReference; +import io.github.chronosx88.influence.models.TextMessage; +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; +import io.github.chronosx88.influence.models.roomEntities.MessageEntity; + +public class ChatLogic implements CoreContracts.IChatLogicContract { + private static Gson gson = new Gson(); + private String chatID; + private volatile String newMessage = ""; + private ChatEntity chatEntity; + private Thread checkNewMessagesThread = null; + private KeyPairManager keyPairManager; + private Timer timer; + + public ChatLogic(ChatEntity chatEntity) { + this.chatEntity = chatEntity; + this.chatID = chatEntity.chatID; + TimerTask timerTask = new TimerTask() { + @Override + public void run() { + checkForNewMessages(); + } + }; + this.timer = new Timer(); + if(AppHelper.getPeerDHT() != null) { + timer.schedule(timerTask, 1, 1000); + } + this.keyPairManager = new KeyPairManager(); + } + + @Override + public void sendMessage(MessageEntity message) { + if(AppHelper.getPeerDHT() == null) { + ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE); + return; + } + new Thread(() -> { + Data data = null; + try { + data = new Data(gson.toJson(new TextMessage(message.senderID, message.messageID, message.chatID, message.username, message.timestamp, message.text, false))); + } catch (IOException e) { + e.printStackTrace(); + } + data.protectEntry(keyPairManager.getKeyPair("mainKeyPair")); + P2PUtils.put(chatID + "_messages" + chatEntity.chunkCursor, message.messageID, data); + try { + P2PUtils.put(chatID + "_newMessage", null, new Data(message.messageID)); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + } + + private void checkForNewMessages() { + if(checkNewMessagesThread == null) { + checkNewMessagesThread = new Thread(() -> { + Map data = P2PUtils.get(chatID + "_newMessage"); + if(data != null) { + for(Map.Entry entry : data.entrySet()) { + String newMessage = null; + try { + newMessage = (String) entry.getValue().object(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + if(!newMessage.equals(this.newMessage)) { + handleNewMessages(chatEntity.chunkCursor); + this.newMessage = newMessage; + } + } + } + }); + } + + if(!checkNewMessagesThread.isAlive()) { + checkNewMessagesThread = new Thread(() -> { + Map data = P2PUtils.get(chatID + "_newMessage"); + if(data != null) { + for(Map.Entry entry : data.entrySet()) { + String newMessage = null; + try { + newMessage = (String) entry.getValue().object(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + if(!newMessage.equals(this.newMessage)) { + handleNewMessages(chatEntity.chunkCursor); + this.newMessage = newMessage; + } + } + } + }); + checkNewMessagesThread.start(); + } + } + + private void handleNewMessages(int chunkID) { + new Thread(() -> { + Map messages = P2PUtils.get(chatEntity.chatID + "_messages" + chunkID); + if (messages != null) { + for (Map.Entry message : messages.entrySet()) { + String json = null; + try { + json = (String) message.getValue().object(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + switch (getMessageAction(json)) { + case NetworkActions.TEXT_MESSAGE: { + TextMessage textMessage = gson.fromJson(json, TextMessage.class); + LocalDBWrapper.createMessageEntry(NetworkActions.TEXT_MESSAGE, textMessage.getMessageID(), textMessage.getChatID(), textMessage.getUsername(), textMessage.getSenderID(), textMessage.getTimestamp(), textMessage.getText(), true, false); + ObservableUtils.notifyUI(UIActions.MESSAGE_RECEIVED, chatID, textMessage.getMessageID()); + break; + } + case NetworkActions.JOIN_CHAT: { + JoinChatMessage joinChatMessage = gson.fromJson(json, JoinChatMessage.class); + LocalDBWrapper.createMessageEntry(NetworkActions.JOIN_CHAT, joinChatMessage.getMessageID(), joinChatMessage.getChatID(), joinChatMessage.getUsername(), joinChatMessage.getSenderID(), joinChatMessage.getTimestamp(), null, true, false); + ObservableUtils.notifyUI(UIActions.MESSAGE_RECEIVED, chatID, joinChatMessage.getMessageID()); + break; + } + case NetworkActions.NEXT_CHUNK_REF: { + NextChunkReference nextChunkReference = gson.fromJson(json, NextChunkReference.class); + chatEntity.chunkCursor = nextChunkReference.getNextChunkID(); + LocalDBWrapper.updateChatEntity(chatEntity); + break; + } + } + } + if(messages.size() > 10) { + String messageID = UUID.randomUUID().toString(); + try { + int nextChunkCursor = chatEntity.chunkCursor + 1; + P2PUtils.put(chatEntity.chatID + "_messages" + chunkID, messageID, new Data(gson.toJson(new NextChunkReference(messageID, AppHelper.getPeerID(), AppHelper.getPeerID(), System.currentTimeMillis(), nextChunkCursor)))); + P2PUtils.put(chatEntity.chatID + "_newMessage", null, new Data(messageID)); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + }).start(); + } + + private int getMessageAction(String json) { + JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); + return jsonObject.get("action").getAsInt(); + } + + @Override + public void stopTrackingForNewMsgs() { + timer.cancel(); + timer.purge(); + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/logic/MainLogic.java b/app/src/main/java/io/github/chronosx88/influence/logic/MainLogic.java new file mode 100644 index 0000000..219d7b3 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/logic/MainLogic.java @@ -0,0 +1,370 @@ +package io.github.chronosx88.influence.logic; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import net.tomp2p.connection.Bindings; +import net.tomp2p.connection.ChannelClientConfiguration; +import net.tomp2p.connection.ChannelServerConfiguration; +import net.tomp2p.connection.Ports; +import net.tomp2p.connection.RSASignatureFactory; +import net.tomp2p.dht.PeerBuilderDHT; +import net.tomp2p.dht.PeerDHT; +import net.tomp2p.dht.Storage; +import net.tomp2p.futures.FutureBootstrap; +import net.tomp2p.futures.FutureDiscover; +import net.tomp2p.nat.FutureRelayNAT; +import net.tomp2p.nat.PeerBuilderNAT; +import net.tomp2p.nat.PeerNAT; +import net.tomp2p.p2p.PeerBuilder; +import net.tomp2p.peers.Number160; +import net.tomp2p.peers.Number640; +import net.tomp2p.peers.PeerAddress; +import net.tomp2p.relay.tcp.TCPRelayClientConfig; +import net.tomp2p.replication.IndirectReplication; +import net.tomp2p.storage.Data; + +import org.jetbrains.annotations.NotNull; + +import java.io.File; +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.security.KeyPair; +import java.util.ArrayList; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.helpers.KeyPairManager; +import io.github.chronosx88.influence.helpers.LocalDBWrapper; +import io.github.chronosx88.influence.helpers.NetworkHandler; +import io.github.chronosx88.influence.helpers.ObservableUtils; +import io.github.chronosx88.influence.helpers.StorageBerkeleyDB; +import io.github.chronosx88.influence.helpers.actions.UIActions; +import io.github.chronosx88.influence.models.ChatMetadata; +import io.github.chronosx88.influence.models.NewChatRequestMessage; +import io.github.chronosx88.influence.models.PublicUserProfile; + +public class MainLogic implements CoreContracts.IMainLogicContract { + private static final String LOG_TAG = MainLogic.class.getName(); + + private SharedPreferences preferences; + private Number160 peerID; + private PeerDHT peerDHT; + private Context context; + private InetAddress bootstrapAddress = null; + private PeerAddress bootstrapPeerAddress = null; + private Gson gson; + private IndirectReplication replication; + private KeyPairManager keyPairManager; + private Thread checkNewChatsThread = null; + private Storage storage; + + public MainLogic() { + this.context = AppHelper.getContext(); + this.preferences = context.getSharedPreferences("io.github.chronosx88.influence_preferences", context.MODE_PRIVATE); + gson = new Gson(); + keyPairManager = new KeyPairManager(); + } + + @Override + public void initPeer() { + org.apache.log4j.BasicConfigurator.configure(); + + if(checkFirstRun()) { + SharedPreferences.Editor editor = preferences.edit(); + String uuid = UUID.randomUUID().toString(); + editor.putString("peerID", uuid); + editor.apply(); + } + + peerID = Number160.createHash(preferences.getString("peerID", null)); + + new Thread(() -> { + try { + File dhtDBEnv = new File(context.getFilesDir(), "dhtDBEnv"); + if(!dhtDBEnv.exists()) + dhtDBEnv.mkdirs(); + Storage storage = new StorageBerkeleyDB(peerID, dhtDBEnv, new RSASignatureFactory()); + this.storage = storage; + peerDHT = new PeerBuilderDHT( + new PeerBuilder(peerID) + .ports(7243) + .channelClientConfiguration(createChannelClientConfig()) + .channelServerConfiguration(createChannelServerConfig()) + .start() + ) + .storage(storage) + .start(); + Runtime.getRuntime().addShutdownHook(new JVMShutdownHook(storage)); + try { + String bootstrapIP = this.preferences.getString("bootstrapAddress", null); + if(bootstrapIP == null) { + throw new NullPointerException(); + } + bootstrapAddress = Inet4Address.getByName(bootstrapIP); + } catch (NullPointerException e) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", UIActions.BOOTSTRAP_NOT_SPECIFIED); + AppHelper.getObservable().notifyUIObservers(jsonObject); + peerDHT.shutdown(); + return; + } catch (UnknownHostException e) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", UIActions.NETWORK_ERROR); + AppHelper.getObservable().notifyUIObservers(jsonObject); + peerDHT.shutdown(); + return; + } + + boolean discoveredExternalAddress = false; + + if(discoverExternalAddress()) { + discoveredExternalAddress = true; + } + + if(!discoveredExternalAddress) { + if(!setupConnectionToRelay()) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", UIActions.RELAY_CONNECTION_ERROR); + AppHelper.getObservable().notifyUIObservers(jsonObject); + return; + } + } + + if(!bootstrapPeer()) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", UIActions.BOOTSTRAP_ERROR); + AppHelper.getObservable().notifyUIObservers(jsonObject); + return; + } + + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("action", UIActions.BOOTSTRAP_SUCCESS); + AppHelper.getObservable().notifyUIObservers(jsonObject); + AppHelper.storePeerID(preferences.getString("peerID", null)); + AppHelper.updateUsername(preferences.getString("username", null)); + AppHelper.storePeerDHT(peerDHT); + AppHelper.initNetworkHandler(); + //setReceiveHandler(); + gson = new Gson(); + publicProfileToDHT(); + SettingsLogic.Companion.publishUsername(AppHelper.getUsername(), AppHelper.getUsername()); + NetworkHandler.handlePendingChatRequests(); + TimerTask timerTask = new TimerTask() { + @Override + public void run() { + if(checkNewChatsThread == null) { + checkNewChatsThread = new Thread(NetworkHandler::handlePendingChatRequests); + checkNewChatsThread.start(); + } + if(!checkNewChatsThread.isAlive()) { + checkNewChatsThread = new Thread(NetworkHandler::handlePendingChatRequests); + checkNewChatsThread.start(); + } + } + }; + Timer timer = new Timer(); + timer.schedule(timerTask, 1, 5000); + replication = new IndirectReplication(peerDHT).start(); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + } + + private boolean bootstrapPeer() { + FutureBootstrap futureBootstrap = peerDHT.peer().bootstrap().inetAddress(bootstrapAddress).ports(7243).start(); + futureBootstrap.awaitUninterruptibly(); + if(futureBootstrap.isSuccess()) { + Log.i("MainLogic", "# Successfully bootstrapped to " + bootstrapAddress.toString()); + return true; + } else { + Log.e("MainLogic", "# Cannot bootstrap to " + bootstrapAddress.toString() + ". Reason: " + futureBootstrap.failedReason()); + return false; + } + } + + private boolean discoverExternalAddress() { + FutureDiscover futureDiscover = peerDHT + .peer() + .discover() + .inetAddress(bootstrapAddress) + .ports(7243) + .start(); + futureDiscover.awaitUninterruptibly(); + bootstrapPeerAddress = futureDiscover.reporter(); + if(futureDiscover.isSuccess()) { + Log.i(LOG_TAG, "# Success discover! Your external IP: " + futureDiscover.peerAddress().toString()); + return true; + } else { + Log.e(LOG_TAG, "# Failed to discover my external IP. Reason: " + futureDiscover.failedReason()); + return false; + } + } + + private boolean setupConnectionToRelay() { + PeerNAT peerNat = new PeerBuilderNAT(peerDHT.peer()).start(); + FutureRelayNAT futureRelayNAT = peerNat.startRelay(new TCPRelayClientConfig(), bootstrapPeerAddress).awaitUninterruptibly(); + if (futureRelayNAT.isSuccess()) { + Log.i(LOG_TAG, "# Successfully connected to relay node."); + return true; + } else { + Log.e(LOG_TAG, "# Cannot connect to relay node. Reason: " + futureRelayNAT.failedReason()); + return false; + } + } + + private void setReceiveHandler() { + AppHelper.getPeerDHT().peer().objectDataReply((s, r) -> { + Log.i(LOG_TAG, "# Incoming message: " + r); + AppHelper.getObservable().notifyNetworkObservers(r); + return null; + }); + } + + @Override + public void shutdownPeer() { + new Thread(() -> { + if(replication != null) { + replication.shutdown(); + } + if(peerDHT != null) { + peerDHT.peer().announceShutdown().start().awaitUninterruptibly(); + peerDHT.peer().shutdown().awaitUninterruptibly(); + } + storage.close(); + System.exit(0); + }).start(); + } + + private boolean checkFirstRun() { + if (preferences.getBoolean("firstRun", true)) { + SharedPreferences.Editor editor = preferences.edit(); + editor.putBoolean("firstRun", false); + editor.apply(); + return true; + } + return false; + } + + private void publicProfileToDHT() { + KeyPair mainKeyPair = keyPairManager.openMainKeyPair(); + PublicUserProfile userProfile = new PublicUserProfile(AppHelper.getUsername(), peerDHT.peerAddress()); + Data serializedUserProfile = null; + try { + serializedUserProfile = new Data(gson.toJson(userProfile)) + .protectEntry(mainKeyPair.getPrivate()); + } catch (IOException e) { + e.printStackTrace(); + } + Log.i(LOG_TAG, P2PUtils.put(AppHelper.getPeerID() + "_profile", null, serializedUserProfile, mainKeyPair) ? "# Profile successfully published!" : "# Profile publishing failed!"); + } + + private ChannelClientConfiguration createChannelClientConfig() { + ChannelClientConfiguration channelClientConfiguration = new ChannelClientConfiguration(); + channelClientConfiguration.bindings(new Bindings()); + channelClientConfiguration.maxPermitsPermanentTCP(250); + channelClientConfiguration.maxPermitsTCP(250); + channelClientConfiguration.maxPermitsUDP(250); + channelClientConfiguration.pipelineFilter(new PeerBuilder.DefaultPipelineFilter()); + channelClientConfiguration.signatureFactory(new RSASignatureFactory()); + channelClientConfiguration.senderTCP((new InetSocketAddress(0)).getAddress()); + channelClientConfiguration.senderUDP((new InetSocketAddress(0)).getAddress()); + channelClientConfiguration.byteBufPool(false); + return channelClientConfiguration; + } + + private ChannelServerConfiguration createChannelServerConfig() { + ChannelServerConfiguration channelServerConfiguration = new ChannelServerConfiguration(); + channelServerConfiguration.bindings(new Bindings()); + //these two values may be overwritten in the peer builder + channelServerConfiguration.ports(new Ports(Ports.DEFAULT_PORT, Ports.DEFAULT_PORT)); + channelServerConfiguration.portsForwarding(new Ports(Ports.DEFAULT_PORT, Ports.DEFAULT_PORT)); + channelServerConfiguration.behindFirewall(false); + channelServerConfiguration.pipelineFilter(new PeerBuilder.DefaultPipelineFilter()); + channelServerConfiguration.signatureFactory(new RSASignatureFactory()); + channelServerConfiguration.byteBufPool(false); + return channelServerConfiguration; + } + + @Override + public void sendStartChatMessage(@NotNull String username) { + if(AppHelper.getPeerDHT() == null) { + ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE); + return; + } + + String companionPeerID = getPeerIDByUsername(username); + if(companionPeerID == null) { + ObservableUtils.notifyUI(UIActions.PEER_NOT_EXIST); + return; + } + PublicUserProfile recipientPublicProfile = getPublicProfile(companionPeerID); + if(recipientPublicProfile == null) { + ObservableUtils.notifyUI(UIActions.PEER_NOT_EXIST); + return; + } + + NewChatRequestMessage newChatRequestMessage = new NewChatRequestMessage(UUID.randomUUID().toString(), UUID.randomUUID().toString(), AppHelper.getPeerID(), AppHelper.getUsername(), System.currentTimeMillis(), 0); + try { + if(P2PUtils.put(companionPeerID + "_pendingChats", newChatRequestMessage.getChatID(), new Data(gson.toJson(newChatRequestMessage)))) { + Log.i(LOG_TAG, "# Create new offline chat request is successful! ChatID: " + newChatRequestMessage.getChatID()); + } else { + Log.e(LOG_TAG, "# Failed to create offline chat request. ChatID: " + newChatRequestMessage.getChatID()); + } + } catch (IOException e) { + e.printStackTrace(); + } + + ArrayList admins = new ArrayList<>(); + admins.add(AppHelper.getPeerID()); + Data data = null; + try { + data = new Data(gson.toJson(new ChatMetadata(username, admins, new ArrayList<>()))); + } catch (IOException e) { + e.printStackTrace(); + } + data.protectEntry(keyPairManager.openMainKeyPair()); + P2PUtils.put(newChatRequestMessage.getChatID() + "_metadata", null, data); + LocalDBWrapper.createChatEntry(newChatRequestMessage.getChatID(), username, newChatRequestMessage.getChatID() + "_metadata", newChatRequestMessage.getChatID() + "_members", 0); + ObservableUtils.notifyUI(UIActions.NEW_CHAT); + } + + private PublicUserProfile getPublicProfile(String peerID) { + PublicUserProfile publicProfile = null; + Map data = P2PUtils.get(peerID + "_profile"); + if (data != null && data.size() == 1) { + try { + publicProfile = gson.fromJson((String) data.values().iterator().next().object(), PublicUserProfile.class); + } catch (ClassNotFoundException | IOException e) { + e.printStackTrace(); + } + return publicProfile; + } + return null; + } + + private String getPeerIDByUsername(String username) { + Map usernameMap = P2PUtils.get(username); + if(usernameMap == null) { + return null; + } + try { + return (String) usernameMap.values().iterator().next().object(); + } catch (ClassNotFoundException | IOException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/logic/SettingsLogic.kt b/app/src/main/java/io/github/chronosx88/influence/logic/SettingsLogic.kt new file mode 100644 index 0000000..e616a87 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/logic/SettingsLogic.kt @@ -0,0 +1,58 @@ +package io.github.chronosx88.influence.logic + +import android.util.Log +import io.github.chronosx88.influence.contracts.CoreContracts +import io.github.chronosx88.influence.helpers.AppHelper +import io.github.chronosx88.influence.helpers.KeyPairManager +import io.github.chronosx88.influence.helpers.ObservableUtils +import io.github.chronosx88.influence.helpers.actions.UIActions +import net.tomp2p.peers.Number640 +import net.tomp2p.storage.Data +import java.io.IOException + +class SettingsLogic : CoreContracts.ISettingsLogic { + + override fun checkUsernameExists(username: String) : Boolean { + if (AppHelper.getPeerDHT() == null) { + ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE) + return false + } + val usernameMap: MutableMap? = P2PUtils.get(username) + usernameMap ?: return false + return true + } + + companion object { + private val LOG_TAG: String = "SettingsLogic" + private val keyPairManager = KeyPairManager() + + fun publishUsername(oldUsername: String?, username: String?) { + if (AppHelper.getPeerDHT() == null) { + ObservableUtils.notifyUI(UIActions.NODE_IS_OFFLINE) + return + } + val mainKeyPair = keyPairManager.openMainKeyPair() + oldUsername?.let { + if(!oldUsername.equals("")) { + P2PUtils.remove(oldUsername, null, mainKeyPair) + } + } + + username?.let { + var data: Data? = null + try { + data = Data(AppHelper.getPeerID()) + } catch (e: IOException) { + e.printStackTrace() + } + + data!!.protectEntry(mainKeyPair) + + val isSuccess = P2PUtils.put(username, null, data, mainKeyPair) + Log.i(LOG_TAG, if (isSuccess) "# Username $username is published!" else "# Username $username isn't published!") + } ?: run { + return + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/models/daos/ChatDao.java b/app/src/main/java/io/github/chronosx88/influence/models/daos/ChatDao.java new file mode 100644 index 0000000..04b3adb --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/models/daos/ChatDao.java @@ -0,0 +1,28 @@ +package io.github.chronosx88.influence.models.daos; + +import java.util.List; + +import androidx.room.Dao; +import androidx.room.Insert; +import androidx.room.OnConflictStrategy; +import androidx.room.Query; +import androidx.room.Update; +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; + +@Dao +public interface ChatDao { + @Insert(onConflict = OnConflictStrategy.IGNORE) + void addChat(ChatEntity chatEntity); + + @Query("DELETE FROM chats WHERE jid = :jid") + void deleteChat(String jid); + + @Query("SELECT * FROM chats") + List getAllChats(); + + @Query("SELECT * FROM chats WHERE jid = :jid") + List getChatByChatID(String jid); + + @Update + void updateChat(ChatEntity chat); +} diff --git a/app/src/main/java/io/github/chronosx88/influence/models/daos/MessageDao.java b/app/src/main/java/io/github/chronosx88/influence/models/daos/MessageDao.java new file mode 100644 index 0000000..bba41ae --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/models/daos/MessageDao.java @@ -0,0 +1,31 @@ +package io.github.chronosx88.influence.models.daos; + +import java.util.List; + +import androidx.room.Dao; +import androidx.room.Insert; +import androidx.room.OnConflictStrategy; +import androidx.room.Query; +import androidx.room.Update; +import io.github.chronosx88.influence.models.roomEntities.MessageEntity; + +@Dao +public interface MessageDao { + @Insert(onConflict = OnConflictStrategy.IGNORE) + long insertMessage(MessageEntity chatModel); + + @Query("DELETE FROM messages WHERE messageID = :messageID") + void deleteMessage(String messageID); + + @Query("DELETE FROM messages WHERE jid = :jid") + void deleteMessagesByChatID(String jid); + + @Query("SELECT * FROM messages WHERE jid = :jid") + List getMessagesByChatID(String jid); + + @Query("SELECT * FROM messages WHERE messageID = :messageID") + List getMessageByID(long messageID); + + @Update + void updateMessage(MessageEntity message); +} diff --git a/app/src/main/java/io/github/chronosx88/influence/models/roomEntities/ChatEntity.java b/app/src/main/java/io/github/chronosx88/influence/models/roomEntities/ChatEntity.java new file mode 100644 index 0000000..8bf0476 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/models/roomEntities/ChatEntity.java @@ -0,0 +1,17 @@ +package io.github.chronosx88.influence.models.roomEntities; + +import androidx.annotation.NonNull; +import androidx.room.ColumnInfo; +import androidx.room.Entity; +import androidx.room.PrimaryKey; + +@Entity(tableName = "chats") +public class ChatEntity { + @PrimaryKey @NonNull public String jid; + @ColumnInfo public String chatName; + + public ChatEntity(@NonNull String jid, String chatName) { + this.jid = jid; + this.chatName = chatName; + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/models/roomEntities/MessageEntity.java b/app/src/main/java/io/github/chronosx88/influence/models/roomEntities/MessageEntity.java new file mode 100644 index 0000000..a152dde --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/models/roomEntities/MessageEntity.java @@ -0,0 +1,32 @@ +package io.github.chronosx88.influence.models.roomEntities; + +import androidx.annotation.NonNull; +import androidx.room.ColumnInfo; +import androidx.room.Entity; +import androidx.room.PrimaryKey; + +@Entity(tableName = "messages") +public class MessageEntity { + @PrimaryKey(autoGenerate = true) public long messageID; // Global message ID + @ColumnInfo public String jid; // Chat ID + @ColumnInfo public String senderJid; + @ColumnInfo public long timestamp; // Timestamp + @ColumnInfo public String text; // Message text + @ColumnInfo public boolean isSent; // Send status indicator + @ColumnInfo public boolean isRead; // Message Read Indicator + + public MessageEntity(String jid, String senderJid, long timestamp, String text, boolean isSent, boolean isRead) { + this.jid = jid; + this.senderJid = senderJid; + this.timestamp = timestamp; + this.text = text; + this.isSent = isSent; + this.isRead = isRead; + } + + @NonNull + @Override + public String toString() { + return text; + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/observable/MainObservable.java b/app/src/main/java/io/github/chronosx88/influence/observable/MainObservable.java new file mode 100644 index 0000000..5d40190 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/observable/MainObservable.java @@ -0,0 +1,56 @@ +package io.github.chronosx88.influence.observable; + +import com.google.gson.JsonObject; + +import java.util.ArrayList; + +import io.github.chronosx88.influence.contracts.observer.INetworkObserver; +import io.github.chronosx88.influence.contracts.observer.IObservable; +import io.github.chronosx88.influence.contracts.observer.IObserver; + +public class MainObservable implements IObservable { + public static final int UI_ACTIONS_CHANNEL = 0; + public static final int OTHER_ACTIONS_CHANNEL = 1; + + private ArrayList uiObservers; + private ArrayList networkObservers; + + public MainObservable() { + this.uiObservers = new ArrayList<>(); + this.networkObservers = new ArrayList<>(); + } + + @Override + public void register(IObserver observer) { + uiObservers.add(observer); + } + + @Override + public void register(INetworkObserver observer) { + networkObservers.add(observer); + } + + @Override + public void unregister(IObserver observer) { + uiObservers.remove(observer); + } + + @Override + public void unregister(INetworkObserver observer) { + networkObservers.remove(observer); + } + + @Override + public void notifyUIObservers(JsonObject jsonObject) { + for (IObserver observer : uiObservers) { + observer.handleEvent(jsonObject); + } + } + + @Override + public void notifyNetworkObservers(Object object) { + for (INetworkObserver observer : networkObservers) { + observer.handleEvent(object); + } + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/presenters/ChatListPresenter.java b/app/src/main/java/io/github/chronosx88/influence/presenters/ChatListPresenter.java new file mode 100644 index 0000000..438cd47 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/presenters/ChatListPresenter.java @@ -0,0 +1,56 @@ +package io.github.chronosx88.influence.presenters; + +import android.content.Intent; +import android.view.MenuItem; + +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.helpers.ChatListAdapter; +import io.github.chronosx88.influence.helpers.LocalDBWrapper; +import io.github.chronosx88.influence.logic.ChatListLogic; +import io.github.chronosx88.influence.models.roomEntities.ChatEntity; +import io.github.chronosx88.influence.views.ChatActivity; + +public class ChatListPresenter implements CoreContracts.IChatListPresenterContract { + private CoreContracts.IChatListViewContract view; + private CoreContracts.IChatListLogicContract logic; + private ChatListAdapter chatListAdapter; + + public ChatListPresenter(CoreContracts.IChatListViewContract view) { + this.view = view; + chatListAdapter = new ChatListAdapter((v, p)-> { + openChat(chatListAdapter.getChatEntity(p).chatID); + }); + this.logic = new ChatListLogic(); + this.view.setRecycleAdapter(chatListAdapter); + } + + @Override + public void updateChatList() { + view.updateChatList(chatListAdapter, logic.loadAllChats()); + } + + @Override + public void openChat(String chatID) { + Intent intent = new Intent(AppHelper.getContext(), ChatActivity.class); + intent.putExtra("chatID", chatID); + intent.putExtra("contactUsername", LocalDBWrapper.getChatByChatID(chatID).name); + view.startActivity(intent); + } + + @Override + public void onContextItemSelected(MenuItem item) { + switch(item.getItemId()) { + case 0: { + if(chatListAdapter.onClickPosition != -1) { + new Thread(() -> { + ChatEntity chat = chatListAdapter.getItem(chatListAdapter.onClickPosition); + AppHelper.getChatDB().chatDao().deleteChat(chat.chatID); + AppHelper.getChatDB().messageDao().deleteMessagesByChatID(chat.chatID); + view.updateChatList(chatListAdapter, logic.loadAllChats()); + }).start(); + } + } + } + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/presenters/ChatPresenter.kt b/app/src/main/java/io/github/chronosx88/influence/presenters/ChatPresenter.kt new file mode 100644 index 0000000..a81e494 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/presenters/ChatPresenter.kt @@ -0,0 +1,70 @@ +package io.github.chronosx88.influence.presenters + +import android.widget.Toast + +import com.google.gson.Gson +import com.google.gson.JsonObject +import com.instacart.library.truetime.TrueTime + +import java.io.IOException +import java.util.ArrayList +import java.util.UUID + +import io.github.chronosx88.influence.contracts.CoreContracts +import io.github.chronosx88.influence.contracts.observer.IObserver +import io.github.chronosx88.influence.helpers.AppHelper +import io.github.chronosx88.influence.helpers.LocalDBWrapper +import io.github.chronosx88.influence.helpers.actions.NetworkActions +import io.github.chronosx88.influence.helpers.actions.UIActions +import io.github.chronosx88.influence.logic.ChatLogic +import io.github.chronosx88.influence.models.roomEntities.ChatEntity +import org.jetbrains.anko.doAsync +import org.jetbrains.anko.doAsyncResult + +class ChatPresenter(private val view: CoreContracts.IChatViewContract, private val chatID: String) : CoreContracts.IChatPresenterContract, IObserver { + private val logic: CoreContracts.IChatLogicContract + private val chatEntity: ChatEntity? + private val gson: Gson + + init { + this.logic = ChatLogic(LocalDBWrapper.getChatByChatID(chatID)!!) + this.chatEntity = LocalDBWrapper.getChatByChatID(chatID) + + AppHelper.getObservable().register(this) + gson = Gson() + } + + override fun sendMessage(text: String) { + doAsync { + val message = LocalDBWrapper.createMessageEntry(NetworkActions.TEXT_MESSAGE, UUID.randomUUID().toString(), chatID, AppHelper.getPeerID(), AppHelper.getPeerID(), TrueTime.now().time, text, false, false) + logic.sendMessage(message!!) + view.updateMessageList(message) + } + } + + override fun handleEvent(obj: JsonObject) { + when (obj.get("action").asInt) { + UIActions.MESSAGE_RECEIVED -> { + val jsonArray = obj.getAsJsonArray("additional") + if (jsonArray.get(0).asString != chatID) { + return + } + val messageEntity = LocalDBWrapper.getMessageByID(jsonArray.get(1).asString) + view.updateMessageList(messageEntity!!) + } + + UIActions.NODE_IS_OFFLINE -> { + Toast.makeText(AppHelper.getContext(), "Нода не запущена!", Toast.LENGTH_SHORT).show() + } + } + } + + override fun updateAdapter() { + val entities = LocalDBWrapper.getMessagesByChatID(chatID) + view.updateMessageList(entities ?: ArrayList()) + } + + override fun onDestroy() { + logic.stopTrackingForNewMsgs() + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/presenters/MainPresenter.kt b/app/src/main/java/io/github/chronosx88/influence/presenters/MainPresenter.kt new file mode 100644 index 0000000..6db7273 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/presenters/MainPresenter.kt @@ -0,0 +1,56 @@ +package io.github.chronosx88.influence.presenters + +import com.google.gson.JsonObject +import io.github.chronosx88.influence.R +import io.github.chronosx88.influence.contracts.CoreContracts +import io.github.chronosx88.influence.contracts.observer.IObserver +import io.github.chronosx88.influence.helpers.AppHelper +import io.github.chronosx88.influence.helpers.actions.UIActions +import io.github.chronosx88.influence.logic.MainLogic +import org.jetbrains.anko.doAsync + +class MainPresenter(private val view: CoreContracts.IMainViewContract) : CoreContracts.IMainPresenterContract, IObserver { + private val logic: CoreContracts.IMainLogicContract = MainLogic() + + init { + AppHelper.getObservable().register(this) + } + + override fun initPeer() { + if (AppHelper.getPeerDHT() == null) { + logic.initPeer() + } else { + view.showSnackbar(AppHelper.getContext().getString(R.string.node_already_running)) + view.showProgressBar(false) + } + } + + override fun startChatWithPeer(username: String) { + doAsync { + logic.sendStartChatMessage(username) + } + } + + override fun handleEvent(obj: JsonObject) { + when(obj.get("action").asInt) { + UIActions.PEER_NOT_EXIST -> { + view.showProgressBar(false) + view.showSnackbar("Данный узел не существует!") + } + + UIActions.NEW_CHAT -> { + view.showProgressBar(false) + view.showSnackbar("Чат успешно создан!") + } + + UIActions.NODE_IS_OFFLINE -> { + view.showProgressBar(false) + view.showSnackbar("Нода не запущена!") + } + } + } + + override fun onDestroy() { + logic.shutdownPeer() + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/presenters/SettingsPresenter.kt b/app/src/main/java/io/github/chronosx88/influence/presenters/SettingsPresenter.kt new file mode 100644 index 0000000..8a538cf --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/presenters/SettingsPresenter.kt @@ -0,0 +1,74 @@ +package io.github.chronosx88.influence.presenters + +import android.content.SharedPreferences +import android.os.Handler +import com.google.gson.JsonObject +import io.github.chronosx88.influence.R +import io.github.chronosx88.influence.contracts.CoreContracts +import io.github.chronosx88.influence.contracts.observer.IObserver +import io.github.chronosx88.influence.helpers.AppHelper +import io.github.chronosx88.influence.helpers.ObservableUtils +import io.github.chronosx88.influence.helpers.actions.UIActions +import io.github.chronosx88.influence.logic.SettingsLogic +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch + +class SettingsPresenter(private val view: CoreContracts.ISettingsView) : CoreContracts.ISettingsPresenter, IObserver { + private val mainThreadHandler: Handler = Handler(AppHelper.getContext().mainLooper) + private val logic: SettingsLogic = SettingsLogic() + + init { + AppHelper.getObservable().register(this) + } + + override fun updateUsername(username: String) { + view.loadingScreen(true) + val editor: SharedPreferences.Editor = AppHelper.getPreferences().edit() + + GlobalScope.launch { + val oldUsername = AppHelper.getPreferences().getString("username", null) + if(username.equals("")) { + SettingsLogic.publishUsername(oldUsername, null) + editor.remove("username") + editor.apply() + AppHelper.updateUsername(null) + ObservableUtils.notifyUI(UIActions.USERNAME_AVAILABLE) + return@launch + } + if(!logic.checkUsernameExists(username)) { + // Save username in SharedPreferences + if(username.equals("")) { + editor.remove("username") + } else { + editor.putString("username", username) + } + editor.apply() + AppHelper.updateUsername(if (username.equals("")) null else username) + + // Publish username on DHT network + SettingsLogic.publishUsername(oldUsername, username) + + ObservableUtils.notifyUI(UIActions.USERNAME_AVAILABLE) + } else { + ObservableUtils.notifyUI(UIActions.USERNAME_ISNT_AVAILABLE) + } + } + } + + override fun handleEvent(json: JsonObject) { + val post = { + when (json.get("action").asInt) { + UIActions.USERNAME_AVAILABLE -> { + view.loadingScreen(false) + view.showMessage(AppHelper.getContext().getString(R.string.username_saved)) + view.refreshScreen() + } + UIActions.USERNAME_ISNT_AVAILABLE -> { + view.loadingScreen(false) + view.showMessage(AppHelper.getContext().getString(R.string.username_isnt_saved)) + } + } + } + mainThreadHandler.post(post) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/views/ChatActivity.kt b/app/src/main/java/io/github/chronosx88/influence/views/ChatActivity.kt new file mode 100644 index 0000000..5101141 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/views/ChatActivity.kt @@ -0,0 +1,87 @@ +package io.github.chronosx88.influence.views + +import android.os.Bundle +import android.view.MenuItem +import android.widget.EditText +import android.widget.ImageButton +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.widget.Toolbar +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import io.github.chronosx88.influence.R +import io.github.chronosx88.influence.contracts.CoreContracts +import io.github.chronosx88.influence.helpers.ChatAdapter +import io.github.chronosx88.influence.models.roomEntities.MessageEntity +import io.github.chronosx88.influence.presenters.ChatPresenter + +class ChatActivity : AppCompatActivity(), CoreContracts.IChatViewContract { + private var chatAdapter: ChatAdapter? = null + private var messageList: RecyclerView? = null + private var sendMessageButton: ImageButton? = null + private var messageTextEdit: EditText? = null + private var contactUsernameTextView: TextView? = null + private var presenter: ChatPresenter? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_chat) + + val intent = intent + + presenter = ChatPresenter(this, intent.getStringExtra("chatID")) + val toolbar = findViewById(R.id.toolbar_chat_activity) + setSupportActionBar(toolbar) + supportActionBar!!.setTitle("") + supportActionBar!!.setDisplayHomeAsUpEnabled(true) + supportActionBar!!.setHomeButtonEnabled(true) + messageList = findViewById(R.id.message_list) + chatAdapter = ChatAdapter() + presenter!!.updateAdapter() + messageList!!.adapter = chatAdapter + messageList!!.layoutManager = LinearLayoutManager(this) + contactUsernameTextView = findViewById(R.id.appbar_username) + messageTextEdit = findViewById(R.id.message_input) + sendMessageButton = findViewById(R.id.send_button) + sendMessageButton!!.setOnClickListener sendMessageButton@{ + if (messageTextEdit!!.text.toString() == "") { + return@sendMessageButton + } + presenter!!.sendMessage(messageTextEdit!!.text.toString()) + messageTextEdit!!.setText("") + } + contactUsernameTextView!!.text = intent.getStringExtra("contactUsername") + messageList!!.scrollToPosition(chatAdapter!!.itemCount - 1) + } + + override fun updateMessageList(message: MessageEntity) { + runOnUiThread { + chatAdapter!!.addMessage(message) + messageList!!.scrollToPosition(chatAdapter!!.itemCount - 1) + chatAdapter!!.notifyDataSetChanged() + } + } + + override fun updateMessageList(messages: List) { + runOnUiThread { + chatAdapter!!.addMessages(messages) + messageList!!.scrollToPosition(chatAdapter!!.itemCount - 1) + chatAdapter!!.notifyDataSetChanged() + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + android.R.id.home -> { + finish() + return true + } + } + return super.onOptionsItemSelected(item) + } + + override fun onDestroy() { + super.onDestroy() + presenter!!.onDestroy() + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/views/LoginActivity.java b/app/src/main/java/io/github/chronosx88/influence/views/LoginActivity.java new file mode 100644 index 0000000..f07a5eb --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/views/LoginActivity.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2019 ChronosX88 + * + * 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 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package io.github.chronosx88.influence.views; + +import android.app.ProgressDialog; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; + +import androidx.appcompat.app.AppCompatActivity; + +import io.github.chronosx88.influence.R; +import io.github.chronosx88.influence.XMPPConnectionService; +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.helpers.AppHelper; + +public class LoginActivity extends AppCompatActivity implements CoreContracts.ILoginViewContract { + private EditText jidEditText; + private EditText passwordEditText; + private Button signInButton; + private BroadcastReceiver broadcastReceiver; + private ProgressDialog progressDialog; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_login); + jidEditText = findViewById(R.id.login_jid); + passwordEditText = findViewById(R.id.login_password); + signInButton = findViewById(R.id.sign_in_button); + progressDialog = new ProgressDialog(LoginActivity.this); + signInButton.setOnClickListener((v) -> { + if(checkLoginCredentials()) { + saveLoginCredentials(); + doLogin(); + } + }); + } + + @Override + public void loadingScreen(boolean state) { + if(state) + progressDialog.show(); + else + progressDialog.dismiss(); + } + + @Override + protected void onResume() { + super.onResume(); + broadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + String action = intent.getAction(); + switch (action) { + case XMPPConnectionService.INTENT_AUTHENTICATED: { + loadingScreen(false); + finish(); + break; + } + case XMPPConnectionService.INTENT_AUTHENTICATION_FAILED: { + loadingScreen(false); + passwordEditText.setError("Invalid JID/Password"); + break; + } + } + } + }; + IntentFilter filter = new IntentFilter(); + filter.addAction(XMPPConnectionService.INTENT_AUTHENTICATED); + filter.addAction(XMPPConnectionService.INTENT_AUTHENTICATION_FAILED); + this.registerReceiver(broadcastReceiver, filter); + } + + @Override + protected void onPause() { + super.onPause(); + this.unregisterReceiver(broadcastReceiver); + } + + private boolean checkLoginCredentials() { + jidEditText.setError(null); + passwordEditText.setError(null); + + String jid = jidEditText.getText().toString(); + String password = passwordEditText.getText().toString(); + + boolean cancel = false; + View focusView = null; + + if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { + passwordEditText.setError("Invalid password"); + focusView = passwordEditText; + cancel = true; + } + + if (TextUtils.isEmpty(jid)) { + jidEditText.setError("Field is required!"); + focusView = jidEditText; + cancel = true; + } else if (!isEmailValid(jid)) { + jidEditText.setError("Invalid JID"); + focusView = jidEditText; + cancel = true; + } + + if (cancel) { + focusView.requestFocus(); + return false; + } else { + return true; + } + } + + private boolean isEmailValid(String email) { + return email.contains("@"); + } + + private boolean isPasswordValid(String password) { + return password.length() > 4; + } + + private void saveLoginCredentials() { + AppHelper.getPreferences().edit() + .putString("jid", jidEditText.getText().toString()) + .putString("pass", passwordEditText.getText().toString()) + .putBoolean("logged_in", true) + .apply(); + } + + private void doLogin() { + loadingScreen(true); + startService(new Intent(this, XMPPConnectionService.class)); + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/views/MainActivity.java b/app/src/main/java/io/github/chronosx88/influence/views/MainActivity.java new file mode 100644 index 0000000..1d3f72f --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/views/MainActivity.java @@ -0,0 +1,152 @@ +package io.github.chronosx88.influence.views; + +import android.app.ProgressDialog; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.Toast; + +import com.google.android.material.bottomnavigation.BottomNavigationView; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.android.material.snackbar.Snackbar; +import com.google.gson.JsonObject; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentTransaction; + +import org.jetbrains.annotations.NotNull; + +import io.github.chronosx88.influence.R; +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.contracts.observer.IObserver; +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.helpers.actions.UIActions; +import io.github.chronosx88.influence.presenters.MainPresenter; +import io.github.chronosx88.influence.views.fragments.ChatListFragment; +import io.github.chronosx88.influence.views.fragments.SettingsFragment; +import kotlin.Pair; + +public class MainActivity extends AppCompatActivity implements CoreContracts.IMainViewContract { + + private CoreContracts.IMainPresenterContract presenter; + private ProgressDialog progressDialog; + private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener + = new BottomNavigationView.OnNavigationItemSelectedListener() { + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem item) { + + Fragment selectedFragment = null; + + switch (item.getItemId()) { + case R.id.action_chats: + selectedFragment = new ChatListFragment(); + break; + case R.id.action_settings: + selectedFragment = new SettingsFragment(); + break; + } + + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.main_fragment_container, selectedFragment); + transaction.commit(); + + return true; + } + + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + BottomNavigationView navigation = findViewById(R.id.main_bottom_navigation); + navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); + + FloatingActionButton fab = findViewById(R.id.add_chat); + fab.setOnClickListener((v) -> { + Pair pair = ViewUtils.INSTANCE.setupEditTextDialog(MainActivity.this, getString(R.string.input_companion_username)); + pair.getFirst().setPositiveButton(getString(R.string.ok), (dialog, which) -> { + progressDialog.show(); + presenter.startChatWithPeer(pair.getSecond().getText().toString()); + }); + pair.getFirst().setNegativeButton(getString(R.string.cancel), (dialog, which) -> { + dialog.cancel(); + }); + pair.getFirst().show(); + }); + + getSupportFragmentManager() + .beginTransaction() + .replace(R.id.main_fragment_container, new ChatListFragment()) + .commit(); + + presenter = new MainPresenter(this); + + + progressDialog = new ProgressDialog(MainActivity.this, R.style.AlertDialogTheme); + progressDialog.setCancelable(false); + progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small); + progressDialog.show(); + presenter.initPeer(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + presenter.onDestroy(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main_actionbar_menu, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if(item.getItemId() == R.id.action_reconnect_network) { + progressDialog.show(); + presenter.initPeer(); + } + return true; + } + + @Override + public void showSnackbar(@NotNull String message) { + runOnUiThread(() -> { + Snackbar.make(getRootView(), message, Snackbar.LENGTH_LONG) + .show(); + }); + } + + @Override + public void showProgressBar(boolean state) { + runOnUiThread(() -> { + if(state) { + progressDialog.show(); + } else { + progressDialog.dismiss(); + } + }); + } + + private View getRootView() { + final ViewGroup contentViewGroup = findViewById(android.R.id.content); + View rootView = null; + + if(contentViewGroup != null) + rootView = contentViewGroup.getChildAt(0); + + if(rootView == null) + rootView = getWindow().getDecorView().getRootView(); + + return rootView; + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/views/ViewUtils.kt b/app/src/main/java/io/github/chronosx88/influence/views/ViewUtils.kt new file mode 100644 index 0000000..d27d377 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/views/ViewUtils.kt @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2019 ChronosX88 + * + * 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 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package io.github.chronosx88.influence.views + +import android.content.Context +import android.widget.EditText +import android.widget.LinearLayout +import androidx.appcompat.app.AlertDialog +import io.github.chronosx88.influence.R + +object ViewUtils { + fun setupEditTextDialog(context: Context, message: String): Pair { + val alertDialog = AlertDialog.Builder(context) + alertDialog.setTitle(message) + + val input = EditText(context) + val lp = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT) + input.setSingleLine() + input.layoutParams = lp + + alertDialog.setView(input) + + return Pair(alertDialog, input) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/github/chronosx88/influence/views/fragments/ChatListFragment.kt b/app/src/main/java/io/github/chronosx88/influence/views/fragments/ChatListFragment.kt new file mode 100644 index 0000000..433db06 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/views/fragments/ChatListFragment.kt @@ -0,0 +1,76 @@ +package io.github.chronosx88.influence.views.fragments + +import android.os.Bundle +import android.os.Handler +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup + +import com.google.gson.JsonObject +import androidx.fragment.app.Fragment +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import io.github.chronosx88.influence.R +import io.github.chronosx88.influence.contracts.CoreContracts +import io.github.chronosx88.influence.contracts.observer.IObserver +import io.github.chronosx88.influence.helpers.AppHelper +import io.github.chronosx88.influence.helpers.ChatListAdapter +import io.github.chronosx88.influence.helpers.actions.UIActions +import io.github.chronosx88.influence.models.roomEntities.ChatEntity +import io.github.chronosx88.influence.presenters.ChatListPresenter + +class ChatListFragment : Fragment(), CoreContracts.IChatListViewContract, IObserver { + private var presenter: CoreContracts.IChatListPresenterContract? = null + private var chatList: RecyclerView? = null + private var mainThreadHandler: Handler? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + AppHelper.getObservable().register(this) + this.mainThreadHandler = Handler(context!!.mainLooper) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.chatlist_fragment, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + chatList = view.findViewById(R.id.chatlist_container) + chatList!!.layoutManager = LinearLayoutManager(context) + presenter = ChatListPresenter(this) + presenter!!.updateChatList() + registerForContextMenu(chatList!!) + } + + override fun setRecycleAdapter(adapter: ChatListAdapter) { + chatList!!.adapter = adapter + } + + override fun onResume() { + super.onResume() + presenter!!.updateChatList() + } + + override fun handleEvent(`object`: JsonObject) { + when (`object`.get("action").asInt) { + UIActions.SUCCESSFUL_CREATE_CHAT, UIActions.NEW_CHAT -> { + presenter!!.updateChatList() + } + } + } + + override fun updateChatList(adapter: ChatListAdapter, chats: List) { + mainThreadHandler!!.post { + adapter.setChatList(chats) + adapter.notifyDataSetChanged() + } + } + + override fun onContextItemSelected(item: MenuItem): Boolean { + presenter!!.onContextItemSelected(item) + return super.onContextItemSelected(item) + } +} diff --git a/app/src/main/java/io/github/chronosx88/influence/views/fragments/SettingsFragment.java b/app/src/main/java/io/github/chronosx88/influence/views/fragments/SettingsFragment.java new file mode 100644 index 0000000..e333c28 --- /dev/null +++ b/app/src/main/java/io/github/chronosx88/influence/views/fragments/SettingsFragment.java @@ -0,0 +1,92 @@ +package io.github.chronosx88.influence.views.fragments; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.os.Bundle; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.Toast; + +import org.jetbrains.annotations.NotNull; + +import androidx.preference.PreferenceFragmentCompat; +import androidx.preference.PreferenceScreen; +import androidx.recyclerview.widget.RecyclerView; + +import io.github.chronosx88.influence.R; +import io.github.chronosx88.influence.contracts.CoreContracts; +import io.github.chronosx88.influence.helpers.AppHelper; +import io.github.chronosx88.influence.presenters.SettingsPresenter; + +public class SettingsFragment extends PreferenceFragmentCompat implements CoreContracts.ISettingsView { + private ProgressDialog progressDialog; + private SettingsPresenter presenter; + + @Override + public void onCreatePreferences(Bundle bundle, String s) { + progressDialog = new ProgressDialog(getContext(), R.style.AlertDialogTheme); + progressDialog.setCancelable(false); + progressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small); + presenter = new SettingsPresenter(this); + // Load the Preferences from the XML file + addPreferencesFromResource(R.xml.main_settings); + getPreferenceScreen().getPreference(0).setSummary(AppHelper.getPeerID()); + getPreferenceScreen().getPreference(0).setOnPreferenceClickListener((preference -> { + ClipboardManager clipboard = (ClipboardManager) AppHelper.getContext().getSystemService(Context.CLIPBOARD_SERVICE); + ClipData clip = ClipData.newPlainText("", AppHelper.getPeerID()); + clipboard.setPrimaryClip(clip); + Toast.makeText(AppHelper.getContext(), "Скопировано в буфер обмена!", Toast.LENGTH_SHORT).show(); + return false; + })); + getPreferenceScreen().getPreference(1).setSummary(AppHelper.getUsername()); + getPreferenceScreen().getPreference(1).setOnPreferenceClickListener((v) -> { + setupUsernameEditDialog().show(); + return true; + }); + getPreferenceScreen().getPreference(1).setOnPreferenceChangeListener((p, nV) -> { + getPreferenceScreen().getPreference(1).setSummary((String) nV); + return true; + }); + } + + @Override + public void loadingScreen(boolean state) { + if(state) + progressDialog.show(); + else + progressDialog.dismiss(); + } + + @Override + public void showMessage(@NotNull String message) { + Toast.makeText(AppHelper.getContext(), message, Toast.LENGTH_LONG).show(); + } + + private AlertDialog.Builder setupUsernameEditDialog() { + AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext()); + alertDialog.setTitle(getContext().getString(R.string.username_settings)); + + final EditText input = new EditText(getContext()); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT); + input.setSingleLine(); + input.setLayoutParams(lp); + input.setText(AppHelper.getPreferences().getString("username", null)); + + alertDialog.setView(input); + alertDialog.setPositiveButton(getContext().getString(R.string.ok), (dialog, which) -> presenter.updateUsername(input.getText().toString())); + alertDialog.setNegativeButton(getContext().getString(R.string.cancel), (dialog, which) -> dialog.cancel()); + + return alertDialog; + } + + @Override + public void refreshScreen() { + getPreferenceScreen().getPreference(1).callChangeListener(AppHelper.getPreferences().getString("username", null)); + } + +} diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..1f6bb29 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_add_white_24dp.xml b/app/src/main/res/drawable/ic_add_white_24dp.xml new file mode 100644 index 0000000..c618030 --- /dev/null +++ b/app/src/main/res/drawable/ic_add_white_24dp.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_autorenew_white_24dp.xml b/app/src/main/res/drawable/ic_autorenew_white_24dp.xml new file mode 100644 index 0000000..a23db6d --- /dev/null +++ b/app/src/main/res/drawable/ic_autorenew_white_24dp.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_chat_white.xml b/app/src/main/res/drawable/ic_chat_white.xml new file mode 100644 index 0000000..9e4340b --- /dev/null +++ b/app/src/main/res/drawable/ic_chat_white.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..0d025f9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_person_add_white.xml b/app/src/main/res/drawable/ic_person_add_white.xml new file mode 100644 index 0000000..c273ca4 --- /dev/null +++ b/app/src/main/res/drawable/ic_person_add_white.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_send_green_24dp.xml b/app/src/main/res/drawable/ic_send_green_24dp.xml new file mode 100644 index 0000000..475c0fa --- /dev/null +++ b/app/src/main/res/drawable/ic_send_green_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings_white.xml b/app/src/main/res/drawable/ic_settings_white.xml new file mode 100644 index 0000000..79af3ab --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_white.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/message_item_left_background.xml b/app/src/main/res/drawable/message_item_left_background.xml new file mode 100644 index 0000000..fb33822 --- /dev/null +++ b/app/src/main/res/drawable/message_item_left_background.xml @@ -0,0 +1,13 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/message_item_right_background.xml b/app/src/main/res/drawable/message_item_right_background.xml new file mode 100644 index 0000000..52d5c17 --- /dev/null +++ b/app/src/main/res/drawable/message_item_right_background.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_chat.xml b/app/src/main/res/layout/activity_chat.xml new file mode 100644 index 0000000..a8b9192 --- /dev/null +++ b/app/src/main/res/layout/activity_chat.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_login.xml b/app/src/main/res/layout/activity_login.xml new file mode 100644 index 0000000..f3ea72f --- /dev/null +++ b/app/src/main/res/layout/activity_login.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + +