diff --git a/.gitignore b/.gitignore index a8b0d1d..aa724b7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,15 @@ -# ---> Android -# Gradle files -.gradle/ -build/ - -# Local configuration file (sdk path, etc) -local.properties - -# Log/OS Files -*.log - -# Android Studio generated files and folders -captures/ -.externalNativeBuild/ -.cxx/ -*.apk -output.json - -# IntelliJ *.iml -.idea/ -misc.xml -deploymentTargetDropDown.xml -render.experimental.xml - -# Keystore files -*.jks -*.keystore - -# Google Services (e.g. APIs or Firebase) -google-services.json - -# Android Profiling -*.hprof - +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..8f1c1c8 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +Befund \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetDropDown.xml b/.idea/deploymentTargetDropDown.xml new file mode 100644 index 0000000..2784c9c --- /dev/null +++ b/.idea/deploymentTargetDropDown.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..a2d7c21 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..487c8e1 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..91072de --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/Documents/Design/Icon.psd b/app/Documents/Design/Icon.psd new file mode 100644 index 0000000..9d4476a Binary files /dev/null and b/app/Documents/Design/Icon.psd differ diff --git a/app/Documents/Keystore/bundle_key.jks b/app/Documents/Keystore/bundle_key.jks new file mode 100644 index 0000000..bef7b6c Binary files /dev/null and b/app/Documents/Keystore/bundle_key.jks differ diff --git a/app/Documents/Keystore/private_key.pepk b/app/Documents/Keystore/private_key.pepk new file mode 100644 index 0000000..ac166d1 Binary files /dev/null and b/app/Documents/Keystore/private_key.pepk differ diff --git a/app/Documents/Licenses/PdfViewer.txt b/app/Documents/Licenses/PdfViewer.txt new file mode 100644 index 0000000..4f44019 --- /dev/null +++ b/app/Documents/Licenses/PdfViewer.txt @@ -0,0 +1,2 @@ +https://github.com/barteksc/AndroidPdfViewer +Apache-2.0 license \ No newline at end of file diff --git a/app/Documents/Licenses/TweetNacl.txt b/app/Documents/Licenses/TweetNacl.txt new file mode 100644 index 0000000..a3f47e6 --- /dev/null +++ b/app/Documents/Licenses/TweetNacl.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2014-present tom zhou + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/app/Documents/Licenses/curve25519.txt b/app/Documents/Licenses/curve25519.txt new file mode 100644 index 0000000..8f9fe91 --- /dev/null +++ b/app/Documents/Licenses/curve25519.txt @@ -0,0 +1,682 @@ +https://github.com/signalapp/curve25519-java +https://mvnrepository.com/artifact/org.whispersystems/curve25519-java/0.5.0 + +/** + * Based on open sourcce + * https://github.com/java-crypto/cross_platform_crypto + **/ + + 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 +. \ No newline at end of file diff --git a/app/Documents/QR-Codes.docx b/app/Documents/QR-Codes.docx new file mode 100644 index 0000000..a96f4b1 Binary files /dev/null and b/app/Documents/QR-Codes.docx differ diff --git a/app/Documents/README.txt b/app/Documents/README.txt new file mode 100644 index 0000000..373995b --- /dev/null +++ b/app/Documents/README.txt @@ -0,0 +1,5 @@ +*** WORK WITH DEVELOPMENT HOST (OUTSIDE_SERVICE) *** +Set the host in befund.Core.Models.Settings ->load by labor to development: + +/** REMOVE BY PRODUCTIVE **/ +result.labor.host = Servers.DEVELOPMENT; \ No newline at end of file diff --git a/app/Documents/pba-datenschutz.html b/app/Documents/pba-datenschutz.html new file mode 100644 index 0000000..5534dd0 --- /dev/null +++ b/app/Documents/pba-datenschutz.html @@ -0,0 +1,164 @@ + + + + + + + + + + + +

Datenschutzerklärung Limbach Patienten App

+

Inhalt

+ +

 

+

ALLGEMEIN

+

Wir nehmen den Schutz Ihrer personenbezogenen Daten sehr ernst und behandeln diese vertraulich und entsprechend der gesetzlichen Datenschutzvorschriften sowie dieser Datenschutzerklärung. Diese Datenschutzerklärung gilt für unsere mobilen iPhone- und Android-Apps (im Folgenden „Limbach Patienten App“, „Befund-App“ oder kurz „App“). In ihr werden Art, Zweck und Umfang der Datenerhebung im Rahmen der APP-Nutzung erläutert. Wir weisen darauf hin, dass die Datenübertragung im Internet Sicherheitslücken aufweisen kann. Ein lückenloser Schutz der Daten vor dem Zugriff durch Dritte ist nicht möglich.

+

 

+

VERANTWORTLICHER

+

Als Verantwortlicher i.S.d. geltenden Datenschutzgesetze für diese Anwendung ergreifen wir,

MVZ Dr. Stein + Kollegen GbR
Tomphecke 45
41169 Mönchengladbach
Tel: 02161/ 8194 -0
Fax: 02161/ 8194 -50

alle nach geltendem Datenschutzrecht erforderlichen Maßnahmen, um den Schutz Ihrer personenbezogenen Daten zu gewährleisten. Bei allen Fragen bezüglich dieser Datenschutzerklärung bitten wir Sie, sich an unseren Datenschutzbeauftragten zu wenden.

2B Advice GmbH
Volker Schrödter
Joseph-Schumpeter-Allee 27
53227 Bonn
E-Mail: stein@2b-advice.com

+

Weitere Angaben zu unserem Unternehmen können Sie im Impressum auf unserer Website https://www.labor-stein.de/impressum/ entnehmen.

+

 

+

DIE APP

+

Die Limbach Patienten App wird zur Verfügung gestellt, um Testergebnisse, darunter auch COVID-19 Testergebnisse, schnell und einfach an Getestete zu übermitteln.

+

Was ist der Funktionsumfang

+

Die App ermöglicht dem Nutzer Befunde von Laboraufträgen digital innerhalb einer App zugänglich zu machen, insofern der Laborauftrag bei einem der teilnehmenden Labore der Limbach Gruppe SE beauftragt wurde.

+

Darüber hinaus bietet die App die optionale Möglichkeit, unter dem Reiter „Meine Patientendaten“ die persönlichen Informationen anzugeben, die notwendig sind, um einen Laborauftrag zu erstellen. Durch Angabe aller Pflichtfelder wird ein QR-Code erzeugt, der bei teilnehmenden Teststellen zur Erstellung eines Analyseauftrags ausgelesen werden kann, um eine schnelle, bequeme und weniger fehleranfällige Angabe der Daten, die ansonsten z.B. in Testzentren eine Ansprechperson vor Ort zu ermöglichen.

+

Welche Daten werden verarbeitet

+

Wenn Sie unsere Patienten App nutzen, verarbeiten wir die folgenden Daten für die Bereitstellung der App und der Befunde sowie zur Wahrung der Sicherheit bei dem Betrieb der App:

+
    +
  • Name und Vorname  (Optional)
  • +
  • Adresse  (Optional)
  • +
  • Telefonnummer  (Optional)
  • +
  • E-Mail-Adresse  (Optional)
  • +
  • Geburtsdatum  (Optional)
  • +
  • Auftragsnummer  (Optional)
  • +
  • Fingerprint und FaceID  (Funktional)
  • +
  • Kennung und Passwort  (Funktional)
  • +
  • Geräte-ID  (Funktional)
  • +
  • APP-ID  (Funktional)
  • +
  • Gesundheitsdaten (Befund*)  (Funktional)
  • +
  • Labor-Auftragsnummer  (Funktional)
  • +
  • Vorsatzwort  (Optional)
  • +
  • Geschlecht  (Optional)
  • +
+

*Die Befunddaten verbleiben auch bei einem Abruf der Daten auf eigenen Servern der Limbach Gruppe SE, die sich in Deutschland befinden. Sofern Sie die Daten nicht aus dem Ausland heraus abrufen, ist eine Übermittlung in Drittstaaten nicht geplant und auch technisch nicht erforderlich. Die Verbindung zwischen der App und unseren Servern ist nach dem Stand der Technik gesichert. Wir weisen an dieser Stelle noch einmal darauf hin, dass der sichere Betrieb der Befund-App zu einem erheblichen Teil davon abhängt, dass Sie ihre Zugangsdaten geheim halten und die Zugangsdaten nicht auf dem Gerät, mit dem Sie die Befund-App nutzen, speichern.

+

Ganz wichtig: Auf keinen Fall verkaufen wir Ihre personenbezogenen Daten an Dritte!

+

Funktional:

+

Die Verarbeitung dieser personenbezogenen Daten ist erforderlich, um die Funktionalitäten der APP zu gewährleisten. Rechtsgrundlage für diese Datenverarbeitung ist unser berechtigtes Interesse im Sinne von Art. 6 Abs. 1 lit. f DSGVO, – sofern ein Vertrag geschlossen wurde – die Erfüllung unserer vertraglichen Verpflichtungen (Art. 6 Abs. 1 lit. b DSGVO).

+

Optional:

+

Die optionalen personenbezogene Daten können Sie angeben, falls Sie die Funktion „Meine Patientendaten erfassen“ nutzen möchten (Zweck: bequeme Datenübermittlung via generiertem QR-Code zur Erstellung eines Testauftrags). Dies ist nicht erforderlich, um die Funktionalität der Übermittlung Ihres Befunds an die App zu nutzen. Rechtsgrundlage für diese Datenverarbeitung ist unser berechtigtes Interesse im Sinne von Art. 6 Abs. 1 lit. f DSGVO, ggf. Ihre Einwilligung im Sinne des Art. 6 Abs. 1 lit. a DSGVO.

+

 

+

Welche Berechtigungen benötigt die App

+

Zur Bereitstellung unserer Dienste über die APP benötigen wir die im folgenden aufgezählten

+

Zugriffsrechte, die es uns ermöglichen, auf bestimmte Funktionen Ihres Geräts zuzugreifen. Der Zugriff auf die Gerätefunktionen ist erforderlich, um die Funktionalitäten der APP zu gewährleisten. Rechtsgrundlage für diese Datenverarbeitung ist unser berechtigtes Interesse im Sinne von Art. 6 Abs. 1 lit. f DSGVO, Ihre Einwilligung im Sinne des Art. 6 Abs. 1 lit. a DSGVO und/oder – sofern ein Vertrag geschlossen wurde – die Erfüllung unserer vertraglichen Verpflichtungen (Art. 6 Abs. 1 lit. b DSGVO).

+

 

+

Kamera

+

Um den Nutzer dem richtigen Laborstandort zuordnen zu können, muss der Nutzer als ersten Schritt einen QR-Code scannen. Dieser wird ihm vom Teststandort z.B. in Form eines Flyers bereitgestellt. Durch Scannen des QR-Codes wird die Labor-ID ausgelesen und der Nutzer dem richtigen Laborstandort zugeordnet, damit die Anfrage des Nutzers am richtigen Labor landet und damit die Voraussetzungen erfüllt sind, dass dieses Labor letztendlich den Befund erfolgreich zustellen kann. Der Scan des QR-Codes innerhalb der App durch den App-Nutzer erfordert deshalb vorübergehend die Berechtigung für die Nutzung des Kamera-Sensors. Im Zuge des Scans eines QR-Codes werden außer der genannten Labor-ID keinerlei Bildinformationen gespeichert. Die Berechtigung für die Nutzung des Kamera-Sensors wird nicht dauerhaft benötigt und kann nach Abschluss des Scan-Vorgangs über die Systemeinstellungen wieder entzogen werden, ohne dass sich eine Einschränkung der weiteren Nutzung der App ergibt.

+

 

+

Push-Benachrichtigungen

+

Die Berechtigung der App zum Senden von Push-Benachrichtigungen ist nicht zwingend notwendig zur Verwendung der App, der Erhalt von Befunden ist grundsätzlich auch ohne diese Berechtigung möglich. Es wird dem Nutzer jedoch stark empfohlen, der App diese Berechtigung zu geben, da er damit über das Vorliegen des Befundes oder auch Probleme mit der Übermittlung informiert werden kann. Eine ausreichende Informationsübermittlung kann ohne die Berechtigung zur Übermittlung von Push-Nachrichten nicht gewährleistet werden. Im Zweifelsfall können Informationen jedoch auch über den Support angefragt werden.

+

 

+

Gerätekennung Ihres Smartphones

+

Die Gerätekennung wird bei der Registrierung durch den Nutzer im Laborinformationssystem mit dem jeweiligen Laborauftrag des Nutzers verknüpft, damit zu einem späteren Zeitpunkt (bei Fertigstellung des Befunds) dem Nutzer via der Gerätekennung (als eindeutiges Merkmal) der Befund auf seine App übertragen werden kann.

+

 

+

ZWECKE DER VERARBEITUNG PERSONENBEZOGENER DATEN UND FREIWILLIGE ANGABEN

+

Die App dient primär dem Zweck, dem Nutzer Befunde von Laboraufträgen digital innerhalb einer App zugänglich zu machen, insofern der Laborauftrag bei einem der teilnehmenden Labore der Limbach Gruppe SE beauftragt wurde. Damit der Nutzer Befunde abrufen kann, muss eine Registrierung stattfinden. Diese erfüllt zwei Zwecke:

+
    +
  1. Durch die Vergabe eines Passworts schützen Sie Ihren entstehenden Zugang zur App und damit künftige persönliche Daten innerhalb der App.
  2. +
  3. Durch die Angabe der persönlichen PLZ, Geburtsdatum und Auftragsnummer stellt der Nutzer eine Anfrage an das Labor zum Abruf seines Befunds. Die Angabe dieser persönlichen Daten dient dem Zweck der eindeutigen Verifizierung des Nutzers und schützt damit den Abruf von Befunddaten durch Unbefugte.
  4. +
+

Darüber hinaus bietet die App die optionale Möglichkeit, unter dem Reiter „Meine Patientendaten“ die persönlichen Informationen anzugeben, die notwendig sind, um einen Laborauftrag zu erstellen. Durch Angabe aller Pflichtfelder wird ein QR-Code erzeugt, der bei teilnehmenden Teststellen zur Erstellung eines Analyseauftrags ausgelesen werden kann. Der Zweck ist hierbei eine schnelle, bequeme und weniger fehleranfällige Angabe der Daten, die ansonsten z.B. in Testzentren eine Ansprechperson vor Ort übernimmt.

+

 

+

AUFBEWAHRUNG

+

Allgemeine Speicherdauer personenbezogener Daten Vorbehaltlich abweichender oder konkretisierender Angaben innerhalb dieser Datenschutzerklärung werden die von dieser APP erhobenen personenbezogenen Daten gespeichert, bis Sie uns zur Löschung auffordern, Ihre Einwilligung zur Speicherung widerrufen, die App löschen oder der Zweck für die Datenspeicherung entfällt. Sofern eine gesetzliche Pflicht zur Aufbewahrung oder ein sonstiger gesetzlich anerkannter Grund zur Speicherung der Daten (z.B. berechtigtes Interesse) besteht, werden die betreffenden personenbezogenen Daten nicht vor Wegfall des jeweiligen Aufbewahrungsgrundes gelöscht.

+

 

+

AUSKUNFT, LÖSCHUNG UND BERICHTIGUNG

+

Sie haben jederzeit das Recht auf unentgeltliche Auskunft über Ihre gespeicherten

+

personenbezogenen Daten, deren Herkunft und Empfänger und den Zweck der

+

Datenverarbeitung sowie ein Recht auf Berichtigung oder Löschung dieser Daten. Hierzu sowie

+

zu weiteren Fragen zum Thema personenbezogene Daten können Sie sich jederzeit unter der im

+

Impressum angegebenen Adresse an uns wenden.

+

Eine Löschung dieser Daten erfolgt unter Umständen in folgenden Fällen:

+
    +
  • Bei einem Reset der Datenbank aus software- und entwicklungsseitigen Gründen
  • +
  • Wahrnehmung des Löschanspruchs des Nutzers.
  • +
+

 

+

ERWEITERTE FUNKTIONEN

+

Die Anwendung erstellt bei der Verwendung eine Protokolldatei, welche unter anderem anonyme Nutzungsdaten enthält. Diese Datei wird niemals automatisch an uns oder Dritte gesendet.

+

WERBUNG

+

Ihre Daten werden zu keinem Zeitpunkt zu kommerziellen Zwecken verwendet. Die Limbach Gruppe SE speichert nur die Informationen, die sie benötigt, um den sicheren und funktionierenden Betrieb der Anwendung zu gewährleisten.

+

 

+

EMPFÄNGER / WEITERGABE VON DATEN

+

Daten, die Sie uns gegenüber angeben, werden grundsätzlich nicht an Dritte weitergegeben, es sei denn, dass dies zum Zwecke der Vertragsabwicklung oder Informationsbereitstellung erforderlich ist.

+

Wir setzen jedoch ggf. Dienstleister und Auftragsverarbeiter für den Betrieb dieser Anwendung oder für weitere Produkte von uns ein. Hier kann es vorkommen, dass ein Dienstleister Kenntnis von personenbezogenen Daten erhält. Wir wählen unsere Dienstleister sorgfältig aus – insbesondere im Hinblick auf Datenschutz und Datensicherheit – und treffen alle datenschutzrechtlich erforderlichen Maßnahmen für eine zulässige Datenverarbeitung.

+

 

+

DATENVERARBEITUNG AUSSERHALB DER EUROPÄISCHEN UNION

+

Eine Datenverarbeitung außerhalb der europäischen Union im Rahmen der Nutzung der App findet grundsätzlich nicht statt.

+

 

+

DATENSCHUTZ-BEAUFTRAGTER

+

Unseren Datenschutzbeauftragten erreichen Sie unter:

+

2B Advice GmbH
Volker Schrödter
Joseph-Schumpeter-Allee 27
53227 Bonn
E-Mail: stein@2b-advice.com

+

 

+

IHRE RECHTE ALS BETROFFENER

+

Die DSGVO gewährt Betroffenen, deren personenbezogene Daten von uns verarbeitet werden, bestimmte Rechte, über die wir Sie an dieser Stelle aufklären möchten:

+

 

+

Widerruf Ihrer Einwilligung zur Datenverarbeitung

+

Viele Datenverarbeitungsvorgänge sind nur mit Ihrer Einwilligung möglich. Diese werden wir vor Beginn der Datenverarbeitung ausdrücklich bei Ihnen einholen. Sie können diese Einwilligung jederzeit widerrufen. Dazu reicht eine formlose Mitteilung per E-Mail an it@labor-stein.de . Die Rechtmäßigkeit der bis zum Widerruf erfolgten Datenverarbeitungsvorgänge bleibt vom Widerruf unberührt.

+

 

+

WIDERSPRUCHSRECHT GEGEN DIE DATENERHEBUNG IN BESONDEREN FÄLLEN

+

SOWIE GEGEN DIREKTWERBUNG (ART. 21 DSGVO)

+

 

+

WENN DIE DATENVERARBEITUNG AUF GRUNDLAGE VON ART. 6 ABS. 1 LIT. E ODER F DSGVO ERFOLGT, HABEN SIE JEDERZEIT DAS RECHT, AUS GRÜNDEN, DIE SICH AUS IHRER BESONDEREN SITUATION ERGEBEN, GEGEN DIE VERARBEITUNG SIE BETREFFENDER PERSONENBEZOGENER DATEN WIDERSPRUCH EINZULEGEN; DIES GILT AUCH FÜR EIN AUF DIESE BESTIMMUNGEN GESTÜTZTES PROFILING. DIE JEWEILIGE RECHTSGRUNDLAGEN, AUF DENEN EINE VERARBEITUNG BERUHT, ENTNEHMEN SIE DIESER DATENSCHUTZERKLÄRUNG. WENN SIE WIDERSPRUCH EINLEGEN, WERDEN WIR DIE BETROFFENEN PERSONENBEZOGENEN DATEN NICHT MEHR VERARBEITEN, ES SEI DENN, WIR KÖNNEN ZWINGENDE SCHUTZWÜRDIGE GRÜNDE FÜR DIE VERARBEITUNG NACHWEISEN, DIE IHRE INTERESSEN, RECHTE UND FREIHEITEN ÜBERWIEGEN ODER DIE DER VERARBEITUNG DER GELTENDMACHUNG, AUSÜBUNG ODER VERTEIDIGUNG VON RECHTSANSPRÜCHEN DIENEN.

+

 

+

BESCHWERDERECHT BEI EINER AUFSICHTSBEHÖRDE

+

Im Falle von Verstößen gegen die DSGVO steht den Betroffenen ein Beschwerderecht bei einer Aufsichtsbehörde zu. Diese finden Sie unter https://www.bfdi.bund.de/DE/.
+Das Beschwerderecht besteht unbeschadet anderweitiger verwaltungsrechtlicher oder gerichtlicher Rechtsbehelfe.

+

 

+

ÄNDERUNG DIESER DATENSCHUTZHINWEISE

+

Wir überarbeiten diese Datenschutzhinweise bei Änderungen an dieser Anwendung oder bei sonstigen Anlässen, die dies erforderlich machen. Die jeweils aktuelle Fassung finden Sie stets unter dem Reiter Datenschutz in dieser Anwendung.

+

 

+

Stand: 19.12.2022

+ \ No newline at end of file diff --git a/app/Documents/~$-Codes.docx b/app/Documents/~$-Codes.docx new file mode 100644 index 0000000..d32f7e3 Binary files /dev/null and b/app/Documents/~$-Codes.docx differ diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..0655d17 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,57 @@ +plugins { + id 'com.android.application' +} + +android { + compileSdk 34 + + defaultConfig { + applicationId "de.labor_stein.befund" + minSdk 26 + targetSdk 34 + versionCode 11 + versionName "1.9" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + buildFeatures { + viewBinding true + } +} + +apply plugin: 'com.android.application' +apply plugin: 'com.google.gms.google-services' + +dependencies { + + implementation 'androidx.appcompat:appcompat:1.4.1' + implementation 'com.google.android.material:material:1.5.0' + implementation 'androidx.constraintlayout:constraintlayout:2.1.3' + implementation 'androidx.navigation:navigation-fragment:2.4.2' + implementation 'androidx.navigation:navigation-ui:2.4.2' + implementation 'com.google.firebase:firebase-messaging:21.1.0' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' + implementation 'androidx.camera:camera-core:1.1.0-alpha03' + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.3' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' + implementation 'org.whispersystems:curve25519-java:0.5.0' + implementation 'com.google.code.gson:gson:2.9.0' + implementation 'com.google.crypto.tink:tink-android:1.6.1' + implementation 'com.github.bumptech.glide:glide:4.9.0' + implementation 'com.github.barteksc:android-pdf-viewer:2.8.2' + implementation 'com.journeyapps:zxing-android-embedded:4.3.0' + implementation("androidx.biometric:biometric:1.1.0") + implementation platform('com.google.firebase:firebase-bom:30.2.0') +} \ No newline at end of file diff --git a/app/google-services.json b/app/google-services.json new file mode 100644 index 0000000..037071e --- /dev/null +++ b/app/google-services.json @@ -0,0 +1,39 @@ +{ + "project_info": { + "project_number": "127283607700", + "project_id": "befund-01", + "storage_bucket": "befund-01.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:127283607700:android:c2f0153fc4c20ef87a5c81", + "android_client_info": { + "package_name": "de.labor_stein.befund" + } + }, + "oauth_client": [ + { + "client_id": "127283607700-phvfe3dp6d41ej37b2m543ng16as8bki.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyBkmPBIyKCsYilMNH6lxjlgfNPxm3OPyoo" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "127283607700-phvfe3dp6d41ej37b2m543ng16as8bki.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /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 \ No newline at end of file diff --git a/app/release/app-release.aab b/app/release/app-release.aab new file mode 100644 index 0000000..b999e15 Binary files /dev/null and b/app/release/app-release.aab differ diff --git a/app/src/androidTest/java/de/labor_stein/befund/ButtonNewPGS.java b/app/src/androidTest/java/de/labor_stein/befund/ButtonNewPGS.java new file mode 100644 index 0000000..3e360c0 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/ButtonNewPGS.java @@ -0,0 +1,2 @@ +package de.labor_stein.befund;public class ButtonNewPGS { +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Controllers/BaseTestController.java b/app/src/androidTest/java/de/labor_stein/befund/Controllers/BaseTestController.java new file mode 100644 index 0000000..53c1908 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Controllers/BaseTestController.java @@ -0,0 +1,15 @@ +// +// BaseTestController.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 23.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Controllers; + +public class BaseTestController +{ + protected final String ServiceOutsideHost = "https://localhost"; + protected final String DeviceToken = "2490374d42c895fb1f3619a4436c6b4ba5f4e824af1eec3a16c2ab5a1135679b"; + protected final String DeviceUDID = "0D36D896-F44E-4A7C-B886-2895866D3DE1"; +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Controllers/ExchangeControllerTest.java b/app/src/androidTest/java/de/labor_stein/befund/Controllers/ExchangeControllerTest.java new file mode 100644 index 0000000..b39d4a5 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Controllers/ExchangeControllerTest.java @@ -0,0 +1,37 @@ +// +// ExchangeControllerTest.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 23.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Controllers; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Https.Servers; + +public class ExchangeControllerTest +{ + @Test + public void KeyExchangeAsync() + { + Request.KeyExchangeAsync(Servers.DEVELOPMENT, + null, + (publicKey) -> + { + assertNotNull(publicKey); + assertNotNull(publicKey.key); + }, + (error) -> + { + assertNull(error); + }); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Controllers/ResultsControllerTest.java b/app/src/androidTest/java/de/labor_stein/befund/Controllers/ResultsControllerTest.java new file mode 100644 index 0000000..1fb607b --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Controllers/ResultsControllerTest.java @@ -0,0 +1,75 @@ +// +// ResultsControllerTest.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 24.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Controllers; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import android.service.controls.DeviceTypes; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Locale; +import java.util.UUID; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Https.Servers; +import de.labor_stein.befund.Core.Models.Database.Results; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Request.Subscribe; +import de.labor_stein.befund.Core.Models.Response.Success; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Curve25519; +import de.labor_stein.befund.Core.Security.SHA512; + +public class ResultsControllerTest extends BaseTestController +{ + @Test + public void Subscribe() + { + Request.KeyExchangeAsync(Servers.DEVELOPMENT, + null, + (publicKey) -> + { + assertNotNull(publicKey); + assertNotNull(publicKey.key); + + Curve25519.KeyPair keyPair = Curve25519.GenerateKeyPair(); + + Subscribe subscribe = new Subscribe(); + subscribe.device_token = this.DeviceToken; + subscribe.udid = UUID.randomUUID().toString().substring(0, 25); + subscribe.pgs = SHA512.Encrypt(UUID.randomUUID().toString()); + subscribe.client_public_key = keyPair.PublicKey; + subscribe.device_type = Results.DeviceTypes.ANDROID.ordinal(); + subscribe.verificator_hash = SHA512.HMAC("Test", AES.GetKey("TEST")); + EncryptedRequest request = new EncryptedRequest("Subscribe", subscribe, keyPair.GetSharedKey(publicKey.key)); + + Request.EncryptedRequestAsync(Servers.DEVELOPMENT, + "results", + "subscribe", + request, + publicKey, + keyPair, + (encryptedResponse) -> + { + Success success = (Success)encryptedResponse.Decrypt(keyPair.GetSharedKey(publicKey.key), Success.class); + Assert.assertTrue(encryptedResponse.descriptor.equals("success")); + }, + (error) -> + { + assertNull(error); + }); + }, + (error) -> + { + assertNull(error); + }); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/ExampleInstrumentedTest.java b/app/src/androidTest/java/de/labor_stein/befund/ExampleInstrumentedTest.java new file mode 100644 index 0000000..2c69f9a --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/ExampleInstrumentedTest.java @@ -0,0 +1,30 @@ +package de.labor_stein.befund; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest +{ + @Test + public void useAppContext() + { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("de.labor_stein.befund", appContext.getPackageName()); + + + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/de/labor_stein/befund/Security/AESTest.java b/app/src/androidTest/java/de/labor_stein/befund/Security/AESTest.java new file mode 100644 index 0000000..114e9cb --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Security/AESTest.java @@ -0,0 +1,70 @@ +// +// AESTest.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Security; + +import static org.junit.Assert.assertEquals; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.nio.charset.StandardCharsets; +import java.util.Random; + +import de.labor_stein.befund.Core.Security.AES; + +@RunWith(AndroidJUnit4.class) +public class AESTest +{ + @Test + public void EncryptDecryptPasswordShort32Length() + { + String password = "a"; + String input = "Hello World"; + String encrypted = AES.Encrypt(input, AES.GetKey(password)); + String decrypted = AES.Decrypt(encrypted, AES.GetKey(password)); + assertEquals(input, decrypted); + } + + @Test + public void EncryptPasswordLong32Length() + { + String password = "aASKDJ ALSKDJLKASJDLKASJDLKJASLKDJASLKJD ASÖLKJ DKJASHDKJASH D KLJ H A S LK J DHASKJLHDKAJSHD K"; + String input = "Hello World"; + String encrypted = AES.Encrypt(input, AES.GetKey(password)); + String decrypted = AES.Decrypt(encrypted, AES.GetKey(password)); + assertEquals(input, decrypted); + } + + @Test + public void EncryptDecrypt() + { + for(int i = 0; i < 1000; i++) + { + int KeySize = new Random().nextInt(4096); + byte[] random = new byte[KeySize]; + new Random().nextBytes(random); + String password = new String(random, StandardCharsets.UTF_8); + String input = "Hello World"; + String encrypted = AES.Encrypt(input, AES.GetKey(password)); + String decrypted = AES.Decrypt(encrypted, AES.GetKey(password)); + assertEquals(input, decrypted); + } + } + + @Test + public void EncryptDecryptFixedValues() + { + String input = "Befundapp"; + String encrypted = "yd/P1usL9VszgMyhk3d7NJCfwat0PppGWWesFzLOj8NZbLMFWw=="; + String password = "a"; + String decrypted = AES.Decrypt(encrypted, AES.GetKey(password)); + assertEquals(input, decrypted); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Security/Base64Test.java b/app/src/androidTest/java/de/labor_stein/befund/Security/Base64Test.java new file mode 100644 index 0000000..48b5172 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Security/Base64Test.java @@ -0,0 +1,41 @@ +// +// Base64Test.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Security; + +import static org.junit.Assert.assertEquals; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.nio.charset.StandardCharsets; + +import de.labor_stein.befund.Core.Security.Base64; + +@RunWith(AndroidJUnit4.class) +public class Base64Test +{ + @Test + public void EncryptDecrypt() + { + String input = "Hello World"; + String encrypted = Base64.ToBase64String(input.getBytes(StandardCharsets.US_ASCII)); + String decrypted = new String(Base64.FromBase64String(encrypted), StandardCharsets.US_ASCII); + assertEquals(input, decrypted); + } + + @Test + public void EncryptDecryptFixedValues() + { + String input = "Hello World"; + String encrypted = "SGVsbG8gV29ybGQ="; + String decrypted = new String(Base64.FromBase64String(encrypted), StandardCharsets.US_ASCII); + assertEquals(input, decrypted); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Security/Curve25519Test.java b/app/src/androidTest/java/de/labor_stein/befund/Security/Curve25519Test.java new file mode 100644 index 0000000..2fb5325 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Security/Curve25519Test.java @@ -0,0 +1,193 @@ +// +// Curve25519Test.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Security; + +import org.junit.Assert; +import org.junit.Test; +import org.whispersystems.curve25519.JCESha512Provider; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Random; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.Security.Curve25519; +import de.labor_stein.befund.Core.Security.Curve25519.KeyPair; +import de.labor_stein.befund.Core.Security.Ed25519; +import de.labor_stein.befund.Core.Security.HKDF; +import de.labor_stein.befund.Core.Security.SHA512; +import de.labor_stein.befund.Core.Security.TweetNaclFast; + +public class Curve25519Test +{ + @Test + public void SharedKeys() + { + KeyPair aliceKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + KeyPair bobKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + + byte[] aliceSharedKey = aliceKey.GetSharedKey(bobKey.PublicKey); + byte[] bobSharedKey = bobKey.GetSharedKey(aliceKey.PublicKey); + + Assert.assertArrayEquals(aliceSharedKey, bobSharedKey); + } + + @Test + public void AliceSendsToBob() + { + KeyPair aliceKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + KeyPair bobKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + + byte[] aliceSharedKey = aliceKey.GetSharedKey(bobKey.PublicKey); + byte[] bobSharedKey = bobKey.GetSharedKey(aliceKey.PublicKey); + + String key = "a dasdas djakl jdklas jdlkjakldhsajkdhsakdhkajhdkjgahkdgsagdas gdj sadag jdsaj gdg jasdagj dgsa gdsa dsga dgsja gdjagdgasj gjhdga gdja"; + String input = "Hello World"; + String encrypted = AES.Encrypt(input, aliceSharedKey); + String decrypted = AES.Decrypt(encrypted, bobSharedKey); + + Assert.assertTrue(input.equals(decrypted)); + } + + @Test + public void BobSendsToAlice() + { + KeyPair aliceKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + KeyPair bobKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + + byte[] aliceSharedKey = aliceKey.GetSharedKey(bobKey.PublicKey); + byte[] bobSharedKey = bobKey.GetSharedKey(aliceKey.PublicKey); + + String key = "a dasdas djakl jdklas jdlkjakldhsajkdhsakdhkajhdkjgahkdgsagdas gdj sadag jdsaj gdg jasdagj dgsa gdsa dsga dgsja gdjagdgasj gjhdga gdja"; + String input = "Hello World"; + String encrypted = AES.Encrypt(input, bobSharedKey); + String decrypted = AES.Decrypt(encrypted, aliceSharedKey); + + Assert.assertTrue(input.equals(decrypted)); + } + + @Test + public void BobVerifiesAlicasSignature() + { + KeyPair aliceKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + KeyPair bobKey = de.labor_stein.befund.Core.Security.Curve25519.GenerateKeyPair(); + + String message = "a dasdas djakl jdklas jdlkjakldhsajkdhsakdhkajhdkjgahkdgsagdas gdj sadag jdsaj gdg jasdagj dgsa gdsa dsga dgsja gdjagdgasj gjhdga gdjaa dasdas djakl jdklas jdlkjakldhsajkdhsakdhk"; + + String aliceSignature = aliceKey.GetSignature(message); + Assert.assertTrue(bobKey.VerifySignature(message, aliceSignature, aliceKey.SigningPublicKey)); + } + + @Test + public void FixedKeys() + { + byte[] bobDefinedPrivateKey = Base64.FromBase64String("sl+zJ6XehkmHhr9GUgdtNGItpBrWy2y9zqUNkxQ+2nc="); + byte[] bobPrivate = Curve25519.ClampPrivateKey(bobDefinedPrivateKey); + byte[] bobPublicKey = Curve25519.GetPublicKey(bobPrivate); + + byte[] alicePublicKey = Base64.FromBase64String("Q6eZkHPevsEB7cpoMRQ4TY0ggjdB4etV+X6aOqqeymc="); + byte[] bobSharedSecret = Curve25519.GetSharedSecret(bobPrivate, alicePublicKey); + String bobSharedSecretBase64 = Base64.ToBase64String(bobSharedSecret); + byte[] bobSharedKey = HKDF.DeriveKey(bobSharedSecret, 32); + String bobSharedKeyBase64 = Base64.ToBase64String(bobSharedKey); + + String bobSecretMessage = "XhK7GpN6JqbFgSl4h2J6kjpwEi+aFGzTPDehrdF/qvEupBUHYPJI9zOWPhbWBi4IZ2i9"; + String bobSecretMessageDecrypted = AES.Decrypt(bobSecretMessage, bobSharedKey); + + System.out.println("Bob Private Key: " + Base64.ToBase64String(bobPrivate)); + System.out.println("Bob Public Key: " + Base64.ToBase64String(bobPublicKey)); + + System.out.println("Alice Public Key: " + Base64.ToBase64String(alicePublicKey)); + System.out.println("Bob Shared Secret: " + Base64.ToBase64String(bobSharedSecret)); + System.out.println("Bob Shared Key(Base64): " + Base64.ToBase64String(bobSharedKey)); + System.out.println("Bob Shared Key(ASCII): " + new String(bobSharedKey, StandardCharsets.US_ASCII)); + System.out.println("Bob Secret Message(Clearly): " + bobSecretMessageDecrypted); + System.out.println("Alice HMAC: " + SHA512.HMAC(bobSecretMessage, bobSharedKey)); + Assert.assertTrue(SHA512.isValidAuthenticationCode(SHA512.HMAC(bobSecretMessage, bobSharedKey), bobSecretMessage, bobSharedKey)); + } + + @Test + public void VerifyFixedSignature() + { + TweetNaclFast.Signature.KeyPair keyPair = generateEd25519KeyPair(); + byte[] privateKey = keyPair.getSecretKey(); + byte[] publicKey = keyPair.getPublicKey(); + System.out.println("privateKey (Base64): " + base64Encoding(privateKey)); + System.out.println("publicKey (Base64): " + base64Encoding(publicKey)); + + System.out.println("\nderive the publicKey from the privateKey"); + byte[] publicKeyDerived = deriveEd25519PublicKey(privateKey); + System.out.println("publicKey (Base64): " + base64Encoding(publicKeyDerived)); + + + System.out.println("Libsodium detached signature string"); + + String dataToSign = "The quick brown fox jumps over the lazy dog"; + System.out.println("plaintext: " + dataToSign); + + // usually we would load the private and public key from a file or keystore + // here we use hardcoded keys for demonstration - don't do this in real programs + + System.out.println("* * * sign the plaintext with the ED25519 private key * * *"); + //byte [] privateKey = loadEd25519PrivateKey(); + String signatureBase64 = libsodiumSignDetachedToBase64(privateKey, dataToSign); + + System.out.println("signature (Base64): " + signatureBase64); + System.out.println("signature expected: x41mufah/9VO347W+nPXu5FYeSJOI894YClbbTiX0pwRrvfAPMymxEvyMMsDFMI0R0sulCnuCRSgN0WOKnZBDg=="); + System.out.println("\n* * * verify the signature against the plaintext with the ED25519 public key * * *"); + //byte[] publicKey = loadEd25519PublicKey(); + System.out.println("signature (Base64): " + signatureBase64); + boolean signatureVerified = libsodiumVerifyDetachedFromBase64(publicKeyDerived, dataToSign, signatureBase64); + System.out.println("signature (Base64) verified: " + signatureVerified); + } + + private static TweetNaclFast.Signature.KeyPair generateEd25519KeyPair() { + SecureRandom secureRandom = new SecureRandom(); + byte[] key = new byte[64]; + secureRandom.nextBytes(key); + TweetNaclFast.Signature.KeyPair keyPair = TweetNaclFast.Signature.keyPair_fromSecretKey(key); + return keyPair; + } + + private static byte[] deriveEd25519PublicKey(byte[] privateKey) { + TweetNaclFast.Signature.KeyPair keyPair = TweetNaclFast.Signature.keyPair_fromSecretKey(privateKey); + return keyPair.getPublicKey(); + } + + private static String base64Encoding(byte[] input) {return Base64.ToBase64String(input);} + + private static String libsodiumSignDetachedToBase64(byte[] privateKey, String dataToSign) { + TweetNaclFast.Signature sig = new TweetNaclFast.Signature(new byte[32], privateKey); + return base64Encoding(sig.detached(dataToSign.getBytes(StandardCharsets.UTF_8))); + }; + + private static boolean libsodiumVerifyDetachedFromBase64(byte[] publicKey, String dataToSign, String signatureBase64) { + TweetNaclFast.Signature sig = new TweetNaclFast.Signature(publicKey, new byte[64]); + return sig.detached_verify(dataToSign.getBytes(StandardCharsets.UTF_8), base64Decoding(signatureBase64)); + } + + private static byte[] loadEd25519PrivateKey() { + // this is a sample key - don't worry ! + return base64Decoding("Gjho7dILimbXJY8RvmQZEBczDzCYbZonGt/e5QQ3Vro2sjTp95EMxOrgEaWiprPduR/KJFBRA+RlDDpkvmhVfw=="); + } + + private static byte[] loadEd25519PublicKey() { + // this is a sample key - don't worry ! + return base64Decoding("NrI06feRDMTq4BGloqaz3bkfyiRQUQPkZQw6ZL5oVX8="); + } + + private static byte[] base64Decoding(String input) {return Base64.FromBase64String(input); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Security/Ed25519Test.java b/app/src/androidTest/java/de/labor_stein/befund/Security/Ed25519Test.java new file mode 100644 index 0000000..05922e3 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Security/Ed25519Test.java @@ -0,0 +1,42 @@ +// +// Ed25519Test.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Security; + +import com.google.crypto.tink.subtle.Ed25519Sign; + +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Signature; + +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.Security.Ed25519; + +public class Ed25519Test +{ + @Test + public void VerifySignature() throws Exception + { + byte[] signingPrivateKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".getBytes(StandardCharsets.US_ASCII); + byte[] publicKey = Ed25519.PublicKey(signingPrivateKey); + byte[] message = "Test".getBytes(StandardCharsets.UTF_8); + + String publicKeyBase64 = Base64.ToBase64String(publicKey); + byte[] signature = Ed25519.Signature(message, signingPrivateKey); + String signatureBase64 = Base64.ToBase64String(signature); + + Assert.assertTrue(Ed25519.CheckValid(signature, message, publicKey)); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Security/MD5Test.java b/app/src/androidTest/java/de/labor_stein/befund/Security/MD5Test.java new file mode 100644 index 0000000..c5c4b69 --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Security/MD5Test.java @@ -0,0 +1,43 @@ +// +// MD5Test.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Security; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.nio.charset.StandardCharsets; +import java.util.Random; + +import de.labor_stein.befund.Core.Security.MD5; + +@RunWith(AndroidJUnit4.class) +public class MD5Test +{ + @Test + public void EncryptDecrypt() + { + assertEquals(MD5.Encrypt("dasd hsadhuiahdiashd uihas uidhasi hdiuashd uihasid asd asd sa"), "63754a7803f653217f6b46e048e5c286"); + assertEquals(MD5.Encrypt("Hello world"), "3e25960a79dbc69b674cd4ec67a72c62"); + + for (int i = 0; i < 1000; i++) + { + int KeySize = new Random().nextInt(4096); + byte[] random = new byte[KeySize]; + new Random().nextBytes(random); + String key = new String(random, StandardCharsets.UTF_8); + assertTrue(MD5.Encrypt(key).length() == 32); + } + + assertEquals(MD5.Encrypt("Hello world".getBytes(StandardCharsets.UTF_8)), "3e25960a79dbc69b674cd4ec67a72c62"); + } +} diff --git a/app/src/androidTest/java/de/labor_stein/befund/Security/SHA512Test.java b/app/src/androidTest/java/de/labor_stein/befund/Security/SHA512Test.java new file mode 100644 index 0000000..abefd3f --- /dev/null +++ b/app/src/androidTest/java/de/labor_stein/befund/Security/SHA512Test.java @@ -0,0 +1,58 @@ +// +// SHA512Test.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Security; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.whispersystems.curve25519.JCESecureRandomProvider; +import org.whispersystems.curve25519.JCESha512Provider; +import org.whispersystems.curve25519.JavaCurve25519Provider; + +import java.nio.charset.StandardCharsets; +import java.util.Random; + +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.Security.SHA512; + +@RunWith(AndroidJUnit4.class) +public class SHA512Test +{ + @Test + public void Encrypt() + { + assertEquals(SHA512.Encrypt("dasd hsadhuiahdiashd uihas uidhasi hdiuashd uihasid asd asd sa"), "a93500a760ec2ad79d540bea6828fc8e740d7a9c63cd0b7911486949051df53a36438887827e05d3f23a57fc4c149b6f6323d63ffc92c63be35a06108b3d6155"); + assertEquals(SHA512.Encrypt("Hello world"), "b7f783baed8297f0db917462184ff4f08e69c2d5e5f79a942600f9725f58ce1f29c18139bf80b06c0fff2bdd34738452ecf40c488c22a7e3d80cdf6f9c1c0d47"); + + for (int i = 0; i < 1000; i++) + { + int KeySize = new Random().nextInt(4096); + byte[] random = new byte[KeySize]; + new Random().nextBytes(random); + String key = new String(random, StandardCharsets.UTF_8); + assertTrue(SHA512.Encrypt(key).length() == 128); + } + + assertEquals(SHA512.Encrypt("Hello world".getBytes(StandardCharsets.UTF_8)), "b7f783baed8297f0db917462184ff4f08e69c2d5e5f79a942600f9725f58ce1f29c18139bf80b06c0fff2bdd34738452ecf40c488c22a7e3d80cdf6f9c1c0d47"); + } + + @Test + public void HMAC() + { + String input = "Hello World"; + String password = "Test"; + String hmac = SHA512.HMAC(input, AES.GetKey(password)); + assertTrue(SHA512.isValidAuthenticationCode(hmac, input, AES.GetKey(password))); + assertTrue(hmac.length() == 128); + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..d5dbf05 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/assets/faq.html b/app/src/main/assets/faq.html new file mode 100644 index 0000000..40aa693 --- /dev/null +++ b/app/src/main/assets/faq.html @@ -0,0 +1,19 @@ + + + + + + + + + +
+ +

Die App wird mir im Store meines Smartphones nicht angezeigt/Ich kann die App nicht herunterladen.

Es ist möglich, dass Sie die App nicht im Appstore oder Google Playstore finden beziehungsweise herunterladen können. Denn aus Sicherheitsgründen werden zu alte Versionen eines Betriebssystems nicht mehr von der App unterstützt. In diesem Fall können Sie die App auf Ihrem Gerät leider nicht installieren. Sollte dies der Fall sein, prüfen Sie bitte unter Einstellungen Ihre aktuelle Betriebssystem-Version, eventuell können Sie diese aktualisieren. In Ihrem Appstore bzw. Google Playstore finden Sie in der App-Beschreibung heraus, welche Versionen des Betriebssystems von der App unterstützt werden. 

Warum benötigt die App den Zugriff auf meine Kamera und die Möglichkeit, mir Nachrichten zu senden?

Den Zugriff auf die Kamera benötigt die App, damit Sie anfangs einen QR-Code auf dem Flyer scannen können. Die App möchte Ihnen Nachrichten senden, um Sie über einen neuen Status wie z.B. der Fertigstellung Ihres Befundes informieren zu können.

Laut App soll ich zuerst einen QR-Code von einem Flyer scannen. Was soll ich tun, wenn mir der Flyer nicht vorliegt?

Bitte wenden Sie sich in diesem Fall an die Teststelle, an der Sie den Test durchgeführt haben, um an den Flyer bzw. den darauf benötigten QR-Code zu gelangen.

Wann kann ich meinen Auftrag in der App registrieren?

Sie können Ihren Auftrag zu jedem Zeitpunkt mithilfe der Auftragsnummer in der App registrieren. Bitte beachten Sie, dass es eine gewisse Zeit dauert, bis der Auftrag im Labor eingeht und daraufhin vom Labor bearbeitet wird.

Wann bekomme ich nach der Registrierung meinen Befund? Oder wann werde ich über den Status benachrichtigt?

Sie können Ihren Auftrag zu jedem Zeitpunkt mithilfe Ihrer Auftragsnummer in der App registrieren. Wird der Befund nach der Registrierung nicht automatisch in der App bereitgestellt, ist der Befund höchstwahrscheinlich noch in Bearbeitung. Sie werden in dem Fall 24 Stunden nach Ihrer Registrierung automatisch darüber informiert, ob Ihr Befund nun vorliegt. Sollte der Befund dann vorhanden sein, können Sie diesen in Ihrer App abrufen. Sollte zu Ihren registrierten Daten kein Auftrag gefunden worden sein, werden Sie ebenfalls darüber benachrichtigt. Bitte prüfen Sie in dem Fall die von Ihnen angegebenen Daten und führen die Registrierung erneut durch.

Hinweis: Der Befund liegt im Normalfall innerhalb von 24 Stunden vor. In Ausnahmefällen, bei hoher Auslastung der Teststellen oder vor Sonn- und Feiertagen kann die Bearbeitung jedoch etwas länger dauern.  

Wo kann ich beim Registrieren das Jahr vom Geburtsdatum ändern/auswählen? (Betrifft Android-Geräte)

Linksoben im Auswahlfenster finden Sie die Jahreszahl. Wenn Sie darauf klicken, können Sie ihr Geburtsjahr auswählen. 

Wird der Befund direkt auf meinem Smartphone abgespeichert?

Nein, der Befund bleibt vorerst für Sie in der App-Oberfläche sichtbar. Sie können diesen jedoch durch Klicken auf das entsprechende Druck-Symbol herunterladen, weiterleiten oder drucken. 

Wie lange kann ich meinen Befund in der App abrufen?

Sobald der Befund fertig ist (Sie werden per Push-Nachricht informiert) können Sie diesen abrufen. Öffnen Sie hierzu einfach die App, der Download des Befunds startet (insofern die erstmalige Registrierung erfolgreich stattfand) automatisch. Der fertige Befund steht in der App zeitlich unlimitiert zur Verfügung.

Sollten Sie Ihren Befund innerhalb von 30 Tagen nachdem Sie die Benachrichtigung des fertigen Befunds erhalten haben nicht aufgerufen haben, wenden Sie sich bitte an den Support, um Ihren Befund zu erhalten.

Was kann ich im Menü unter "Meine Patientendaten hinzufügen" machen?

Diese Option ist rein optional. Bei manchen Teststellen können Sie hiermit selbst Ihre persönlichen Daten, die für die Testung benötigt werden, angeben. Den daraufhin erzeugte QR-Code kann von der Teststelle ausgelesen werden und direkt einen Auftrag damit erzeugen. Damit können Sie z.B. sicherstellen, dass persönliche Angaben wie z.B. Ihr Name auch korrekt erfasst sind. Bitte fragen Sie zuvor an der jeweiligen Teststelle, ob diese Möglichkeit besteht. 

Muss ich jeden weiteren Befund wieder in der App registrieren?

Nein, zukünftige Befunde werden Ihnen nach der ersten Registrierung automatisch in der App bereitgestellt. Bitte beachten Sie jedoch: Die Voraussetzung hierfür ist, dass die App in der Zwischenzeit nicht deinstalliert und neu installiert wurde, auch z.B. auf einem neuen Gerät. Nach einer Neuinstallation der App muss eine erneute Registrierung erfolgen.

Ich habe keine Push-Benachrichtigung erhalten. Woran liegt das?

Bitte prüfen Sie folgende Optionen:

  • Möglicherweise ist in Ihrem Smartphone/Tablet nicht die Berechtigung hinterlegt, dass die App Push-Nachrichten an ihr Smartphone senden darf. Dies können Sie unter Ihren App-Einstellungen für zukünftige Befunde anpassen.
  • Möglicherweise wurde noch keine Push-Nachricht an Sie versendet. Genauere Informationen finden Sie unter "Wann werde ich über den Status meines Tests benachrichtigt?" .
  • Sollten Sie in der Zwischenzeit die App deinstalliert und neu installiert haben, kann Ihrer "neu installierten" App der Befund nicht mehr zugeordnet werden. In dem Fall wenden Sie sich bitte an den Support. Siehe auch "Ich habe die App nach der Registrierung meines Auftrags deinstalliert. Gibt es bei der Neuinstallation etwas zu beachten?"
  • Während die App geöffnet ist, werden keine Push-Nachrichten versendet. Sollte der Befund fertig werden, während Sie die App geöffnet haben, wird dieser automatisch heruntergeladen und Ihnen in der App angezeigt.

Ich habe die App nach der Registrierung meines Auftrags deinstalliert. Gibt es bei der Neuinstallation etwas zu beachten?

Sollten Sie die App nach der Registrierung Ihres Auftrags deinstalliert haben, kann einer anschließend "neu installierten" App der Befund nicht mehr zugeordnet werden, da die Zuordnung über eine eindeutige "App-ID" stattfindet. Um an Ihren Befund zu kommen wenden Sie sich bitte an den Support. Diesen finden Sie in der App unter: Menü → Support.

Die biometrische Authentifizierung funktioniert nicht, um meine PIN zurückzusetzen. Was soll ich tun?

Das Problem tritt höchstwahrscheinlich deswegen auf, weil die App nicht die Berechtigung zum Abrufen der biometrischen Authentifizieren von Ihrem Smartphone hat. Dann erhalten Sie die Fehlermeldung "Sie können der App in den Einstellungen Ihres Smartphones die entsprechende Berechtigung erteilen. Danach sollte die biometrische Authentifizierung (bei IPhones "Face ID" genannt) funktionieren. Sollte das Problem damit nicht gelöst sein, können Sie sich in der App an den Support wenden. 

+ + + + +
+ + \ No newline at end of file diff --git a/app/src/main/assets/no_connection.html b/app/src/main/assets/no_connection.html new file mode 100644 index 0000000..b81dfb4 --- /dev/null +++ b/app/src/main/assets/no_connection.html @@ -0,0 +1,17 @@ + + + + + +[NO_CONNECTION] + + +
+ +
+ +
+

[NO_CONNECTION]

+
+ + \ No newline at end of file diff --git a/app/src/main/assets/privacy_policy.html b/app/src/main/assets/privacy_policy.html new file mode 100644 index 0000000..9a70f53 --- /dev/null +++ b/app/src/main/assets/privacy_policy.html @@ -0,0 +1,186 @@ + + + + + + + + + +

Datenschutz

+

Datenschutzhinweise
+ Datenschutzhinweise Stand: 30.04.2019
+
+ Vorwort
+ Unabhängig davon, ob Sie Kunde, Interessent, Bewerber oder Besucher unserer Website sind: Wir, MVZ Dr. Stein + Kollegen GbR (im Folgenden: „MVZ Dr. Stein“, „wir“) nehmen den Schutz Ihrer personenbezogenen Daten sehr wichtig. Doch was bedeutet dies konkret? Im Folgenden ermöglichen wir Ihnen, sich einen Einblick darüber zu verschaffen, welche personenbezogenen Daten wir von Ihnen erheben und in welcher Form wir sie verarbeiten. Des Weiteren erhalten Sie eine Übersicht über die Ihnen zustehenden Rechte nach geltendem Datenschutzrecht. Zudem nennen wir Ihnen Ihre Ansprechpartner, falls Sie noch Fragen haben sollten.
+ Als Verantwortlicher i.S.d. geltenden Datenschutzgesetze ergreifen wir,
+
+ MVZ Dr. Stein + Kollegen GbR
+ Tomphecke 45
+ 41169 Mönchengladbach
+ Tel: 02161/ 8194 -0
+ Fax: 02161/ 8194 -50
+
+ alle nach geltendem Datenschutzrecht erforderlichen Maßnahmen, um den Schutz Ihrer personenbezogenen Daten zu gewährleisten. Bei allen Fragen bezüglich dieser Datenschutzerklärung bitten wir Sie, sich an unseren Datenschutzbeauftragten zu wenden.
+
+ 2B Advice GmbH
+ Volker Schrödter
+ Joseph-Schumpeter-Allee 27
+ 53227 Bonn
+ E-Mail: stein@2b-advice.com
+
+ Anwendungsbereich der Datenschutzerklärung
+ Unter der Verarbeitung personenbezogener Daten versteht der Gesetzgeber Tätigkeiten wie das Erheben, das Erfassen, die Organisation, das Ordnen, die Speicherung, die Anpassung oder Veränderung, das Auslesen, das Abfragen, die Verwendung, die Offenlegung durch Übermittlung, Verbreitung oder eine andere Form der Bereitstellung, den Abgleich oder die Verknüpfung, die Einschränkung, das Löschen oder die Vernichtung personenbezogener Daten. Personenbezogene Daten sind alle Informationen, die sich auf eine identifizierte oder identifizierbare natürliche Person beziehen. In dieser Datenschutzerklärung geht es um die personenbezogenen Daten von Kunden, Interessenten, Bewerbern oder Besuchern.
+
+ Welche personenbezogenen Daten verarbeiten wir?
+ Ihre personenbezogenen Daten werden von uns erhoben, wenn Sie mit uns, z.B. als Interessent oder Kunde, in Kontakt treten. Dies kann beispielsweise geschehen, indem Sie sich für unsere Produkte interessieren, sich für unsere Online-Dienste registrieren, sich über unsere Kommunikationskanäle an uns wenden, oder wenn Sie im Rahmen bestehender Geschäftsbeziehungen unsere Produkte oder Dienstleistungen nutzen.
+
+ Folgende Arten personenbezogenen Daten werden bei uns verarbeitet:
+ • Angaben zur persönlichen Identifikation z.B. Vor- und Nachname, Anschriftendaten, E-Mail-Adresse, Telefonnummer, Faxnummer
+ • Unternehmensbezogene Daten z.B. Firmierung, Abteilung, Tätigkeit
+ • Daten zu Ihrem Online-Verhalten z.B. IP-Adressen, Benutzernamen, Daten zu Ihren Besuchen auf unserer Webseite, in den Kundenportalen oder in der App, ausgeführte Aktionen auf unseren Webseiten und in den Kundenportalen,
+ Ort des Zugriffs
+ • Informationen zu Ihren Interessen und Wünschen, welche Sie uns mitteilen z.B. über unser Kontaktformular oder über sonstige Kommunikationskanäle
+ • Informationen über Ihren beruflichen Werdegang z.B. Berufsausbildung, bisherige Arbeitgeber, sonstige Qualifikationen sowie weitere mit diesen Datenkategorien vergleichbare Informationen.
+
+ Sensible Daten
+ Sensible Daten, also besondere Kategorien personenbezogener Daten wie z.B. Informationen zur Religions- oder Gewerkschaftszugehörigkeit, werden über diesen Weg nicht erhoben.
+
+ Nutzung von Cookies
+ Was sind Cookies?
+ Cookies sind Dateien, die von unserer Webseite oder von den Kundenportalen auf Ihren Computer abgelegt werden, während Sie die Seite aufrufen. Diese Dateien speichern Informationen, die Ihre Nutzung dieser Seite effizienter gestalten. Wir verwenden als Webanalysedienst Matomo(PIWIK), um das Nutzungsverhalten auf der Webseite und in den Kundenportalen zu analysieren. Für diese Analyse werden die durch den Cookie erzeugten Nutzungsinformationen (einschließlich der gekürzten IP-Adresse des Nutzers) an unsere Server übertragen und zu Nutzungsanalysezwecken gespeichert. Die Nutzungsanalyse verwenden wir, um die eigenen Webseiten, die Kundenportale, die Kundenansprache und sonstige Werbemaßnahmen zu optimieren sowie zu Marktforschungszwecken. Die IP-Adresse der Nutzer wird bei diesem Vorgang umgehend verkürzt, so dass die Identifikation der Nutzer über die IP-Adresse nicht mehr möglich ist. Jeder Nutzer, der mit der Speicherung und Auswertung seiner anonymisierten Nutzerdaten zu seinem Besuch auf unserer Webseite nicht einverstanden ist, kann dieser Speicherung und Nutzung jederzeit widersprechen. Eine anonymisierte Nutzung der Kundenportale ist nicht möglich.
+ Wofür verarbeiten wir Ihre personenbezogenen Daten – und auf Basis welcher Rechtsgrundlage?
+
+ Vertragserfüllung
+ Wir verarbeiten Ihre Daten, um unsere Verträge erfüllen zu können. Das gilt ebenso für Angaben, die Sie uns gegenüber im Rahmen vorvertraglicher Korrespondenz machen. Die konkreten Zwecke der Datenverarbeitung hängen vom jeweiligen Produkt und oder dem von Ihnen gestellten Antrag ab.
+
+ Durchführung des Vertragsverhältnisses
+ Zur Durchführung des Vertragsverhältnisses benötigen wir Ihren Namen, Ihre Anschrift, Ihre Telefonnummer bzw. Ihre E-Mail-Adresse, damit wir Sie kontaktieren können.
+
+ Anbieten von Waren- und Dienstleistungen
+ Wir benötigen Ihre personenbezogenen Daten ebenfalls, um prüfen zu können, ob und welche Produkte und Dienstleistungen wir Ihnen anbieten können und dürfen. Einzelheiten zu den jeweiligen Zwecken der Datenverarbeitung können Sie den Vertragsunterlagen und unseren Allgemeinen Geschäftsbedingungen entnehmen.
+
+ Durchführung des Bewerbungsverfahrens
+ Wir verarbeiten Ihre Daten, die Sie uns im Rahmen Ihrer Bewerbung übersandt haben, um zu prüfen, ob Ihre fachlichen Qualifikationen für die ausgeschriebene Stelle geeignet sind. Wir nutzen Ihre Informationen lediglich für das Bewerbungsverfahren und überführen diese bei einem Vertragsschluss in Ihre Personalakte. Falls es nicht zu einer Übereinkunft kommen sollte, werden Ihre Informationen gelöscht bzw. vernichtet. Wir werden Ihre Bewerberinformationen für keine anderen Zwecke verwenden als für die Durchführung des Bewerbungsverfahrens.
+
+ Datenverarbeitung und -analyse zu Marketingzwecken
+ Ihre Bedürfnisse sind uns wichtig, und wir versuchen, Ihnen Informationen zu Produkten und Dienstleistungen zu geben, die genau zu Ihnen passen. Dafür verwenden wir die Erkenntnisse aus unserer gemeinsamen Geschäftsbeziehung sowie aus der Marktforschung. Wesentliches Ziel ist dabei die Anpassung unserer Produktvorschläge an Ihre Bedürfnisse. In diesem Zusammenhang garantieren wir, dass wir die Daten immer in Übereinstimmung mit geltendem Datenschutzrecht verarbeiten. Wichtig: Sie können jederzeit der Nutzung Ihrer personenbezogenen Daten zu diesem Zweck widersprechen.
+
+ Was analysieren und verarbeiten wir konkret?
+ • Ergebnisse unserer Marketingaktionen, um die Effizienz und Relevanz unserer Kampagnen zu messen;
+ • Informationen aus Ihren Besuchen auf unserer Webseite;
+ • Wir analysieren den möglichen Bedarf unserer Produkte und Dienstleistungen.
+ Maßnahmen, die Ihrer Sicherheit dienen
+
+ Wir nutzen Ihre personenbezogenen Daten unter anderem in den folgenden Fällen:
+ • Um Sie bzw. Ihr Unternehmen vor betrügerischen Aktivitäten zu schützen, analysieren wir Ihre Daten. Dies kann z.B. vorkommen, wenn Sie Opfer eines Identitätsdiebstahls geworden sind oder sich Unberechtigte auf andere Weise Zugriff auf Ihr Benutzerkonto verschafft haben;
+ • Um die Zuverlässigkeit unserer Webanwendungen zu verbessern, arbeitet unser IT-Support eng mit Ihnen im Falle von technischen Problemen zusammen. In diesem Zusammenhang werten wir auch Protokollierungen von Seitenzugriffen, durchgeführten Aktionen usw. aus;
+ • Um die IT-Sicherheit gewährleisten zu können;
+ • Um im Falle möglicher Rechtsstreitigkeiten Sachverhalte erfassen und nachweisen zu können.
+ Aufgrund Ihrer Einwilligung
+ Sofern Sie in die Verarbeitung Ihrer personenbezogenen Daten für einen oder mehrere konkretisierte Zwecke eingewilligt haben, ist die Verarbeitung Ihrer Daten durch uns zulässig. Sie können diese Einwilligung mit Blick auf die Zukunft jederzeit widerrufen, ohne dass Ihnen hierfür andere als die Übermittlungskosten nach den Basistarifen (Kosten Ihres Internet-Anschlusses) entstehen. Der Widerruf der Einwilligung berührt jedoch nicht die Rechtmäßigkeit der bis zum Widerruf erfolgten Verarbeitungen. Aufgrund gesetzlicher Vorgaben oder im öffentlichen Interesse
+ Als Unternehmen unterliegen wir den unterschiedlichsten gesetzlichen Anforderungen (bspw. aus der Steuergesetzgebung).
+ Um unseren gesetzlichen Verpflichtungen nachzukommen, verarbeiten wir Ihre personenbezogenen Daten.
+
+ Wohin wir Daten übermitteln und warum Datennutzung innerhalb MVZ Dr. Stein
+ Innerhalb von MVZ Dr. Stein erhalten nur die Stellen Zugriff auf Ihre personenbezogenen Daten, die diese benötigen, um unsere vertraglichen oder gesetzlichen Verpflichtungen zu erfüllen, oder um unsere berechtigten Interessen zu wahren.
+
+ Datennutzung außerhalb MVZ Dr. Stein
+ Wir achten den Schutz Ihrer personenbezogenen Daten und geben Informationen über Sie nur dann weiter, wenn gesetzliche Bestimmungen dies gebieten, Sie eingewilligt haben, oder zur Erfüllung vertraglicher Verpflichtungen. Bei folgenden Empfängern kommt eine gesetzliche Verpflichtung zur Weitergabe Ihrer personenbezogenen Daten beispielsweise in Betracht:
+ - Öffentliche Stellen oder Aufsichtsbehörden, z.B. Steuerbehörden, Zollbehörden;
+ - Justiz- und Strafverfolgungsbehörden, z.B. Polizei, Gerichte, Staatsanwaltschaft;
+ - Anwälte oder Notare, z.B. in Rechtsstreitigkeiten;
+ - Wirtschaftsprüfer.
+ Damit wir unsere vertraglichen Verpflichtungen erfüllen können, kooperieren wir mit anderen Unternehmen.
+ Dazu gehören:
+ - Transportdienstleister und Speditionen;
+ - Veranstalter und Schulungsdienstleister, wenn Sie sich über uns für bestimmte Messen oder Events angemeldet haben;
+ - Banken und Finanzdienstleister zur Abwicklung aller finanziellen Angelegenheiten.
+
+ Eigene Dienstleister
+ Um unseren Betrieb effizient gestalten zu können, greifen wir auf die Dienste externer Dienstleister zurück, die zur Erfüllung der beschriebenen Zwecke personenbezogene Daten von Ihnen erhalten können, darunter IT-Dienstleister, Druck- und Telekommunikationsdienstleister, Inkasso-, Beratungs- oder Vertriebsunternehmen.
+
+ Befund-Applikation (APP)
+ Wenn Sie Nutzer der Befund-App sind, verarbeiten wir die folgenden Daten für die Bereitstellung der App und der Befunde sowie zur Wahrung der Sicherheit bei dem Betrieb der App:
+ - Fingerprint und mit FaceID (Sicheres Öffnen der APP).
+ - Kennung und Passwort (Zur Anmeldung am Dienst)
+ - Mac-Adresse (hin und wieder auch Hardware-Adresse Ihres mobilen Endgerätes genannt) und Mobilnummer (zur Wahrung der Sicherheit bei der Anmeldung)
+ - Zur Anzeige der Befunde wird an Apple und Google eine Pushnachricht gesendet.
+ Der Inhalt ist nur die APP-ID, die Geräte-ID und die Labor-Tagesnummer.
+ - Die APP greift auf die Kamera und auf die Bilder zu. (Zum Scannen von Auftragsbarcodes). Die Befunddaten verbleiben auch bei einem Abruf der Daten auf unseren eigenen Servern, die sich in Deutschland befinden. Sofern Sie die Daten nicht aus dem Ausland heraus abrufen, ist eine Übermittlung in Drittsaaten nicht geplant und auch technisch nicht erforderlich. Die Verbindung zwischen der App und unseren Servern ist nach dem Stand der Technik gesichert. Wir weisen an dieser Stelle noch einmal darauf hin, dass der sichere Betrieb der Befund-App zu einem erheblichen Teil davon abhängt, dass Sie ihre Zugangsdaten geheim halten und die Zugangsdaten nicht auf dem Gerät, mit dem Sie die Befund-App nutzen, speichern. Im Falle einer Wartung und Pflege der Systeme hat gegebenenfalls der Hersteller der Befund-App Zugang zu den gespeicherten personenbezogenen Daten. Wir haben mit dem Hersteller einen entsprechenden Vertrag zur Auftragsverarbeitung gemäß Artikel 28 Datenschutz-Grundverordnung (DS-GVO) geschlossen.
+ Wichtig: Wir achten genau auf Ihre personenbezogenen Daten! Um sicherzustellen, dass bei den Dienstleistern dieselben datenschutzrechtlichen Standards wie in unserem Haus eingehalten werden, haben wir entsprechende Verträge zur Auftragsverarbeitung abgeschlossen.
+ Diese Verträge regeln u.a.:
+ - dass Dritte nur Zugriff auf die Daten erhalten, die sie zur Erledigung der an sich übertragenen Aufgaben benötigen;
+ - dass bei den Dienstleistern nur Mitarbeiter Zugriff auf Ihre Daten erhalten, die sich explizit zur Einhaltung der datenschutzrechtlichen Regelungen verpflichtet haben;
+ - dass bei den Dienstleistern technische und organisatorische Maßnahmen eingehalten werden, welche die Datensicherheit und den Datenschutz gewährleisten;
+ - was mit den Daten geschieht, wenn das Geschäftsverhältnis zwischen dem Dienstleister und uns beendet wird. Bei Dienstleistern, die ihren Sitz außerhalb des Europäischen Wirtschaftsraums (EWR) haben, nehmen wir spezielle Sicherheitsmaßnahmen (z.B. durch die Verwendung besonderer Vertragsklauseln) vor, um zu gewährleisten, dass die Daten mit demselben Maß an Umsicht behandelt werden wie im EWR. Wir überprüfen alle unsere Dienstleister regelmäßig auf die Einhaltung unserer Vorgaben.
+ Ganz wichtig: Auf keinen Fall verkaufen wir Ihre personenbezogenen Daten an Dritte!
+
+ Sind Sie verpflichtet, uns personenbezogene Daten zur Verfügung zu stellen?
+ Im Kontext der Geschäftsbeziehung zwischen Ihnen und MVZ Dr. Stein benötigen wir von Ihnen folgende Kategorien personenbezogener Daten:
+ - alle notwendigen Daten für die Aufnahme und die Durchführung einer Geschäftsbeziehung;
+ - Daten, die zur Erfüllung von vertraglichen Pflichten benötigt werden;
+ - Daten, zu deren Erhebung wir gesetzlich verpflichtet sind.
+ Ohne diese Daten ist es uns nicht möglich, Verträge mit Ihnen einzugehen oder durchzuführen. Löschfristen Gemäß den geltenden Datenschutzbestimmungen speichern wir Ihre personenbezogenen Daten nicht länger, als wir sie für die Zwecke der jeweiligen Verarbeitung benötigen. Sofern die Daten nicht mehr zur Erfüllung vertraglicher oder gesetzlicher Pflichten benötigt werden, werden sie von uns regelmäßig gelöscht, außer, ihre befristete Aufbewahrung ist weiter notwendig.
+ Folgende Gründe können für eine weitere Aufbewahrung vorliegen:
+ - Es müssen handels- bzw. steuerrechtliche Aufbewahrungspflichten eingehalten werden:
+ Die Fristen zur Aufbewahrung vorrangig nach den Regelungen des Handelsgesetzbuches und der Abgabenordnung liegen bei bis zu 10 Jahren.
+ - Zum Erhalt von Beweismitteln im Falle rechtlicher Streitigkeiten im Rahmen der gesetzlichen Verjährungsvorschriften: Verjährungsfristen können im Zivilrecht bis zu 30 Jahre betragen, wobei die regelmäßige Verjährung nach drei Jahren eintritt.
+
+ Ihre Rechte
+ Im Rahmen der Verarbeitung Ihrer personenbezogenen Daten stehen Ihnen auch bestimmte Rechte zu. Genaueres ergibt sich aus den entsprechenden Regelungen der Datenschutz-Grundverordnung (dort in den Artikeln 15 bis 21). Recht auf Auskunft und Berichtigung Sie haben das Recht, von uns darüber Auskunft zu erhalten, welche Ihrer personenbezogenen Daten wir verarbeiten. Sofern diese Informationen nicht (mehr) stimmen sollten, können Sie von uns die Berichtigung der Daten verlangen, bei unvollständigen Angaben deren Ergänzung. Sofern wir Ihre Daten an Dritte weitergegeben haben, informieren wir die entsprechenden Dritten bei entsprechender Rechtslage.
+
+ Recht auf Löschung
+ Unter folgenden Umständen können Sie die unverzügliche Löschung Ihrer personenbezogenen Daten verlangen:
+ - Wenn Ihre personenbezogenen Daten nicht länger für die Zwecke, für die sie erhoben wurden, benötigt werden;
+ - Wenn Sie Ihre Einwilligung widerrufen haben und es an einer sonstigen Rechtsgrundlage zur Datenverarbeitung fehlt;
+ - Wenn Sie der Verarbeitung widersprechen und es keine vorrangigen berechtigten Gründe für eine Datenverarbeitung gibt;
+ - Wenn Ihre Daten unrechtmäßig verarbeitet werden;
+ - Wenn Ihre personenbezogenen Daten zur Erfüllung gesetzlicher Pflichten gelöscht werden müssen.
+ Beachten Sie bitte, dass wir vor der Löschung Ihrer Daten prüfen müssen, ob kein legitimer Grund zur Verarbeitung Ihrer personenbezogenen Daten vorliegt.
+
+ Recht auf Einschränkung der Verarbeitung („Recht auf Sperrung“)
+ Aus einem der folgenden Gründe können Sie von uns die Einschränkung der Verarbeitung Ihrer personenbezogenen Daten verlangen:
+ - Wenn Sie die Richtigkeit der Daten bestreiten, bis wir die Gelegenheit hatten, uns von der Richtigkeit der Daten zu überzeugen;
+ - Wenn die Daten unrechtmäßig verarbeitet werden, Sie aber anstelle der Löschung lediglich die Einschränkung der Nutzung der personenbezogenen Daten verlangen;
+ - Wenn wir die personenbezogenen Daten zwar nicht mehr für die Zwecke der Verarbeitung benötigen, Sie diese aber noch zur Geltendmachung, Ausübung oder Verteidigung von Rechtsansprüchen benötigen;
+ - Wenn Sie Widerspruch gegen die Verarbeitung eingelegt haben und noch nicht feststeht, ob Ihre berechtigen Interessen gegenüber unseren überwiegen.
+ Recht auf Widerspruch
+ Einzelfallbezogenes Widerspruchsrecht Sofern die Verarbeitung im öffentlichen Interesse oder auf Grundlage einer Interessenabwägung erfolgt, haben Sie das Recht, aus Gründen, die sich aus Ihrer besonderen Situation ergeben, Widerspruch gegen die Verarbeitung einzulegen. Bei erfolgtem Widerspruch werden wir Ihre personenbezogenen Daten nicht weiter verarbeiten, es sei denn, wir können zwingende schutzwürdige Gründe für die Verarbeitung Ihrer Daten nachweisen, die Ihren Interessen, Rechten und Freiheiten überwiegen, oder weil Ihre personenbezogenen Daten der Geltendmachung, Ausübung oder Verteidigung von Rechtsansprüchen dienen. Der Widerspruch steht der Rechtmäßigkeit der bis zum Widerspruch erfolgten Verarbeitung nicht entgegen.
+
+ Werbewiderspruch
+ In den Fällen, in denen Ihre personenbezogenen Daten für Werbemaßnahmen verwendet werden, können Sie jederzeit gegen diese Form der Verarbeitung Widerspruch einlegen. Wir werden dann Ihre personenbezogenen Daten nicht länger für diese Zwecke verarbeiten. Der Widerspruch kann formfrei erfolgen und sollte adressiert werden an: info(at)labor-stein.de
+
+ Recht auf Datenübertragbarkeit
+ Sie haben das Recht, personenbezogene Daten, die Sie uns zur Verarbeitung gegeben haben, auf Anfrage in einem übertragbaren und maschinenlesbaren Format zu erhalten. Recht auf Beschwerde bei der Aufsichtsbehörde (Art. 77 DS-GVO) Wir versuchen, Ihre Anfragen und Ansprüche immer schnellstmöglich zu bearbeiten, um Ihre Rechte entsprechend zu wahren. Je nach Häufigkeit der Anfragen kann es jedoch sein, dass bis zu 30 Tage vergehen, ehe wir Sie über Ihr Anliegen weiter informieren können. Falls es länger dauern sollte, werden wir Sie zeitnah über die Gründe für die Verzögerung benachrichtigen und das weitere Verfahren mit Ihnen besprechen. In einigen Fällen dürfen oder können wir Ihnen keine Auskunft geben. Sofern rechtlich zulässig, teilen wir Ihnen den Grund für die Verweigerung der Auskunft mit. Sofern Sie dennoch nicht mit unseren Antworten und Reaktionen zufrieden sind oder der Ansicht sind, dass wir gegen geltendes Datenschutzrecht verstoßen, steht es Ihnen frei, sowohl bei unserem Datenschutzbeauftragten als auch bei der zuständigen Aufsichtsbehörde Beschwerde einzureichen.
+ Die für uns zuständige Aufsichtsbehörde ist:
+
+ Landesbeauftragte für Datenschutz und Informationsfreiheit Nordrhein-Westfalen
+ Postfach 20 04 44
+ 40102 Düsseldorf
+ Tel.: 0211/38424-0
+ Fax: 0211/38424-10
+ E-Mail: poststelle(at)ldi.nrw.de
+
+ Matomo Statistikauswertung
+ Die folgenden von uns verwendeten Tracking-Maßnahmen werden gemäß Artikel 6 Absatz 1 Buchstabe f der DSGVO durchgeführt. Durch die Tracking-Maßnahmen wollen wir die bedarfsgerechte Gestaltung und laufende Optimierung unserer Website sicherstellen. Wir verwenden diese Tracking-Maßnahmen auch, um die Nutzung unserer Website statistisch zu erfassen und zu bewerten, wie wir unseren Service optimieren können. Diese Interessen können gemäß der vorgenannten Regelung als legitim angesehen werden. Wir verwenden die Open-Source-Software Matomo, um die Nutzung unserer Website zu analysieren und statistisch auszuwerten. Hierbei werden Cookies verwendet. Die durch den Cookie erzeugten Informationen über die Benutzung der Website werden an unseren Server übermittelt und in pseudonymen Benutzerprofilen zusammengefasst. Die Informationen werden verwendet, um die Nutzung unserer Website zu bewerten und eine bedarfsgerechte Gestaltung unserer Website zu ermöglichen. Informationen werden nicht an Dritte weitergegeben. Die IP-Adresse wird in keinem Fall mit anderen Daten des Benutzers in Verbindung gebracht. Die IP-Adressen werden anonymisiert, so dass eine Zuordnung nicht möglich ist (IP-Maskierung). Ihre Tracking-Optionen werden in der Cookie-Richtlinie festgelegt. Bitte wählen Sie die bevorzugte Option mithilfe des Cookie-Banners oben auf dieser Website. Sie können Ihre Einstellungen jederzeit ändern, indem Sie auf das kleine Cookie-Richtlinienbanner oben links auf der Website klicken.
+
+

+

Version
+ Diese Datenschutzerklärung ist vom Stand 30.04.2019.
+ Frühere Versionen der Datenschutzerklärung sind über unseren Datenschutzbeauftragten erhältlich.
+ Nutzungsbedingungen
+ 1. Inhalt des Onlineangebotes
+ Der Autor übernimmt keinerlei Gewähr für die Aktualität, Korrektheit, Vollständigkeit oder Qualität der bereitgestellten Informationen. Haftungsansprüche gegen den Autor, welche sich auf Schäden materieller oder ideeller Art beziehen, die durch die Nutzung oder Nichtnutzung der dargebotenen Informationen bzw. durch die Nutzung fehlerhafter und unvollständiger Informationen verursacht wurden sind grundsätzlich ausgeschlossen, sofern seitens des Autors kein nachweislich vorsätzliches oder grob varlässiges Verschulden vorliegt. Alle Angebote sind freibleibend und unverbindlich. Der Autor behält es sich ausdrücklich vor, Teile der Seiten oder das gesamte Angebot ohne gesonderte Ankündigung zu verändern, zu ergänzen, zu löschen oder die Veröffentlichung zeitweise oder entgültig einzustellen.
+ 2. Verweise und Links
+ Bei direkten oder indirekten Verweisen auf fremde Internetseiten ("Links"), die außerhalb des Verantwortungsbereiches des Autors liegen, würde eine Haftungsverpflichtung ausschließlich in dem Fall in Kraft treten, in dem der Autor von den Inhalten Kenntnis hat und es ihm technisch möglich und zumutbar wäre, die Nutzung im Falle rechtswidriger Inhalte zu verhindern. Der Autor erklärt daher ausdrücklich, dass zum Zeitpunkt der Linksetzung die entsprechenden verlinkten Seiten frei von illegalen Inhalten waren. Der Autor hat keinerlei Einfluss auf die aktuelle und zukünftige gestaltung und auf die Inhalte der gelinkten/verknüpften Seiten. Deshalb distanziert er sich hiermit ausdrücklich von allen Inhalten aller gelinkten/verknüpften Seiten, die nach der Linksetzung verändert wurden. Diese Feststellung gilt für alle innerhalb des eigenen Internetangebotes gesetzten Links und Verweise sowie für Fremdeinträge in vom Autor eingerichteten Gästebüchern, Diskussionsforen und Mailinglisten. Für illegale, fehlerhafte oder unvollständige Inhalte und insbesondere für Schäden, die aus der Nutzung oder Nichtnutzung solcherart dargebotener Informationen entstehen, haftet allein der Anbieter der Seite, auf welche verwiesen wurde, nicht derjenige, der über Links auf die jeweilige Veröffentlichung lediglich verweist.
+ 3. Urheber- und Kennzeichenrecht
+ Der Autor ist bestrebt, in allen Publikationen die Urheberrechte der verwendeten Grafiken, Tondokumente, Videosequenzen und Texte zu beachten, von ihm selbst erstellte Grafiken, Tondokumente, Videosequenzen und Texte zu nutzen oder auf lizenzfreie Grafiken, Tondokumente, Viedeosequenzen und Texte zurückzugreifen. Alle innerhalb des Internetangebotes genannten und ggf. durch dritte geschützten Marken- und Warenzeichen unterliegen uneingeschränkt den Bestimmungen des jeweils gültigen Kennzeichenrechts und den Besitzrechten der jeweiligen eingetragenenEigentümer. Allein aufgrund der bloßen Nennung ist nicht der Schluß zu ziehen, dass Markenzeichen nicht durch die Rechte Dritter geschützt sind! Das Copyright für veröffentlichte, vom Autor selbst erstellte Objekte bleibt allein beim Autor der Seiten. Eine Vervielfältigung oder Verwendung solcher Grafiken, Tondokumente, Videosequenzen und Texte in anderen elektronischen oder gedruckten Publikationenist ohne ausdrückliche Zustimmung des Autors nicht gestattet.
+ 4. Datenschutz
+ Sofern innerhalb des Internetangebotes die Möglichkeit zur Eingabe persönlicher oder geschäftlicher Daten (Emailadressen, Namen, Anschriften) besteht, so erfolgt die Preisgabe dieser Daten seitens des Nutzers auf ausdrücklich freiwilliger Basis. Die Inanspruchnahme und Bezahlung aller angebotenen Dienste ist -soweit technisch möglich und zumutbar - auch ohne Angabe solcher Daten bzw. unter Angabe anonymisierter Daten oder eines Pseudonyms gestattet.
+ 5. Rechtswirksamkeit dieses Haftungsausschlusses
+ Dieser Haftungsausschluss ist als Teil des Internetangebotes zu betrachten, von dem aus auf diese Seite verwiesen wurde. Sofern Teile oder einzelne Formulierungen dieses Textes der geltenden Rechtslage nicht, nicht mehr oder nicht vollständig entsprechen sollten, bleiben die übrigen Teile des Dokumentes in ihrem Inhalt und ihrer Gültigkeit davon unberührt.  

+

 

+ + + \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Adapters/ResultsTableAdapter.java b/app/src/main/java/de/labor_stein/befund/Adapters/ResultsTableAdapter.java new file mode 100644 index 0000000..518f4ad --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Adapters/ResultsTableAdapter.java @@ -0,0 +1,265 @@ +// +// ResultsTableAdapter.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 30.06.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Adapters; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.recyclerview.widget.RecyclerView; + +import com.bumptech.glide.Glide; + +import java.util.ArrayList; +import java.util.List; + +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Models.Database.Results; +import de.labor_stein.befund.MainActivity; +import de.labor_stein.befund.R; + +public class ResultsTableAdapter extends RecyclerView.Adapter +{ + private RecyclerView RecyclerView;; + private List Results; + private MainActivity MainActivity; + + public ResultsTableAdapter(List results, MainActivity mainActivity, RecyclerView recyclerView) + { + this.Results = (results == null ? results = new ArrayList<>() : results); + this.MainActivity = mainActivity; + this.RecyclerView = recyclerView; + } + + /** + * Sets the status for results + * + * @param results - results for status + * @param status - status of results row + * @param icon - icon of results row + * @param downloading - flag of downloading + * @param newState - newState of results + */ + public void SetStatusForRow(Results results, String status, Drawable icon, Boolean downloading, Results newState) + { + if(results != null && Results != null && Results.size() > 0) + { + TableRow row = this.GetRowForResult(results); + + if(row != null) + { + row.Results = newState; + row.Results.downloading = downloading; + row.CustomStatus = true; + row.txtSubtitle.setText(status); + + if(icon != null) + { + row.imgIcon.setImageDrawable(icon); + row.imgIcon.setPadding(0, 0, 0, 0); + row.imgIcon.setScaleX(0.7f); + row.imgIcon.setScaleY(0.7f); + } + } + } + } + + /** + * Sets the downloading status for results + * + * @param results - results that is downloading + */ + public void SetDownloadingForRow(Results results) + { + if(results != null && Results != null && Results.size() > 0) + { + TableRow row = this.GetRowForResult(results); + + if(row != null) + { + row.Results.downloading = true; + row.CustomStatus = true; + + row.txtSubtitle.setText(Lang.Get("LBL_DOWNLOADING")); + + Glide.with(this.MainActivity) + .load(R.drawable.ic_downloading) + .into(row.imgIcon); + + row.imgIcon.setPadding(20, 20, 20, 20); + } + } + } + + /*** + * Returns TableRow for results + * + * @param results - results for row + * @return returns TableRow + */ + public TableRow GetRowForResult(Results results) + { + TableRow result = null; + + if(results != null && Results != null && Results.size() > 0) + { + int index = -1; + + for(int i = 0; i < Results.size(); i++) + { + if(Results.get(i).pgs.equals(results.pgs)) + { + index = i; + break; + } + } + + if(index >= 0 && index < Results.size()) + { + result = (TableRow)this.RecyclerView.findViewHolderForAdapterPosition(index); + } + } + + return result; + } + + /** + * Delete results at index + * @param position + */ + public void deleteItem(int position) + { + if(position >= 0 && position <= this.Results.size()) + { + Results results = this.Results.get(position); + + if(results != null) + { + this.Results.remove(results); + this.MainActivity.DeleteResults(results); + + TableRow row = (TableRow)this.RecyclerView.findViewHolderForAdapterPosition(position); + + if(row != null) + { + row.CustomStatus = false; + } + + notifyDataSetChanged(); + } + } + } + + /** + * Refresh results + * @param results - new results + */ + public void reloadData(List results) + { + this.Results.clear(); + + if(results != null) + { + this.Results.addAll(results); + } + + notifyDataSetChanged(); + } + + @Override + public ResultsTableAdapter.TableRow onCreateViewHolder(ViewGroup parent, int viewType) + { + Context context = parent.getContext(); + LayoutInflater inflater = LayoutInflater.from(context); + + View rowView = inflater.inflate(R.layout.results_table_row, parent, false); + + TableRow viewHolder = new TableRow(rowView, this.MainActivity); + return viewHolder; + } + + @Override + public void onBindViewHolder(ResultsTableAdapter.TableRow tableRow, int position) + { + Results results = Results.get(position); + + if(!tableRow.CustomStatus) + { + tableRow.Results = results; + tableRow.txtTitle.setText(results.GetFormatedCreatedDate()); + tableRow.txtSubtitle.setText(results.GetStatusText()); + tableRow.txtIdentifier.setText((results != null && results.pgs != null ? results.pgs.substring(0, 40) + "..." : "")); + tableRow.txtIdentifier.setVisibility(View.INVISIBLE); + tableRow.imgIcon.setImageDrawable(results.GetStatusIcon(this.MainActivity)); + tableRow.imgIcon.setPadding(0, 0, 0, 0); + tableRow.imgIcon.setScaleX(0.7f); + tableRow.imgIcon.setScaleY(0.7f); + } + } + + @Override + public int getItemCount() + { + return Results.size(); + } + + public class TableRow extends RecyclerView.ViewHolder + { + private MainActivity MainActivity; + public Results Results; + public TextView txtTitle; + public TextView txtSubtitle; + public TextView txtIdentifier; + public ImageView imgIcon; + public boolean CustomStatus = false; + + public TableRow(View rowView, MainActivity mainActivity) + { + super(rowView); + + this.MainActivity = mainActivity; + txtTitle = (TextView)itemView.findViewById(R.id.ResultsTableTitle); + txtSubtitle = (TextView)itemView.findViewById(R.id.ResultsTableSubtitle); + txtIdentifier = (TextView)itemView.findViewById(R.id.ResultsTableIdentifier); + imgIcon = (ImageView)itemView.findViewById(R.id.ResultsTableIcon); + + imgIcon.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if(Results != null) + { + if(Results.GetStatus() == de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.COMPLETED && + Results.available && + !Results.picked_up && + !Results.downloaded && + !Results.downloading) + { + MainActivity.Download(Results); + } + else if(Results.GetStatus() == de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.COMPLETED && + Results.available && + (Results.picked_up || Results.downloaded)) + { + MainActivity.EncryptResults(Results); + } + } + + return false; + } + }); + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Adapters/ResultsTableAdapterSwipeToDeleteCallback.java b/app/src/main/java/de/labor_stein/befund/Adapters/ResultsTableAdapterSwipeToDeleteCallback.java new file mode 100644 index 0000000..40a80d2 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Adapters/ResultsTableAdapterSwipeToDeleteCallback.java @@ -0,0 +1,118 @@ +// +// ResultsTableAdapterSwipeToDeleteCallback.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 30.06.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Adapters; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.Rect; +import android.graphics.drawable.ColorDrawable; +import android.view.View; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.ItemTouchHelper; +import androidx.recyclerview.widget.RecyclerView; + +import de.labor_stein.befund.Core.Lang.Lang; + +public class ResultsTableAdapterSwipeToDeleteCallback extends ItemTouchHelper.Callback +{ + private ResultsTableAdapter Adapter; + private Context Context; + private Paint mClearPaint; + private ColorDrawable mBackground; + private int backgroundColor; + + /*** + * Constructor of ResultsTableAdapterSwipeToDeleteCallback + * @param adapter - ResultsTableAdapter + */ + public ResultsTableAdapterSwipeToDeleteCallback(ResultsTableAdapter adapter, Context context) + { + this.Adapter = adapter; + this.Context = context;; + mBackground = new ColorDrawable(); + backgroundColor = Color.RED; + mClearPaint = new Paint(); + mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); + } + + @Override + public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) + { + return makeMovementFlags(0, ItemTouchHelper.LEFT); + } + + @Override + public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) + { + return false; + } + + @Override + public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) + { + int position = viewHolder.getAdapterPosition(); + this.Adapter.deleteItem(position); + } + + @Override + public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { + + super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); + + View itemView = viewHolder.itemView; + int itemHeight = itemView.getHeight(); + + boolean isCancelled = dX == 0 && !isCurrentlyActive; + + if (isCancelled) + { + clearCanvas(c, itemView.getRight() + dX, (float) itemView.getTop(), (float) itemView.getRight(), (float) itemView.getBottom()); + super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); + return; + } + + mBackground.setColor(backgroundColor); + mBackground.setBounds(itemView.getRight() + (int) dX, itemView.getTop(), itemView.getRight(), itemView.getBottom()); + mBackground.draw(c); + + String text = Lang.Get("BTN_DELETE"); + + int spSize = 15; + float scaledSizeInPixels = spSize * this.Context.getResources().getDisplayMetrics().scaledDensity; + + Paint textPaint = new Paint(); + textPaint.setColor(Color.WHITE); + textPaint.setTextSize(scaledSizeInPixels); + textPaint.setTextAlign(Paint.Align.LEFT); + + Rect bounds = new Rect(); + textPaint.getTextBounds(text, 0, text.length(), bounds); + + float textSize = textPaint.measureText(text); + float x = (itemView.getRight() - (textSize + 20)); + float y = itemView.getTop() + ((itemView.getHeight() / 2) + (bounds.height() / 2)); + + c.drawText(text, x, y, textPaint); + } + + private void clearCanvas(Canvas c, Float left, Float top, Float right, Float bottom) + { + c.drawRect(left, top, right, bottom, mClearPaint); + } + + @Override + public float getSwipeThreshold(@NonNull RecyclerView.ViewHolder viewHolder) + { + return 0.7f; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Database/Logs.java b/app/src/main/java/de/labor_stein/befund/Core/Database/Logs.java new file mode 100644 index 0000000..7764a65 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Database/Logs.java @@ -0,0 +1,259 @@ +// +// Logs.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Database; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.DbLog; +import de.labor_stein.befund.Core.System; + +public class Logs extends SQLiteOpenHelper +{ + private static final int DATABASE_VERSION = 1; + private Context CurrentContext = null; + + public Logs(Context context) + { + super(context, System.LogsDatabasePath(context), null, DATABASE_VERSION); + CurrentContext = context; + } + + public boolean CreateDBIfNotExists() + { + boolean result = false; + + try + { + if(!this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if (con != null) + { + String Logs_Table = "create table if not exists logs(" + + "id integer primary key autoincrement not null, " + + "guid text not null, " + + "message text not null, " + + "type text not null, " + + "created datetime not null " + + ")"; + + con.execSQL(Logs_Table); + con.close(); + result = true; + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "Core.Database.Logs", "CreateDBIfNotExists(Context)"); + } + + return result; + } + + public boolean Create(DbLog log) + { + boolean result = false; + + try + { + if(log != null && log.message != null && !log.message.isEmpty() && log.type != null) + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if (con != null) + { + ContentValues values = new ContentValues(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + String guid = (log.guid != null ? log.guid : UUID.randomUUID().toString()); + + values.put("guid", guid); + values.put("message", log.message); + values.put("type", log.type); + values.put("created", dateFormat.format(new Date())); + con.insert("logs", null, values); + con.close(); + + result = true; + } + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Logs", "Create(DbLog)"); + } + + return result; + } + + public List GetLogs() + { + List result = null; + + try + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if (con != null) + { + Cursor cursor = con.rawQuery("select id, guid, message, type, created from logs order by created desc", null); + + if(cursor != null && cursor.moveToFirst()) + { + result = new ArrayList(); + + do + { + DbLog log = new DbLog(); + log.id = cursor.getInt(0); + log.guid = cursor.getString(1); + log.message = cursor.getString(2); + log.type = cursor.getString(3); + String created_str = cursor.getString(4); + + if(created_str != null && created_str != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + log.created = dateFormat.parse(created_str); + } + + if(log.id > 0) + { + result.add(log); + } + } + while (cursor.moveToNext()); + } + + con.close(); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Logs", "GetLogs"); + } + + return result; + } + + public List GetLogs(String type) + { + List result = null; + + try + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if (con != null) + { + Cursor cursor = con.rawQuery("select id, guid, message, type, created from logs where type = ? order by created desc", new String[] { type }); + + if(cursor != null && cursor.moveToFirst()) + { + result = new ArrayList(); + + do + { + DbLog log = new DbLog(); + log.id = cursor.getInt(0); + log.guid = cursor.getString(1); + log.message = cursor.getString(2); + log.type = cursor.getString(3); + String created_str = cursor.getString(4); + + if(created_str != null && created_str != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + log.created = dateFormat.parse(created_str); + } + + if(log.id > 0) + { + result.add(log); + } + } + while (cursor.moveToNext()); + } + + con.close(); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Logs", "GetLogs(String)"); + } + + return result; + } + + private boolean DeleteLogs() + { + boolean result = false; + + String dbPath = System.LogsDatabasePath(CurrentContext); + + if(dbPath != null) + { + result = System.DeleteFile(dbPath); + } + + return result; + } + + private boolean DatabaseExists() + { + String dbPath = System.LogsDatabasePath(CurrentContext); + return (dbPath != null && System.FileExists(dbPath)); + } + + private SQLiteDatabase CreateConnection() + { + SQLiteDatabase result = null; + + String dbPath = System.LogsDatabasePath(CurrentContext); + + if(dbPath != null) + { + result = SQLiteDatabase.openOrCreateDatabase(dbPath, null); + } + + return result; + } + + @Override + public void onCreate(SQLiteDatabase db) + { + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) + { + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Database/Results.java b/app/src/main/java/de/labor_stein/befund/Core/Database/Results.java new file mode 100644 index 0000000..183ef2b --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Database/Results.java @@ -0,0 +1,701 @@ +// +// Results.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Database; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.System; + +public class Results extends SQLiteOpenHelper +{ + private static final int DATABASE_VERSION = 1; + private Context CurrentContext = null; + + public Results(Context context) + { + super(context, System.ResultsDatabasePath(context), null, DATABASE_VERSION); + CurrentContext = context; + } + + /** + * Creates database if it does not exist + * + * @return returns true if database successfully created or it already exists + */ + public boolean CreateDBIfNotExists() + { + boolean result = false; + + try + { + if(!this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + String Results_Table = "create table if not exists results(" + + "pgs text primary key not null," + + "available integer not null default 0," + + "available_ts datetime default null," + + "picked_up bit(1) not null default 0," + + "picked_up_ts datetime default null," + + "downloaded bit(1) not null default 0," + + "downloaded_ts datetime default null," + + "downloaded_file text default null," + + "server_public_key text default null," + + "file_checksum text default null," + + "status text not null," + + "modified datetime default null," + + "created datetime not null" + + ")"; + + con.execSQL(Results_Table); + con.close(); + result = true; + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "CreateDBIfNotExists(Context)"); + } + + return result; + } + + /** + * Creates results in the database + * + * @param results - results that should be inserted in the database + * @return retursn true if successfully inserted + */ + public Boolean Create(de.labor_stein.befund.Core.Models.Database.Results results) + { + Boolean result = false; + + try + { + if(results != null && results.pgs != null && !results.pgs.equals("")) + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + ContentValues values = new ContentValues(); + values.put("pgs", results.pgs); + values.put("available", (results.available ? 1 : 0)); + + if(results.available_ts != null && !results.available_ts.equals("")) + { + values.put("available_ts", results.available_ts); + } + else + { + values.putNull("available_ts"); + } + + values.put("picked_up", (results.picked_up ? 1 : 0)); + + if(results.picked_up_ts != null && !results.picked_up_ts.equals("")) + { + values.put("picked_up_ts", results.picked_up_ts); + } + else + { + values.putNull("picked_up_ts"); + } + + if(results.file_checksum != null && !results.file_checksum.equals("")) + { + values.put("file_checksum", results.file_checksum); + } + else + { + values.putNull("file_checksum"); + } + + values.put("downloaded", (results.downloaded ? 1 : 0)); + + if(results.downloaded_ts != null && !results.downloaded_ts.equals("")) + { + values.put("downloaded_ts", results.downloaded_ts); + } + else + { + values.putNull("downloaded_ts"); + } + + if(results.downloaded_file != null && !results.downloaded_file.equals("")) + { + values.put("downloaded_file", results.downloaded_file); + } + else + { + values.putNull("downloaded_file"); + } + + if(results.server_public_key != null && !results.server_public_key.equals("")) + { + values.put("server_public_key", results.server_public_key); + } + else + { + values.putNull("server_public_key"); + } + + values.put("status", results.status); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + values.put("created", dateFormat.format(new Date())); + con.insert("results", null, values); + con.close(); + + result = true; + } + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Results", "Create(Results)"); + } + + return result; + } + + /** + * Updates results in the database + * + * @param results - results that should be updated in the database + * @param update_server_public_key - flag if server_public_key has to be updated in the db + * @return returns true if successfully updated + */ + public Boolean Update(de.labor_stein.befund.Core.Models.Database.Results results, boolean update_server_public_key) + { + Boolean result = false; + + try + { + if(results != null && results.pgs != null && !results.pgs.equals("")) + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + ContentValues values = new ContentValues(); + values.put("available", (results.available ? 1 : 0)); + + if(results.available_ts != null && !results.available_ts.equals("")) + { + values.put("available_ts", results.available_ts); + } + else + { + values.putNull("available_ts"); + } + + values.put("picked_up", (results.picked_up ? 1 : 0)); + + if(results.picked_up_ts != null && !results.picked_up_ts.equals("")) + { + values.put("picked_up_ts", results.picked_up_ts); + } + else + { + values.putNull("picked_up_ts"); + } + + if(results.file_checksum != null && !results.file_checksum.equals("")) + { + values.put("file_checksum", results.file_checksum); + } + else + { + values.putNull("file_checksum"); + } + + values.put("downloaded", (results.downloaded ? 1 : 0)); + + if(results.downloaded_ts != null && !results.downloaded_ts.equals("")) + { + values.put("downloaded_ts", results.downloaded_ts); + } + else + { + values.putNull("downloaded_ts"); + } + + if(results.downloaded_file != null && !results.downloaded_file.equals("")) + { + values.put("downloaded_file", results.downloaded_file); + } + else + { + values.putNull("downloaded_file"); + } + + if(update_server_public_key) + { + if(results.server_public_key != null && !results.server_public_key.equals("")) + { + values.put("server_public_key", results.server_public_key); + } + else + { + values.putNull("server_public_key"); + } + } + + values.put("status", results.status); + + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + values.put("modified", dateFormat.format(new Date())); + con.update("results", values, "pgs = ?", new String[] { results.pgs }); + con.close(); + + result = true; + } + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "Update(Results)"); + } + + return result; + } + + /** + * Deletes results from the database + * + * @param results - results that should be deleted from the database + * @return returns true if successfully deleted + */ + public Boolean Delete(de.labor_stein.befund.Core.Models.Database.Results results) + { + Boolean result = false; + + try + { + if(results != null && results.pgs != null && !results.pgs.equals("")) + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + con.delete("results", "pgs = ?", new String[] { results.pgs }); + con.close(); + + result = System.DeleteFile(System.GetPathForStorageEncryptedFile(results.pgs, CurrentContext)); + } + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "Delete(Results)"); + } + + return result; + } + + /** + * Creates or updates results in the database + * + * @param results - results that should be ether inserted or updated in the database + * @return returns true if successfully inserted/updated + */ + public Boolean CreateOrUpdate(de.labor_stein.befund.Core.Models.Database.Results results) + { + de.labor_stein.befund.Core.Models.Database.Results dbResults = this.GetResults(results.pgs); + + if(dbResults != null) + { + return this.Update(results, false); + } + else + { + return this.Create(results); + } + } + + /** + * Returns results from the datbase by pgs + * + * @param pgs - pgs of results + * @return returns results + */ + public de.labor_stein.befund.Core.Models.Database.Results GetResults(String pgs) + { + de.labor_stein.befund.Core.Models.Database.Results result = null; + + try + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + Cursor cursor = con.rawQuery("select " + + "pgs," + + "available," + + "available_ts," + + "picked_up, " + + "picked_up_ts, " + + "file_checksum, " + + "status, " + + "downloaded, " + + "downloaded_ts, " + + "downloaded_file, " + + "server_public_key, " + + "modified, " + + "created" + + " from " + + " results " + + " where " + + "pgs = ?", new String[] { pgs }); + + if(cursor != null && cursor.moveToFirst()) + { + result = new de.labor_stein.befund.Core.Models.Database.Results(); + result.pgs = cursor.getString(0); + result.available = (cursor.getInt(1) == 1); + result.available_ts = cursor.getString(2); + result.picked_up = (cursor.getInt(3) == 1); + result.picked_up_ts = cursor.getString(4); + result.file_checksum = cursor.getString(5); + result.status = cursor.getString(6); + result.downloaded = (cursor.getInt(7) == 1); + result.downloaded_ts = cursor.getString(8); + result.downloaded_file = cursor.getString(9); + result.server_public_key = cursor.getString(10); + result.modified = cursor.getString(11); + result.created = cursor.getString(12); + + con.close(); + } + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "GetResults(String)"); + } + + return result; + } + + /** + * Returns results from the database + * + * @return returns List of results + */ + public List GetResults() + { + List result = null; + + try + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + Cursor cursor = con.rawQuery("select " + + "pgs," + + "available," + + "available_ts," + + "picked_up, " + + "picked_up_ts, " + + "file_checksum, " + + "status, " + + "downloaded, " + + "downloaded_ts, " + + "downloaded_file, " + + "server_public_key, " + + "modified, " + + "created" + + " from " + + "results " + + "order by " + + "created desc", null); + + if(cursor != null && cursor.moveToFirst()) + { + result = new ArrayList(); + + do + { + de.labor_stein.befund.Core.Models.Database.Results results = new de.labor_stein.befund.Core.Models.Database.Results(); + results.pgs = cursor.getString(0); + results.available = (cursor.getInt(1) == 1); + results.available_ts = cursor.getString(2); + results.picked_up = (cursor.getInt(3) == 1); + results.picked_up_ts = cursor.getString(4); + results.file_checksum = cursor.getString(5); + results.status = cursor.getString(6); + results.downloaded = (cursor.getInt(7) == 1); + results.downloaded_ts = cursor.getString(8); + results.downloaded_file = cursor.getString(9); + results.server_public_key = cursor.getString(10); + results.modified = cursor.getString(11); + results.created = cursor.getString(12); + + if(results.pgs != null) + { + result.add(results); + } + } + while (cursor.moveToNext()); + } + + con.close(); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "GetResults"); + } + + return result; + } + + /** + * Returns all active results from the database + * + * @return returns List of results + */ + public List GetResults(boolean activeOnly) + { + List result = null; + + try + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + Cursor cursor = con.rawQuery("select " + + "pgs," + + "available," + + "available_ts," + + "picked_up, " + + "picked_up_ts, " + + "file_checksum, " + + "status, " + + "downloaded, " + + "downloaded_ts, " + + "downloaded_file, " + + "server_public_key, " + + "modified, " + + "created" + + " from " + + "results " + + "order by " + + "created desc", null); + + if(cursor != null && cursor.moveToFirst()) + { + result = new ArrayList(); + + do + { + de.labor_stein.befund.Core.Models.Database.Results results = new de.labor_stein.befund.Core.Models.Database.Results(); + results.pgs = cursor.getString(0); + results.available = (cursor.getInt(1) == 1); + results.available_ts = cursor.getString(2); + results.picked_up = (cursor.getInt(3) == 1); + results.picked_up_ts = cursor.getString(4); + results.file_checksum = cursor.getString(5); + results.status = cursor.getString(6); + results.downloaded = (cursor.getInt(7) == 1); + results.downloaded_ts = cursor.getString(8); + results.downloaded_file = cursor.getString(9); + results.server_public_key = cursor.getString(10); + results.modified = cursor.getString(11); + results.created = cursor.getString(12); + + if(results.pgs != null) + { + if(activeOnly) + { + de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus status = results.GetStatus(); + + if((status == de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.COMPLETED || + status == de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.EXPIRED) && + (results.picked_up || results.available)) + { + result.add(results); + } + } + else + { + result.add(results); + } + } + } + while (cursor.moveToNext()); + } + + con.close(); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "GetResults"); + } + + return result; + } + + /** + * Deletes all inactive results from the database, that are older than 24h and have status pending + * + * @return returns List of results + */ + public void DeleteOldInactiveResults() + { + try + { + if(this.DatabaseExists()) + { + SQLiteDatabase con = this.CreateConnection(); + + if(con != null) + { + Cursor cursor = con.rawQuery("select " + + "pgs," + + "available," + + "available_ts," + + "picked_up, " + + "picked_up_ts, " + + "file_checksum, " + + "status, " + + "downloaded, " + + "downloaded_ts, " + + "downloaded_file, " + + "server_public_key, " + + "modified, " + + "created" + + " from " + + "results " + + "order by " + + "created desc", null); + + if(cursor != null && cursor.moveToFirst()) + { + do + { + de.labor_stein.befund.Core.Models.Database.Results results = new de.labor_stein.befund.Core.Models.Database.Results(); + results.pgs = cursor.getString(0); + results.available = (cursor.getInt(1) == 1); + results.available_ts = cursor.getString(2); + results.picked_up = (cursor.getInt(3) == 1); + results.picked_up_ts = cursor.getString(4); + results.file_checksum = cursor.getString(5); + results.status = cursor.getString(6); + results.downloaded = (cursor.getInt(7) == 1); + results.downloaded_ts = cursor.getString(8); + results.downloaded_file = cursor.getString(9); + results.server_public_key = cursor.getString(10); + results.modified = cursor.getString(11); + results.created = cursor.getString(12); + + if(results.pgs != null && results.created != null) + { + de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus status = results.GetStatus(); + Date created = results.GetCreated(); + Date now = new Date(); + long difference = Math.abs(created.getTime() - now.getTime()); + long differenceHours = difference / (60 * 60 * 1000); + + if(status != de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.COMPLETED && + status != de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.EXPIRED && + !results.picked_up && !results.available && differenceHours >= 24) + { + this.Delete(results); + } + } + } + while (cursor.moveToNext()); + } + + con.close(); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Database.Database", "DeleteOldInactiveResults"); + } + } + + /** + * Check if database exists + * + * @return returns true if database exists + */ + private boolean DatabaseExists() + { + String dbPath = System.ResultsDatabasePath(CurrentContext); + return (dbPath != null && System.FileExists(dbPath)); + } + + /** + * Creates sqldatabase context + * + * @return retursn SQLiteDatabase context + */ + private SQLiteDatabase CreateConnection() + { + SQLiteDatabase result = null; + + String dbPath = System.ResultsDatabasePath(CurrentContext); + + if(dbPath != null) + { + result = SQLiteDatabase.openOrCreateDatabase(dbPath, null); + } + + return result; + } + + @Override + public void onCreate(SQLiteDatabase db) + { + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) + { + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Helpers/DateHelper.java b/app/src/main/java/de/labor_stein/befund/Core/Helpers/DateHelper.java new file mode 100644 index 0000000..6a9dd6c --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Helpers/DateHelper.java @@ -0,0 +1,75 @@ +// +// DateHelper.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Helpers; + +import android.widget.DatePicker; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; + +public class DateHelper +{ + /** + * Gets Date from datepicker + * @param datePicker - datepicker that contains date + * @return returns Date + */ + public static Date getDateFromDatePicket(DatePicker datePicker) + { + int day = datePicker.getDayOfMonth(); + int month = datePicker.getMonth(); + int year = datePicker.getYear(); + + Calendar calendar = Calendar.getInstance(); + calendar.set(year, month, day); + + return calendar.getTime(); + } + + /** + * Gets full year by date + * @param date - date + * @return returns year in full format - yyyy + */ + public static int GetFullYearFromDate(Date date) + { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + return Integer.parseInt(df.format(date)); + } + + /** + * Gets full month by date + * @param date - date + * @return returns month in full format - MM + */ + public static int GetFullMonthFromDate(Date date) + { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat df = new SimpleDateFormat("MM"); + return Integer.parseInt(df.format(date)); + } + + /** + * Gets full day of month by date + * @param date - date + * @return returns day of month in full format dd + */ + public static int GetFullDayFromDate(Date date) + { + SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + SimpleDateFormat df = new SimpleDateFormat("dd"); + return Integer.parseInt(df.format(date)); + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Helpers/ImageHelper.java b/app/src/main/java/de/labor_stein/befund/Core/Helpers/ImageHelper.java new file mode 100644 index 0000000..ed6c196 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Helpers/ImageHelper.java @@ -0,0 +1,51 @@ +// +// ImageHelper.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Helpers; + +import android.graphics.Bitmap; +import android.graphics.Color; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.common.BitMatrix; + +import de.labor_stein.befund.Core.Log; + +public class ImageHelper +{ + public static Bitmap QRCode(String content, int width, int height) + { + Bitmap result = null; + + try + { + if(content != null && !content.isEmpty()) + { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + + BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height); + + result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); + + for (int i = 0; i < width; i++) + { + for (int j = 0; j < height; j++) + { + result.setPixel(i, j, bitMatrix.get(i,j) ? Color.BLACK : Color.WHITE); + } + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "ImageHelper", "QRCode(String)"); + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Https/Request.java b/app/src/main/java/de/labor_stein/befund/Core/Https/Request.java new file mode 100644 index 0000000..e3aa669 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Https/Request.java @@ -0,0 +1,667 @@ +// +// Request.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Https; + +import android.os.AsyncTask; + +import com.google.gson.Gson; + +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.channels.AsynchronousChannelGroup; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.security.Security; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import de.labor_stein.befund.BuildConfig; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Request.KeyExchange; +import de.labor_stein.befund.Core.Models.Response.EncryptedResponse; +import de.labor_stein.befund.Core.Models.Response.PublicKey; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Curve25519; + +public class Request +{ + /** + * Low Level Header protector + */ + private static final String HeaderSecureHash = "3HzKQw/&>*VH^?cAR{Qd5pP~6w(V5%aZ"; + private static final String HeaderValueSecureHash = "7*R3P!f:sC4Q8XS:@*J/z:4/sS;V3GnM"; + + /** + * Sends Key Exchange Request to the server in async mode and calls callback(onSucces or onError) + * @param host - Servers.Host that should get this request + * @param keyPair - Client keyPair(if not given it will create a new one) + * @param onSuccess - onSuccess Handler + * @param onError - onError Handler + */ + public static void KeyExchangeAsync(Servers host, Curve25519.KeyPair keyPair, Consumer onSuccess, Consumer onError) + { + try + { + new PostKeyExchangeRequestAsync().RunAsync(host, "exchange", "key", keyPair, onSuccess, onError); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request", "KeyExchangeAsync(KeyPair, Consumer)"); + } + } + + /** + * Sends Encrypted Request to the server in async mode and calls callback(onSucces or onError) + * @param host - Servers.Host that should get this request + * @param controller - controller of the request + * @param action - controller action of the request + * @param request - Encrypted Request that should be sent to the server + * @param serverPublicKey - Server Public Key from Exchange Request + * @param keyPair - Client KeyPair (if not given it will create a new one) + * @param onSuccess - onSuccess Handler + * @param onError - onError Handler + */ + public static void EncryptedRequestAsync(Servers host, String controller, String action, EncryptedRequest request, PublicKey serverPublicKey, Curve25519.KeyPair keyPair, Consumer onSuccess, Consumer onError) + { + try + { + new PostEncryptedRequestAsync().RunAsync(host, controller, action, request, keyPair, serverPublicKey, onSuccess, onError); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request", "EncryptedRequestAsync(KeyPair, Consumer)"); + } + } + + /** + * Gets http response of an url + */ + public static void GetResponseAsync(String url, String method, Consumer onSuccess, Consumer onError) + { + try + { + new HttpsRequestAsync().RunAsync(url, method, onSuccess, onError); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request", "GetResponseAsync(String, String, Consumer, Consumer)"); + } + } + + /** + * Sends EncryptedRequest to the server in async mode and calls callback(onSucces or onError) + */ + public static class PostEncryptedRequestAsync extends AsyncTask + { + private Servers Host = null; + private String Controller = null; + private String Action = null; + private EncryptedRequest EncryptedRequest = null; + private Curve25519.KeyPair KeyPair = null; + private PublicKey ServerPublicKey = null; + private Consumer OnSuccess = null; + private Consumer OnError = null; + private String Url = null; + + /** + * Construct all necessary parameters for the async request + * @param host - Host that should get the request + * @param controller - Controller that should be called + * @param action - Controller Action that should be called + * @param encryptedRequest - Encrypted request + * @param keyPair - KeyPair of the client(if not given, it will create a new one) + * @param serverPublicKey - Server Public Key from Exchange Request + * @param onSuccess - onSuccess Handler + * @param onError - onError Handler + */ + public void RunAsync(Servers host, String controller, String action, EncryptedRequest encryptedRequest, Curve25519.KeyPair keyPair, PublicKey serverPublicKey, ConsumeronSuccess, Consumer onError) + { + this.Host = host; + this.Controller = controller; + this.Action = action; + this.EncryptedRequest = encryptedRequest; + this.KeyPair = (keyPair != null ? keyPair : Curve25519.GenerateKeyPair()); + this.ServerPublicKey = serverPublicKey; + this.OnSuccess = onSuccess; + this.OnError = onError; + this.Url = wellFormedControllerAction(host, controller, action); + this.doInBackground(); + } + + /** + * Runs the https request in the background and calls ether onSuccess or onError Callbacks + * @param params + * @return + */ + protected Boolean doInBackground(Void... params) + { + boolean result = false; + + try + { + URL uri = new URL(this.Url); + HttpsURLConnection client = (HttpsURLConnection)uri.openConnection(); + client.setRequestMethod("POST"); + client.setRequestProperty("Host", this.Host.getUrl()); + client.setRequestProperty("User-Agent", "BefundApp"); + client.setRequestProperty("Content-Type", "application/json"); + client.setRequestProperty("Client-Hash", AES.Encrypt(HeaderValueSecureHash, AES.GetKey(HeaderSecureHash))); + client.setRequestProperty("Client-Key", this.KeyPair.PublicKey); + client.setRequestProperty("Client-Signature-Key", this.KeyPair.SigningPublicKey); + client.setRequestProperty("Client-Signature", this.KeyPair.GetSignature((this.EncryptedRequest.encrypted_content != null ? this.EncryptedRequest.encrypted_content : this.EncryptedRequest.descriptor))); + + String json = new Gson().toJson(this.EncryptedRequest); + + client.setDoOutput(true); + client.setDoInput(true); + OutputStream os = client.getOutputStream(); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); + writer.write(json); + writer.flush(); + writer.close(); + os.flush(); + os.close(); + + int responseCode = client.getResponseCode(); + + if (responseCode == 429) + { + Session.Maintenance = false; + Session.MaintenanceNotified = false; + + this.responseError(Lang.Get("ERROR_TOO_MANY_REQUESTS")); + } + else if (responseCode == 503) + { + Session.Maintenance = true; + this.responseError(Lang.Get("MSG_MAINTENANCE")); + } + else + { + Session.Maintenance = false; + Session.MaintenanceNotified = false; + + if(!validServerHeaders(client)) + { + this.responseError(Lang.Get("ERROR_INVALID_RESPONSE")); + } + else + { + String jsonResponse = responseJson(client); + + if(jsonResponse != null && !jsonResponse.isEmpty()) + { + EncryptedResponse encryptedResponse = new Gson().fromJson(jsonResponse, EncryptedResponse.class); + + if(validServerSignature(client, encryptedResponse, this.KeyPair.GetSharedKey(this.ServerPublicKey.key))) + { + this.responseEncryptedResponse(encryptedResponse); + } + } + } + } + + client.disconnect(); + result = true; + } + catch(Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request.PostEncryptedRequestAsync", "doInBackground"); + this.responseError(Lang.Get("ERROR_SERVER_NOT_REACHABLE")); + } + + return result; + } + + /** + * Calls OnError Handler with a error message + * @param message - error message + */ + private void responseError(String message) + { + if(this.OnError != null) + { + this.OnError.accept(message); + } + } + + /** + * Calls OnSuccess Handler with a EncryptedResponse + * @param encryptedResponse - EncryptedResponse of the server + */ + private void responseEncryptedResponse(EncryptedResponse encryptedResponse) + { + if(this.OnSuccess != null) + { + this.OnSuccess.accept(encryptedResponse); + } + } + } + + /** + * Sends Key Exchange Post request to the server in async mode and calls callback(onSucces or onError) + */ + public static class PostKeyExchangeRequestAsync extends AsyncTask + { + private Servers Host = null; + private String Controller = null; + private String Action = null; + private Curve25519.KeyPair KeyPair = null; + private Consumer OnSuccess = null; + private Consumer OnError = null; + private String Url = null; + + /** + * Construct all necessary parameters for the async request + * @param host - Host that should get the request + * @param controller - Controller that should be called + * @param action - Controller Action that should be called + * @param keyPair - KeyPair of the client(if not given, it will create a new one) + * @param onSuccess - onSuccess Handler + * @param onError - onError Handler + */ + public void RunAsync(Servers host, String controller, String action, Curve25519.KeyPair keyPair, ConsumeronSuccess, Consumer onError) + { + this.Host = host; + this.Controller = controller; + this.Action = action; + this.KeyPair = (keyPair != null ? keyPair : Curve25519.GenerateKeyPair()); + this.OnSuccess = onSuccess; + this.OnError = onError; + this.Url = wellFormedControllerAction(host, "exchange", "key"); + this.doInBackground(); + } + + /** + * Runs the https request in the background and calls ether onSuccess or onError Callbacks + * @param params + * @return + */ + protected Boolean doInBackground(Void... params) + { + boolean result = false; + + try + { + trustSelfSignedCertificateInDebugMode(); + + URL uri = new URL(this.Url); + HttpsURLConnection client = (HttpsURLConnection)uri.openConnection(); + client.setRequestMethod("POST"); + client.setRequestProperty("Host", this.Host.getUrl()); + client.setRequestProperty("User-Agent", "BefundApp"); + client.setRequestProperty("Content-Type", "application/json"); + client.setRequestProperty("Client-Hash", AES.Encrypt(HeaderValueSecureHash, AES.GetKey(HeaderSecureHash))); + client.setRequestProperty("Client-Key", this.KeyPair.PublicKey); + + String json = new Gson().toJson(new KeyExchange()); + + client.setDoOutput(true); + client.setDoInput(true); + OutputStream os = client.getOutputStream(); + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); + writer.write(json); + writer.flush(); + writer.close(); + os.flush(); + os.close(); + + int responseCode = client.getResponseCode(); + + if (responseCode == 429) + { + Session.Maintenance = false; + Session.MaintenanceNotified = false; + this.responseError(Lang.Get("ERROR_TOO_MANY_REQUESTS")); + } + else if (responseCode == 503) + { + Session.Maintenance = true; + this.responseError(Lang.Get("MSG_MAINTENANCE")); + } + else + { + Session.Maintenance = false; + Session.MaintenanceNotified = false; + + if(!validServerHeaders(client)) + { + this.responseError(Lang.Get("ERROR_INVALID_RESPONSE")); + } + else + { + String jsonResponse = responseJson(client); + + if(jsonResponse != null && !jsonResponse.isEmpty()) + { + this.responsePublicKey(new Gson().fromJson(jsonResponse, PublicKey.class)); + } + else + { + this.responseError(Lang.Get("ERROR_INVALID_RESPONSE")); + } + } + } + + client.disconnect(); + result = true; + } + catch(Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request.PostKeyExchangeRequestAsync", "doInBackground"); + this.responseError(Lang.Get("ERROR_SERVER_NOT_REACHABLE")); + } + + return result; + } + + /** + * Calls OnError Handler with a error message + * @param message - error message + */ + private void responseError(String message) + { + if(this.OnError != null) + { + this.OnError.accept(message); + } + } + + /** + * Calls OnSuccess Handler with a PublicKey + * @param publicKey - Public Key of the server + */ + private void responsePublicKey(PublicKey publicKey) + { + if(this.OnSuccess != null) + { + this.OnSuccess.accept(publicKey); + } + } + } + + /** + * Gets http response of an url + */ + public static class HttpsRequestAsync extends AsyncTask + { + private String Url = null; + private String Method = "GET"; + private Consumer OnSuccess = null; + private Consumer OnError = null; + + /** + * Construct all necessary parameters for the async request + * @param url - Url of request + * @param method - method of http request + * @param onSuccess - onSuccess Handler + * @param onError - onError Handler + */ + public void RunAsync(String url, String method, ConsumeronSuccess, Consumer onError) + { + this.Url = url; + this.Method = (method != null ? method : "GET"); + this.OnSuccess = onSuccess; + this.OnError = onError; + this.doInBackground(); + } + + protected Boolean doInBackground(Void... params) + { + boolean result = false; + + try + { + trustSelfSignedCertificateInDebugMode(); + + URL uri = new URL(this.Url); + HttpsURLConnection client = (HttpsURLConnection)uri.openConnection(); + client.setRequestMethod(this.Method); + client.setRequestProperty("Host", uri.getHost()); + client.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"); + + int responseCode = client.getResponseCode(); + + if (responseCode == 200) + { + String response = responseJson(client); + + if(response != null && !response.isEmpty()) + { + this.responseSuccess(response); + } + } + else + { + this.responseError("Not available"); + } + + client.disconnect(); + result = true; + } + catch(Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request.HttpsRequestAsync", "doInBackground"); + this.responseError(Lang.Get("ERROR_SERVER_NOT_REACHABLE")); + } + + return result; + } + + /** + * Calls OnSuccess Handler with a content of response + * @param message - error message + */ + private void responseSuccess(String message) + { + if(this.OnSuccess != null) + { + this.OnSuccess.accept(message); + } + } + + /** + * Calls OnError Handler with a error message + * @param message - error message + */ + private void responseError(String message) + { + if(this.OnError != null) + { + this.OnError.accept(message); + } + } + } + + /** + * Trusts self signed SSL/HTTPS Certificate in the DEBUG Mode + */ + public static void trustSelfSignedCertificateInDebugMode() + { + try + { + // Trust self signed certificate on debug mode + if(BuildConfig.DEBUG) + { + TrustManager[] trustAllCerts = new TrustManager[] + { + new X509TrustManager() + { + public X509Certificate[] getAcceptedIssuers() + { + X509Certificate[] trusted = new X509Certificate[0]; + return trusted; + } + + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) + { + } + + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) + { + } + } + }; + + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() + { + @Override + public boolean verify(String arg0, SSLSession arg1) + { + return true; + } + }); + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Https.Request", "verifyCertificate"); + } + } + + /** + * Verifies server header + * @param server - server that sends response to the client + * @return returns true if server header and signature are valid + */ + private static boolean validServerHeaders(HttpsURLConnection server) + { + boolean result = false; + + if(server != null) + { + String userAgent = server.getHeaderField("User-Agent"); + String contentType = server.getHeaderField("Content-Type"); + String serverHash = server.getHeaderField("Server-Hash"); + String serverKey = server.getHeaderField("Server-Key"); + + if(userAgent != null && + userAgent.equals("BefundAppServer") && + contentType != null && + contentType.equals("application/json") && + serverHash != null && + HeaderValueSecureHash.equals(AES.Decrypt(serverHash, AES.GetKey(HeaderSecureHash))) + && serverKey != null) + { + result = true; + } + } + + return result; + } + + /** + * Validates the server response by signature and HMAC + * + * @param server - server that sends response to the client + * @param encryptedResponse - encrypted response with hmac + * @param deriveKey - derive key with server + * @return returns true if valid + */ + private static boolean validServerSignature(HttpsURLConnection server, EncryptedResponse encryptedResponse, byte[] deriveKey) + { + boolean result = false; + + if(server != null && encryptedResponse != null) + { + String signature = server.getHeaderField("Server-Signature"); + String signatureKey = server.getHeaderField("Server-Signature-Key"); + + if(signature != null && signatureKey != null && encryptedResponse.ValidSignature(deriveKey, signature, signatureKey)) + { + result = true; + } + } + + return result; + } + + /** + * Response json from the client stream + * @param client - client that contains json response + */ + private static String responseJson(HttpsURLConnection client) + { + String result = null; + + try + { + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len; + InputStream in = client.getInputStream(); + + while ((len = in.read(buffer)) != -1) + { + outStream.write(buffer, 0, len); + } + + byte[] data = outStream.toByteArray(); + + if(data != null) + { + result = new String(data, StandardCharsets.UTF_8); + } + + in.close(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Https.Request", "responseJson(HttpsURLConnection)"); + } + + return result; + } + + /** + * Forms a controller action for the request + * @param host - Host of URL + * @param controller - Controller of request + * @param action - Action of Controller, that should be called + * @return returns well formed url for the request + */ + private static String wellFormedControllerAction(Servers host, String controller, String action) + { + String result = "https://" + host.getUrl(); + + if(controller != null && !controller.isEmpty()) + { + result = result + "/" + controller; + } + + if(action != null && !action.isEmpty()) + { + result = result + "/" + action; + } + + return result; + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Https/Servers.java b/app/src/main/java/de/labor_stein/befund/Core/Https/Servers.java new file mode 100644 index 0000000..8d2d1a1 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Https/Servers.java @@ -0,0 +1,61 @@ +// +// Servers.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Https; + +public enum Servers +{ + // Development server change ip to your local ip + DEVELOPMENT("192.168.10.26"), + //DEVELOPMENT("172.21.200.145"), + + /** + * HOST´s of productive outside services + */ + LIS_SIMULATOR("pba-simulator.patientenbefundapp.labor-limbach-hannover.de:8443"), + LABOR_HEIDELBERG("patientenbefundapp.labor-limbach.de"), + LABOR_LUDWIGSBURG("patientenbefundapp.mvz-labor-lb.de"), + LABOR_ULM("patientenbefundapp.humangenetik-ulm.de"), + LABOR_AACHEN("patientenbefundapp.labor-aachen.de"), + LABOR_BERLIN("patientenbefundapp.mdi-limbach-berlin.de"), + LABOR_COTTBUS("patientenbefundapp.labor-cottbus.de"), + LABOR_DESSAU("patientenbefundapp.laborpraxis-dessau.de"), + LABOR_DORTMUND("patientenbefundapp.labor-dortmund.de"), + LABOR_DRESDEN("patientenbefundapp.labordresden.de"), + LABOR_ERFURT("patientenbefundapp.labor-erfurt.de"), + LABOR_ESSEN("patientenbefundapp.labor-eveld.de"), + LABOR_FREIBURG("patientenbefundapp.mvz-clotten.de"), + LABOR_HANNOVER("patientenbefundapp.labor-limbach-hannover.de"), + LABOR_HOFHEIM("patientenbefundapp.labor-hofheim.de"), + LABOR_KARLSRUHE("patientenbefundapp.laborvolkmann.de"), + LABOR_LEIPZIG("patientenbefundapp.labor-leipzig.de"), + LABOR_MOENCHENGLADBACH("patientenbefundapp.labor-stein.de"), + LABOR_MUENCHEN("patientenbefundapp.labor-limbach-muenchen.de"), + LABOR_MUENSTER("patientenbefundapp.labor-muenster.de"), + LABOR_NUERBERG("patientenbefundapp.labor-limbach-nuernberg.de"), + LABOR_PASSAU("patientenbefundapp.labor-passau.de"), + LABOR_RAVENSBURG("patientenbefundapp.labor-gaertner.de"), + LABOR_ROSENHEIM("patientenbefundapp.medlabor.de"), + LABOR_SCHWEINFURT("patientenbefundapp.laboraerzte-schweinfurt.de"), + LABOR_SCHWERIN("patientenbefundapp.labor-schwerin.de"), + LABOR_STRALSUND("patientenbefundapp.labor-stralsund.de"), + LABOR_SUHL("patientenbefundapp.labor-suhl.de"), + LABOR_KASSEL("MISSING"), + LABOR_HANNOVER_MLM("patientenbefundapp.mlh.de"), + LABOR_MAINZ("patientenbefundapp.medgen-mainz.de"), + LABOR_FRANKFURT("patientenbefundapp.laborarztpraxis.de"); + + private String Url; + Servers(String url) + { + this.Url = url; + } + public String getUrl() + { + return this.Url; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Lang/DE.java b/app/src/main/java/de/labor_stein/befund/Core/Lang/DE.java new file mode 100644 index 0000000..9694c1a --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Lang/DE.java @@ -0,0 +1,201 @@ +// +// DE.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Lang; + +import java.util.HashMap; + +public class DE +{ + public static HashMap GetDict() + { + HashMap result = new HashMap(); + + //MARK: LABELS + result.put("LBL_MY_RESULTS", "Meine Befunde"); + result.put("LBL_ZIP", "PLZ"); + result.put("LBL_BIRTHDAY", "Geb. Datum"); + result.put("LBL_SAMPLEID", "Auftragsnummer"); + result.put("LBL_PASSWORD", "Passwort"); + result.put("LBL_PASSWORD_CONFIRM", "Passwort bestätigen"); + result.put("LBL_PENDING", "Ausstehend"); + result.put("LBL_READY_TO_DOWNLOAD", "Bereit zum Herunterladen"); + result.put("LBL_ALREADY_DOWNLOAD", "Heruntergeladen"); + result.put("LBL_REJECTED", "Abgelehnt"); + result.put("LBL_EXPIRED", "Abgelaufen"); + result.put("LBL_NO_RESULTS", "Sie haben aktuell keinen Befund"); + //result.put("LBL_OLD_PASSWORD", "Altes Passwort"); + //result.put("LBL_SUPPORT_CODE", "Support Code"); + result.put("LBL_PRIVACY_POLICY", "AGB und Datenschutzerklärung"); + result.put("LBL_DOWNLOADING", "Wird geladen..."); + result.put("LBL_SELECT_LABOR", "Wählen Sie Ihr Labor aus"); + result.put("LBL_SELECT_LABOR_MANUEL", "Für die manuelle Auswahl wischen Sie nach rechts"); + result.put("LBL_MENU", "MENU"); + result.put("LBL_BIOMETRICAL_AUTHENTIFICATION", "Biometrische Authentifizierung"); + //result.put("LBL_ERROR", "Fehler"); + result.put("LBL_PIN", "PIN"); + result.put("LBL_CURRENT_PASSWORD", "Aktuelles Passwort"); + result.put("LBL_NEW_PASSWORD", "Neues Passwort"); + result.put("LBL_NEW_PASSWORD_CONFIRM", "Passwort bestätigen"); + result.put("LBL_NEW_PIN", "Neue PIN"); + result.put("LBL_OEGD", "Meine Patientendaten"); + result.put("LBL_NO_OEGD", "Sie haben Ihre Patientendaten noch nicht erfasst.\nWählen Sie das Menü unten aus, um Ihre persönlichen Daten zu erfassen."); + result.put("LBL_SCAN_QR_CODE", "Bitte klicken Sie auf das QR-Code-Symbol, um den QR-Code zu scannen.\n\nDamit wird Ihre App automatisch mit dem passenden Labor verknüpft"); + result.put("LBL_NEW_OEGD", "Meine Patientendaten erfassen"); + result.put("LBL_TITLE", "Titel"); + result.put("LBL_FIRSTNAME", "Vorname"); + result.put("LBL_LASTNAME", "Nachname"); + result.put("LBL_NAME_PREFIX", "Vorsatzwort"); + result.put("LBL_ADDITION_NAME", "Zusatzname"); + result.put("LBL_GENDER", "Geschlecht"); + result.put("LBL_STREET", "Straße"); + result.put("LBL_STREET_NUMBER", "HausNr."); + result.put("LBL_CITY", "Ort"); + result.put("LBL_GENDER_M", "Männlich"); + result.put("LBL_GENDER_W", "Weiblich"); + result.put("LBL_GENDER_D", "Divers"); + result.put("LBL_GENDER_X", "Unbekannt"); + result.put("LBL_TELEFON", "Telefon"); + result.put("LBL_CWA_POLICY", "CWA Einverständniserklärung"); + result.put("LBL_EDIT_OEGD", "Meine Patientendaten bearbeiten"); + result.put("LBL_SETTINGS", "Einstellungen"); + result.put("LBL_YOUR_LABOR", "Ihr Labor"); + result.put("LBL_CONNECTED", "Verbindung erfolgreich"); + result.put("LBL_DISCONNECTED", "Verbindung nicht erfolgreich"); + result.put("LBL_LANGUAGE", "Sprache"); + result.put("LBL_PASSWORD_CHANGE", "Passwort ändern"); + result.put("LBL_SUPPORT", "Support"); + result.put("LBL_EMAIL", "E-Mail"); + result.put("LBL_TEXT", "Text"); + result.put("LBL_SUPPORT_TOPIC_INFO", "Information"); + result.put("LBL_SUPPORT_TOPIC_TROUBLE", "Störung"); + result.put("LBL_SUPPORT_TOPIC_ACCOUNT_DELETE", "Account löschen"); + result.put("LBL_REFERENCE_NUMBER", "Referenznummer"); + result.put("LBL_PUSH_NOTIFICATION_EXPLAIN_HEADER", "App-Benachrichtigungen"); + result.put("LBL_MAINTENANCE", "App-Wartungsarbeiten"); + result.put("LBL_FAQ", "FAQ"); + result.put("LBL_RESULTS_NOTICE", "Die Übermittlung eines Befundes ersetzt kein Gespräch mit Ihrem Arzt."); + + //MARK: BUTTONS + result.put("BTN_NEW_RESULTS", "Neuer Befund"); + result.put("BTN_MY_RESULT", "Mein Befund"); + result.put("BTN_PRIVACY_POLICY", "Datenschutzerklärung"); + result.put("BTN_ADD", "Registrieren"); + result.put("BTN_NEXT", "Weiter"); + //result.put("BTN_DONE", "Fertig"); + result.put("BTN_CANCEL", "Abbrechen"); + result.put("BTN_BACK", "Zurück"); + //result.put("BTN_ENCRYPT", "Entschlüsseln"); + result.put("BTN_DELETE", "Löschen"); + //result.put("BTN_TAKE_OVER", "Übernehmen"); + result.put("BTN_ACCEPT_PRIVACY_POLICY", "Ich akzeptiere die AGB und Datenschutzerklärung"); + result.put("BTN_SELECT", "Auswählen"); + result.put("BTN_SETTINGS", "Einstellungen"); + result.put("BTN_CHANGE_PASSWORD", "Passwort ändern"); + result.put("BTN_OEGD", "Meine Patientendaten erfassen"); + result.put("BTN_SUPPORT", "Support"); + result.put("BTN_FAQ", "FAQ"); + result.put("BTN_CLOSE", "Schließen"); + result.put("BTN_LOGIN", "Login"); + result.put("BTN_FORGOT", "Vergessen"); + result.put("BTN_EDIT", "Bearbeiten"); + result.put("BTN_CHANGE", "Ändern"); + result.put("BTN_PIN_REQUEST", "PIN anfordern"); + result.put("BTN_PRINT", "Drucken"); + result.put("BTN_FILE_SHARE", "Dateifreigabe"); + result.put("BTN_CREATE", "Erstellen"); + result.put("BTN_ACCEPT_CWA_POLICY", "CWA Einverständniserklärung"); + result.put("BTN_NO", "Nein"); + result.put("BTN_YES", "Ja"); + result.put("BTN_SAVE", "Speichern"); + result.put("BTN_SEND", "Senden"); + result.put("BTN_HIDE_KEYBOARD", "Tastatur aus"); + result.put("BTN_OK", "OK"); + + //MARK: ERRORS + result.put("ERROR_ENTER_ZIP", "Bitte geben Sie die PLZ Ihres Wohnortes ein."); + result.put("ERROR_ENTER_BIRTHDAY", "Bitte geben Sie Ihr Geburtsdatum ein."); + result.put("ERROR_ENTER_SAMPLEID", "Bitte geben Sie eine Auftragsnummer ein."); + result.put("ERROR_ENTER_PASSWORD", "Bitte geben Sie Ihr persönliches Kennwort ein."); + result.put("ERROR_ENTER_STRONG_PASSWORD", "Das Passwort muss min. 8 Zeichen, darunter min. 1 Großbuchstabe, 1 Kleinbuchstabe, 1 Ziffer und 1 Sonderzeichen enthalten."); + result.put("ERROR_CONFIRM_PASSWORD", "Die Passwörter stimmen nicht überein."); + result.put("ERROR_COULD_NOT_SAVE", "Die Daten konnten auf dem Gerät nicht geschrieben werden. Bitte prüfen Sie, ob die Berechtigung zum Datenschreiben erlaubt ist."); + result.put("ERROR_ENCRYPTION_NOT_SUPPORTED", "Leider Ihr Gerät unterstützt keine Verschlüsselung und kann für unsere Applikation nicht verwendet werden."); + result.put("ERROR_SERVER_NOT_REACHABLE", "Leider ist aktuell der Server nicht erreichbar. Bitte versuchen Sie es später erneut."); + result.put("ERROR_ENTER_VALID_ZIP", "Bitte geben Sie eine gültige PLZ ein."); + result.put("ERROR_ENTER_VALID_BIRTHDAY", "Bitte geben Sie ein gültiges Geburtsdatum ein."); + result.put("ERROR_ENTER_VALID_SAMPLEID", "Bitte geben Sie eine gültige Auftragsnummer ein."); + result.put("ERROR_INVALID_RESPONSE", "Die Antwort vom Server konnte nicht validiert werden. Bitte versuchen Sie es später erneut."); + //result.put("ERROR_KEYS_COULD_NOT_EXCHANGED", "Der Sicherheitsschlüssel konnte mit dem Server nicht ausgetauscht werden."); + result.put("ERROR_COULD_NOT_REGISTER_PGS", "Leider konnte Ihre Anfrage für diesen Auftrag nicht registriert werden."); + result.put("ERROR_MAX_OPENED_REQUEST_LIMIT", "Sie haben die Anzahl der maximalen zulässigen öffenen Anfragen überschritten. (Max. 10 offenen Anfragen erlaubt)."); + result.put("ERROR_ALREADY_SUBSCRIBTED", "Die von Ihnen eingegebene Auftragsnummer wurde bereits auf einem anderen Gerät registriert. Sollte die App neu installiert worden sein, kann das Problem ebenfalls auftreten. Wenden Sie sich in diesem Fall bitte an den Support (siehe Menü), um an Ihren Befund zu kommen."); + result.put("ERROR_TOO_MANY_REQUESTS", "Sie haben in letzter Zeit zu viele Anfragen gesendet. Bitte warten Sie und versuchen Sie es später erneut."); + result.put("ERROR_INVALID_PASSWORD", "Das eingegebene Passwort ist ungültig."); + //result.put("ERROR_DOWNLOAD_NOT_FOUND", "Der Befund konnte leider nicht heruntergeladen werden. Bitte versuchen Sie es später erneut."); + result.put("ERROR_COULD_NOT_DECRYPT", "Der Befund konnte leider nicht entschlüsselt werden. Bitte versuchen Sie es später erneut."); + result.put("ERROR_COULD_NOT_SAVE_ENCRYPTED", "Der Befund konnte nicht gespeichert werden."); + result.put("ERROR_ENCRYPTED_FILE_NOT_FOUND", "Die Befunddatei wurde auf Ihrem Gerät nicht gefunden."); + //result.put("ERROR_ENTER_OLD_PASSWORD", "Bitte geben Sie das alte Passwort ein."); + //result.put("ERROR_NOT_AUTHORIZED_TO_TAKE_OVER", "Leider konnte der Befund nicht übernommen werden. Bitte wenden Sie sich an unseren Support."); + //result.put("ERROR_SUPPORT_CODE_NEEDED", "Bitte wenden Sie sich an unseren Support, um diesen Befund übernehmen zu können."); + //result.put("ERROR_ENTER_SUPPORT_CODE_PASSWORD", "Bitte geben Sie einen Support Code ein. Wenn Sie noch keinen Support Code erhalten haben, wenden Sie sich dafür an unseren Support."); + result.put("ERROR_ACCEPT_PRIVACY_POLICY", "Bitte akzeptieren Sie die AGB und Datenschutzerklärung."); + //result.put("ERROR_CAMERA_PERMISSION_DENIED", "Die Berechtigung für Kamera wurde verweigert."); + //result.put("ERROR_PUSH_PERMISSION_DENIED", "Die Berechtigung für PUSH-Benachrichtigungen wurde verweigert."); + result.put("ERROR_RESULTS_COULD_NOT_DOWNLOADED", "Download nicht möglich."); + result.put("ERROR_COULD_NOT_READ_QRCODE", "QR-Code konnte nicht gelesen werden."); + result.put("ERROR_COULD_NOT_READ_BARCODE", "Barcode konnte nicht gelesen werden."); + result.put("ERROR_BIOMETRICAL_AUTHENTIFICATION_COULD_NOT_ACTIVATED", "Die biometrische Authentifizierung konnte nicht aktiviert werden."); + result.put("ERROR_ENTER_PIN", "Bitte geben Sie eine PIN ein."); + result.put("ERROR_ENTER_NEW_PIN", "Bitte geben Sie eine neue PIN ein."); + result.put("ERROR_PIN_LENGTH", "PIN muss aus 5 Ziffern bestehen."); + result.put("ERROR_ENTER_YOUR_PIN", "Bitte geben Sie Ihre PIN ein."); + result.put("ERROR_ENTER_YOUR_CURRENT_PASSWORD", "Bitte geben Sie Ihr aktuelles Passwort ein."); + result.put("ERROR_INVALID_PASSWORD_RESET_PIN", "Die von Ihnen eingegebene PIN ist nicht gültig."); + result.put("ERROR_COULD_NOT_GET_PIN", "PIN konnte vom Server nicht empfangen werden."); + result.put("ERROR_COULD_NOT_CHANGE_PASSWORD", "Das Passwort konnte nicht geändert werden."); + //result.put("ERROR_ACCEPT_CWA_POLICY", "Für die Erfassung der Patientendaten benötigen wir Ihre Einverständniserklärung."); + result.put("ERROR_COULD_NOT_SAVE_OEGD", "Die Patientendaten konnten nicht gespeichert werden."); + result.put("ERROR_ENTER_FIRSTNAME", "Bitte geben Sie Ihren Vornamen ein."); + result.put("ERROR_ENTER_LASTNAME", "Bitte geben Sie Ihren Nachnamen ein."); + result.put("ERROR_ENTER_GENDER", "Bitte geben Sie Ihr Geschlecht ein."); + result.put("ERROR_ENTER_STREET", "Bitte geben Sie die Straße ein."); + result.put("ERROR_ENTER_STREET_NUMBER", "Bitte geben Sie die HausNr. ein."); + result.put("ERROR_ENTER_CITY", "Bitte geben Sie Ihren Wohnort ein."); + result.put("ERROR_YOUR_CURRENT_PASSWORD_IS_INVALID", "Ihr aktuelles Passwort ist leider nicht gültig."); + result.put("ERROR_ENTER_EMAIL", "Bitte geben Sie Ihre E-Mail ein."); + result.put("ERROR_ENTER_TOPIC", "Bitte wählen Sie ein Thema aus."); + result.put("ERROR_ENTER_TEXT", "Bitte geben Sie den Text ein."); + result.put("ERROR_ACCOUNT_COULD_NOT_DELETED", "Account konnte nicht gelöscht werden. Bitte versuchen Sie es später erneut."); + result.put("ERROR_SUPPORT_COULD_NOT_SENT", "Ihre Anfrage konnte leider nicht versendet werden. Bitte versuchen Sie es später erneut."); + result.put("ERROR_PRIVACY_POLICY_NEEDS_CONNECTION", "Um unsere Datenschutzerklärung lesen und akzeptieren zu können müssen Sie mit dem Internet verbunden sein"); + result.put("ERROR_FAQ_NEEDS_CONNECTION", "Um unsere FAQ lesen zu können müssen Sie mit dem Internet verbunden sein"); + + //MARK: MESSAGES + result.put("MSG_PGS_ALREADY_EXISTS", "Es liegt aktuell noch kein Befund vor. Sie werden per Push-Nachricht informiert, sobald Ihr Befund vorliegt."); + result.put("MSG_PGS_SUCCESSFULLY_CREATED", "Vielen Dank, Ihre Anfrage wird nun bearbeitet. Wir werden Sie über einen neuen Status zu Ihrem Befund benachrichtigen. (Bitte beachten Sie, dass die App dazu die Berechtigung benötigt, Ihnen Nachrichten zu senden.)."); + //result.put("MSG_DATA_REFRESHING", "Daten werden aktualisiert..."); + result.put("MSG_PGS_ALREADY_AVAILABLE", "Vielen Dank. Ein Status zu Ihrem Befund ist bereits vorhanden."); + //result.put("MSG_ENTER_OLD_PASSWORD", "Bitte geben Sie das Passwort von Ihrem alten Gerät ein."); + //result.put("MSG_PGS_SUCCESSFULLY_OVER_TOOK", "Der Befund wurde aus Ihrem alten Gerät erfolgreich übernommen."); + result.put("MSG_YOU_ARE_NOT_REGISTERED", "Sie sind noch nicht registriert."); + result.put("MSG_PASSWORD_HAS_BEEN_CHANGED", "Ihr Passwort wurde erfolgreich geändert."); + result.put("MSG_SURE_WANT_DELETE", "Möchten Sie den ausgewählten Eintrag([ITEM]) wirklick löschen?"); + result.put("MSG_SUPPORT_SUCCESSFULLY_SENT", "Vielen Dank, Ihre Anfrage wurde erfolgreich versendet."); + result.put("MSG_ACCOUNT_SUCCESSFULLY_DELETED", "Ihr Account wurde erfolgreich gelöscht."); + result.put("MSG_REQUESTED_RESULTS_NOT_FOUND", "Zu den von Ihnen gemachten Angaben konnte kein Auftrag gefunden werden. Bitte überprüfen Sie Ihre Angaben."); + result.put("MSG_REQUESTED_RESULTS_REJECTED", " Ihr Befund konnte im Labor bisher nicht eindeutig zugeordnet werden. Bitte prüfen Sie ihre gemachten Angaben. Sollten Sie trotz korrekter Angaben weiterhin dieses Ergebnis erhalten, wenden Sie sich bitte an den Support."); + result.put("MSG_PUSH_NOTIFICATION_EXPLAIN_TEXT", "Damit Sie direkt bei Vorliegen Ihres Befundes informiert werden können, ist es wichtig, dass diese App Ihnen Push-Nachrichten senden kann."); + result.put("MSG_MAINTENANCE", "Aktuell führen wir Wartungsarbeiten durch. Bitte beachten Sie, dass unsere App nur eingeschränkt zur Verfügung steht."); + result.put("MSG_CAMERA_PERMISSION_TITLE", "Befundapp möchte auf deine Kamera zugreifen"); + result.put("MSG_CAMERA_PERMISSION_MSG", "Die Kamera wird verwendet, um den QR-Code des Labors zu scannen."); + + + return result; + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Lang/EN.java b/app/src/main/java/de/labor_stein/befund/Core/Lang/EN.java new file mode 100644 index 0000000..8a0bb16 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Lang/EN.java @@ -0,0 +1,200 @@ +// +// EN.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Lang; + +import java.util.HashMap; + +public class EN +{ + public static HashMap GetDict() + { + HashMap result = new HashMap(); + + //MARK: LABELS + result.put("LBL_MY_RESULTS", "My Findings"); + result.put("LBL_ZIP", "ZIP CODE"); + result.put("LBL_BIRTHDAY", "Date Born"); + result.put("LBL_SAMPLEID", "Order number"); + result.put("LBL_PASSWORD", "Password"); + result.put("LBL_PASSWORD_CONFIRM", "Confirm Password"); + result.put("LBL_PENDING", "Pending"); + result.put("LBL_READY_TO_DOWNLOAD", "Ready to download"); + result.put("LBL_ALREADY_DOWNLOAD", "Downloaded"); + result.put("LBL_REJECTED", "Rejected"); + result.put("LBL_EXPIRED", "Expired"); + result.put("LBL_NO_RESULTS", "You currently have no findings"); + result.put("LBL_OLD_PASSWORD", "Old Password"); + result.put("LBL_SUPPORT_CODE", "Support Code"); + result.put("LBL_PRIVACY_POLICY", "T&C and Privacy Policy"); + result.put("LBL_DOWNLOADING", "Loading..."); + result.put("LBL_SELECT_LABOR", "Select your lab"); + result.put("LBL_SELECT_LABOR_MANUEL", "For manual selection, swipe right"); + result.put("LBL_MENU", "MENU"); + result.put("LBL_BIOMETRICAL_AUTHENTIFICATION", "Biometric Authentication"); + result.put("LBL_ERROR", "Error"); + result.put("LBL_PIN", "PIN"); + result.put("LBL_CURRENT_PASSWORD", "Current password"); + result.put("LBL_NEW_PASSWORD", "New password"); + result.put("LBL_NEW_PASSWORD_CONFIRM", "Confirm Password"); + result.put("LBL_NEW_PIN", "New PIN"); + result.put("LBL_OEGD", "My patient data"); + result.put("LBL_NO_OEGD", "You have not yet entered your patient data.\nSelect the menu below to enter your personal data."); + result.put("LBL_SCAN_QR_CODE", "Please click the QR code icon to scan the QR code.\nThis will automatically link your app to the appropriate lab."); + result.put("LBL_NEW_OEGD", "Capture my patient data"); + result.put("LBL_TITLE", "Title"); + result.put("LBL_FIRSTNAME", "FirstName"); + result.put("LBL_LASTNAME", "LastName"); + result.put("LBL_NAME_PREFIX", "prefix"); + result.put("LBL_ADDITION_NAME", "additional name"); + result.put("LBL_GENDER", "Gender"); + result.put("LBL_STREET", "Street"); + result.put("LBL_STREET_NUMBER", "HOUSE NO."); + result.put("LBL_CITY", "City"); + result.put("LBL_GENDER_M", "Male"); + result.put("LBL_GENDER_W", "Female"); + result.put("LBL_GENDER_D", "Various"); + result.put("LBL_GENDER_X", "unknown"); + result.put("LBL_TELEFON", "telephone"); + result.put("LBL_CWA_POLICY", "CWA Consent Form"); + result.put("LBL_EDIT_OEGD", "Edit My Patient Data"); + result.put("LBL_SETTINGS", "Settings"); + result.put("LBL_YOUR_LABOR", "Your Lab"); + result.put("LBL_CONNECTED", "Connection successful"); + result.put("LBL_DISCONNECTED", "Connection not successful"); + result.put("LBL_LANGUAGE", "Language"); + result.put("LBL_PASSWORD_CHANGE", "Change Password"); + result.put("LBL_SUPPORT", "Support"); + result.put("LBL_EMAIL", "E-mail"); + result.put("LBL_TEXT", "text"); + result.put("LBL_SUPPORT_TOPIC_INFO", "information"); + result.put("LBL_SUPPORT_TOPIC_TROUBLE", " malfunction"); + result.put("LBL_SUPPORT_TOPIC_ACCOUNT_DELETE", "Delete Account"); + result.put("LBL_REFERENCE_NUMBER", "reference number"); + result.put("LBL_PUSH_NOTIFICATION_EXPLAIN_HEADER", "App notifications"); + result.put("LBL_MAINTENANCE", "App Maintenance"); + result.put("LBL_FAQ", "FAQ"); + result.put("LBL_RESULTS_NOTICE", "Submitting a report does not replace a conversation with your doctor."); + + //MARK: BUTTONS + result.put("BTN_NEW_RESULTS", "New finding"); + result.put("BTN_MY_RESULT", "My Findings"); + result.put("BTN_PRIVACY_POLICY", "Privacy Policy"); + result.put("BTN_ADD", "Register"); + result.put("BTN_NEXT", "Next"); + result.put("BTN_DONE", "Done"); + result.put("BTN_CANCEL", "Cancel"); + result.put("BTN_BACK", "Back"); + result.put("BTN_ENCRYPT", "Decrypt"); + result.put("BTN_DELETE", "Delete"); + result.put("BTN_TAKE_OVER", "Apply"); + result.put("BTN_ACCEPT_PRIVACY_POLICY", "I accept the terms and conditions and privacy policy"); + result.put("BTN_SELECT", "Select"); + result.put("BTN_SETTINGS", "Settings"); + result.put("BTN_CHANGE_PASSWORD", "Change Password"); + result.put("BTN_OEGD", "Enter my patient data"); + result.put("BTN_SUPPORT", "Support"); + result.put("BTN_FAQ", "FAQ"); + result.put("BTN_CLOSE", "Close"); + result.put("BTN_LOGIN", "Login"); + result.put("BTN_FORGOT", "Forget"); + result.put("BTN_EDIT", "Edit"); + result.put("BTN_CHANGE", "Modify"); + result.put("BTN_PIN_REQUEST", "Request PIN"); + result.put("BTN_PRINT", "Print"); + result.put("BTN_FILE_SHARE", "File Share"); + result.put("BTN_CREATE", "Create"); + result.put("BTN_ACCEPT_CWA_POLICY", "CWA Consent Form"); + result.put("BTN_NO", "No"); + result.put("BTN_YES", "Yes"); + result.put("BTN_SAVE", "Save"); + result.put("BTN_SEND", "Send"); + result.put("BTN_HIDE_KEYBOARD", "Keyboard off"); + result.put("BTN_OK", "OK"); + + //MARK: ERRORS + result.put("ERROR_ENTER_ZIP", "Please enter the zip code of your city of residence."); + result.put("ERROR_ENTER_BIRTHDAY", "Please enter your date of birth."); + result.put("ERROR_ENTER_SAMPLEID", "Please enter an order number."); + result.put("ERROR_ENTER_PASSWORD", "Please enter your personal password."); + result.put("ERROR_ENTER_STRONG_PASSWORD", "The password must contain min. 8 characters, including min. 1 uppercase letter, 1 lowercase letter, 1 digit and 1 special character."); + result.put("ERROR_CONFIRM_PASSWORD", "The passwords do not match."); + result.put("ERROR_COULD_NOT_SAVE", "The data could not be written on the device. Please check if the permission to write data is allowed."); + result.put("ERROR_ENCRYPTION_NOT_SUPPORTED", "Unfortunately your device does not support encryption and cannot be used for our application."); + result.put("ERROR_SERVER_NOT_REACHABLE", "Unfortunately, currently the server is not accessible. Please try again later."); + result.put("ERROR_ENTER_VALID_ZIP", "Please enter a valid zip code."); + result.put("ERROR_ENTER_VALID_BIRTHDAY", "Please enter a valid date of birth."); + result.put("ERROR_ENTER_VALID_SAMPLEID", "Please enter a valid order number."); + result.put("ERROR_INVALID_RESPONSE", "The response from the server could not be validated. Please try again later."); + result.put("ERROR_KEYS_COULD_NOT_EXCHANGED", "The security key could not be exchanged with the server."); + result.put("ERROR_COULD_NOT_REGISTER_PGS", "Unfortunately, your request could not be registered for this job."); + result.put("ERROR_MAX_OPENED_REQUEST_LIMIT", "You have exceeded the maximum number of open requests allowed. (Max 10 open requests allowed)."); + result.put("ERROR_ALREADY_SUBSCRIBTED", "The order number you entered has already been registered on another device. If the app has been newly installed, the problem may also occur. In this case, please contact support (see menu) to get your finding."); + result.put("ERROR_TOO_MANY_REQUESTS", "You have sent too many requests recently. Please wait and try again later."); + result.put("ERROR_INVALID_PASSWORD", "The password you entered is invalid."); + result.put("ERROR_DOWNLOAD_NOT_FOUND", "Sorry, the finding could not be downloaded. Please try again later."); + result.put("ERROR_COULD_NOT_DECRYPT", "Sorry, the finding could not be decrypted. Please try again later."); + result.put("ERROR_COULD_NOT_SAVE_ENCRYPTED", "The findings could not be saved."); + result.put("ERROR_ENCRYPTED_FILE_NOT_FOUND", "The findings file was not found on your device."); + result.put("ERROR_ENTER_OLD_PASSWORD", "Please enter the old password."); + result.put("ERROR_NOT_AUTHORIZED_TO_TAKE_OVER", "Unfortunately, the findings could not be transferred. Please contact our support."); + result.put("ERROR_SUPPORT_CODE_NEEDED", "Please contact our support to be able to adopt this finding."); + result.put("ERROR_ENTER_SUPPORT_CODE_PASSWORD", "Please enter a support code. If you have not received a support code yet, please contact our support for it."); + result.put("ERROR_ACCEPT_PRIVACY_POLICY", "Please accept the terms and conditions and privacy policy."); + result.put("ERROR_CAMERA_PERMISSION_DENIED", "Authorization for camera has been denied."); + result.put("ERROR_PUSH_PERMISSION_DENIED", "Permission for PUSH notifications has been denied."); + result.put("ERROR_RESULTS_COULD_NOT_DOWNLOADED", "Unable to download."); + result.put("ERROR_COULD_NOT_READ_QRCODE", "QR code could not be read."); + result.put("ERROR_COULD_NOT_READ_BARCODE", "Barcode could not be read."); + result.put("ERROR_BIOMETRICAL_AUTHENTIFICATION_COULD_NOT_ACTIVATED", "Biometric authentication could not be enabled."); + result.put("ERROR_ENTER_PIN", "Please enter a PIN."); + result.put("ERROR_ENTER_NEW_PIN", "Please enter a new PIN."); + result.put("ERROR_PIN_LENGTH", "PIN must consist of 5 digits."); + result.put("ERROR_ENTER_YOUR_PIN", "Please enter your PIN."); + result.put("ERROR_ENTER_YOUR_CURRENT_PASSWORD", "Please enter your current password."); + result.put("ERROR_INVALID_PASSWORD_RESET_PIN", "The PIN you entered is not valid."); + result.put("ERROR_COULD_NOT_GET_PIN", "PIN could not be received from the server."); + result.put("ERROR_COULD_NOT_CHANGE_PASSWORD", "Password could not be changed."); + result.put("ERROR_ACCEPT_CWA_POLICY", "We need your consent form to record the patient data."); + result.put("ERROR_COULD_NOT_SAVE_OEGD", "The patient data could not be saved."); + result.put("ERROR_ENTER_FIRSTNAME", "Please enter your first name."); + result.put("ERROR_ENTER_LASTNAME", "Please enter your last name."); + result.put("ERROR_ENTER_GENDER", "Please enter your gender."); + result.put("ERROR_ENTER_STREET", "Please enter the street."); + result.put("ERROR_ENTER_STREET_NUMBER", "Please enter the house no."); + result.put("ERROR_ENTER_CITY", "Please enter your city of residence."); + result.put("ERROR_YOUR_CURRENT_PASSWORD_IS_INVALID", "Sorry, your current password is not valid."); + result.put("ERROR_ENTER_EMAIL", "Please enter your email."); + result.put("ERROR_ENTER_TOPIC", "Please select a topic."); + result.put("ERROR_ENTER_TEXT", "Please enter the text."); + result.put("ERROR_ACCOUNT_COULD_NOT_DELETED", "Account could not be deleted. Please try again later."); + result.put("ERROR_SUPPORT_COULD_NOT_SENT", "Sorry, your request could not be sent. Please try again later."); + result.put("ERROR_PRIVACY_POLICY_NEEDS_CONNECTION", "To read and accept our privacy policy you must be connected to the Internet."); + + //MARK: MESSAGES + result.put("MSG_PGS_ALREADY_EXISTS", "There are currently no findings. You will be notified via push message as soon as your findings are available."); + result.put("MSG_PGS_SUCCESSFULLY_CREATED", "Thank you, your request is now being processed. We will notify you of a new status on your finding. (Please note that the app needs permission to send you messages to do this.)"); + result.put("MSG_DATA_REFRESHING", "Data is being updated..."); + result.put("MSG_PGS_ALREADY_AVAILABLE", "Thank you. A status to your findings is already available."); + result.put("MSG_ENTER_OLD_PASSWORD", "Please enter the password from your old device."); + result.put("MSG_PGS_SUCCESSFULLY_OVER_TOOK", "The finding has been successfully transferred from your old device."); + result.put("MSG_YOU_ARE_NOT_REGISTERED", "You are not registered yet."); + result.put("MSG_PASSWORD_HAS_BEEN_CHANGED", "Your password has been successfully changed."); + result.put("MSG_SURE_WANT_DELETE", "Do you really want to delete the selected entry([ITEM]) ?"); + result.put("MSG_SUPPORT_SUCCESSFULLY_SENT", "Thank you, your request has been sent successfully."); + result.put("MSG_ACCOUNT_SUCCESSFULLY_DELETED", "Your account has been successfully deleted."); + result.put("MSG_REQUESTED_RESULTS_NOT_FOUND", "No order could be found for the information you provided. Please check your information."); + result.put("MSG_REQUESTED_RESULTS_REJECTED", " Your findings could not be clearly assigned in the laboratory so far. Please check the information you have provided. If you still receive this result despite correct information, please contact support."); + result.put("MSG_PUSH_NOTIFICATION_EXPLAIN_TEXT", "So that you can be informed directly when your findings are available, it is important that this app can send you push messages."); + result.put("MSG_MAINTENANCE", "Currently, we are performing maintenance. Please note that our app is only available on a limited basis."); + result.put("MSG_CAMERA_PERMISSION_TITLE", "Befundapp wants to access your camera"); + result.put("MSG_CAMERA_PERMISSION_MSG", "The camera is used to scan the lab's QR code."); + + + return result; + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Lang/Lang.java b/app/src/main/java/de/labor_stein/befund/Core/Lang/Lang.java new file mode 100644 index 0000000..e7766a6 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Lang/Lang.java @@ -0,0 +1,108 @@ +// +// Lang.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Lang; + +import java.util.HashMap; +import java.util.Locale; + +import de.labor_stein.befund.Core.Log; + +public class Lang +{ + public enum Languages { DE, EN } + + private static String _locale = "de_DE"; + private static HashMap _dict = null; + + /** + * Sets the language of application UI + * @param lang - lang that should be set + */ + public static void SetLanguage(Languages lang) + { + switch(lang) + { + case DE: + _dict = DE.GetDict(); + _locale = "de_DE"; + break; + + case EN: + _dict = EN.GetDict(); + _locale = "en_GB"; + break; + } + } + + /** + * Gets the translated word of ey + * @param key - key of word that should return translated value + * @return + */ + public static String Get(String key) + { + String result = key; + + if(_dict != null) + { + String value = _dict.get(key); + + if(value != null) + { + result = value; + } + } + + return result; + } + + /** + * Returns language locale + * @return returns string locale + */ + public static String GetLocale() + { + return _locale; + } + + /** + * Returns lang depended on system language + * @return + */ + public static Languages GetSystemLang() + { + Languages result = Languages.EN; + + try + { + String sysLang = Locale.getDefault().getLanguage(); + + if(sysLang != null && !sysLang.isEmpty()) + { + sysLang = sysLang.toLowerCase(); + + switch (sysLang) + { + case "de": + result = Languages.DE; + break; + + default: + result = Languages.EN; + break; + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Lang", "GetSystemLang"); + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Log.java b/app/src/main/java/de/labor_stein/befund/Core/Log.java new file mode 100644 index 0000000..e126420 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Log.java @@ -0,0 +1,99 @@ +// +// Log.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core; + +import android.content.Context; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import de.labor_stein.befund.Core.Database.Logs; +import de.labor_stein.befund.Core.Models.Database.DbLog; +import de.labor_stein.befund.Core.Models.Response.Exception; + +public class Log +{ + private static Context CurrentContext = null; + private static Logs _dbLogs = null; + + public enum LogTypes { CRITICAL, ERROR, INFO, LOG, DEBUG, WARNING } + + public static void Initialize(Context context) + { + _dbLogs = new Logs(context); + } + + public static void Critical(Exception err, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + err.message; + Write(message, LogTypes.CRITICAL); + } + + public static void Critical(String msg, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + msg; + Write(message, LogTypes.CRITICAL); + } + + public static void Error(Exception err, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + err.message; + Write(message, LogTypes.ERROR); + } + + public static void Error(String msg, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + msg; + Write(message, LogTypes.ERROR); + } + + public static void Info(String msg, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + msg; + Write(message, LogTypes.INFO); + } + + public static void Debug(String msg, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + msg; + Write(message, LogTypes.DEBUG); + } + + public static void Warning(String msg, String namespace, String method) + { + String message = "(" + namespace + "->" + method + "): " + msg; + Write(message, LogTypes.WARNING); + } + + public static void Write(String message, LogTypes type) + { + try + { + Date now = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String msg = dateFormat.format(now) + " [" + type.name() + "]:" + message + "\r\n"; + + if(type == LogTypes.DEBUG) + { + java.lang.System.out.println(msg); + } + + DbLog dbLog = new DbLog(); + dbLog.guid = UUID.randomUUID().toString(); + dbLog.message = msg; + dbLog.type = type.name(); + + _dbLogs.Create(dbLog); + } + catch (java.lang.Exception ex) + { + java.lang.System.out.println(ex.getLocalizedMessage()); + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Database/DbLog.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Database/DbLog.java new file mode 100644 index 0000000..ef39892 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Database/DbLog.java @@ -0,0 +1,19 @@ +// +// DbLog.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Database; + +import java.util.Date; + +public class DbLog +{ + public int id = 0; + public String guid = null; + public String message = null; + public String type = null; + public Date created = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Database/Results.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Database/Results.java new file mode 100644 index 0000000..8589745 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Database/Results.java @@ -0,0 +1,350 @@ +// +// Results.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Database; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.drawable.Drawable; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Request.Subscribe; +import de.labor_stein.befund.R; + +public class Results +{ + public enum DeviceTypes { NONE, IOS, ANDROID } + public enum ResultsStatus { NONE, CREATED, REJECTED, EXPIRED, COMPLETED, DELETED } + + public String pgs = null; + public Boolean available = false; + public String available_ts = null; + public Boolean picked_up = false; + public String picked_up_ts = null; + public Boolean downloaded = false; + public String downloaded_ts = null; + public String downloaded_file = null; + public String server_public_key = null; + public String file_checksum = null; + public String status = null; + public String modified = null; + public String created = null; + + /** Runtime flag not stored in the database **/ + public Boolean downloading = false; + + public ResultsStatus GetStatus() + { + switch(this.status) + { + case "CREATED": return ResultsStatus.CREATED; + case "REJECTED": return ResultsStatus.REJECTED; + case "EXPIRED": return ResultsStatus.EXPIRED; + case "COMPLETED": return ResultsStatus.COMPLETED; + case "DELETED": return ResultsStatus.DELETED; + default: return ResultsStatus.NONE; + } + } + + public String GetStatusText() + { + String result = Lang.Get("LBL_PENDING"); + + if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && this.downloaded) + { + result = Lang.Get("LBL_ALREADY_DOWNLOAD"); + } + else if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && !this.picked_up) + { + result = Lang.Get("LBL_READY_TO_DOWNLOAD"); + } + else if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && this.picked_up) + { + result = Lang.Get("LBL_ALREADY_DOWNLOAD"); + } + else if(!this.available && this.GetStatus() == ResultsStatus.REJECTED) + { + result = Lang.Get("LBL_REJECTED"); + } + else if(!this.available && this.GetStatus() == ResultsStatus.EXPIRED) + { + result = Lang.Get("LBL_EXPIRED"); + } + + return result; + } + + public Drawable GetStatusIcon(Context context) + { + Drawable result = context.getDrawable(R.drawable.ic_opacity); + + if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && this.downloaded) + { + result = context.getDrawable(R.drawable.ic_picture_as_pdf); + } + else if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && !this.picked_up) + { + result = context.getDrawable(R.drawable.ic_file_download); + } + else if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && this.picked_up) + { + result = context.getDrawable(R.drawable.ic_picture_as_pdf); + } + else if(!this.available && this.GetStatus() == ResultsStatus.REJECTED) + { + result = context.getDrawable(R.drawable.ic_do_not_disturb_on); + } + else if(!this.available && this.GetStatus() == ResultsStatus.EXPIRED) + { + result = context.getDrawable(R.drawable.ic_av_timer); + } + + return result; + } + + public Color GetStatusColor() + { + Color result = Color.valueOf(192/255, 192/255, 192/255, 1); + + if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && this.downloaded) + { + result = Color.valueOf(250/255, 138/255, 47/255, 1); + } + else if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && !this.picked_up) + { + result = Color.valueOf(101/255, 246/255, 107/255, 1); + } + else if(this.available && this.GetStatus() == ResultsStatus.COMPLETED && this.picked_up) + { + result = Color.valueOf(250/255, 138/255, 47/255, 1); + } + else if(!this.available && this.GetStatus() == ResultsStatus.REJECTED) + { + result = Color.valueOf(250/255, 46/255, 46/255, 1); + } + else if(!this.available && this.GetStatus() == ResultsStatus.EXPIRED) + { + result = Color.valueOf(250/255, 46/255, 46/255, 1); + } + + return result; + } + + public Date GetModified() + { + Date result = null; + + try + { + if(this.modified != null && this.modified != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.modified); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Results", "GetModified"); + } + + return result; + } + + public Date GetCreated() + { + Date result = null; + + try + { + if(this.created != null && this.created != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.created); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Results", "GetCreated"); + } + + return result; + } + + public Date GetAvailableTS() + { + Date result = null; + + try + { + if(this.available_ts != null && this.available_ts != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.available_ts); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Results", "GetAvailableTS"); + } + + return result; + } + + public Date GetPickedUpTS() + { + Date result = null; + + try + { + if(this.picked_up_ts != null && this.picked_up_ts != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.picked_up_ts); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Results", "GetPickedUpTS"); + } + + return result; + } + + public Date GetDownloadedTS() + { + Date result = null; + + try + { + if(this.downloaded_ts != null && this.downloaded_ts != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.downloaded_ts); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Results", "GetDownloadedTS"); + } + + return result; + } + + public String GetFormatedModifiedDate() + { + String result = null; + + try + { + Date date = this.GetModified(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Results", "GetFormatedModifiedDate"); + } + + return result; + } + + public String GetFormatedCreatedDate() + { + String result = null; + + try + { + Date date = this.GetCreated(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Results", "GetFormatedCreatedDate"); + } + + return result; + } + + public String GetFormatedAvailableTSDate() + { + String result = null; + + try + { + Date date = this.GetAvailableTS(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Results", "GetFormatedAvailableTSDate"); + } + + return result; + } + + public String GetFormatedPickedUpTSDate() + { + String result = null; + + try + { + Date date = this.GetPickedUpTS(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Results", "GetFormatedPickedUpTSDate"); + } + + return result; + } + + public String GetFormatedDownloadedTSDate() + { + String result = null; + + try + { + Date date = this.GetDownloadedTS(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Results", "GetFormatedDownloadedTSDate"); + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Database/Status.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Database/Status.java new file mode 100644 index 0000000..79fb69d --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Database/Status.java @@ -0,0 +1,122 @@ +// +// Status.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Database; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import de.labor_stein.befund.Core.Log; + +public class Status +{ + public String pgs = null; + public Boolean available = false; + public String available_ts = null; + public Boolean picked_up = false; + public String picked_up_ts = null; + public Boolean notified = false; + public String notified_ts = null; + public String results_status = Results.ResultsStatus.NONE.name(); + public String results_message = null; + public String file_checksum = null; + public String created = null; + + public Date GetAvailableTS() + { + Date result = null; + + try + { + if(this.available_ts != null && this.available_ts != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.available_ts); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Status", "GetAvailableTS"); + } + + return result; + } + + public Date GetPickedUpTS() + { + Date result = null; + + try + { + if(this.picked_up_ts != null && this.picked_up_ts != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.picked_up_ts); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Status", "GetPickedUpTS"); + } + + return result; + } + + public Date GetNotifiedTS() + { + Date result = null; + + try + { + if(this.notified_ts != null && this.notified_ts != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.notified_ts); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Status", "GetNotifiedTS"); + } + + return result; + } + + public Date GetCreated() + { + Date result = null; + + try + { + if(this.created != null && this.created != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + result = dateFormat.parse(this.created); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Database.Status", "GetCreated"); + } + + return result; + } + + public Results ToResults() + { + Results result = new Results(); + result.pgs = this.pgs; + result.available = this.available; + result.available_ts = this.available_ts; + result.picked_up = this.picked_up; + result.picked_up_ts = this.picked_up_ts; + result.status = this.results_status; + result.file_checksum = this.file_checksum; + result.created = this.created; + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Labor.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Labor.java new file mode 100644 index 0000000..7587b97 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Labor.java @@ -0,0 +1,512 @@ +// +// Labor.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 04.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models; + +import java.util.ArrayList; +import java.util.List; + +import de.labor_stein.befund.Core.Https.Servers; +import de.labor_stein.befund.R; + +public class Labor +{ + public String id; + public String name; + public String street; + public String city; + public String zip; + public String tel; + public String web; + public int logo; + public Servers host; + public boolean active = false; + + /** + * Returns labor by id + * + * @param id - id of labor + * @return Labor object + */ + public static Labor GetLaborByName(String id) + { + Labor result = null; + + List labors = Labors(); + + for(int i = 0; i < labors.size(); i++) + { + Labor l = labors.get(i); + + if(l.id.toLowerCase().equals(id.toLowerCase())) + { + result = l; + break; + } + } + + return result; + } + + /** + * Returns list of all available labors + */ + public static List Labors() + { + List result = new ArrayList(); + + /** QRCode selektor : befund://labor?id=LABOR_HEIDELBERG **/ + /** LIS Simulator **/ + Labor lis_simulator = new Labor(); + lis_simulator.id = "LIS_SIMULATOR"; + lis_simulator.name = "LIS Simulator"; + lis_simulator.street = "Teststr. 7"; + lis_simulator.city = "Testort"; + lis_simulator.zip = "77777"; + lis_simulator.tel = "+49 77 123 456"; + lis_simulator.web = "pba-simulator.patientenbefundapp.labor-limbach-hannover.de"; + lis_simulator.logo = R.drawable.labor_hannover; + lis_simulator.host = Servers.LIS_SIMULATOR; + lis_simulator.active = true; + result.add(lis_simulator); + + /** MVZ Labor Dr. Limbach & Kollegen GbR **/ + Labor labor_heidelberg = new Labor(); + labor_heidelberg.id = "LABOR_HEIDELBERG"; + labor_heidelberg.name = "MVZ Labor Dr. Limbach & Kollegen GbR"; + labor_heidelberg.street = "Im Breitspiel 16"; + labor_heidelberg.city = "Heidelberg"; + labor_heidelberg.zip = "69126"; + labor_heidelberg.tel = "+49 6221 3432-0"; + labor_heidelberg.web = "www.labor-limbach.de"; + labor_heidelberg.logo = R.drawable.labor_heidelberg; + labor_heidelberg.host = Servers.LABOR_HEIDELBERG; + labor_heidelberg.active = true; + result.add(labor_heidelberg); + + /** MVZ Labor Ludwigsburg GbR **/ + Labor labor_ludwigsburg = new Labor(); + labor_ludwigsburg.id = "LABOR_LUDWIGSBURG"; + labor_ludwigsburg.name = "MVZ Labor Ludwigsburg GbR"; + labor_ludwigsburg.street = "Wernerstraße 33"; + labor_ludwigsburg.city = "Ludwigsburg"; + labor_ludwigsburg.zip = "71636"; + labor_ludwigsburg.tel = "+49 7141 966-0"; + labor_ludwigsburg.web = "www.mvz-labor-lb.de"; + labor_ludwigsburg.logo = R.drawable.labor_ludwigsburg; + labor_ludwigsburg.host = Servers.LABOR_LUDWIGSBURG; + labor_ludwigsburg.active = true; + result.add(labor_ludwigsburg); + + /** MVZ Humangenetik Ulm **/ + Labor labor_ulm = new Labor(); + labor_ulm.id = "LABOR_ULM"; + labor_ulm.name = "MVZ Humangenetik Ulm"; + labor_ulm.street = "Karlstraße 31-33"; + labor_ulm.city = "Ulm"; + labor_ulm.zip = "89073"; + labor_ulm.tel = "+49 731 850773-0"; + labor_ulm.web = "www.humangenetik-ulm.de"; + labor_ulm.logo = R.drawable.labor_ulm; + labor_ulm.host = Servers.LABOR_ULM; + labor_ulm.active = true; + result.add(labor_ulm); + + /** MVZ Labor Limbach Aachen **/ + Labor labor_aachen = new Labor(); + labor_aachen.id = "LABOR_AACHEN"; + labor_aachen.name = "MVZ Labor Limbach Aachen"; + labor_aachen.street = "Karl-Carstens-Straße 19"; + labor_aachen.city = "Würselen"; + labor_aachen.zip = "52146"; + labor_aachen.tel = "+49 2405 4891-0"; + labor_aachen.web = "www.labor-aachen.de"; + labor_aachen.logo = R.drawable.labor_aachen; + labor_aachen.host = Servers.LABOR_AACHEN; + labor_aachen.active = true; + result.add(labor_aachen); + + /** MDI Limbach Berlin GmbH **/ + Labor labor_berlin = new Labor(); + labor_berlin.id = "LABOR_BERLIN"; + labor_berlin.name = "MDI Limbach Berlin GmbH"; + labor_berlin.street = "Aroser Allee 84"; + labor_berlin.city = "Berlin"; + labor_berlin.zip = "13407"; + labor_berlin.tel = "+49 30 890645-0"; + labor_berlin.web = "www.mdi-limbach-berlin.de"; + labor_berlin.logo = R.drawable.labor_berlin; + labor_berlin.host = Servers.LABOR_BERLIN; + labor_berlin.active = true; + result.add(labor_berlin); + + /** MVZ Gemeinschaftslabor Cottbus GbR **/ + Labor labor_cottbus = new Labor(); + labor_cottbus.id = "LABOR_COTTBUS"; + labor_cottbus.name = "MVZ Gemeinschaftslabor Cottbus GbR"; + labor_cottbus.street = "Uhlandstraße 53"; + labor_cottbus.city = "Cottbus"; + labor_cottbus.zip = "03050"; + labor_cottbus.tel = "+49 355 58402-0"; + labor_cottbus.web = "www.labor-cottbus.de"; + labor_cottbus.logo = R.drawable.labor_cottbus; + labor_cottbus.host = Servers.LABOR_COTTBUS; + labor_cottbus.active = true; + result.add(labor_cottbus); + + /** MVZ Medizinische Labore Dessau Kassel GmbH **/ + Labor labor_dessau = new Labor(); + labor_dessau.id = "LABOR_DESSAU"; + labor_dessau.name = "MVZ Medizinische Labore Dessau Kassel GmbH"; + labor_dessau.street = "Bauhüttenstraße 6"; + labor_dessau.city = "Dessau"; + labor_dessau.zip = "06847"; + labor_dessau.tel = "+49 340 54053-0"; + labor_dessau.web = "www.laborpraxis-dessau.de"; + labor_dessau.logo = R.drawable.labor_dessau; + labor_dessau.host = Servers.LABOR_DESSAU; + labor_dessau.active = true; + result.add(labor_dessau); + + /** MVZ Labor Dortmund Leopoldstraße GmbH **/ + Labor labor_dortmund = new Labor(); + labor_dortmund.id = "LABOR_DORTMUND"; + labor_dortmund.name = "MVZ Labor Dortmund Leopoldstraße GmbH"; + labor_dortmund.street = "Leopoldstraße 10"; + labor_dortmund.city = "Dortmund"; + labor_dortmund.zip = "44147"; + labor_dortmund.tel = "+49 231 86027-0"; + labor_dortmund.web = "www.labor-dortmund.de"; + labor_dortmund.logo = R.drawable.labor_dortmund; + labor_dortmund.host = Servers.LABOR_DORTMUND; + labor_dortmund.active = true; + result.add(labor_dortmund); + + /** MVZ Labor Limbach Dresden GbR **/ + Labor labor_dresden = new Labor(); + labor_dresden.id = "LABOR_DRESDEN"; + labor_dresden.name = "MVZ Labor Limbach Dresden GbR"; + labor_dresden.street = "Köhlerstraße 14 A"; + labor_dresden.city = "Dresden"; + labor_dresden.zip = "01239"; + labor_dresden.tel = "+49 351 47049-0"; + labor_dresden.web = "www.labordresden.de"; + labor_dresden.logo = R.drawable.labor_dresden; + labor_dresden.host = Servers.LABOR_DRESDEN; + labor_dresden.active = true; + result.add(labor_dresden); + + /** MVZ Labor Limbach Erfurt GmbH **/ + Labor labor_erfurt = new Labor(); + labor_erfurt.id = "LABOR_ERFURT"; + labor_erfurt.name = "MVZ Labor Limbach Erfurt GmbH"; + labor_erfurt.street = "Nordhäuser Straße 74"; + labor_erfurt.city = "Erfurt"; + labor_erfurt.zip = "99089"; + labor_erfurt.tel = "+49 361 781-2701"; + labor_erfurt.web = "www.labor-erfurt.de"; + labor_erfurt.logo = R.drawable.labor_erfurt; + labor_erfurt.host = Servers.LABOR_ERFURT; + labor_erfurt.active = true; + result.add(labor_erfurt); + + /** MVZ Labor Limbach Erfurt GmbH **/ + Labor labor_essen = new Labor(); + labor_essen.id = "LABOR_ESSEN"; + labor_essen.name = "MVZ Labor Essen Nienkampstraße GmbH"; + labor_essen.street = "Nienkampstraße 1"; + labor_essen.city = "Essen"; + labor_essen.zip = "45326"; + labor_essen.tel = "+49 201 8379-0"; + labor_essen.web = "www.labor-eveld.de"; + labor_essen.logo = R.drawable.labor_essen; + labor_essen.host = Servers.LABOR_ESSEN; + labor_essen.active = true; + result.add(labor_essen); + + /** MVZ Clotten Labor Dr. Haas, Dr. Raif & Kollegen GbR **/ + Labor labor_freiburg = new Labor(); + labor_freiburg.id = "LABOR_FREIBURG"; + labor_freiburg.name = "MVZ Clotten Labor Dr. Haas, Dr. Raif & Kollegen GbR"; + labor_freiburg.street = "Merzhauser Straße 112 a"; + labor_freiburg.city = "Freiburg"; + labor_freiburg.zip = "79100"; + labor_freiburg.tel = "+49 761 31905-0"; + labor_freiburg.web = "www.mvz-clotten.de"; + labor_freiburg.logo = R.drawable.labor_freiburg; + labor_freiburg.host = Servers.LABOR_FREIBURG; + labor_freiburg.active = true; + result.add(labor_freiburg); + + /** MVZ Labor Limbach Hannover GbR **/ + Labor labor_hannover = new Labor(); + labor_hannover.id = "LABOR_HANNOVER"; + labor_hannover.name = "MVZ Labor Limbach Hannover GbR"; + labor_hannover.street = "Auf den Pohläckern 12"; + labor_hannover.city = "Lehrte"; + labor_hannover.zip = "31275"; + labor_hannover.tel = "+49 5132 8695-0"; + labor_hannover.web = "www.labor-limbach-hannover.de"; + labor_hannover.logo = R.drawable.labor_hannover; + labor_hannover.host = Servers.LABOR_HANNOVER; + labor_hannover.active = true; + result.add(labor_hannover); + + + /** MVZ Medizinisches Labor Main-Taunus GbR **/ + Labor labor_hofheim = new Labor(); + labor_hofheim.id = "LABOR_HOFHEIM"; + labor_hofheim.name = "MVZ Medizinisches Labor Main-Taunus GbR"; + labor_hofheim.street = "Hofheimer Straße 71"; + labor_hofheim.city = "Hofheim"; + labor_hofheim.zip = "65719"; + labor_hofheim.tel = "+49 6192 9924-0"; + labor_hofheim.web = "www.labor-hofheim.de"; + labor_hofheim.logo = R.drawable.labor_hofheim; + labor_hofheim.host = Servers.LABOR_HOFHEIM; + labor_hofheim.active = true; + result.add(labor_hofheim); + + /** MVZ Labor PD Dr. Volkmann und Kollegen GbR **/ + Labor labor_karlsruhe = new Labor(); + labor_karlsruhe.id = "LABOR_KARLSRUHE"; + labor_karlsruhe.name = "MVZ Labor PD Dr. Volkmann und Kollegen GbR"; + labor_karlsruhe.street = "Gerwigstraße 67"; + labor_karlsruhe.city = "Karlsruhe"; + labor_karlsruhe.zip = "76131"; + labor_karlsruhe.tel = "+49 721 85000-0"; + labor_karlsruhe.web = "www.laborvolkmann.de"; + labor_karlsruhe.logo = R.drawable.labor_karlsruhe; + labor_karlsruhe.host = Servers.LABOR_KARLSRUHE; + labor_karlsruhe.active = true; + result.add(labor_karlsruhe); + + /** MVZ Labor Dr. Reising-Ackermann und Kollegen GbR **/ + Labor labor_leipzig = new Labor(); + labor_leipzig.id = "LABOR_LEIPZIG"; + labor_leipzig.name = "MVZ Labor Dr. Reising-Ackermann und Kollegen GbR"; + labor_leipzig.street = "Strümpellstraße 40"; + labor_leipzig.city = "Leipzig"; + labor_leipzig.zip = "04289"; + labor_leipzig.tel = "+49 341 6565-100"; + labor_leipzig.web = "www.labor-leipzig.de"; + labor_leipzig.logo = R.drawable.labor_leipzig; + labor_leipzig.host = Servers.LABOR_LEIPZIG; + labor_leipzig.active = true; + result.add(labor_leipzig); + + /** MVZ Dr. Stein + Kollegen GbR **/ + Labor labor_moenchengladbach = new Labor(); + labor_moenchengladbach.id = "LABOR_MOENCHENGLADBACH"; + labor_moenchengladbach.name = "MVZ Dr. Stein + Kollegen GbR"; + labor_moenchengladbach.street = "Tomphecke 45"; + labor_moenchengladbach.city = "Mönchengladbach"; + labor_moenchengladbach.zip = "41169"; + labor_moenchengladbach.tel = "+49 2161 8194-0"; + labor_moenchengladbach.web = "www.labor-stein.de"; + labor_moenchengladbach.logo = R.drawable.labor_moenchengladbach; + labor_moenchengladbach.host = Servers.LABOR_MOENCHENGLADBACH; + labor_moenchengladbach.active = true; + result.add(labor_moenchengladbach); + + /** MVZ Labor Limbach München GmbH **/ + Labor labor_muenchen = new Labor(); + labor_muenchen.id = "LABOR_MUENCHEN"; + labor_muenchen.name = "MVZ Labor Limbach München GmbH"; + labor_muenchen.street = "Richard-Strauss-Straße 80 – 82"; + labor_muenchen.city = "München"; + labor_muenchen.zip = "81679"; + labor_muenchen.tel = "+49 89 9992970-0"; + labor_muenchen.web = "www.labor-limbach-muenchen.de"; + labor_muenchen.logo = R.drawable.labor_muenchen; + labor_muenchen.host = Servers.LABOR_MUENCHEN; + labor_muenchen.active = true; + result.add(labor_muenchen); + + /** MVZ Labor Münster Hafenweg GmbH **/ + Labor labor_muenster = new Labor(); + labor_muenster.id = "LABOR_MUENSTER"; + labor_muenster.name = "MVZ Labor Münster Hafenweg GmbH"; + labor_muenster.street = "Hafenweg 9 – 11"; + labor_muenster.city = "Münster"; + labor_muenster.zip = "48155"; + labor_muenster.tel = "+49 251 60916-0"; + labor_muenster.web = "www.labor-muenster.de"; + labor_muenster.logo = R.drawable.labor_muenster; + labor_muenster.host = Servers.LABOR_MUENSTER; + labor_muenster.active = true; + result.add(labor_muenster); + + /** MVZ Labor Limbach Nürnberg GmbH **/ + Labor labor_nuernberg = new Labor(); + labor_nuernberg.id = "LABOR_NUERBERG"; + labor_nuernberg.name = "MVZ Labor Limbach Nürnberg GmbH"; + labor_nuernberg.street = "Handwerkerweg 1"; + labor_nuernberg.city = "Wendelstein"; + labor_nuernberg.zip = "90530"; + labor_nuernberg.tel = "+49 9129 90570-0"; + labor_nuernberg.web = "www.labor-limbach-nuernberg.de"; + labor_nuernberg.logo = R.drawable.labor_nuernberg; + labor_nuernberg.host = Servers.LABOR_NUERBERG; + labor_nuernberg.active = true; + result.add(labor_nuernberg); + + /** MVZ Labor Passau GbR **/ + Labor labor_passau = new Labor(); + labor_passau.id = "LABOR_PASSAU"; + labor_passau.name = "MVZ Labor Passau GbR"; + labor_passau.street = "Wörth 15"; + labor_passau.city = "Passau"; + labor_passau.zip = "94034"; + labor_passau.tel = "+49 851 9593-00"; + labor_passau.web = "www.labor-passau.de"; + labor_passau.logo = R.drawable.labor_passau; + labor_passau.host = Servers.LABOR_PASSAU; + labor_passau.active = true; + result.add(labor_passau); + + /** MVZ Labor Ravensburg GbR **/ + Labor labor_ravensburg = new Labor(); + labor_ravensburg.id = "LABOR_RAVENSBURG"; + labor_ravensburg.name = "MVZ Labor Ravensburg GbR"; + labor_ravensburg.street = "Elisabethenstraße 11"; + labor_ravensburg.city = "Ravensburg"; + labor_ravensburg.zip = "88212"; + labor_ravensburg.tel = "+49 751 502-0"; + labor_ravensburg.web = "www.labor-gaertner.de"; + labor_ravensburg.logo = R.drawable.labor_ravensburg; + labor_ravensburg.host = Servers.LABOR_RAVENSBURG; + labor_ravensburg.active = true; + result.add(labor_ravensburg); + + /** Medizinisches Labor Rosenheim MVZ GbR **/ + Labor labor_rosenheim = new Labor(); + labor_rosenheim.id = "LABOR_ROSENHEIM"; + labor_rosenheim.name = "Medizinisches Labor Rosenheim MVZ GbR"; + labor_rosenheim.street = "Brückenstraße 1"; + labor_rosenheim.city = "Rosenheim"; + labor_rosenheim.zip = "83022"; + labor_rosenheim.tel = "+49 8031 8005-0"; + labor_rosenheim.web = "www.medlabor.de"; + labor_rosenheim.logo = R.drawable.labor_rosenheim; + labor_rosenheim.host = Servers.LABOR_ROSENHEIM; + labor_rosenheim.active = true; + result.add(labor_rosenheim); + + /** MVZ Labor Schweinfurt GmbH **/ + Labor labor_schweinfurt = new Labor(); + labor_schweinfurt.id = "LABOR_SCHWEINFURT"; + labor_schweinfurt.name = "MVZ Labor Schweinfurt GmbH"; + labor_schweinfurt.street = "Gustav-Adolf-Straße 8"; + labor_schweinfurt.city = "Schweinfurt"; + labor_schweinfurt.zip = "97422"; + labor_schweinfurt.tel = "+49 9721 533320"; + labor_schweinfurt.web = "www.laboraerzte-schweinfurt.de"; + labor_schweinfurt.logo = R.drawable.labor_schweinfurt; + labor_schweinfurt.host = Servers.LABOR_SCHWEINFURT; + labor_schweinfurt.active = true; + result.add(labor_schweinfurt); + + /** Labor MVZ Westmecklenburg GbR **/ + Labor labor_schwerin = new Labor(); + labor_schwerin.id = "LABOR_SCHWERIN"; + labor_schwerin.name = "Labor MVZ Westmecklenburg GbR"; + labor_schwerin.street = "Ellerried 5 – 7"; + labor_schwerin.city = "Schwerin"; + labor_schwerin.zip = "19061"; + labor_schwerin.tel = "+49 385 64424-0"; + labor_schwerin.web = "www.labor-schwerin.de"; + labor_schwerin.logo = R.drawable.labor_schwerin; + labor_schwerin.host = Servers.LABOR_SCHWERIN; + labor_schwerin.active = true; + result.add(labor_schwerin); + + /** MVZ Labor Limbach Vorpommern-Rügen GmbH **/ + Labor labor_stralsrund = new Labor(); + labor_stralsrund.id = "LABOR_STRALSUND"; + labor_stralsrund.name = "MVZ Labor Limbach Vorpommern-Rügen GmbH"; + labor_stralsrund.street = "Große-Parower-Straße 47-53"; + labor_stralsrund.city = "Stralsund"; + labor_stralsrund.zip = "18435"; + labor_stralsrund.tel = "+49 3831 668770"; + labor_stralsrund.web = "www.labor-stralsund.de"; + labor_stralsrund.logo = R.drawable.labor_stralsrund; + labor_stralsrund.host = Servers.LABOR_STRALSUND; + labor_stralsrund.active = true; + result.add(labor_stralsrund); + + /** MVZ Gemeinschaftslabor Suhl Dr. Siegmund & Kollegen GbR **/ + Labor labor_suhl = new Labor(); + labor_suhl.id = "LABOR_SUHL"; + labor_suhl.name = "MVZ Gemeinschaftslabor Suhl Dr. Siegmund & Kollegen GbR"; + labor_suhl.street = "Albert-Schweitzer-Straße 4"; + labor_suhl.city = "Suhl"; + labor_suhl.zip = "98527"; + labor_suhl.tel = "+49 3681 39860"; + labor_suhl.web = "www.labor-suhl.de"; + labor_suhl.logo = R.drawable.labor_suhl; + labor_suhl.host = Servers.LABOR_SUHL; + labor_suhl.active = true; + result.add(labor_suhl); + + /** MVZ Medizinische Labore Dessau Kassel GmbH **/ + Labor labor_kassel = new Labor(); + labor_kassel.id = "LABOR_KASSEL"; + labor_kassel.name = "MVZ Medizinische Labore Dessau Kassel GmbH"; + labor_kassel.street = "Marburger Straße 85"; + labor_kassel.city = "Kassel"; + labor_kassel.zip = "34127"; + labor_kassel.logo = R.drawable.labor_kassel; + labor_kassel.host = Servers.LABOR_KASSEL; + labor_kassel.active = true; + result.add(labor_kassel); + + /** MVZ Medizinisches Labor Hannover **/ + Labor labor_hannover_mlh = new Labor(); + labor_hannover_mlh.id = "LABOR_HANNOVER_MLM"; + labor_hannover_mlh.name = "MVZ Medizinisches Labor Hannover"; + labor_hannover_mlh.street = "Am TÜV 6"; + labor_hannover_mlh.city = "Hannover"; + labor_hannover_mlh.zip = "30519"; + labor_hannover_mlh.tel = "+49 511 85622-0"; + labor_hannover_mlh.web = "www.mlh.de"; + labor_hannover_mlh.logo = R.drawable.labor_hannover_mlh; + labor_hannover_mlh.host = Servers.LABOR_HANNOVER_MLM; + labor_hannover_mlh.active = true; + result.add(labor_hannover_mlh); + + /** Medizinische Genetik Mainz **/ + Labor labor_mainz = new Labor(); + labor_mainz.id = "LABOR_MAINZ"; + labor_mainz.name = "Medizinische Genetik Mainz"; + labor_mainz.street = "Haifa-Allee 38"; + labor_mainz.city = "Mainz"; + labor_mainz.zip = "55128"; + labor_mainz.tel = "+49 6131 27661-0"; + labor_mainz.web = "www.medgen-mainz.de"; + labor_mainz.logo = R.drawable.labor_mainz; + labor_mainz.host = Servers.LABOR_MAINZ; + labor_mainz.active = true; + result.add(labor_mainz); + + /** Laborarztpraxis Rhein-Main MVZ GbR **/ + Labor labor_frankfurt = new Labor(); + labor_frankfurt.id = "LABOR_FRANKFURT"; + labor_frankfurt.name = "Laborarztpraxis Rhein-Main MVZ GbR"; + labor_frankfurt.street = "Berner Straße 117"; + labor_frankfurt.city = "Frankfurt"; + labor_frankfurt.zip = "60437"; + labor_frankfurt.tel = "+49 69 669003-900"; + labor_frankfurt.web = "www.laborarztpraxis.de"; + labor_frankfurt.logo = R.drawable.labor_frankfurt; + labor_frankfurt.host = Servers.LABOR_FRANKFURT; + labor_frankfurt.active = true; + result.add(labor_frankfurt); + + return result; + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/OEGD.java b/app/src/main/java/de/labor_stein/befund/Core/Models/OEGD.java new file mode 100644 index 0000000..de69bff --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/OEGD.java @@ -0,0 +1,90 @@ +// +// OEGD.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 05.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import de.labor_stein.befund.Core.Log; + +public class OEGD +{ + public String last_name; + public String first_name; + public String birthdate; + public String gender; + public String title; + public String name_addition; + public String prefix; + public Address address; + public boolean cwa_consent_flag; + public String phone; + + public static class Address + { + public String zip_code; + public String city; + public String street_number; + public String country_code; + + public static Address createInstance() + { + return new Address(); + } + } + + /** + * Returns Birthday from settings + * @return returns Date + */ + public Date GetBirthday() + { + Date result = null; + + try + { + if(this.birthdate != null && this.birthdate != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + result = dateFormat.parse(this.birthdate); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.OEGD", "GetBirthday"); + } + + return result; + } + + /** + * Returns Birthday as string from settings + * @return returns string + */ + public String GetFormatedBirthday() + { + String result = null; + + try + { + Date date = this.GetBirthday(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.OEGD", "GetFormatedBirthday"); + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/OEGDFile.java b/app/src/main/java/de/labor_stein/befund/Core/Models/OEGDFile.java new file mode 100644 index 0000000..7859bdf --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/OEGDFile.java @@ -0,0 +1,14 @@ +// +// OEGDFile.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 07.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models; + +public class OEGDFile +{ + public OEGD OEGD; + public String filename; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/ChangeVerificatorHash.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/ChangeVerificatorHash.java new file mode 100644 index 0000000..d957b4c --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/ChangeVerificatorHash.java @@ -0,0 +1,16 @@ +// +// ChangeVerificatorHash.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 06.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class ChangeVerificatorHash +{ + public String udid; + public String old_verificator_hash; + public String new_verificator_hash; + public String pin; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/CheckFileChecksum.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/CheckFileChecksum.java new file mode 100644 index 0000000..eeb0ad9 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/CheckFileChecksum.java @@ -0,0 +1,19 @@ +// +// CheckFileChecksum.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class CheckFileChecksum +{ + public String pgs = null; + public String udid = null; + public String device_token = null; + public int device_type = 2; + public String client_public_key = null; + public String verificator_hash = null; + public String file_checksum = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/DeviceToken.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/DeviceToken.java new file mode 100644 index 0000000..e26f505 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/DeviceToken.java @@ -0,0 +1,15 @@ +// +// DeviceToken.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 30.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class DeviceToken +{ + public String udid = null; + public String verificator_hash = null; + public String device_token = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/EncryptedRequest.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/EncryptedRequest.java new file mode 100644 index 0000000..e784333 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/EncryptedRequest.java @@ -0,0 +1,74 @@ +// +// EncryptedRequest.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +import com.google.gson.Gson; + +import java.nio.charset.StandardCharsets; + +import javax.crypto.SecretKey; + +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.Security.Ed25519; +import de.labor_stein.befund.Core.Security.SHA512; + +public class EncryptedRequest +{ + public String descriptor = null; + public String encrypted_content = null; + public String hmac = null; + + /** + * Constructor for EncryptedRequest + * @param descriptor - descriptor of the content object + * @param contentObject - content object that should be encrypted + * @param deriveKey - shared deriveKey that should be used in the encrption + */ + public EncryptedRequest(String descriptor, Object contentObject, byte[] deriveKey) + { + String encrypted_content = null; + + if(contentObject != null) + { + encrypted_content = new Gson().toJson(contentObject); + } + + this.Encrypt(descriptor, encrypted_content, deriveKey); + } + + /** + * Encrypts the content of request with derive key + * + * @param descriptor - descriptor of object + * @param encrypted_content - content that should be encrypted + * @param deriveKey - derive key that should be used for the encryption + */ + public void Encrypt(String descriptor, String encrypted_content, byte[] deriveKey) + { + if(descriptor != null && deriveKey != null) + { + this.descriptor = AES.Encrypt(descriptor, deriveKey); + + if(encrypted_content != null) + { + this.encrypted_content = AES.Encrypt(encrypted_content, deriveKey); + + if(this.encrypted_content != null) + { + this.hmac = SHA512.HMAC(this.encrypted_content, deriveKey); + } + } + else + { + this.hmac = SHA512.HMAC(this.descriptor, deriveKey); + } + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/GetOpened.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/GetOpened.java new file mode 100644 index 0000000..7984847 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/GetOpened.java @@ -0,0 +1,14 @@ +// +// GetOpened.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 30.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class GetOpened +{ + public String udid = null; + public String verificator_hash = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/GetPIN.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/GetPIN.java new file mode 100644 index 0000000..0e27e2d --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/GetPIN.java @@ -0,0 +1,14 @@ +// +// GetPIN.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 06.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class GetPIN +{ + public String udid = null; + public String verificator_hash = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/KeyExchange.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/KeyExchange.java new file mode 100644 index 0000000..68268cb --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/KeyExchange.java @@ -0,0 +1,13 @@ +// +// KeyExchange.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class KeyExchange +{ + public String key_type = "PublicKey"; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/Subscribe.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/Subscribe.java new file mode 100644 index 0000000..b98588e --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/Subscribe.java @@ -0,0 +1,29 @@ +// +// Subscribe.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; +import de.labor_stein.befund.Core.Models.Database.Results; + +public class Subscribe +{ + public String pgs = null; + public String pgs_hash = null; + public String udid = null; + public String device_token = null; + public int device_type = 2; + public String client_public_key = null; + public String verificator_hash = null; + public String pin = null; + + public Results ToResults() + { + Results result = new Results(); + result.pgs = this.pgs; + result.status = Results.ResultsStatus.NONE.name(); + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Request/Support.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/Support.java new file mode 100644 index 0000000..6ffc598 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Request/Support.java @@ -0,0 +1,18 @@ +// +// Support.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 11.07.2022 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Request; + +public class Support +{ + public String udid = null; + public String verificator_hash = null; + public String email; + public String topic; + public String text; + public boolean delete_device; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Download.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Download.java new file mode 100644 index 0000000..fdfc513 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Download.java @@ -0,0 +1,14 @@ +// +// Download.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Response; + +public class Download +{ + public String encrypted_content = null; + public String server_public_key = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Response/EncryptedResponse.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/EncryptedResponse.java new file mode 100644 index 0000000..2fac4b5 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/EncryptedResponse.java @@ -0,0 +1,157 @@ +// +// EncryptedResponse.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 25.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Response; + +import com.google.gson.Gson; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; + +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.Status; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.Security.Ed25519; +import de.labor_stein.befund.Core.Security.SHA512; + +public class EncryptedResponse +{ + public String descriptor = null; + public String encrypted_content = null; + public String hmac = null; + + /** + * Decrypts the encrypted content + * + * @param deriveKey - shared deriveKey for the decryption + * @return returns decrypted object + */ + public Object Decrypt(byte[] deriveKey, Class objClass) + { + Object result = null; + + try + { + if (deriveKey != null && deriveKey.length > 0 && this.descriptor != null && !this.descriptor.isEmpty()) + { + this.descriptor = AES.Decrypt(this.descriptor, deriveKey); + + if (this.encrypted_content != null && !this.encrypted_content.isEmpty()) + { + String json = AES.Decrypt(this.encrypted_content, deriveKey); + + if (json != null && !json.isEmpty()) + { + result = new Gson().fromJson(json, objClass); + } + } + } + } + catch (java.lang.Exception ex) + { + Log.Error(ex.getMessage(), "Core.Models.Response.EncryptedResponse", "Decrypt(byte[], Class)"); + } + + return result; + } + + /** + * Decrypts the encrypted content yb descriptor + * + * @param deriveKey - shared deriveKey for the decryption + * @return returns decrypted object + */ + public Object Decrypt(byte[] deriveKey) + { + Object result = null; + + try + { + if (deriveKey != null && deriveKey.length > 0 && this.descriptor != null && !this.descriptor.isEmpty()) + { + this.descriptor = AES.Decrypt(this.descriptor, deriveKey); + + if (this.encrypted_content != null && !this.encrypted_content.isEmpty()) + { + String json = AES.Decrypt(this.encrypted_content, deriveKey); + + if (json != null && !json.isEmpty()) + { + switch (this.descriptor.toLowerCase()) + { + case "success": + result = new Gson().fromJson(json, Success.class); + break; + + case "responseexception": + result = new Gson().fromJson(json, Exception.class); + break; + + case "list": + result = Arrays.asList(new Gson().fromJson(json, Status[].class)); + break; + + case "download": + result = new Gson().fromJson(json, Download.class); + break; + + case "pin": + result = new Gson().fromJson(json, PIN.class); + break; + } + } + } + } + } + catch (java.lang.Exception ex) + { + Log.Error(ex.getMessage(), "Core.Models.Response.EncryptedResponse", "Decrypt(byte[])"); + } + + return result; + } + + /** + * Validates the encrypted response by HMAC and Ed25519 + * + * @param deriveKey - shared derive key, that should be used for the HMAC Authentification + * @param serverSignature - server signature, that should be verified + * @param serverSignatureKey - server public signature key, that was used in client signature + * @return returns true if request is valid + */ + public boolean ValidSignature(byte[] deriveKey, String serverSignature, String serverSignatureKey) + { + if (this.encrypted_content != null && !this.encrypted_content.isEmpty()) + { + return + // Validate over HMAC + (this.hmac != null && !this.hmac.isEmpty() && + deriveKey != null && + deriveKey.length > 0 && + SHA512.isValidAuthenticationCode(hmac, this.encrypted_content, deriveKey)) && + + //Validate over Ed25519 + (serverSignature != null && !serverSignature.isEmpty() && + Ed25519.CheckValid(Base64.FromBase64String(serverSignature), this.encrypted_content.getBytes(StandardCharsets.UTF_8), Base64.FromBase64String(serverSignatureKey))); + } + else + { + return + // Validate over HMAC + (this.hmac != null && !this.hmac.isEmpty() && + deriveKey != null && + deriveKey.length > 0 && + SHA512.isValidAuthenticationCode(hmac, this.descriptor, deriveKey)) && + + //Validate over Ed25519 + (serverSignature != null && !serverSignature.isEmpty() && + Ed25519.CheckValid(Base64.FromBase64String(serverSignature), this.descriptor.getBytes(StandardCharsets.UTF_8), Base64.FromBase64String(serverSignatureKey))); + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Exception.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Exception.java new file mode 100644 index 0000000..6392217 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Exception.java @@ -0,0 +1,30 @@ +// +// Exception.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Response; + +public class Exception +{ + public String response_type; + public int error_type = Types.NONE; + public String message; + + public static class Types + { + public static final int NONE = 0; + public static final int InvalidClient = 1000; + public static final int InvalidRequest= 1001; + public static final int MissingArgument = 1002; + public static final int InvalidArgument = 1003; + public static final int Unknown = 1004; + public static final int AlreadySubscribted = 1005; + public static final int NotAuthorized = 1007; + public static final int MaxOpenedRequestLimit = 1008; + public static final int NotAvailable = 1009; + public static final int WrongFileChecksum = 1010; + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Response/PIN.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/PIN.java new file mode 100644 index 0000000..3d2bc9f --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/PIN.java @@ -0,0 +1,13 @@ +// +// PIN.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 06.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Response; + +public class PIN +{ + public String code = null; +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Response/PublicKey.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/PublicKey.java new file mode 100644 index 0000000..556bf94 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/PublicKey.java @@ -0,0 +1,13 @@ +// +// PublicKey.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Response; + +public class PublicKey +{ + public String key = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Success.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Success.java new file mode 100644 index 0000000..41dfb78 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Response/Success.java @@ -0,0 +1,13 @@ +// +// Success.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.Response; + +public class Success +{ + public String message = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Session.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Session.java new file mode 100644 index 0000000..508b1d8 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Session.java @@ -0,0 +1,29 @@ +// +// Session.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 05.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models; + +import de.labor_stein.befund.Core.Models.System.Device; + +public class Session +{ + public static Boolean NotificationGranted = false; + public static Boolean CameraGranted = false; + public static Device Device = null; + public static String DevicePassword = null; + public static boolean Maintenance = false; + public static boolean MaintenanceNotified = false; + + /** + * Checks if user has been logged in by password/biomedical authentication + * @return returns true if successfully + */ + public static boolean IsLoggedIn() + { + return (Session.DevicePassword != null && !Session.DevicePassword.isEmpty()); + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/Settings.java b/app/src/main/java/de/labor_stein/befund/Core/Models/Settings.java new file mode 100644 index 0000000..ef6c225 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/Settings.java @@ -0,0 +1,307 @@ +// +// Settings.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 05.07.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import de.labor_stein.befund.Core.Https.Servers; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; + +public class Settings +{ + // Change this variable to enforce Privacy Policy Popup on update to this version + public static String PrivacyPolicyAcceptedKey = "privacy_policy_accepted_2"; + + public String public_key = null; + public String hashed_private_key = null; + public String verificator_hash = null; + public String password_hash = null; + public String password_reset_hash = null; + public String zip = null; + public String birthday = null; + public String udid = null; + public Lang.Languages lang = Lang.Languages.DE; + public Labor labor = null; + + private String privacy_policy_url_de = "https://www.limbachgruppe.com/fileadmin/downloads/pba-datenschutz.html"; + private String faq_url_de = "https://www.limbachgruppe.com/fileadmin/downloads/098672600.html"; + + private String privacy_policy_url_en = "https://www.limbachgruppe.com/fileadmin/downloads/pba-data-protection.html"; + private String faq_url_en = "https://www.limbachgruppe.com/fileadmin/downloads/098235490.html"; + + public boolean PushNotificationExplained = false; + public boolean PushNotificationAccepted = false; + public boolean PrivacyPolicyAccepted = false; + + /** + * Loads settings from the file + * @param context - Current context, that using the settings + * @return returns settings object + */ + public static Settings load(Context context) + { + Settings result = null; + + try + { + if(context != null) + { + Activity CurrentActivity = (Activity)context; + + SharedPreferences dic = CurrentActivity.getSharedPreferences("befund_pref", Context.MODE_PRIVATE); + + if(dic != null) + { + result = new Settings(); + + result.public_key = dic.getString("public_key", null); + result.hashed_private_key = dic.getString("hashed_private_key", null); + result.verificator_hash = dic.getString("verificator_hash", null); + result.password_hash = dic.getString("password_hash", null); + result.password_reset_hash = dic.getString("password_reset_hash", null); + result.zip = dic.getString("zip", null); + result.birthday = dic.getString("birthday", null); + result.udid = dic.getString("udid", null); + result.lang = Lang.Languages.valueOf(dic.getString("lang", Lang.Languages.DE.name())); + result.PushNotificationExplained = dic.getBoolean("push_explained", false); + result.PushNotificationAccepted = dic.getBoolean("push_accepted", false); + result.PrivacyPolicyAccepted = dic.getBoolean(PrivacyPolicyAcceptedKey, false); + + String labor_id = dic.getString("labor", null); + + if(labor_id != null && !labor_id.isEmpty()) + { + result.labor = Labor.GetLaborByName(labor_id); + + /** REMOVE FOR PRODUCTIVE **/ + //result.labor.host = Servers.DEVELOPMENT; + } + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Settings", "load(Context)"); + } + + return result; + } + + /** + * Saves settings to the file + * @param context - current context, that using the settings + * @return returns true if successfully saved + */ + public boolean save(Context context) + { + boolean result = false; + + try + { + if(context != null) + { + Activity CurrentActivity = (Activity)context; + + SharedPreferences sharedPref = CurrentActivity.getSharedPreferences("befund_pref", Context.MODE_PRIVATE); + + if(sharedPref != null) + { + /** generates a new udid **/ + if(this.udid == null) + { + this.udid = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID) + "_" + UUID.randomUUID().toString(); + } + + SharedPreferences.Editor dic = sharedPref.edit(); + dic.putString("public_key", this.public_key); + dic.putString("hashed_private_key", this.hashed_private_key); + dic.putString("verificator_hash", this.verificator_hash); + dic.putString("password_hash", this.password_hash); + dic.putString("password_reset_hash", this.password_reset_hash); + dic.putString("zip", this.zip); + dic.putString("birthday", this.birthday); + dic.putString("udid", this.udid); + dic.putString("lang", this.lang.name()); + + if(this.labor != null) + { + dic.putString("labor", this.labor.id); + } + + dic.putBoolean("push_explained", this.PushNotificationExplained); + dic.putBoolean("push_accepted", this.PushNotificationAccepted); + dic.putBoolean(PrivacyPolicyAcceptedKey, this.PrivacyPolicyAccepted); + + dic.commit(); + + result = (CurrentActivity.getSharedPreferences("befund_pref", Context.MODE_PRIVATE) != null); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Settings", "save(Context)"); + } + + return result; + } + + /** + * delete settings + * + * @param context - current context, that using the settings + * @return returns true if successfully saved + */ + public boolean delete(Context context) + { + boolean result = false; + + try + { + if(context != null) + { + Activity CurrentActivity = (Activity)context; + + SharedPreferences sharedPref = CurrentActivity.getSharedPreferences("befund_pref", Context.MODE_PRIVATE); + + if(sharedPref != null) + { + SharedPreferences.Editor dic = sharedPref.edit(); + dic.remove("udid"); + dic.remove("public_key"); + dic.remove("hashed_private_key"); + dic.remove("verificator_hash"); + dic.remove("password_hash"); + dic.remove("password_reset_hash"); + dic.remove("zip"); + dic.remove("birthday"); + dic.remove("udid"); + dic.remove("lang"); + dic.remove("labor"); + dic.commit(); + + result = (CurrentActivity.getSharedPreferences("befund_pref", Context.MODE_PRIVATE) != null); + } + } + } + catch(Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Settings", "delete(Context)"); + } + + return result; + } + + /** + * Returns Birthday from settings + * @return returns Date + */ + public Date GetBirthday() + { + Date result = null; + + try + { + if(this.birthday != null && this.birthday != "") + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + result = dateFormat.parse(this.birthday); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Settings", "GetBirthday"); + } + + return result; + } + + /** + * Returns Birthday as string from settings + * @return returns string + */ + public String GetFormatedBirthday() + { + String result = null; + + try + { + Date date = this.GetBirthday(); + + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); + result = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Settings", "GetFormatedBirthday"); + } + + return result; + } + + /** + * Sets birthday to the settings + * @param date - date that should be set to the settings + */ + public void SetBirthday(Date date) + { + String result = null; + + try + { + if(date != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + this.birthday = dateFormat.format(date); + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), " de.labor_stein.befund.Core.Models.Settings", "SetBirthday(Date)"); + } + } + + /** + * Gets privacy policy URL depended on lang + */ + public String GetPrivacyPolicyURL() + { + switch (this.lang) + { + case DE: + return this.privacy_policy_url_de; + + default: + return this.privacy_policy_url_en; + } + } + + /** + * Gets FAQ URL depended on lang + */ + public String GetFAQURL() + { + switch (this.lang) + { + case DE: + return this.faq_url_de; + + default: + return this.faq_url_en; + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/System/Device.java b/app/src/main/java/de/labor_stein/befund/Core/Models/System/Device.java new file mode 100644 index 0000000..4376755 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/System/Device.java @@ -0,0 +1,18 @@ +// +// Device.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.System; + +public class Device +{ + public String udid = null; + public String name = null; + public String model = null; + public String manufacturer = null; + public String os = null; + public String token = null; +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Models/System/StorageInfo.java b/app/src/main/java/de/labor_stein/befund/Core/Models/System/StorageInfo.java new file mode 100644 index 0000000..313d080 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Models/System/StorageInfo.java @@ -0,0 +1,27 @@ +// +// StorageInfo.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Models.System; + +public class StorageInfo +{ + public Double total = 0.0; + public Double free = 0.0; + public Double used = 0.0; + + public Double GetStoragePercent() + { + if(this.free > 0.0 && this.total > 0.0) + { + return (this.free / this.total); + } + else + { + return 0.0; + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Security/AES.java b/app/src/main/java/de/labor_stein/befund/Core/Security/AES.java new file mode 100644 index 0000000..d96dfac --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Security/AES.java @@ -0,0 +1,153 @@ +// +// AES.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Security; + +import java.io.ByteArrayInputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import de.labor_stein.befund.Core.Log; + +public class AES +{ + private static final int MAX_NONCE_SIZE = 12; + private static final int MAX_TAG_SIZE = 16; + public static final String PGS_ENCRYPT_PARTIAL_KEY = "wA6j@x.CcmM>~5Ss^C_!#,zch)$YsDsd59,::>dW#F`@U]Ye5ETZcMT7}&+#*!%z"; + + /** + * Encrypts string with key + * + * @param value - string value that should be encrypted + * @param deriveKey - shared deriveKey that should be used for encryption(max. 32 bytes) + * @return - returns encrypted base64 string + */ + public static String Encrypt(String value, byte[] deriveKey) + { + String result = null; + + try + { + if(value != null && deriveKey != null) + { + byte[] nonce = new byte[MAX_NONCE_SIZE]; + new SecureRandom().nextBytes(nonce); + byte[] tag = new byte[MAX_TAG_SIZE]; + new SecureRandom().nextBytes(tag); + byte[] plainText = value.getBytes(StandardCharsets.UTF_8); + + GCMParameterSpec gcmSpec = new GCMParameterSpec(MAX_TAG_SIZE * 8, nonce); + + SecretKey key = new SecretKeySpec(deriveKey, "AES"); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + + cipher.init(Cipher.ENCRYPT_MODE, key, gcmSpec); + + byte[] chiperText = cipher.doFinal(plainText); + + ByteBuffer byteBuffer = ByteBuffer.allocate(nonce.length + chiperText.length); + byteBuffer.put(nonce); + byteBuffer.put(chiperText); + result = Base64.ToBase64String(byteBuffer.array()); + } + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + /** + * Decrypts encrypted base64 string with key + * + * @param value - base64 string that should be decrypted + * @param deriveKey - key that should be used for the decryption(max. 32 bytes) + * @return + */ + public static String Decrypt(String value, byte[] deriveKey) + { + String result = null; + + try + { + if(value != null && deriveKey != null) + { + byte[] combined = Base64.FromBase64String(value); + ByteArrayInputStream byteReader = new ByteArrayInputStream(combined); + + byte[] nonce = new byte[MAX_NONCE_SIZE]; + //byte[] tag = new byte[MAX_TAG_SIZE]; + byte[] chiperText = new byte[combined.length - nonce.length]; + + byteReader.read(nonce, 0, MAX_NONCE_SIZE); + byteReader.read(chiperText, 0, chiperText.length); + + final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + GCMParameterSpec parameterSpec = new GCMParameterSpec(MAX_TAG_SIZE * 8, nonce); + SecretKey secretKey = new SecretKeySpec(deriveKey, "AES"); + cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec); + byte[] plainText = cipher.doFinal(chiperText); + result = new String(plainText, StandardCharsets.UTF_8); + } + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + /** + * Converts the text passed password to the 32 byte array + * + * @param password - Text based password + * @return returns password as byte array + */ + public static byte[] GetKey(String password) + { + byte[] result = null; + + try + { + if(password != null && !password.isEmpty()) + { + if(password.length() < 32) + { + StringBuilder padded = new StringBuilder(password); + + while (padded.length() < 32) + { + padded.append("@"); + } + + password = padded.toString(); + } + else if(password.length() > 32) + { + password = MD5.Encrypt(password); + } + + result = password.getBytes(StandardCharsets.US_ASCII); + } + } + catch (Exception ex) + { + result = null; + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Security/Base64.java b/app/src/main/java/de/labor_stein/befund/Core/Security/Base64.java new file mode 100644 index 0000000..bc574c2 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Security/Base64.java @@ -0,0 +1,44 @@ +// +// Base64.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Security; + +public class Base64 +{ + /** + * Converts byte array to the base64 String + * + * @param data - byte array that should be converted in to base64 string + * @return returns base64 String + */ + public static String ToBase64String(byte[] data) + { + String result = null; + + try + { + result = android.util.Base64.encodeToString(data, android.util.Base64.NO_WRAP); + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + /** + * Converts base64 string in to byte array + * + * @param base64 - base64 String, that should be converted in to byte array + * @return returns byte array + */ + public static byte[] FromBase64String(String base64) + { + return android.util.Base64.decode(base64, android.util.Base64.NO_WRAP); + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Security/Curve25519.java b/app/src/main/java/de/labor_stein/befund/Core/Security/Curve25519.java new file mode 100644 index 0000000..2b65262 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Security/Curve25519.java @@ -0,0 +1,276 @@ +// +// Curve25519.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 21.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Security; +import org.whispersystems.curve25519.JCESha512Provider; +import org.whispersystems.curve25519.java.curve_sigs; +import org.whispersystems.curve25519.java.scalarmult; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; + +import de.labor_stein.befund.Core.Log; + +public class Curve25519 +{ + private static final int KeySize = 32; + + /** + * Generates the KeyPair with Private & Public Keys + * + * @return returns KeyPair with Public & Private Keys(incl. Signing Private & Public Keys) + */ + public static Curve25519.KeyPair GenerateKeyPair() + { + byte[] random = new byte[KeySize]; + new SecureRandom().nextBytes(random); + + byte[] privateKey = Curve25519.ClampPrivateKey(random); + byte[] publicKey = Curve25519.GetPublicKey(privateKey); + + return new KeyPair(privateKey, publicKey); + } + + /** + * Creates KeyPair from private and public key + * + * @param _privateKey - private key of KeyPair + * @param _publicKey - public key of KeyPair + * @return returns KeyPair + */ + public static Curve25519.KeyPair CreateKeyPair(String _privateKey, String _publicKey) + { + KeyPair result = null; + + try + { + byte[] privateKey = ClampPrivateKey(Base64.FromBase64String(_privateKey)); + byte[] publicKey = Base64.FromBase64String(_publicKey); + + result = new KeyPair(privateKey, publicKey); + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "Core.Security.Curve25519", "CreateKeyPair(string, string)"); + } + + return result; + } + + /** + * Private key clamping + * + * @param rawKey - rawKey + * @return returns Curve25519 Private Key + */ + public static byte[] ClampPrivateKey(byte[] rawKey) + { + byte[] privateKey = new byte[32]; + + System.arraycopy(rawKey, 0, privateKey, 0, 32); + privateKey[0] &= 248; + privateKey[31] &= 127; + privateKey[31] |= 64; + + return privateKey; + } + + /** + * Generates the public key out of the clamped private key + * + * @param privateKey - private key (must use ClampPrivateKey first!) + * @return returns Curve25519 Private Key + */ + public static byte[] GetPublicKey(byte[] privateKey) + { + byte[] publicKey = new byte[32]; + curve_sigs.curve25519_keygen(publicKey, privateKey); + return publicKey; + } + + /** + * Generates a shared secret by private & public keys + * + * @param privateKey - private key + * @param peerPublicKey - public key + * @return returns shared secret for private & public keys + */ + public static byte[] GetSharedSecret(byte[] privateKey, byte[] peerPublicKey) + { + byte[] agreement = new byte[32]; + scalarmult.crypto_scalarmult(agreement, privateKey, peerPublicKey); + return agreement; + } + + /** + * Generates a signature for the given message + * + * @param message - message that should signed + * @param privateKey - private key for signature + * @return byte array of signature + */ + public static byte[] GetSignature(byte[] message, byte[] privateKey) + { + byte[] result = null; + + try + { + result = new byte[64]; + + byte[] random = new byte[64]; + new SecureRandom().nextBytes(random); + org.whispersystems.curve25519.java.Sha512 sha512provider = new JCESha512Provider(); + + if (curve_sigs.curve25519_sign(sha512provider, result, privateKey, message, message.length, random) != 0) + { + throw new IllegalArgumentException("Message exceeds max length!"); + } + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + /** + * Verifies a signature with public key + * + * @param publicKey - public key of signature + * @param message - message that should be verify the signature + * @param signature - signature of the message + * @return returns true if valid signature + */ + public static boolean verifySignature(byte[] publicKey, byte[] message, byte[] signature) + { + boolean result = false; + + try + { + org.whispersystems.curve25519.java.Sha512 sha512provider = new JCESha512Provider(); + result = curve_sigs.curve25519_verify(sha512provider, signature, publicKey, message, message.length) == 0; + } + catch (Exception ex) + { + result = false; + } + + return result; + } + + /** + * KeyPair with Private & Public Key and Signature Keys + */ + public static class KeyPair + { + public String PrivateKey = null; + public String PublicKey = null; + public String SigningPublicKey = null; + public String SigningPrivateKey = null; + + /** + * Constructor for KeyPair + * + * @param privateKey - Private Key + * @param publicKey - Public Key + */ + public KeyPair(byte[] privateKey, byte[] publicKey) + { + this.PrivateKey = Base64.ToBase64String(privateKey); + this.PublicKey = Base64.ToBase64String(publicKey); + + byte[] signingPrivateKey = new byte[32]; + new SecureRandom().nextBytes(signingPrivateKey); + byte[] signingPublicKey = Ed25519.PublicKey(signingPrivateKey); + + this.SigningPrivateKey = Base64.ToBase64String(signingPrivateKey); + this.SigningPublicKey = Base64.ToBase64String(signingPublicKey); + } + + /** + * Returns a shared key with the public key + * + * @param peerPublicKeyBase64 - Public key of peer in base64 string format + * @return returns shared key as byte array + */ + public byte[] GetSharedKey(String peerPublicKeyBase64) + { + byte[] result = null; + + try + { + byte[] privateKey = Base64.FromBase64String(this.PrivateKey); + byte[] peerPublicKey = Base64.FromBase64String(peerPublicKeyBase64); + byte[] sharedSecret = Curve25519.GetSharedSecret(privateKey, peerPublicKey); + result = HKDF.DeriveKey(sharedSecret, 32); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Security.Curve25519.KeyPair", "GetSharedKey(String)"); + } + + return result; + } + + /** + * Returns a Signature as base64 string for a string value + * + * @param signingValue - string value that should be signed + * @return returns base64 signed value hash + */ + public String GetSignature(String signingValue) + { + String result = null; + + try + { + byte[] signingData = signingValue.getBytes(StandardCharsets.UTF_8); + byte[] privateKey = Base64.FromBase64String(this.SigningPrivateKey); + byte[] signature = Ed25519.Signature(signingData, privateKey); + + if(signature != null) + { + result = Base64.ToBase64String(signature); + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Security.Curve25519.KeyPair", "GetSignature(String)"); + } + + return result; + } + + /** + * Verify signature hash(base64) with shared key + * + * @param signingValue - string value that should be signed + * @param signatureValue - signature Hash that should be verified + * @param peerPublicKeyBase64 - Public key of peer in base64 string format + * @return returns true if signature is valid + */ + public boolean VerifySignature(String signingValue, String signatureValue, String peerPublicKeyBase64) + { + boolean result = false; + + try + { + byte[] signingData = signingValue.getBytes(StandardCharsets.UTF_8); + byte[] signingPublicKey = Base64.FromBase64String(peerPublicKeyBase64); + byte[] signature = Base64.FromBase64String(signatureValue); + result = Ed25519.CheckValid(signature, signingData, signingPublicKey); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Security.Curve25519.KeyPair", "VerifySignature(String, String, String)"); + } + + return result; + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Security/Ed25519.java b/app/src/main/java/de/labor_stein/befund/Core/Security/Ed25519.java new file mode 100644 index 0000000..6b545c7 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Security/Ed25519.java @@ -0,0 +1,87 @@ +// +// Ed25519.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 25.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Security; + +import com.google.crypto.tink.subtle.Ed25519Sign; +import com.google.crypto.tink.subtle.Ed25519Verify; + +public class Ed25519 +{ + /** + * Generates Ed25519 Public Key for signing + * + * @param privateKey - private key for public key + * @return returns public key for the signature + */ + public static byte[] PublicKey(byte[] privateKey) + { + byte[] result = null; + + try + { + Ed25519Sign.KeyPair keyPair = Ed25519Sign.KeyPair.newKeyPairFromSeed(privateKey); + result = keyPair.getPublicKey(); + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + /** + * Generates a Ed25519 Signature by private key + * + * @param message - message that should be signed + * @param privateKey - private key for the signature + * @return returns signature + */ + public static byte[] Signature(byte[] message, byte[] privateKey) + { + byte[] result = null; + + try + { + Ed25519Sign signer = new Ed25519Sign(privateKey); + result = signer.sign(message); + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + /** + * Validates a ED25519 Signature with message and public key of sender + * + * @param signature - signature that should be validated + * @param message - message that was signed + * @param publicKey - public key that was used by sender for the message to sign it + * @return returns true if valid + */ + public static boolean CheckValid(byte[] signature, byte[] message, byte[] publicKey) + { + boolean result = false; + + try + { + Ed25519Verify verifier = new Ed25519Verify(publicKey); + verifier.verify(signature, message); + result = true; + } + catch (Exception ex) + { + result = false; + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/Security/HKDF.java b/app/src/main/java/de/labor_stein/befund/Core/Security/HKDF.java new file mode 100644 index 0000000..71feefd --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/Security/HKDF.java @@ -0,0 +1,88 @@ +// +// HKDF.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 25.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core.Security; + +import java.io.ByteArrayOutputStream; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +// Git: https://github.com/signalapp/libsignal-protocol-java/blob/master/java/src/main/java/org/whispersystems/libsignal/kdf/HKDF.java + +public class HKDF +{ + private static final int HASH_OUTPUT_SIZE = 32; + + public static byte[] DeriveKey(byte[] inputKeyMaterial, int outputLength) + { + byte[] salt = new byte[HASH_OUTPUT_SIZE]; + return deriveSecrets(inputKeyMaterial, salt, outputLength); + } + + public static byte[] deriveSecrets(byte[] inputKeyMaterial, byte[] salt, int outputLength) + { + byte[] prk = extract(salt, inputKeyMaterial); + return expand(prk, outputLength); + } + + private static byte[] extract(byte[] salt, byte[] inputKeyMaterial) + { + byte[] result = null; + + try + { + Mac mac = Mac.getInstance("HmacSHA512"); + mac.init(new SecretKeySpec(salt, "HmacSHA512")); + return mac.doFinal(inputKeyMaterial); + } + catch (Exception ex) + { + result = null; + } + + return result; + } + + private static byte[] expand(byte[] prk, int outputSize) + { + byte[] result = null; + + try + { + int iterations = (int) Math.ceil((double) outputSize / (double) HASH_OUTPUT_SIZE); + byte[] mixin = new byte[0]; + ByteArrayOutputStream results = new ByteArrayOutputStream(); + int remainingBytes = outputSize; + + for (int i= 1; i>> 0); + n[i+1] = (byte) (nonce>>> 8); + n[i+2] = (byte) (nonce>>>16); + n[i+3] = (byte) (nonce>>>24); + n[i+4] = (byte) (nonce>>>32); + n[i+5] = (byte) (nonce>>>40); + n[i+6] = (byte) (nonce>>>48); + n[i+7] = (byte) (nonce>>>56); + } + + return n; + } + + /* + * @description + * Encrypt and authenticates message using peer's public key, + * our secret key, and the given nonce, which must be unique + * for each distinct message for a key pair. + * + * Returns an encrypted and authenticated message, + * which is nacl.box.overheadLength longer than the original message. + * */ + public byte [] box(byte [] message) { + if (message==null) return null; + return box(message, 0, message.length); + } + + public byte [] box(byte [] message, final int moff) { + if (!(message!=null && message.length>moff)) return null; + return box(message, moff, message.length-moff); + } + + public byte [] box(byte [] message, final int moff, final int mlen) { + if (!(message!=null && message.length>=(moff+mlen))) return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return after(message, moff, mlen); + } + + /* + * @description + * Encrypt and authenticates message using peer's public key, + * our secret key, and the given nonce, which must be unique + * for each distinct message for a key pair. + * + * Explicitly pass the nonce + * + * Returns an encrypted and authenticated message, + * which is nacl.box.overheadLength longer than the original message. + * */ + public byte [] box(byte [] message, byte [] theNonce) { + if (message==null) return null; + return box(message, 0, message.length, theNonce); + } + + public byte [] box(byte [] message, final int moff, byte [] theNonce) { + if (!(message!=null && message.length>moff)) return null; + return box(message, moff, message.length-moff, theNonce); + } + + public byte [] box(byte [] message, final int moff, final int mlen, byte [] theNonce) { + if (!(message!=null && message.length>=(moff+mlen) && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return after(message, moff, mlen, theNonce); + } + + /* + * @description + * Authenticates and decrypts the given box with peer's public key, + * our secret key, and the given nonce. + * + * Returns the original message, or null if authentication fails. + * */ + public byte [] open(byte [] box) { + if (box==null) return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return open_after(box, 0, box.length); + } + public byte [] open(byte [] box, final int boxoff) { + if (!(box!=null && box.length>boxoff)) return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return open_after(box, boxoff, box.length-boxoff); + } + public byte [] open(byte [] box, final int boxoff, final int boxlen) { + if (!(box!=null && box.length>=(boxoff+boxlen))) return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return open_after(box, boxoff, boxlen); + } + + + /* + * @description + * Authenticates and decrypts the given box with peer's public key, + * our secret key, and the given nonce. + * Explicit passing of nonce + * Returns the original message, or null if authentication fails. + * */ + public byte [] open(byte [] box, byte [] theNonce) { + if (!(box!=null && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return open_after(box, 0, box.length, theNonce); + } + public byte [] open(byte [] box, final int boxoff, byte [] theNonce) { + if (!(box!=null && box.length>boxoff && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return open_after(box, boxoff, box.length-boxoff, theNonce); + } + public byte [] open(byte [] box, final int boxoff, final int boxlen, byte [] theNonce) { + if (!(box!=null && box.length>=(boxoff+boxlen) && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // prepare shared key + if (this.sharedKey == null) before(); + + return open_after(box, boxoff, boxlen, theNonce); + } + + + /* + * @description + * Returns a precomputed shared key + * which can be used in nacl.box.after and nacl.box.open.after. + * */ + public byte [] before() { + if (this.sharedKey == null) { + this.sharedKey = new byte[sharedKeyLength]; + crypto_box_beforenm(this.sharedKey, this.theirPublicKey, this.mySecretKey); + } + + return this.sharedKey; + } + + /* + * @description + * Same as nacl.box, but uses a shared key precomputed with nacl.box.before. + * */ + public byte [] after(byte [] message, final int moff, final int mlen) { + return after(message, moff, mlen, generateNonce()); + } + + /* + * @description + * Same as nacl.box, but uses a shared key precomputed with nacl.box.before, + * and passes a nonce explicitly. + * */ + public byte [] after(byte [] message, final int moff, final int mlen, byte [] theNonce) { + // check message + if (!(message!=null && message.length>=(moff+mlen) && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // message buffer + byte [] m = new byte[mlen + zerobytesLength]; + + // cipher buffer + byte [] c = new byte[m.length]; + + for (int i = 0; i < mlen; i ++) + m[i+zerobytesLength] = message[i+moff]; + + if (0 != crypto_box_afternm(c, m, m.length, theNonce, sharedKey)) + return null; + + // wrap byte_buf_t on c offset@boxzerobytesLength + ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength); + byte [] ret = new byte[c.length-boxzerobytesLength]; + + for (int i = 0; i < ret.length; i ++) + ret[i] = c[i+boxzerobytesLength]; + + return ret; + } + + /* + * @description + * Same as nacl.box.open, + * but uses a shared key pre-computed with nacl.box.before. + * */ + public byte [] open_after(byte [] box, final int boxoff, final int boxlen) { + return open_after(box, boxoff, boxlen, generateNonce()); + } + + public byte [] open_after(byte [] box, final int boxoff, final int boxlen, byte [] theNonce) { + // check message + if (!(box!=null && box.length>=(boxoff+boxlen) && boxlen>=boxzerobytesLength)) + return null; + + // cipher buffer + byte [] c = new byte[boxlen + boxzerobytesLength]; + + // message buffer + byte [] m = new byte[c.length]; + + for (int i = 0; i < boxlen; i++) + c[i+boxzerobytesLength] = box[i+boxoff]; + + if (crypto_box_open_afternm(m, c, c.length, theNonce, sharedKey) != 0) + return null; + + // wrap byte_buf_t on m offset@zerobytesLength + ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength); + byte [] ret = new byte[m.length-zerobytesLength]; + + for (int i = 0; i < ret.length; i ++) + ret[i] = m[i+zerobytesLength]; + + return ret; + } + + /* + * @description + * Length of public key in bytes. + * */ + public static final int publicKeyLength = 32; + + /* + * @description + * Length of secret key in bytes. + * */ + public static final int secretKeyLength = 32; + + /* + * @description + * Length of precomputed shared key in bytes. + * */ + public static final int sharedKeyLength = 32; + + /* + * @description + * Length of nonce in bytes. + * */ + public static final int nonceLength = 24; + + /* + * @description + * zero bytes in case box + * */ + public static final int zerobytesLength = 32; + /* + * @description + * zero bytes in case open box + * */ + public static final int boxzerobytesLength = 16; + + /* + * @description + * Length of overhead added to box compared to original message. + * */ + public static final int overheadLength = 16; + + public static class KeyPair { + private byte [] publicKey; + private byte [] secretKey; + + public KeyPair() { + publicKey = new byte[publicKeyLength]; + secretKey = new byte[secretKeyLength]; + } + + public byte [] getPublicKey() { + return publicKey; + } + + public byte [] getSecretKey() { + return secretKey; + } + } + + /* + * @description + * Generates a new random key pair for box and + * returns it as an object with publicKey and secretKey members: + * */ + public static KeyPair keyPair() { + KeyPair kp = new KeyPair(); + + crypto_box_keypair(kp.getPublicKey(), kp.getSecretKey()); + return kp; + } + + public static KeyPair keyPair_fromSecretKey(byte [] secretKey) { + KeyPair kp = new KeyPair(); + byte [] sk = kp.getSecretKey(); + byte [] pk = kp.getPublicKey(); + + // copy sk + for (int i = 0; i < sk.length; i ++) + sk[i] = secretKey[i]; + + crypto_scalarmult_base(pk, sk); + return kp; + } + + } + + /* + * @description + * Secret Box algorithm, secret key + * */ + public static final class SecretBox { + + private final static String TAG = "SecretBox"; + + private AtomicLong nonce; + + private byte [] key; + + public SecretBox(byte [] key) { + this(key, 68); + } + + public SecretBox(byte [] key, long nonce) { + this.key = key; + + this.nonce = new AtomicLong(nonce); + } + + public void setNonce(long nonce) { + this.nonce.set(nonce); + } + public long getNonce() { + return this.nonce.get(); + } + public long incrNonce() { + return this.nonce.incrementAndGet(); + } + private byte[] generateNonce() { + // generate nonce + long nonce = this.nonce.get(); + + byte [] n = new byte[nonceLength]; + for (int i = 0; i < nonceLength; i += 8) { + n[i+0] = (byte) (nonce>>> 0); + n[i+1] = (byte) (nonce>>> 8); + n[i+2] = (byte) (nonce>>>16); + n[i+3] = (byte) (nonce>>>24); + n[i+4] = (byte) (nonce>>>32); + n[i+5] = (byte) (nonce>>>40); + n[i+6] = (byte) (nonce>>>48); + n[i+7] = (byte) (nonce>>>56); + } + + return n; + } + + /* + * @description + * Encrypt and authenticates message using the key and the nonce. + * The nonce must be unique for each distinct message for this key. + * + * Returns an encrypted and authenticated message, + * which is nacl.secretbox.overheadLength longer than the original message. + * */ + public byte [] box(byte [] message) { + if (message==null) return null; + return box(message, 0, message.length); + } + + public byte [] box(byte [] message, final int moff) { + if (!(message!=null && message.length>moff)) return null; + return box(message, moff, message.length-moff); + } + + public byte [] box(byte [] message, final int moff, final int mlen) { + // check message + if (!(message!=null && message.length>=(moff+mlen))) + return null; + return box(message, moff, message.length-moff, generateNonce()); + } + + public byte [] box(byte [] message, byte [] theNonce) { + if (message==null) return null; + return box(message, 0, message.length, theNonce); + } + + public byte [] box(byte [] message, final int moff, byte [] theNonce) { + if (!(message!=null && message.length>moff)) return null; + return box(message, moff, message.length-moff, theNonce); + } + + public byte [] box(byte [] message, final int moff, final int mlen, byte [] theNonce) { + // check message + if (!(message!=null && message.length>=(moff+mlen) && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // message buffer + byte [] m = new byte[mlen + zerobytesLength]; + + // cipher buffer + byte [] c = new byte[m.length]; + + for (int i = 0; i < mlen; i ++) + m[i+zerobytesLength] = message[i+moff]; + + if (0 != crypto_secretbox(c, m, m.length, theNonce, key)) + return null; + + // TBD optimizing ... + // wrap byte_buf_t on c offset@boxzerobytesLength + ///return new byte_buf_t(c, boxzerobytesLength, c.length-boxzerobytesLength); + byte [] ret = new byte[c.length-boxzerobytesLength]; + + for (int i = 0; i < ret.length; i ++) + ret[i] = c[i+boxzerobytesLength]; + + return ret; + } + + /* + * @description + * Authenticates and decrypts the given secret box + * using the key and the nonce. + * + * Returns the original message, or null if authentication fails. + * */ + public byte [] open(byte [] box) { + if (box==null) return null; + return open(box, 0, box.length); + } + + public byte [] open(byte [] box, final int boxoff) { + if (!(box!=null && box.length>boxoff)) return null; + return open(box, boxoff, box.length-boxoff); + } + + public byte [] open(byte [] box, final int boxoff, final int boxlen) { + // check message + if (!(box!=null && box.length>=(boxoff+boxlen) && boxlen>=boxzerobytesLength)) + return null; + return open(box, boxoff, box.length-boxoff, generateNonce()); + } + + public byte [] open(byte [] box, byte [] theNonce) { + if (box==null) return null; + return open(box, 0, box.length, theNonce); + } + + public byte [] open(byte [] box, final int boxoff, byte [] theNonce) { + if (!(box!=null && box.length>boxoff)) return null; + return open(box, boxoff, box.length-boxoff, theNonce); + } + + public byte [] open(byte [] box, final int boxoff, final int boxlen, byte [] theNonce) { + // check message + if (!(box!=null && box.length>=(boxoff+boxlen) && boxlen>=boxzerobytesLength && + theNonce!=null && theNonce.length==nonceLength)) + return null; + + // cipher buffer + byte [] c = new byte[boxlen + boxzerobytesLength]; + + // message buffer + byte [] m = new byte[c.length]; + + for (int i = 0; i < boxlen; i++) + c[i+boxzerobytesLength] = box[i+boxoff]; + + if (0 != crypto_secretbox_open(m, c, c.length, theNonce, key)) + return null; + + // wrap byte_buf_t on m offset@zerobytesLength + ///return new byte_buf_t(m, zerobytesLength, m.length-zerobytesLength); + byte [] ret = new byte[m.length-zerobytesLength]; + + for (int i = 0; i < ret.length; i ++) + ret[i] = m[i+zerobytesLength]; + + return ret; + } + + /* + * @description + * Length of key in bytes. + * */ + public static final int keyLength = 32; + + /* + * @description + * Length of nonce in bytes. + * */ + public static final int nonceLength = 24; + + /* + * @description + * Length of overhead added to secret box compared to original message. + * */ + public static final int overheadLength = 16; + + /* + * @description + * zero bytes in case box + * */ + public static final int zerobytesLength = 32; + /* + * @description + * zero bytes in case open box + * */ + public static final int boxzerobytesLength = 16; + + } + + /* + * @description + * Scalar multiplication, Implements curve25519. + * */ + public static final class ScalarMult { + + private final static String TAG = "ScalarMult"; + + /* + * @description + * Multiplies an integer n by a group element p and + * returns the resulting group element. + * */ + public static byte [] scalseMult(byte [] n, byte [] p) { + if (!(n.length==scalarLength && p.length==groupElementLength)) + return null; + + byte [] q = new byte [scalarLength]; + + crypto_scalarmult(q, n, p); + + return q; + } + + /* + * @description + * Multiplies an integer n by a standard group element and + * returns the resulting group element. + * */ + public static byte [] scalseMult_base(byte [] n) { + if (!(n.length==scalarLength)) + return null; + + byte [] q = new byte [scalarLength]; + + crypto_scalarmult_base(q, n); + + return q; + } + + /* + * @description + * Length of scalar in bytes. + * */ + public static final int scalarLength = 32; + + /* + * @description + * Length of group element in bytes. + * */ + public static final int groupElementLength = 32; + + } + + + /* + * @description + * Hash algorithm, Implements SHA-512. + * */ + public static final class Hash { + + private final static String TAG = "Hash"; + + /* + * @description + * Returns SHA-512 hash of the message. + * */ + public static byte[] sha512(byte [] message) { + if (!(message!=null && message.length>0)) + return null; + + byte [] out = new byte[hashLength]; + + crypto_hash(out, message); + + return out; + } + public static byte[] sha512(String message) throws UnsupportedEncodingException { + return sha512(message.getBytes("utf-8")); + } + + /* + * @description + * Length of hash in bytes. + * */ + public static final int hashLength = 64; + + } + + + /* + * @description + * Signature algorithm, Implements ed25519. + * */ + public static final class Signature { + + private final static String TAG = "Signature"; + + private byte [] theirPublicKey; + private byte [] mySecretKey; + + public Signature(byte [] theirPublicKey, byte [] mySecretKey) { + this.theirPublicKey = theirPublicKey; + this.mySecretKey = mySecretKey; + } + + /* + * @description + * Signs the message using the secret key and returns a signed message. + * */ + public byte [] sign(byte [] message) { + if (message==null) return null; + + return sign(message, 0, message.length); + } + public byte [] sign(byte [] message, final int moff) { + if (!(message!=null && message.length>moff)) return null; + + return sign(message, moff, message.length-moff); + } + public byte [] sign(byte [] message, final int moff, final int mlen) { + // check message + if (!(message!=null && message.length>=(moff+mlen))) + return null; + + // signed message + byte [] sm = new byte[mlen + signatureLength]; + + crypto_sign(sm, -1, message, moff, mlen, mySecretKey); + + return sm; + } + + /* + * @description + * Verifies the signed message and returns the message without signature. + * Returns null if verification failed. + * */ + public byte [] open(byte [] signedMessage) { + if (signedMessage==null) return null; + + return open(signedMessage, 0, signedMessage.length); + } + public byte [] open(byte [] signedMessage, final int smoff) { + if (!(signedMessage!=null && signedMessage.length>smoff)) return null; + + return open(signedMessage, smoff, signedMessage.length-smoff); + } + public byte [] open(byte [] signedMessage, final int smoff, final int smlen) { + // check sm length + if (!(signedMessage!=null && signedMessage.length>=(smoff+smlen) && smlen>=signatureLength)) + return null; + + // temp buffer + byte [] tmp = new byte[smlen]; + + if (0 != crypto_sign_open(tmp, -1, signedMessage, smoff, smlen, theirPublicKey)) + return null; + + // message + byte [] msg = new byte[smlen-signatureLength]; + for (int i = 0; i < msg.length; i ++) + msg[i] = signedMessage[smoff+ i+signatureLength]; + + return msg; + } + + /* + * @description + * Signs the message using the secret key and returns a signature. + * */ + public byte [] detached(byte [] message) { + byte[] signedMsg = this.sign(message); + byte[] sig = new byte[signatureLength]; + for (int i = 0; i < sig.length; i++) + sig[i] = signedMsg[i]; + return sig; + } + + /* + * @description + * Verifies the signature for the message and + * returns true if verification succeeded or false if it failed. + * */ + public boolean detached_verify(byte [] message, byte [] signature) { + if (signature.length != signatureLength) + return false; + if (theirPublicKey.length != publicKeyLength) + return false; + byte [] sm = new byte[signatureLength + message.length]; + byte [] m = new byte[signatureLength + message.length]; + for (int i = 0; i < signatureLength; i++) + sm[i] = signature[i]; + for (int i = 0; i < message.length; i++) + sm[i + signatureLength] = message[i]; + return (crypto_sign_open(m, -1, sm, 0, sm.length, theirPublicKey) >= 0); + } + + /* + * @description + * Generates new random key pair for signing and + * returns it as an object with publicKey and secretKey members + * */ + public static class KeyPair { + private byte [] publicKey; + private byte [] secretKey; + + public KeyPair() { + publicKey = new byte[publicKeyLength]; + secretKey = new byte[secretKeyLength]; + } + + public byte [] getPublicKey() { + return publicKey; + } + + public byte [] getSecretKey() { + return secretKey; + } + } + + /* + * @description + * Signs the message using the secret key and returns a signed message. + * */ + public static KeyPair keyPair() { + KeyPair kp = new KeyPair(); + + crypto_sign_keypair(kp.getPublicKey(), kp.getSecretKey(), false); + return kp; + } + public static KeyPair keyPair_fromSecretKey(byte [] secretKey) { + KeyPair kp = new KeyPair(); + byte [] pk = kp.getPublicKey(); + byte [] sk = kp.getSecretKey(); + + // copy sk + for (int i = 0; i < kp.getSecretKey().length; i ++) + sk[i] = secretKey[i]; + + // copy pk from sk + for (int i = 0; i < kp.getPublicKey().length; i ++) + pk[i] = secretKey[32+i]; // hard-copy + + return kp; + } + + public static KeyPair keyPair_fromSeed(byte [] seed) { + KeyPair kp = new KeyPair(); + byte [] pk = kp.getPublicKey(); + byte [] sk = kp.getSecretKey(); + + // copy sk + for (int i = 0; i < seedLength; i ++) + sk[i] = seed[i]; + + // generate pk from sk + crypto_sign_keypair(pk, sk, true); + + return kp; + } + + /* + * @description + * Length of signing public key in bytes. + * */ + public static final int publicKeyLength = 32; + + /* + * @description + * Length of signing secret key in bytes. + * */ + public static final int secretKeyLength = 64; + + /* + * @description + * Length of seed for nacl.sign.keyPair.fromSeed in bytes. + * */ + public static final int seedLength = 32; + + /* + * @description + * Length of signature in bytes. + * */ + public static final int signatureLength = 64; + } + + + //////////////////////////////////////////////////////////////////////////////////// + /* + * @description + * Codes below are ported tweetnacl-fast.js from TweetNacl.c/TweetNacl.h + * */ + + private static final byte [] _0 = new byte[16]; + private static final byte [] _9 = new byte[32]; + static { + ///for (int i = 0; i < _0.length; i ++) _0[i] = 0; + + ///for (int i = 0; i < _9.length; i ++) _9[i] = 0; + _9[0] = 9; + } + + private static final long [] gf0 = new long[16]; + private static final long [] gf1 = new long[16]; + private static final long [] _121665 = new long[16]; + static { + ///for (int i = 0; i < gf0.length; i ++) gf0[i] = 0; + + ///for (int i = 0; i < gf1.length; i ++) gf1[i] = 0; + gf1[0] = 1; + + ///for (int i = 0; i < _121665.length; i ++) _121665[i] = 0; + _121665[0] = 0xDB41; _121665[1] = 1; + } + + private static final long [] D = new long [] { + 0x78a3, 0x1359, 0x4dca, 0x75eb, + 0xd8ab, 0x4141, 0x0a4d, 0x0070, + 0xe898, 0x7779, 0x4079, 0x8cc7, + 0xfe73, 0x2b6f, 0x6cee, 0x5203 + }; + private static final long [] D2 = new long [] { + 0xf159, 0x26b2, 0x9b94, 0xebd6, + 0xb156, 0x8283, 0x149a, 0x00e0, + 0xd130, 0xeef3, 0x80f2, 0x198e, + 0xfce7, 0x56df, 0xd9dc, 0x2406 + }; + private static final long [] X = new long [] { + 0xd51a, 0x8f25, 0x2d60, 0xc956, + 0xa7b2, 0x9525, 0xc760, 0x692c, + 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, + 0x53fe, 0xcd6e, 0x36d3, 0x2169 + }; + private static final long [] Y = new long [] { + 0x6658, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666 + }; + private static final long [] I = new long [] { + 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, + 0xe478, 0xad2f, 0x1806, 0x2f43, + 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, + 0xdf0b, 0x4fc1, 0x2480, 0x2b83 + }; + + private static void ts64(byte [] x, final int xoff, long u) + { + ///int i; + ///for (i = 7;i >= 0;--i) { x[i+xoff] = (byte)(u&0xff); u >>>= 8; } + + x[7+xoff] = (byte)(u&0xff); u >>>= 8; + x[6+xoff] = (byte)(u&0xff); u >>>= 8; + x[5+xoff] = (byte)(u&0xff); u >>>= 8; + x[4+xoff] = (byte)(u&0xff); u >>>= 8; + x[3+xoff] = (byte)(u&0xff); u >>>= 8; + x[2+xoff] = (byte)(u&0xff); u >>>= 8; + x[1+xoff] = (byte)(u&0xff); u >>>= 8; + x[0+xoff] = (byte)(u&0xff); ///u >>>= 8; + } + + private static int vn( + byte [] x, final int xoff, + byte [] y, final int yoff, + int n) + { + int i,d = 0; + for (i = 0; i < n; i ++) d |= (x[i+xoff]^y[i+yoff]) & 0xff; + return (1 & ((d - 1) >>> 8)) - 1; + } + + private static int crypto_verify_16( + byte [] x, final int xoff, + byte [] y, final int yoff) + { + return vn(x,xoff,y,yoff,16); + } + public static int crypto_verify_16(byte [] x, byte [] y) + { + return crypto_verify_16(x,0, y,0); + } + + private static int crypto_verify_32( + byte [] x, final int xoff, + byte [] y, final int yoff) + { + return vn(x,xoff,y,yoff,32); + } + public static int crypto_verify_32(byte [] x, byte [] y) + { + return crypto_verify_32(x,0, y,0); + } + + private static void core_salsa20(byte [] o, byte [] p, byte [] k, byte [] c) { + int j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + int x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (int i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; + + o[ 0] = (byte) (x0 >>> 0 & 0xff); + o[ 1] = (byte) (x0 >>> 8 & 0xff); + o[ 2] = (byte) (x0 >>> 16 & 0xff); + o[ 3] = (byte) (x0 >>> 24 & 0xff); + + o[ 4] = (byte) (x1 >>> 0 & 0xff); + o[ 5] = (byte) (x1 >>> 8 & 0xff); + o[ 6] = (byte) (x1 >>> 16 & 0xff); + o[ 7] = (byte) (x1 >>> 24 & 0xff); + + o[ 8] = (byte) (x2 >>> 0 & 0xff); + o[ 9] = (byte) (x2 >>> 8 & 0xff); + o[10] = (byte) (x2 >>> 16 & 0xff); + o[11] = (byte) (x2 >>> 24 & 0xff); + + o[12] = (byte) (x3 >>> 0 & 0xff); + o[13] = (byte) (x3 >>> 8 & 0xff); + o[14] = (byte) (x3 >>> 16 & 0xff); + o[15] = (byte) (x3 >>> 24 & 0xff); + + o[16] = (byte) (x4 >>> 0 & 0xff); + o[17] = (byte) (x4 >>> 8 & 0xff); + o[18] = (byte) (x4 >>> 16 & 0xff); + o[19] = (byte) (x4 >>> 24 & 0xff); + + o[20] = (byte) (x5 >>> 0 & 0xff); + o[21] = (byte) (x5 >>> 8 & 0xff); + o[22] = (byte) (x5 >>> 16 & 0xff); + o[23] = (byte) (x5 >>> 24 & 0xff); + + o[24] = (byte) (x6 >>> 0 & 0xff); + o[25] = (byte) (x6 >>> 8 & 0xff); + o[26] = (byte) (x6 >>> 16 & 0xff); + o[27] = (byte) (x6 >>> 24 & 0xff); + + o[28] = (byte) (x7 >>> 0 & 0xff); + o[29] = (byte) (x7 >>> 8 & 0xff); + o[30] = (byte) (x7 >>> 16 & 0xff); + o[31] = (byte) (x7 >>> 24 & 0xff); + + o[32] = (byte) (x8 >>> 0 & 0xff); + o[33] = (byte) (x8 >>> 8 & 0xff); + o[34] = (byte) (x8 >>> 16 & 0xff); + o[35] = (byte) (x8 >>> 24 & 0xff); + + o[36] = (byte) (x9 >>> 0 & 0xff); + o[37] = (byte) (x9 >>> 8 & 0xff); + o[38] = (byte) (x9 >>> 16 & 0xff); + o[39] = (byte) (x9 >>> 24 & 0xff); + + o[40] = (byte) (x10 >>> 0 & 0xff); + o[41] = (byte) (x10 >>> 8 & 0xff); + o[42] = (byte) (x10 >>> 16 & 0xff); + o[43] = (byte) (x10 >>> 24 & 0xff); + + o[44] = (byte) (x11 >>> 0 & 0xff); + o[45] = (byte) (x11 >>> 8 & 0xff); + o[46] = (byte) (x11 >>> 16 & 0xff); + o[47] = (byte) (x11 >>> 24 & 0xff); + + o[48] = (byte) (x12 >>> 0 & 0xff); + o[49] = (byte) (x12 >>> 8 & 0xff); + o[50] = (byte) (x12 >>> 16 & 0xff); + o[51] = (byte) (x12 >>> 24 & 0xff); + + o[52] = (byte) (x13 >>> 0 & 0xff); + o[53] = (byte) (x13 >>> 8 & 0xff); + o[54] = (byte) (x13 >>> 16 & 0xff); + o[55] = (byte) (x13 >>> 24 & 0xff); + + o[56] = (byte) (x14 >>> 0 & 0xff); + o[57] = (byte) (x14 >>> 8 & 0xff); + o[58] = (byte) (x14 >>> 16 & 0xff); + o[59] = (byte) (x14 >>> 24 & 0xff); + + o[60] = (byte) (x15 >>> 0 & 0xff); + o[61] = (byte) (x15 >>> 8 & 0xff); + o[62] = (byte) (x15 >>> 16 & 0xff); + o[63] = (byte) (x15 >>> 24 & 0xff); + + /*String dbgt = ""; + for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o[dbg]; + Log.d(TAG, "core_salsa20 -> "+dbgt); +*/ + } + + private static void core_hsalsa20(byte [] o, byte [] p, byte [] k, byte [] c) { + int j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + + int x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; + + for (int i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); + + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); + + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + + o[ 0] = (byte) (x0 >>> 0 & 0xff); + o[ 1] = (byte) (x0 >>> 8 & 0xff); + o[ 2] = (byte) (x0 >>> 16 & 0xff); + o[ 3] = (byte) (x0 >>> 24 & 0xff); + + o[ 4] = (byte) (x5 >>> 0 & 0xff); + o[ 5] = (byte) (x5 >>> 8 & 0xff); + o[ 6] = (byte) (x5 >>> 16 & 0xff); + o[ 7] = (byte) (x5 >>> 24 & 0xff); + + o[ 8] = (byte) (x10 >>> 0 & 0xff); + o[ 9] = (byte) (x10 >>> 8 & 0xff); + o[10] = (byte) (x10 >>> 16 & 0xff); + o[11] = (byte) (x10 >>> 24 & 0xff); + + o[12] = (byte) (x15 >>> 0 & 0xff); + o[13] = (byte) (x15 >>> 8 & 0xff); + o[14] = (byte) (x15 >>> 16 & 0xff); + o[15] = (byte) (x15 >>> 24 & 0xff); + + o[16] = (byte) (x6 >>> 0 & 0xff); + o[17] = (byte) (x6 >>> 8 & 0xff); + o[18] = (byte) (x6 >>> 16 & 0xff); + o[19] = (byte) (x6 >>> 24 & 0xff); + + o[20] = (byte) (x7 >>> 0 & 0xff); + o[21] = (byte) (x7 >>> 8 & 0xff); + o[22] = (byte) (x7 >>> 16 & 0xff); + o[23] = (byte) (x7 >>> 24 & 0xff); + + o[24] = (byte) (x8 >>> 0 & 0xff); + o[25] = (byte) (x8 >>> 8 & 0xff); + o[26] = (byte) (x8 >>> 16 & 0xff); + o[27] = (byte) (x8 >>> 24 & 0xff); + + o[28] = (byte) (x9 >>> 0 & 0xff); + o[29] = (byte) (x9 >>> 8 & 0xff); + o[30] = (byte) (x9 >>> 16 & 0xff); + o[31] = (byte) (x9 >>> 24 & 0xff); + + + /*String dbgt = ""; + for (int dbg = 0; dbg < o.length; dbg ++) dbgt += " "+o[dbg]; + Log.d(TAG, "core_hsalsa20 -> "+dbgt); +*/ + } + + public static int crypto_core_salsa20(byte [] out, byte [] in, byte [] k, byte [] c) + { + ///core(out,in,k,c,0); + core_salsa20(out,in,k,c); + + ///String dbgt = ""; + ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg]; + ///L/og.d(TAG, "crypto_core_salsa20 -> "+dbgt); + + return 0; + } + + public static int crypto_core_hsalsa20(byte [] out, byte [] in, byte [] k, byte [] c) + { + ///core(out,in,k,c,1); + core_hsalsa20(out,in,k,c); + + ///String dbgt = ""; + ///for (int dbg = 0; dbg < out.length; dbg ++) dbgt += " "+out[dbg]; + ///L/og.d(TAG, "crypto_core_hsalsa20 -> "+dbgt); + + return 0; + } + + // "expand 32-byte k" + private static final byte[] sigma = {101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107}; + + /*static { + try { + sigma = "expand 32-byte k".getBytes("utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + }*/ + + private static int crypto_stream_salsa20_xor(byte [] c,int cpos, byte [] m,int mpos, long b, byte [] n, byte [] k) + { + byte [] z = new byte[16], x = new byte[64]; + int u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = (byte) ((m[mpos+i] ^ x[i]) & 0xff); + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = (byte) (u & 0xff); + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = (byte) ((m[mpos+i] ^ x[i]) & 0xff); + } + + ///String dbgt = ""; + ///for (int dbg = 0; dbg < c.length-cpos; dbg ++) dbgt += " "+c[dbg +cpos]; + ///Log.d(TAG, "crypto_stream_salsa20_xor, c -> "+dbgt); + + return 0; + } + + public static int crypto_stream_salsa20(byte [] c,int cpos, long b, byte [] n, byte [] k) { + byte [] z = new byte[16], x = new byte[64]; + int u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = (byte) (u & 0xff); + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + + ///String dbgt = ""; + ///for (int dbg = 0; dbg < c.length-cpos; dbg ++) dbgt += " "+c[dbg +cpos]; + ///Log.d(TAG, "crypto_stream_salsa20, c -> "+dbgt); + + return 0; + } + + public static int crypto_stream(byte [] c,int cpos, long d, byte [] n, byte [] k) { + byte [] s = new byte[32]; + crypto_core_hsalsa20(s,n,k,sigma); + byte [] sn = new byte[8]; + for (int i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); + } + + public static int crypto_stream_xor(byte [] c,int cpos, byte [] m,int mpos, long d, byte [] n, byte [] k) { + byte [] s = new byte[32]; + + /*String dbgt = ""; + for (int dbg = 0; dbg < n.length; dbg ++) dbgt += " "+n[dbg]; + Log.d(TAG, "crypto_stream_xor, nonce -> "+dbgt); + dbgt = ""; + for (int dbg = 0; dbg < k.length; dbg ++) dbgt += " "+k[dbg]; + Log.d(TAG, "crypto_stream_xor, shk -> "+dbgt); + */ + + crypto_core_hsalsa20(s,n,k,sigma); + byte [] sn = new byte[8]; + for (int i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); + } + + /* + * Port of Andrew Moon's Poly1305-donna-16. Public domain. + * https://github.com/floodyberry/poly1305-donna + */ + public static final class poly1305 { + + private byte[] buffer; + private int[] r; + private int[] h; + private int[] pad; + private int leftover; + private int fin; + + public poly1305(byte [] key) { + this.buffer = new byte[16]; + this.r = new int[10]; + this.h = new int[10]; + this.pad = new int[8]; + this.leftover = 0; + this.fin = 0; + + int t0, t1, t2, t3, t4, t5, t6, t7; + + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; + + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; + } + + public poly1305 blocks(byte [] m, int mpos, int bytes) { + int hibit = this.fin!=0 ? 0 : (1 << 11); + int t0, t1, t2, t3, t4, t5, t6, t7, c; + int d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; + + int h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; + + int r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; + + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; + + c = 0; + + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; + + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; + + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; + + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; + + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; + + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; + + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; + + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; + + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; + + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; + + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; + + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; + + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; + + return this; + } + + public poly1305 finish(byte [] mac, int macpos) { + int [] g = new int[10]; + int c, mask, f, i; + + if (this.leftover != 0) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); + } + + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; + } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; + + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= (1 << 13); g[9] &= 0xffff; + + /* + backport from tweetnacl-fast.js https://github.com/dchest/tweetnacl-js/releases/tag/v0.14.3 + <<< + "The issue was not properly detecting if st->h was >= 2^130 - 5, + coupled with [testing mistake] not catching the failure. + The chance of the bug affecting anything in the real world is essentially zero luckily, + but it's good to have it fixed." + >>> + */ + ///change mask = (g[9] >>> ((2 * 8) - 1)) - 1; to as + mask = (c ^ 1) - 1; + mask &= 0xffff; + /////////////////////////////////////// + + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; + + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; + } + + mac[macpos+ 0] = (byte) ((this.h[0] >>> 0) & 0xff); + mac[macpos+ 1] = (byte) ((this.h[0] >>> 8) & 0xff); + mac[macpos+ 2] = (byte) ((this.h[1] >>> 0) & 0xff); + mac[macpos+ 3] = (byte) ((this.h[1] >>> 8) & 0xff); + mac[macpos+ 4] = (byte) ((this.h[2] >>> 0) & 0xff); + mac[macpos+ 5] = (byte) ((this.h[2] >>> 8) & 0xff); + mac[macpos+ 6] = (byte) ((this.h[3] >>> 0) & 0xff); + mac[macpos+ 7] = (byte) ((this.h[3] >>> 8) & 0xff); + mac[macpos+ 8] = (byte) ((this.h[4] >>> 0) & 0xff); + mac[macpos+ 9] = (byte) ((this.h[4] >>> 8) & 0xff); + mac[macpos+10] = (byte) ((this.h[5] >>> 0) & 0xff); + mac[macpos+11] = (byte) ((this.h[5] >>> 8) & 0xff); + mac[macpos+12] = (byte) ((this.h[6] >>> 0) & 0xff); + mac[macpos+13] = (byte) ((this.h[6] >>> 8) & 0xff); + mac[macpos+14] = (byte) ((this.h[7] >>> 0) & 0xff); + mac[macpos+15] = (byte) ((this.h[7] >>> 8) & 0xff); + + return this; + } + + public poly1305 update(byte [] m, int mpos, int bytes) { + int i, want; + + if (this.leftover != 0) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return this; + this.blocks(buffer, 0, 16); + this.leftover = 0; + } + + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; + } + + if (bytes != 0) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; + } + + return this; + } + + } + + private static int crypto_onetimeauth( + byte[] out,final int outpos, + byte[] m,final int mpos, + int n, + byte [] k) + { + poly1305 s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + + /*String dbgt = ""; + for (int dbg = 0; dbg < out.length-outpos; dbg ++) dbgt += " "+out[dbg+outpos]; + Log.d(TAG, "crypto_onetimeauth -> "+dbgt); + */ + + return 0; + } + public static int crypto_onetimeauth(byte [] out, byte [] m, int /*long*/ n , byte [] k) { + return crypto_onetimeauth(out,0, m,0, n, k); + } + + private static int crypto_onetimeauth_verify( + byte[] h,final int hoff, + byte[] m,final int moff, + int /*long*/ n, + byte [] k) + { + byte [] x = new byte[16]; + crypto_onetimeauth(x,0,m,moff,n,k); + return crypto_verify_16(h,hoff,x,0); + } + public static int crypto_onetimeauth_verify(byte [] h, byte [] m, int /*long*/ n, byte [] k) { + return crypto_onetimeauth_verify(h,0, m,0, n, k); + } + public static int crypto_onetimeauth_verify(byte [] h, byte [] m, byte [] k) { + return crypto_onetimeauth_verify(h, m, m!=null? m.length:0, k); + } + + public static int crypto_secretbox(byte [] c, byte [] m, int /*long*/ d, byte [] n, byte [] k) + { + int i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c,16, c,32, d-32, c); + ///for (i = 0; i < 16; i++) c[i] = 0; + return 0; + } + + public static int crypto_secretbox_open(byte []m,byte []c,int /*long*/ d,byte []n,byte []k) + { + int i; + byte[] x = new byte[32]; + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c,16, c,32, d-32, x) != 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + ///for (i = 0; i < 32; i++) m[i] = 0; + return 0; + } + + private static void set25519(long [] r, long [] a) + { + int i; + for (i = 0; i < 16; i ++) r[i]=a[i]; + } + + private static void car25519(long [] o) + { + int i; + long v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = v>>16; + o[i] = v - c * 65536; + } + o[0] += c-1 + 37 * (c-1); + } + + private static void sel25519( + long[] p, + long[] q, + int b) + { + sel25519(p,0, q,0, b); + } + private static void sel25519( + long[] p,final int poff, + long[] q,final int qoff, + int b) + { + long t, c = ~(b-1); + for (int i = 0; i < 16; i++) { + t = c & (p[i+poff] ^ q[i+qoff]); + p[i+poff] ^= t; + q[i+qoff] ^= t; + } + } + + private static void pack25519(byte [] o, long [] n,final int noff) + { + int i, j, b; + long [] m = new long[16], t = new long[16]; + for (i = 0; i < 16; i++) t[i] = n[i+noff]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (int) ((m[15]>>16) & 1); + m[14] &= 0xffff; + sel25519(t,0, m,0, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = (byte) (t[i] & 0xff); + o[2*i+1] = (byte) (t[i]>>8); + } + } + + private static int neq25519(long [] a, long [] b) { + return neq25519(a,0, b,0); + } + private static int neq25519(long [] a,final int aoff, long [] b,final int boff) + { + byte [] c = new byte[32], d = new byte[32]; + pack25519(c, a,aoff); + pack25519(d, b,boff); + return crypto_verify_32(c, 0, d, 0); + } + + private static byte par25519(long [] a) + { + return par25519(a,0); + } + private static byte par25519(long [] a,final int aoff) + { + byte [] d = new byte[32]; + pack25519(d, a,aoff); + return (byte) (d[0] & 1); + } + + private static void unpack25519(long [] o, byte [] n) + { + int i; + for (i = 0; i < 16; i ++) o[i]=(n[2*i]&0xff)+((long)((n[2*i+1]<<8)&0xffff)); + o[15] &= 0x7fff; + } + + private static void A( + long [] o, + long [] a, + long [] b) + { + A(o,0, a,0, b,0); + } + private static void A( + long [] o,final int ooff, + long [] a,final int aoff, + long [] b,final int boff) + { + int i; + for (i = 0; i < 16; i ++) o[i+ooff] = a[i+aoff] + b[i+boff]; + } + + private static void Z( + long [] o, + long [] a, + long [] b) + { + Z(o,0, a,0, b,0); + } + private static void Z( + long [] o,final int ooff, + long [] a,final int aoff, + long [] b,final int boff) + { + int i; + for (i = 0; i < 16; i ++) o[i+ooff] = a[i+aoff] - b[i+boff]; + } + + private static void M( + long [] o, + long [] a, + long [] b) + { + M(o,0, a,0, b,0); + } + private static void M( + long [] o,final int ooff, + long [] a,final int aoff, + long [] b,final int boff) + { + long v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0 +boff], + b1 = b[1 +boff], + b2 = b[2 +boff], + b3 = b[3 +boff], + b4 = b[4 +boff], + b5 = b[5 +boff], + b6 = b[6 +boff], + b7 = b[7 +boff], + b8 = b[8 +boff], + b9 = b[9 +boff], + b10 = b[10 +boff], + b11 = b[11 +boff], + b12 = b[12 +boff], + b13 = b[13 +boff], + b14 = b[14 +boff], + b15 = b[15 +boff]; + + v = a[0 +aoff]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1 +aoff]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2 +aoff]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3 +aoff]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4 +aoff]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5 +aoff]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6 +aoff]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7 +aoff]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8 +aoff]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9 +aoff]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10 +aoff]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11 +aoff]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12 +aoff]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13 +aoff]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14 +aoff]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15 +aoff]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = v >> 16; t0 = v - c * 65536; + v = t1 + c + 65535; c = v >> 16; t1 = v - c * 65536; + v = t2 + c + 65535; c = v >> 16; t2 = v - c * 65536; + v = t3 + c + 65535; c = v >> 16; t3 = v - c * 65536; + v = t4 + c + 65535; c = v >> 16; t4 = v - c * 65536; + v = t5 + c + 65535; c = v >> 16; t5 = v - c * 65536; + v = t6 + c + 65535; c = v >> 16; t6 = v - c * 65536; + v = t7 + c + 65535; c = v >> 16; t7 = v - c * 65536; + v = t8 + c + 65535; c = v >> 16; t8 = v - c * 65536; + v = t9 + c + 65535; c = v >> 16; t9 = v - c * 65536; + v = t10 + c + 65535; c = v >> 16; t10 = v - c * 65536; + v = t11 + c + 65535; c = v >> 16; t11 = v - c * 65536; + v = t12 + c + 65535; c = v >> 16; t12 = v - c * 65536; + v = t13 + c + 65535; c = v >> 16; t13 = v - c * 65536; + v = t14 + c + 65535; c = v >> 16; t14 = v - c * 65536; + v = t15 + c + 65535; c = v >> 16; t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = v >> 16; t0 = v - c * 65536; + v = t1 + c + 65535; c = v >> 16; t1 = v - c * 65536; + v = t2 + c + 65535; c = v >> 16; t2 = v - c * 65536; + v = t3 + c + 65535; c = v >> 16; t3 = v - c * 65536; + v = t4 + c + 65535; c = v >> 16; t4 = v - c * 65536; + v = t5 + c + 65535; c = v >> 16; t5 = v - c * 65536; + v = t6 + c + 65535; c = v >> 16; t6 = v - c * 65536; + v = t7 + c + 65535; c = v >> 16; t7 = v - c * 65536; + v = t8 + c + 65535; c = v >> 16; t8 = v - c * 65536; + v = t9 + c + 65535; c = v >> 16; t9 = v - c * 65536; + v = t10 + c + 65535; c = v >> 16; t10 = v - c * 65536; + v = t11 + c + 65535; c = v >> 16; t11 = v - c * 65536; + v = t12 + c + 65535; c = v >> 16; t12 = v - c * 65536; + v = t13 + c + 65535; c = v >> 16; t13 = v - c * 65536; + v = t14 + c + 65535; c = v >> 16; t14 = v - c * 65536; + v = t15 + c + 65535; c = v >> 16; t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0 +ooff] = t0; + o[ 1 +ooff] = t1; + o[ 2 +ooff] = t2; + o[ 3 +ooff] = t3; + o[ 4 +ooff] = t4; + o[ 5 +ooff] = t5; + o[ 6 +ooff] = t6; + o[ 7 +ooff] = t7; + o[ 8 +ooff] = t8; + o[ 9 +ooff] = t9; + o[10 +ooff] = t10; + o[11 +ooff] = t11; + o[12 +ooff] = t12; + o[13 +ooff] = t13; + o[14 +ooff] = t14; + o[15 +ooff] = t15; + } + + private static void S( + long [] o, + long [] a) + { + S(o,0, a,0); + } + private static void S( + long [] o,final int ooff, + long [] a,final int aoff) + { + M(o,ooff, a,aoff, a,aoff); + } + + private static void inv25519( + long [] o,final int ooff, + long [] i,final int ioff) + { + long [] c = new long[16]; + int a; + for (a = 0; a < 16; a++) c[a] = i[a+ioff]; + for (a = 253; a >= 0; a--) { + S(c,0, c,0); + if(a != 2 && a != 4) M(c,0, c,0, i,ioff); + } + for (a = 0; a < 16; a++) o[a+ooff] = c[a]; + } + + private static void pow2523(long [] o,long [] i) + { + long [] c = new long[16]; + int a; + + for (a = 0; a < 16; a ++) c[a]=i[a]; + + for(a=250;a>=0;a--) { + S(c,0, c,0); + if(a!=1) M(c,0, c,0, i,0); + } + + for (a = 0; a < 16; a ++) o[a]=c[a]; + } + + public static int crypto_scalarmult(byte []q,byte []n,byte []p) + { + byte [] z = new byte[32]; + long [] x = new long[80]; + int r, i; + long [] a = new long[16], b = new long[16], c = new long[16], + d = new long[16], e = new long[16], f = new long[16]; + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(byte) (((n[31]&127)|64) & 0xff); + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254;i>=0;--i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + inv25519(x,32, x,32); + M(x,16, x,16, x,32); + pack25519(q, x,16); + + return 0; + } + + public static int crypto_scalarmult_base(byte []q,byte []n) + { + return crypto_scalarmult(q,n,_9); + } + + public static int crypto_box_keypair(byte [] y, byte [] x) + { + randombytes(x,32); + return crypto_scalarmult_base(y,x); + } + + public static int crypto_box_beforenm(byte []k,byte []y,byte []x) + { + byte[] s = new byte[32]; + crypto_scalarmult(s,x,y); + + /*String dbgt = ""; + for (int dbg = 0; dbg < s.length; dbg ++) dbgt += " "+s[dbg]; + Log.d(TAG, "crypto_box_beforenm -> "+dbgt); + dbgt = ""; + for (int dbg = 0; dbg < x.length; dbg ++) dbgt += " "+x[dbg]; + Log.d(TAG, "crypto_box_beforenm, x -> "+dbgt); + dbgt = ""; + for (int dbg = 0; dbg < y.length; dbg ++) dbgt += " "+y[dbg]; + Log.d(TAG, "crypto_box_beforenm, y -> "+dbgt); + */ + + return crypto_core_hsalsa20(k, _0, s, sigma); + } + + public static int crypto_box_afternm(byte []c,byte []m,int /*long*/ d,byte []n,byte []k) + { + return crypto_secretbox(c,m,d,n,k); + } + + public static int crypto_box_open_afternm(byte []m,byte []c,int /*long*/ d,byte []n,byte []k) + { + return crypto_secretbox_open(m,c,d,n,k); + } + + public static int crypto_box(byte []c,byte []m,int /*long*/ d,byte []n,byte []y,byte []x) + { + byte[] k = new byte[32]; + + ///L/og.d(TAG, "crypto_box start ..."); + + crypto_box_beforenm(k,y,x); + return crypto_box_afternm(c,m,d,n,k); + } + + public static int crypto_box_open(byte []m,byte []c,int /*long*/ d,byte []n,byte []y,byte []x) + { + byte[] k = new byte[32]; + crypto_box_beforenm(k,y,x); + return crypto_box_open_afternm(m,c,d,n,k); + } + + private static final long K[] = { + 0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL, + 0x3956c25bf348b538L, 0x59f111f1b605d019L, 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L, + 0xd807aa98a3030242L, 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L, + 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L, 0xc19bf174cf692694L, + 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L, 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L, + 0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L, + 0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L, + 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L, 0x06ca6351e003826fL, 0x142929670a0e6e70L, + 0x27b70a8546d22ffcL, 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL, + 0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L, 0x92722c851482353bL, + 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L, 0xc24b8b70d0f89791L, 0xc76c51a30654be30L, + 0xd192e819d6ef5218L, 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L, + 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L, + 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL, 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L, + 0x748f82ee5defb2fcL, 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL, + 0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL, + 0xca273eceea26619cL, 0xd186b8c721c0c207L, 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L, + 0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL, + 0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL, + 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL, 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L + }; + + private static int crypto_hashblocks_hl(int [] hh,int [] hl, byte [] m,final int moff, int n) { + + ///String dbgt = ""; + ///for (int dbg = 0; dbg < n; dbg ++) dbgt += " "+m[dbg+moff]; + ///Log.d(TAG, "crypto_hashblocks_hl m/"+n + "-> "+dbgt); + + int [] wh = new int[16], wl = new int[16]; + int bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, h, l, i, j, a, b, c, d; + + int ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], + + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; + + int pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = ((m[j+0+moff]&0xff) << 24) | ((m[j+1+moff]&0xff) << 16) | ((m[j+2+moff]&0xff) << 8) | ((m[j+3+moff]&0xff) << 0); + wl[i] = ((m[j+4+moff]&0xff) << 24) | ((m[j+5+moff]&0xff) << 16) | ((m[j+6+moff]&0xff) << 8) | ((m[j+7+moff]&0xff) << 0); + } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; + + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; + + // add + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // K + ///h = K[i*2]; + ///l = K[i*2+1]; + h = (int) ((K[i]>>>32) & 0xffffffff); + l = (int) ((K[i]>>> 0) & 0xffffffff); + + ///Log.d(TAG, "i"+i + ",h:0x"+Integer.toHexString(h) + ",l:0x"+Integer.toHexString(l)); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // w + h = wh[i%16]; + l = wl[i%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; + + // add + h = th; + l = tl; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); + + // add + h = bh3; + l = bl3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = th; + l = tl; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); + + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; + + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; + + if (i%16 == 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } + + // add + h = ah0; + l = al0; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[0]; + l = hl[0]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); + + h = ah1; + l = al1; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[1]; + l = hl[1]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); + + h = ah2; + l = al2; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[2]; + l = hl[2]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); + + h = ah3; + l = al3; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[3]; + l = hl[3]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); + + h = ah4; + l = al4; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[4]; + l = hl[4]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); + + h = ah5; + l = al5; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[5]; + l = hl[5]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); + + h = ah6; + l = al6; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[6]; + l = hl[6]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); + + h = ah7; + l = al7; + + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + + h = hh[7]; + l = hl[7]; + + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; + + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); + + pos += 128; + n -= 128; + + /*dbgt = ""; + for (int dbg = 0; dbg < hh.length; dbg ++) dbgt += " "+hh[dbg]; + Log.d(TAG, "\ncrypto_hashblocks_hl hh -> "+dbgt); + dbgt = ""; + for (int dbg = 0; dbg < hl.length; dbg ++) dbgt += " "+hl[dbg]; + Log.d(TAG, "\ncrypto_hashblocks_hl hl -> "+dbgt);*/ + } + + return n; + } + + // TBD 64bits of n + ///int crypto_hash(byte [] out, byte [] m, long n) + public static int crypto_hash(byte [] out, byte [] m,final int moff, int n) + { + int [] hh = new int[8], + hl = new int[8]; + byte [] x = new byte[256]; + int i, b = n; + long u; + + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; + + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; + + if (n >= 128) { + crypto_hashblocks_hl(hh, hl, m,moff, n); + n %= 128; + } + + for (i = 0; i < n; i++) x[i] = m[b-n+i +moff]; + x[n] = (byte) 128; + + n = 256-128*(n<112?1:0); + x[n-9] = 0; + + ts64(x, n-8, b<<3/*(b / 0x20000000) | 0, b << 3*/); + + crypto_hashblocks_hl(hh, hl, x,0, n); + + for (i = 0; i < 8; i++) { + u = hh[i]; u <<= 32; u |= hl[i]&0xffffffffL; + ts64(out, 8*i, u); + } + + return 0; + } + public static int crypto_hash(byte [] out, byte [] m) { + return crypto_hash(out, m,0, m!=null? m.length : 0); + } + + // gf: long[16] + ///private static void add(gf p[4],gf q[4]) + private static void add(long [] p[], long [] q[]) + { + long [] a = new long[16]; + long [] b = new long[16]; + long [] c = new long[16]; + long [] d = new long[16]; + long [] t = new long[16]; + long [] e = new long[16]; + long [] f = new long[16]; + long [] g = new long[16]; + long [] h = new long[16]; + + + long [] p0 = p[0]; + long [] p1 = p[1]; + long [] p2 = p[2]; + long [] p3 = p[3]; + + long [] q0 = q[0]; + long [] q1 = q[1]; + long [] q2 = q[2]; + long [] q3 = q[3]; + + Z(a,0, p1,0, p0,0); + Z(t,0, q1,0, q0,0); + M(a,0, a,0, t,0); + A(b,0, p0,0, p1,0); + A(t,0, q0,0, q1,0); + M(b,0, b,0, t,0); + M(c,0, p3,0, q3,0); + M(c,0, c,0, D2,0); + M(d,0, p2,0, q2,0); + + A(d,0, d,0, d,0); + Z(e,0, b,0, a,0); + Z(f,0, d,0, c,0); + A(g,0, d,0, c,0); + A(h,0, b,0, a,0); + + M(p0,0, e,0, f,0); + M(p1,0, h,0, g,0); + M(p2,0, g,0, f,0); + M(p3,0, e,0, h,0); + } + + private static void cswap(long [] p[], long [] q[], byte b) + { + int i; + + for (i = 0; i < 4; i ++) + sel25519(p[i],0, q[i],0, b); + } + + private static void pack(byte [] r, long [] p[]) + { + long [] tx = new long[16]; + long [] ty = new long[16]; + long [] zi = new long[16]; + + inv25519(zi,0, p[2],0); + + M(tx,0, p[0],0, zi,0); + M(ty,0, p[1],0, zi,0); + + pack25519(r, ty,0); + + r[31] ^= par25519(tx,0) << 7; + } + + private static void scalarmult(long [] p[], long [] q[], byte[] s,final int soff) + { + int i; + + set25519(p[0],gf0); + set25519(p[1],gf1); + set25519(p[2],gf1); + set25519(p[3],gf0); + + for (i = 255;i >= 0;--i) { + byte b = (byte) ((s[i/8+soff] >>> (i&7))&1); + + cswap(p,q,b); + add(q,p); + add(p,p); + cswap(p,q,b); + } + + ///String dbgt = ""; + ///for (int dbg = 0; dbg < p.length; dbg ++) for (int dd = 0; dd < p[dbg].length; dd ++) dbgt += " "+p[dbg][dd]; + ///L/og.d(TAG, "scalarmult -> "+dbgt); + } + + private static void scalarbase(long [] p[], byte[] s,final int soff) + { + long [] [] q = new long [4] []; + + q[0] = new long [16]; + q[1] = new long [16]; + q[2] = new long [16]; + q[3] = new long [16]; + + set25519(q[0],X); + set25519(q[1],Y); + set25519(q[2],gf1); + M(q[3],0, X,0, Y,0); + scalarmult(p,q, s,soff); + } + + public static int crypto_sign_keypair(byte [] pk, byte [] sk, boolean seeded) { + byte [] d = new byte[64]; + long [] [] p = new long [4] []; + + p[0] = new long [16]; + p[1] = new long [16]; + p[2] = new long [16]; + p[3] = new long [16]; + + int i; + + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk,0, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d,0); + pack(pk, p); + + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; + } + + private static final long L[] = { + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0x10 + }; + + private static void modL(byte[] r,final int roff, long x[]) + { + long carry; + int i, j; + + for (i = 63;i >= 32;--i) { + carry = 0; + for (j = i - 32;j < i - 12;++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry << 8; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + + for (j = 0; j < 32; j ++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + + for (j = 0; j < 32; j ++) x[j] -= carry * L[j]; + + for (i = 0; i < 32; i ++) { + x[i+1] += x[i] >> 8; + r[i+roff] = (byte) (x[i] & 255); + } + } + + private static void reduce(byte [] r) + { + long[] x = new long [64]; + int i; + + for (i = 0; i < 64; i ++) x[i] = (long) (r[i]&0xff); + + for (i = 0; i < 64; i ++) r[i] = 0; + + modL(r,0, x); + } + + // TBD... 64bits of n + ///int crypto_sign(byte [] sm, long * smlen, byte [] m, long n, byte [] sk) + public static int crypto_sign(byte [] sm, long dummy /* *smlen not used*/, byte [] m,final int moff, int/*long*/ n, byte [] sk) + { + byte[] d = new byte[64], h = new byte[64], r = new byte[64]; + + int i, j; + long [] x = new long[64]; + + long [] [] p = new long [4] []; + p[0] = new long [16]; + p[1] = new long [16]; + p[2] = new long [16]; + p[3] = new long [16]; + + crypto_hash(d, sk,0, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + ///*smlen = n+64; + + for (i = 0; i < n; i ++) sm[64 + i] = m[i+moff]; + + for (i = 0; i < 32; i ++) sm[32 + i] = d[32 + i]; + + crypto_hash(r, sm,32, n+32); + reduce(r); + scalarbase(p, r,0); + pack(sm,p); + + for (i = 0; i < 32; i ++) sm[i+32] = sk[i+32]; + crypto_hash(h, sm,0, n + 64); + reduce(h); + + for (i = 0; i < 64; i ++) x[i] = 0; + + for (i = 0; i < 32; i ++) x[i] = (long) (r[i]&0xff); + + for (i = 0; i < 32; i ++) for (j = 0; j < 32; j ++) x[i+j] += (h[i]&0xff) * (long) (d[j]&0xff); + + modL(sm,32, x); + + return 0; + } + + private static int unpackneg(long [] r[], byte p[]) + { + long [] t = new long [16]; + long [] chk = new long [16]; + long [] num = new long [16]; + long [] den = new long [16]; + long [] den2 = new long [16]; + long [] den4 = new long [16]; + long [] den6 = new long [16]; + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)!=0) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)!=0) return -1; + + if (par25519(r[0]) == ((p[31]&0xFF)>>>7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + + return 0; + } + + /// TBD 64bits of mlen + ///int crypto_sign_open(byte []m,long *mlen,byte []sm,long n,byte []pk) + public static int crypto_sign_open(byte [] m, long dummy /* *mlen not used*/, byte [] sm,final int smoff, int/*long*/ n, byte []pk) + { + int i; + byte[] t = new byte[32], h = new byte[64]; + + long [] [] p = new long [4] []; + p[0] = new long [16]; + p[1] = new long [16]; + p[2] = new long [16]; + p[3] = new long [16]; + + long [] [] q = new long [4] []; + q[0] = new long [16]; + q[1] = new long [16]; + q[2] = new long [16]; + q[3] = new long [16]; + + ///*mlen = -1; + + if (n < 64) return -1; + + if (unpackneg(q,pk)!=0) return -1; + + for (i = 0; i < n; i ++) m[i] = sm[i+smoff]; + + for (i = 0; i < 32; i ++) m[i+32] = pk[i]; + + crypto_hash(h, m,0, n); + + reduce(h); + scalarmult(p,q, h,0); + + scalarbase(q, sm,32+smoff); + add(p,q); + pack(t,p); + + n -= 64; + if (crypto_verify_32(sm,smoff, t,0)!=0) { + // optimizing it + ///for (i = 0; i < n; i ++) m[i] = 0; + return -1; + } + + // TBD optimizing ... + ///for (i = 0; i < n; i ++) m[i] = sm[i + 64 + smoff]; + ///*mlen = n; + + return 0; + } + + /* + * @description + * Java SecureRandom generator + * */ + private static final SecureRandom jrandom = new SecureRandom(); + + public static byte[] randombytes(byte [] x) { + jrandom.nextBytes(x); + return x; + } + + public static byte[] randombytes(int len) { + return randombytes(new byte[len]); + } + + public static byte[] randombytes(byte [] x, int len) { + byte [] b = randombytes(len); + System.arraycopy(b, 0, x, 0, len); + return x; + } + +/* + public static byte[] randombytes(byte [] x, int len) { + int ret = len % 8; + long rnd; + for (int i = 0; i < len-ret; i += 8) { + rnd = jrandom.nextLong(); + x[i+0] = (byte) (rnd >>> 0); + x[i+1] = (byte) (rnd >>> 8); + x[i+2] = (byte) (rnd >>> 16); + x[i+3] = (byte) (rnd >>> 24); + x[i+4] = (byte) (rnd >>> 32); + x[i+5] = (byte) (rnd >>> 40); + x[i+6] = (byte) (rnd >>> 48); + x[i+7] = (byte) (rnd >>> 56); + } + if (ret > 0) { + rnd = jrandom.nextLong(); + for (int i = len-ret; i < len; i ++) + x[i] = (byte) (rnd >>> 8*i); + } + return x; + } +*/ + + public static byte[] makeBoxNonce() { + return randombytes(Box.nonceLength); + } + + public static byte[] makeSecretBoxNonce() { + return randombytes(SecretBox.nonceLength); + } + + public static String hexEncodeToString( byte [] raw ) { + String HEXES = "0123456789ABCDEF"; + final StringBuilder hex = new StringBuilder( 2 * raw.length ); + for ( final byte b : raw ) { + hex.append(HEXES.charAt((b & 0xF0) >> 4)) + .append(HEXES.charAt((b & 0x0F))); + } + return hex.toString(); + } + + public static byte[] hexDecode(String s) { + byte[] b = new byte[s.length() / 2]; + for (int i = 0; i < s.length(); i += 2) { + b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i+1), 16)); + } + return b; + } + + // public static boolean java.util.Arrays.equals(array1, array2); +} diff --git a/app/src/main/java/de/labor_stein/befund/Core/System.java b/app/src/main/java/de/labor_stein/befund/Core/System.java new file mode 100644 index 0000000..92c7971 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Core/System.java @@ -0,0 +1,751 @@ +// +// System.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 13.06.22 +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Core; + +import android.content.Context; +import android.content.res.AssetManager; +import android.os.Build; +import android.os.Environment; + +import java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +import de.labor_stein.befund.Core.Models.System.Device; +import de.labor_stein.befund.Core.Models.System.StorageInfo; + +public class System +{ + public static String ApplicationDirectoryPath = null; + + /** + * Returns path of application directory + * @param context - current context + * @return returns path as string + */ + public static String ApplicationDirectoryPath(Context context) + { + String result = null; + + if(ApplicationDirectoryPath != null) + { + result = ApplicationDirectoryPath; + } + else + { + result = GetInternalStorage(context); + + if(result == null) + { + File file = context.getFilesDir(); + + if(file != null) + { + result = file.getAbsolutePath(); + } + } + + ApplicationDirectoryPath = result; + } + + return result; + } + + /** + * Returns path of settings.json + * @param context - current context + * @return returns path as string + */ + public static String SettingsPath(Context context) + { + return ApplicationDirectoryPath(context) + "/settings.json"; + } + + /** + * Returns path of storage + * @param context - current context + * @return returns path as string + */ + public static String StorageDirectoryPath(Context context) + { + String result = ApplicationDirectoryPath(context) + "/storage"; + + try + { + File fileManager = new File(result); + + if(!fileManager.exists()) + { + fileManager.mkdir(); + } + + if(!fileManager.exists() || !fileManager.isDirectory()) + { + result = null; + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "StorageDirectoryPath(Context)"); + } + + return result; + } + + /** + * Returns path of encrypted path + * @param context - current context + * @return returns path as string + */ + public static String EncryptedStorageDirectoryPath(Context context) + { + String result = StorageDirectoryPath(context) + "/encrypted"; + + try + { + File fileManager = new File(result); + + if(!fileManager.exists()) + { + fileManager.mkdir(); + } + + if(!fileManager.exists() || !fileManager.isDirectory()) + { + result = null; + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "EncryptedStorageDirectoryPath(Context)"); + } + + return result; + } + + /** + * Returns path of databases directory + * @param context - current context + * @return returns directory path as string + */ + public static String DatabaseDirectoryPath(Context context) + { + String result = ApplicationDirectoryPath(context) + "/databases"; + + try + { + File fileManager = new File(result); + + if(!fileManager.exists()) + { + fileManager.mkdir(); + } + + if(!fileManager.exists() || !fileManager.isDirectory()) + { + result = null; + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "DatabaseDirectoryPath(Context)"); + } + + return result; + } + + /** + * Returns path of logs database + * @param context - current context + * @return returns database path as string + */ + public static String LogsDatabasePath(Context context) + { + String result = null; + + try + { + String dbDirectory = DatabaseDirectoryPath(context); + + if(dbDirectory != null && dbDirectory != "") + { + result = dbDirectory + "/logs.db"; + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "LogsDatabasePath(Context)"); + } + + return result; + } + + /** + * Returns path of database + * @param context - current context + * @return returns database path as string + */ + public static String ResultsDatabasePath(Context context) + { + String result = null; + + try + { + String dbDirectory = DatabaseDirectoryPath(context); + + if(dbDirectory != null && dbDirectory != "") + { + result = dbDirectory + "/results.db"; + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "ResultsDatabasePath(Context)"); + } + + return result; + } + + /** + * Checks if file exits at path + * + * @param atPath - filename that should be checked + * @return returns true if successfully + */ + public static Boolean FileExists(String atPath) + { + if(atPath != null && atPath != "") + { + File file = new File(atPath); + return file.exists(); + } + else + { + return false; + } + } + + /** + * Deletes file at path + * + * @param atPath - filename that should be deleted + * @return returns true if successfully + */ + public static Boolean DeleteFile(String atPath) + { + Boolean result = false; + + try + { + if(atPath != null && atPath != "") + { + File file = new File(atPath); + + if(file.exists()) + { + file.delete(); + } + } + + return !FileExists(atPath); + } + catch(Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "DeleteFile(String)"); + } + + return result; + } + + /** + * Writes content to the file + * + * @param filename - filename of storage + * @param context - current context + * @return returns byte array + */ + public static Boolean WriteToStorage(String filename, byte[] data, Context context) + { + Boolean result = false; + + try + { + String storageDirectory = StorageDirectoryPath(context); + + if(storageDirectory != null && storageDirectory != "") + { + String filePath = storageDirectory + "/" + filename; + + if(filePath != null && filePath != "") + { + if(FileExists(filePath)) + { + DeleteFile(filePath); + } + + FileOutputStream out = new FileOutputStream(filePath); + out.write(data); + out.close(); + + result = true; + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "WriteToStorage(String, byte[], Context)"); + } + + return result; + } + + /** + * Writes content to the file + * + * @param filename - filename of encrypted file storage + * @param context - current context + * @return returns byte array + */ + public static Boolean WriteToEncryptedStorage(String filename, byte[] data, Context context) + { + Boolean result = false; + + try + { + String storageDirectory = EncryptedStorageDirectoryPath(context); + + if(storageDirectory != null && storageDirectory != "") + { + String filePath = storageDirectory + "/" + filename; + + if(filePath != null && filePath != "") + { + if(FileExists(filePath)) + { + DeleteFile(filePath); + } + + FileOutputStream out = new FileOutputStream(filePath); + out.write(data); + out.close(); + + result = true; + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "WriteToEncryptedStorage(String, byte[], Context)"); + } + + return result; + } + + /** + * Reads content of file as byte array + * + * @param filename - filename of storage file + * @param context - current context + * @return returns byte array + */ + public static byte[] ReadFromStorage(String filename, Context context) + { + byte[] result = null; + + try + { + String storageDirectory = StorageDirectoryPath(context); + + if(storageDirectory != null && storageDirectory != "") + { + String filePath = storageDirectory + "/" + filename; + File file = new File(filePath); + + if(file.exists() && file.canRead()) + { + result = new byte[(int) file.length()]; + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + DataInputStream dis = new DataInputStream(bis); + dis.readFully(result); + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "ReadFromStorage(String, Context)"); + } + + return result; + } + + /** + * Reads content of encrypted file as byte array + * + * @param filename - filename of encrypted file + * @param context - current context + * @return returns byte array + */ + public static byte[] ReadFromEncryptedStorage(String filename, Context context) + { + byte[] result = null; + + try + { + String storageDirectory = EncryptedStorageDirectoryPath(context); + + if(storageDirectory != null && storageDirectory != "") + { + String filePath = storageDirectory + "/" + filename; + File file = new File(filePath); + + if(file.exists() && file.canRead()) + { + result = new byte[(int) file.length()]; + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + DataInputStream dis = new DataInputStream(bis); + dis.readFully(result); + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "ReadFromEncryptedStorage(String, Context)"); + } + + return result; + } + + /** + * Returns file path from storage + * @param filename - filename in storage + * @param context - current context + * @return retunrs path as string + */ + public static String GetPathForStorageFile(String filename, Context context) + { + String result = null; + + try + { + if(filename != null) + { + String storageDirectory = StorageDirectoryPath(context); + + if(storageDirectory != null && storageDirectory != "") + { + result = storageDirectory + "/" + filename; + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "GetPathForStorageFile(String, Context)"); + } + + return result; + } + + /** + * Returns path for encrypted file + * + * @param filename - filename in the encrypted storage + * @param context - current context + * @return returns path as string + */ + public static String GetPathForStorageEncryptedFile(String filename, Context context) + { + String result = null; + + try + { + if(filename != null) + { + String storageDirectory = EncryptedStorageDirectoryPath(context); + + if(storageDirectory != null && storageDirectory != "") + { + result = storageDirectory + "/" + filename; + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "GetPathForStorageEncryptedFile(String, Context)"); + } + + return result; + } + + /** + * Returns all files from encrypted storage + * + * @param context - current context + * @return returns list of files + */ + public static List GetEncryptedFiles(Context context) + { + List result = null; + + try + { + String path = EncryptedStorageDirectoryPath(context); + + result = Files.walk(Paths.get(path)) + .filter(Files::isRegularFile) + .map(Path::toFile) + .collect(Collectors.toList()); + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "GetEncryptedFiles(String, Context)"); + } + + return result; + } + + /** + * Returns all oegd files from storage + * + * @param context - current context + * @return returns list of files + */ + public static List GetOEGDFiles(Context context) + { + List result = null; + + try + { + String path = StorageDirectoryPath(context); + + List files = Files.walk(Paths.get(path)) + .filter(Files::isRegularFile) + .map(Path::toFile) + .collect(Collectors.toList()); + + if(files != null && files.size() > 0) + { + result = new ArrayList<>(); + + for(int i = 0; i < files.size(); i++) + { + File f = files.get(i); + + if(f.getName().toLowerCase().contains(".oegd")) + { + result.add(f); + } + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "GetOEGDFiles(String, Context)"); + } + + return result; + } + + /** + * Returns device info object + * + * @param settings + * @return + */ + public static Device GetDeviceInfo(de.labor_stein.befund.Core.Models.Settings settings) + { + Device result = new Device(); + + if(Build.MANUFACTURER != null && Build.MODEL != null) + { + char firstChar = Build.MANUFACTURER.charAt(0); + result.udid = settings.udid; + result.name = Character.toUpperCase(firstChar) + Build.MANUFACTURER.substring(1) + " (" + Build.MODEL + ")"; + result.manufacturer = Character.toUpperCase(firstChar) + Build.MANUFACTURER.substring(1); + result.model = Build.MODEL; + result.os = Build.VERSION.RELEASE; + } + + return result; + } + + /** + * Returns storage info object + * @param context - current context + * @return returns storage info + */ + public static StorageInfo GetStorageInfo(Context context) + { + StorageInfo result = null; + + String application_directory = ApplicationDirectoryPath(context); + + if(application_directory != null && application_directory != "") + { + File directory = new File(application_directory); + + if(directory.exists()) + { + result = new StorageInfo(); + + result.total = (double)directory.getTotalSpace() / 1000000000; + result.free = (double)directory.getFreeSpace() / 1000000000; + result.used = (result.total - result.free); + } + } + + return result; + } + + /** + * Returns file creation date + * @param atPath - path of file + * @return returns path as string + */ + public static Date GetFileCreationDate(String atPath) + { + if(atPath != null && atPath != "") + { + File file = new File(atPath); + + if(file.exists()) + { + return new Date(file.lastModified()); + } + else + { + return null; + } + } + else + { + return null; + } + } + + /** + * Returns internal storage + * @param context - current context + * @return returns storage path as string + */ + private static String GetInternalStorage(Context context) + { + String result = null; + File[] fileDirs = context.getExternalFilesDirs(null); + + if (fileDirs != null && fileDirs.length > 0) + { + for (File file : fileDirs) + { + if(file != null && Environment.isExternalStorageEmulated(file)) + { + result = file.getAbsolutePath(); + break; + } + } + } + + return result; + } + + /** + * Deletes all files from device + * + * @return returns true if successfully + */ + public static boolean DeleteAllFiles(Context context) + { + boolean result = false; + + try + { + List files = GetEncryptedFiles(context); + + /** delete results **/ + if(files != null && files.size() > 0) + { + for(int i = 0; i < files.size(); i++) + { + File f = files.get(i); + + DeleteFile(f.getPath()); + } + } + + /** Delete oegd´s **/ + List oegds = GetOEGDFiles(context); + + if(oegds != null && oegds.size() > 0) + { + for(int i = 0; i < oegds.size(); i++) + { + File f = files.get(i); + + DeleteFile(f.getPath()); + } + } + + /** Delete logs database **/ + DeleteFile(LogsDatabasePath(context)); + + /** Delete results database **/ + DeleteFile(ResultsDatabasePath(context)); + + /** Delete settubgs **/ + DeleteFile(SettingsPath(context)); + + /** check if successfully deleted **/ + result = !FileExists(SettingsPath(context)); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.System", "DeleteAllFiles"); + } + + return result; + } + + public static byte[] ReadFromAssets(String filename, Context context) + { + byte[] result = null; + + try + { + AssetManager am = context.getAssets(); + + if(am != null) + { + InputStream is = am.open(filename); + + if(is != null) + { + int length = is.available(); + byte[] buffer = new byte[length]; + is.read(buffer); + result = buffer; + is.close(); + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getLocalizedMessage(), "de.labor_stein.befund.Core.System", "ReadFromAssets(String, Context)"); + } + + return result; + } +} diff --git a/app/src/main/java/de/labor_stein/befund/EditOEGDActivity.java b/app/src/main/java/de/labor_stein/befund/EditOEGDActivity.java new file mode 100644 index 0000000..146a634 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/EditOEGDActivity.java @@ -0,0 +1,457 @@ +// +// EditOEGDActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 02.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.app.DatePickerDialog; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.text.Editable; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.Spinner; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.gson.Gson; + +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.UUID; + +import de.labor_stein.befund.Core.Helpers.DateHelper; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.OEGD; +import de.labor_stein.befund.Core.Models.OEGDFile; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.System; + +public class EditOEGDActivity extends AppCompatActivity +{ + /** EditOEGDActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + + /** Controls **/ + private TextView lblEditOEGD; + private TextView EditOEGDActivitylblButtonBack; + private EditText EditOEGDActivity_txtTitle; + private EditText EditOEGDActivity_txtFirstname; + private EditText EditOEGDActivity_txtLastname; + private EditText EditOEGDActivity_txtAdditionLastname; + private EditText EditOEGDActivity_txtPrefix; + private Spinner EditOEGDActivity_txtGenders; + private EditText EditOEGDActivity_txtBirthday; + private DatePickerDialog BirthdayPicker; + private EditText EditOEGDActivity_txtStreet; + private EditText EditOEGDActivity_txtZIP; + private EditText EditOEGDActivity_txtCity; + private EditText EditOEGDActivity_txtTelefon; + + private Button EditOEGDActivity_btnSave; + private TextView EditOEGDActivity_Status; + + /** Buttons **/ + private FloatingActionButton OEGDButtonBack; + + /** List items **/ + private String[] Genders = { Lang.Get("LBL_GENDER"), Lang.Get("LBL_GENDER_M"), Lang.Get("LBL_GENDER_W"), Lang.Get("LBL_GENDER_D"), Lang.Get("LBL_GENDER_X") }; + + /** Current OEGDFile for editing **/ + private OEGDFile CurrentOEGD = null; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_edit_oegd); + + try + { + Bundle parameters = getIntent().getExtras(); + + if(parameters != null) + { + String file = parameters.getString("file"); + + if(file != null) + { + byte[] encrypted_content = System.ReadFromStorage(file, this); + + if(encrypted_content != null) + { + String json = AES.Decrypt(new String(encrypted_content, StandardCharsets.UTF_8), AES.GetKey(Session.DevicePassword)); + + if(json != null) + { + CurrentOEGD = new OEGDFile(); + CurrentOEGD.filename = file; + CurrentOEGD.OEGD = new Gson().fromJson(json, OEGD.class); + } + } + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "EditOEGDActivity", "onCreate"); + } + + this.Initialize(); + } + + /** + * Initializes eIDActivity + */ + private void Initialize() + { + MainContext = this; + Log.Initialize(this); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializeControls(); + + this.InitializeLanguages(); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblEditOEGD.setText(Lang.Get("LBL_EDIT_OEGD")); + EditOEGDActivitylblButtonBack.setText(Lang.Get("BTN_BACK")); + + EditOEGDActivity_txtTitle.setHint(Lang.Get("LBL_TITLE")); + EditOEGDActivity_txtFirstname.setHint(Lang.Get("LBL_FIRSTNAME")); + EditOEGDActivity_txtLastname.setHint(Lang.Get("LBL_LASTNAME")); + EditOEGDActivity_txtAdditionLastname.setHint(Lang.Get("LBL_ADDITION_NAME")); + EditOEGDActivity_txtPrefix.setHint(Lang.Get("LBL_NAME_PREFIX")); + EditOEGDActivity_txtBirthday.setHint(Lang.Get("LBL_BIRTHDAY")); + EditOEGDActivity_txtStreet.setHint(Lang.Get("LBL_STREET")); + EditOEGDActivity_txtZIP.setHint(Lang.Get("LBL_ZIP")); + EditOEGDActivity_txtCity.setHint(Lang.Get("LBL_CITY")); + EditOEGDActivity_txtTelefon.setHint(Lang.Get("LBL_TELEFON")); + EditOEGDActivity_btnSave.setText(Lang.Get("BTN_SAVE")); + } + + /** + * Initializes controls + */ + private void InitializeControls() + { + EditOEGDActivity_btnSave = findViewById(R.id.EditOEGDActivity_btnSave); + + if(this.CurrentOEGD != null && this.CurrentOEGD.OEGD != null) + { + EditOEGDActivity_btnSave.setOnClickListener(v -> { this.EditOEGDActivity_btnSave_Click(); }); + } + + EditOEGDActivity_txtTitle = findViewById(R.id.EditOEGDActivity_txtTitle); + EditOEGDActivity_txtFirstname = findViewById(R.id.EditOEGDActivity_txtFirstname); + EditOEGDActivity_txtLastname = findViewById(R.id.EditOEGDActivity_txtLastname); + EditOEGDActivity_txtAdditionLastname = findViewById(R.id.EditOEGDActivity_txtAdditionLastname); + EditOEGDActivity_txtPrefix = findViewById(R.id.EditOEGDActivity_txtPrefix); + EditOEGDActivity_txtGenders = findViewById(R.id.EditOEGDActivity_txtGenders); + EditOEGDActivity_txtBirthday = findViewById(R.id.EditOEGDActivity_txtBirthday); + EditOEGDActivity_txtStreet = findViewById(R.id.EditOEGDActivity_txtStreet); + EditOEGDActivity_txtZIP = findViewById(R.id.EditOEGDActivity_txtZIP); + EditOEGDActivity_txtCity = findViewById(R.id.EditOEGDActivity_txtCity); + EditOEGDActivity_txtTelefon = findViewById(R.id.EditOEGDActivity_txtTelefon); + EditOEGDActivity_Status = findViewById(R.id.EditOEGDActivity_Status); + + ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, this.Genders); + aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + EditOEGDActivity_txtGenders.setAdapter(aa); + + /** DatePicker **/ + BirthdayPicker = new DatePickerDialog(this, R.style.MySpinnerDatePickerStyle); + BirthdayPicker.getDatePicker().setMaxDate(new Date().getTime()); + BirthdayPicker.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() + { + @Override + public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) + { + Date selectedDate = DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker()); + + if(selectedDate != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); + EditOEGDActivity_txtBirthday.setText(dateFormat.format(selectedDate)); + } + } + }); + + /** Disable directly key insert in the birthday field(it should be set by DatePicker for well formed value) **/ + EditOEGDActivity_txtBirthday.setOnKeyListener((View v, int keyCode, KeyEvent event) -> { return true; }); + + /** Show/Hide DatePicker **/ + EditOEGDActivity_txtBirthday.setOnFocusChangeListener((View v, boolean hasFocus) -> { if(hasFocus) { BirthdayPicker.show(); } }); + EditOEGDActivity_txtBirthday.setOnTouchListener((View v, MotionEvent event) -> { BirthdayPicker.show(); return true; }); + + /** Set the values to the fields **/ + if(this.CurrentOEGD != null && this.CurrentOEGD.OEGD != null) + { + if(this.CurrentOEGD.OEGD.title != null && !this.CurrentOEGD.OEGD.title.isEmpty()) + { + EditOEGDActivity_txtTitle.setText(this.CurrentOEGD.OEGD.title); + } + + EditOEGDActivity_txtFirstname.setText(this.CurrentOEGD.OEGD.first_name); + EditOEGDActivity_txtLastname.setText(this.CurrentOEGD.OEGD.last_name); + + if(this.CurrentOEGD.OEGD.name_addition != null && !this.CurrentOEGD.OEGD.name_addition.isEmpty()) + { + EditOEGDActivity_txtAdditionLastname.setText(this.CurrentOEGD.OEGD.name_addition); + } + + if(this.CurrentOEGD.OEGD.prefix != null && !this.CurrentOEGD.OEGD.prefix.isEmpty()) + { + EditOEGDActivity_txtPrefix.setText(this.CurrentOEGD.OEGD.prefix); + } + + if(this.CurrentOEGD.OEGD.gender.toLowerCase().equals("m")) + { + EditOEGDActivity_txtGenders.setSelection(1); + } + else if(this.CurrentOEGD.OEGD.gender.toLowerCase().equals("w")) + { + EditOEGDActivity_txtGenders.setSelection(2); + } + else if(this.CurrentOEGD.OEGD.gender.toLowerCase().equals("d")) + { + EditOEGDActivity_txtGenders.setSelection(3); + } + else if(this.CurrentOEGD.OEGD.gender.toLowerCase().equals("x")) + { + EditOEGDActivity_txtGenders.setSelection(4); + } + + if(this.CurrentOEGD.OEGD.birthdate != null && !this.CurrentOEGD.OEGD.birthdate.isEmpty()) + { + Date birthday = this.CurrentOEGD.OEGD.GetBirthday(); + + if(birthday != null) + { + int year = DateHelper.GetFullYearFromDate(birthday); + int month = DateHelper.GetFullMonthFromDate(birthday); + int day = DateHelper.GetFullDayFromDate(birthday); + + BirthdayPicker.updateDate(year, month - 1, day); + EditOEGDActivity_txtBirthday.setText(this.CurrentOEGD.OEGD.GetFormatedBirthday()); + } + } + + EditOEGDActivity_txtStreet.setText(this.CurrentOEGD.OEGD.address.street_number); + EditOEGDActivity_txtCity.setText(this.CurrentOEGD.OEGD.address.city); + EditOEGDActivity_txtZIP.setText(this.CurrentOEGD.OEGD.address.zip_code); + + if(this.CurrentOEGD.OEGD.phone != null && !this.CurrentOEGD.OEGD.phone.isEmpty()) + { + EditOEGDActivity_txtTelefon.setText(this.CurrentOEGD.OEGD.phone); + } + } + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.EditOEGDActivityRootLayout); + } + + /** + * Initializes Labels + */ + private void InitializeLabels() + { + lblEditOEGD = ActivityRootLayout.findViewById(R.id.lblEditOEGD); + EditOEGDActivitylblButtonBack = ActivityRootLayout.findViewById(R.id.EditOEGDActivitylblButtonBack); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + OEGDButtonBack = ActivityRootLayout.findViewById(R.id.OEGDButtonBack); + OEGDButtonBack.setOnClickListener(v ->{ OEGDButtonBack_Click(); }); + } + + /** + * Go Back to OEGDActivity + */ + private void OEGDButtonBack_Click() + { + Intent intent = new Intent(this, OEGDActivity.class); + startActivity(intent); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } + + /** + * Save current OEGD + */ + private void EditOEGDActivity_btnSave_Click() + { + try + { + EditOEGDActivity_Status.setText(""); + + if(EditOEGDActivity_txtFirstname.getText() == null || EditOEGDActivity_txtFirstname.getText().toString().isEmpty()) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_FIRSTNAME")); + } + else if(EditOEGDActivity_txtLastname.getText() == null || EditOEGDActivity_txtLastname.getText().toString().isEmpty()) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_LASTNAME")); + } + else if(EditOEGDActivity_txtBirthday.getText() == null || EditOEGDActivity_txtBirthday.getText().toString().isEmpty()) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_BIRTHDAY")); + } + else if(EditOEGDActivity_txtGenders.getSelectedItemPosition() <= 0) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_GENDER")); + } + else if(EditOEGDActivity_txtStreet.getText() == null || EditOEGDActivity_txtStreet.getText().toString().isEmpty()) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_STREET")); + } + else if(EditOEGDActivity_txtZIP.getText() == null || EditOEGDActivity_txtZIP.getText().toString().isEmpty()) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_ZIP")); + } + else if(EditOEGDActivity_txtCity.getText() == null || EditOEGDActivity_txtCity.getText().toString().isEmpty()) + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_CITY")); + } + else + { + OEGD oegd = new OEGD(); + oegd.first_name = EditOEGDActivity_txtFirstname.getText().toString(); + oegd.last_name = EditOEGDActivity_txtLastname.getText().toString(); + + Date selectedDate = DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker()); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + oegd.birthdate = dateFormat.format(selectedDate); + + int genderIndex = (int)EditOEGDActivity_txtGenders.getSelectedItemId(); + String gender_full_name = Genders[genderIndex]; + + if(gender_full_name.equals(Lang.Get("LBL_GENDER_M"))) + { + oegd.gender = "M"; + } + else if(gender_full_name.equals(Lang.Get("LBL_GENDER_W"))) + { + oegd.gender = "W"; + } + else if(gender_full_name.equals(Lang.Get("LBL_GENDER_D"))) + { + oegd.gender = "D"; + } + else + { + oegd.gender = "X"; + } + + if(EditOEGDActivity_txtTitle.getText() != null && !EditOEGDActivity_txtTitle.getText().toString().isEmpty()) + { + oegd.title = EditOEGDActivity_txtTitle.getText().toString(); + } + + if(EditOEGDActivity_txtAdditionLastname.getText() != null && !EditOEGDActivity_txtAdditionLastname.getText().toString().isEmpty()) + { + oegd.name_addition = EditOEGDActivity_txtAdditionLastname.getText().toString(); + } + + if(EditOEGDActivity_txtPrefix.getText() != null && !EditOEGDActivity_txtPrefix.getText().toString().isEmpty()) + { + oegd.prefix = EditOEGDActivity_txtPrefix.getText().toString(); + } + + oegd.address = OEGD.Address.createInstance(); + oegd.address.zip_code = EditOEGDActivity_txtZIP.getText().toString(); + oegd.address.city = EditOEGDActivity_txtCity.getText().toString(); + oegd.address.street_number = EditOEGDActivity_txtStreet.getText().toString(); + oegd.address.country_code = "D"; + oegd.cwa_consent_flag = true; + + if(EditOEGDActivity_txtTelefon.getText() != null && !EditOEGDActivity_txtTelefon.getText().toString().isEmpty()) + { + oegd.phone = EditOEGDActivity_txtTelefon.getText().toString(); + } + + String json = new Gson().toJson(oegd); + + if(json != null) + { + String encrypted_content = AES.Encrypt(json, AES.GetKey(Session.DevicePassword)); + + if(encrypted_content != null) + { + if(System.WriteToStorage(this.CurrentOEGD.filename, encrypted_content.getBytes(StandardCharsets.UTF_8), this)) + { + GoToOEGDActivity(); + } + else + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_COULD_NOT_SAVE_OEGD")); + } + } + else + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_COULD_NOT_SAVE_OEGD")); + } + } + else + { + EditOEGDActivity_Status.setText(Lang.Get("ERROR_COULD_NOT_SAVE_OEGD")); + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "EditOEGDActivity", "EditOEGDActivity_btnCreate_Click"); + } + } + + /** + * Goes back to OEGDActivity + */ + private void GoToOEGDActivity() + { + Intent OEGDActivity = new Intent(this, OEGDActivity.class); + startActivity(OEGDActivity); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/FAQActivity.java b/app/src/main/java/de/labor_stein/befund/FAQActivity.java new file mode 100644 index 0000000..8ffbd11 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/FAQActivity.java @@ -0,0 +1,173 @@ +package de.labor_stein.befund; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.webkit.WebView; +import android.widget.Button; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Settings; +import de.labor_stein.befund.Core.System; + +public class FAQActivity extends AppCompatActivity +{ + /** SupportActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + + /** Controls **/ + private TextView lblFAQActivity; + private TextView lblFAQActivityButtonBack; + + /** Buttons **/ + private FloatingActionButton FAQButtonBack; + + /** WebView **/ + private WebView FAQ_web; + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_faq); + + this.Initialize(); + } + + @Override + protected void onResume() + { + super.onResume(); + this.InitializeLanguages(); + } + + /** + * Initialize LaborActivity + */ + private void Initialize() + { + MainContext = this; + Log.Initialize(this); + + this.InitializeControls(); + this.InitializeLanguages(); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblFAQActivity.setText(Lang.Get("LBL_FAQ")); + lblFAQActivityButtonBack.setText(Lang.Get("BTN_BACK")); + } + + /** + * Initializes Controls + */ + private void InitializeControls() + { + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.FAQActivityRootLayout); + lblFAQActivity = ActivityRootLayout.findViewById(R.id.lblFAQActivity); + lblFAQActivityButtonBack = ActivityRootLayout.findViewById(R.id.lblFAQButtonBack); + FAQButtonBack = ActivityRootLayout.findViewById(R.id.FAQButtonBack); + + FAQ_web = ActivityRootLayout.findViewById(R.id.FAQ_web); + + FAQButtonBack.setOnClickListener(v ->{ FAQButtonBack_Click(); }); + + this.LoadFAQ(); + } + + /** + * Load FAQ + */ + private void LoadFAQ() + { + try + { + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.GetResponseAsync(Settings.GetFAQURL(), + "GET", + (content) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + FAQ_web.loadUrl(Settings.GetFAQURL()); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { +// byte[] local_faq_data = System.ReadFromAssets("faq.html", MainContext); +// +// if(local_faq_data != null && local_faq_data.length > 0) +// { +// FAQ_web.loadData(new String(local_faq_data), "text/html", "utf-8"); +// } + byte[] local_data = System.ReadFromAssets("no_connection.html", MainContext); + + if(local_data != null && local_data.length > 0) + { + String html = new String(local_data); + html = html.replace("[NO_CONNECTION]", Lang.Get("ERROR_FAQ_NEEDS_CONNECTION")); + FAQ_web.loadData(html, "text/html", "utf-8"); + } + } + }); + }); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "FAQActivity", "LoadFAQ"); + } + } + + /** + * Go Back to MainActivity + */ + private void FAQButtonBack_Click() + { + this.finish(); +// Intent intent = new Intent(this, MainActivity.class); +// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); +// Bundle parameters = new Bundle(); +// parameters.putBoolean("SplashScreenLoaded", true); +// intent.putExtras(parameters); +// startActivity(intent); +// overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } +} diff --git a/app/src/main/java/de/labor_stein/befund/LaborActivity.java b/app/src/main/java/de/labor_stein/befund/LaborActivity.java new file mode 100644 index 0000000..985e6f8 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/LaborActivity.java @@ -0,0 +1,491 @@ +// +// LaborActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 04.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.Manifest; +import android.os.Build; +import android.app.AlertDialog; +import android.app.NotificationManager; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.viewpager.widget.PagerAdapter; +import androidx.viewpager.widget.ViewPager; + +import com.journeyapps.barcodescanner.ScanContract; +import com.journeyapps.barcodescanner.ScanOptions; + +import java.util.List; + +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Labor; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Models.Settings; + +public class LaborActivity extends AppCompatActivity +{ + /** MainActivityContext **/ + private Context MainContext; + private AppCompatActivity CurrentActivity; + + /** ViewPager **/ + private ViewPager Pager; + private PagerAdapter Adapter; + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + /** PERMISSION FLAGS **/ + private static int CAMERA_PERMISSION = 1000; + private static int POST_NOTIFICATIONS_PERMISSION = 1000; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_labor); + + CurrentActivity = this; + + this.Initialize(); + } + + /** + * Initialize LaborActivity + */ + private void Initialize() + { + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + Lang.SetLanguage(this.Settings.lang); + + Pager = (ViewPager) findViewById(R.id.LaborPager); + Adapter = new LaborPagerAdapter(getSupportFragmentManager(), Labor.Labors(), this); + Pager.setAdapter(Adapter); + + TextView lblSelectLabor = findViewById(R.id.lblSelectLabor); + lblSelectLabor.setText(Lang.Get("LBL_SELECT_LABOR")); + + this.RequestAuthorizations(); + //this.RequestPushNotification(); + } + + /** + * Check necessary permission if already granted + */ + private void RequestAuthorizations() + { + + int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); + + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) + { + if (result != PackageManager.PERMISSION_GRANTED) + { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); + alertBuilder.setCancelable(true); + alertBuilder.setTitle(Lang.Get("MSG_CAMERA_PERMISSION_TITLE")); + alertBuilder.setMessage(Lang.Get("MSG_CAMERA_PERMISSION_MSG")); + alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + ActivityCompat.requestPermissions(CurrentActivity, new String[] { Manifest.permission.CAMERA }, CAMERA_PERMISSION); + } + }); + AlertDialog alert = alertBuilder.create(); + alert.show(); + } + else + { + Session.CameraGranted = true; + } + } + else + { + if (result != PackageManager.PERMISSION_GRANTED) + { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); + alertBuilder.setCancelable(true); + alertBuilder.setTitle(Lang.Get("MSG_CAMERA_PERMISSION_TITLE")); + alertBuilder.setMessage(Lang.Get("MSG_CAMERA_PERMISSION_MSG")); + alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + ActivityCompat.requestPermissions(CurrentActivity, new String[] { Manifest.permission.CAMERA }, CAMERA_PERMISSION); + } + }); + AlertDialog alert = alertBuilder.create(); + alert.show(); + } + else + { + Session.CameraGranted = true; + } + } + } + + private void RequestPushNotification() { + if (Build.VERSION.SDK_INT >= 33) { + int result = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS); + + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.POST_NOTIFICATIONS)) { + if (result != PackageManager.PERMISSION_GRANTED) { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); + alertBuilder.setCancelable(true); + alertBuilder.setTitle(Lang.Get("MSG_POST_NOTIFICATION_PERMISSION_TITLE")); + alertBuilder.setMessage(Lang.Get("MSG_POST_NOTIFICATION_MSG")); + alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + ActivityCompat.requestPermissions(CurrentActivity, new String[]{Manifest.permission.POST_NOTIFICATIONS}, POST_NOTIFICATIONS_PERMISSION); + } + }); + AlertDialog alert = alertBuilder.create(); + alert.show(); + } else { + Session.NotificationGranted = true; + } + } else { + if (result != PackageManager.PERMISSION_GRANTED) { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); + alertBuilder.setCancelable(true); + alertBuilder.setTitle(Lang.Get("MSG_POST_NOTIFICATIONS_PERMISSION_TITLE")); + alertBuilder.setMessage(Lang.Get("MSG_POST_NOTIFICATIONS_PERMISSION_MSG")); + alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + ActivityCompat.requestPermissions(CurrentActivity, new String[]{Manifest.permission.POST_NOTIFICATIONS}, POST_NOTIFICATIONS_PERMISSION); + } + }); + AlertDialog alert = alertBuilder.create(); + alert.show(); + } else { + Session.CameraGranted = true; + } + } + } + } + + /** + * Saves selected labor + * + * @param labor + */ + public void SelectLabor(Labor labor) + { + try + { + if(this.Settings == null) + { + this.Settings = new Settings(); + this.Settings.lang = Lang.GetSystemLang(); + } + + this.Settings.labor = labor; + this.Settings.save(this); + + this.GoToSplashScreen(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LaborActivity", "SelectLabor(Labor)"); + } + } + + /** Launches camera to get qr code **/ + private final ActivityResultLauncher barcodeLauncher = registerForActivityResult(new ScanContract(), + result -> + { + try + { + if(result.getContents() != null) + { + String url = result.getContents().toString(); + + if(url != null && !url.isEmpty()) + { + int indexOfId = url.lastIndexOf("id="); + + if(indexOfId > 0) + { + String id = url.substring(indexOfId).replace("id=", ""); + + if(id != null && !id.isEmpty()) + { + Labor labor = Labor.GetLaborByName(id); + + if(labor != null) + { + this.SelectLabor(labor); + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_QRCODE"), Toast.LENGTH_SHORT).show(); + } + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_QRCODE"), Toast.LENGTH_SHORT).show(); + } + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_QRCODE"), Toast.LENGTH_SHORT).show(); + } + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_QRCODE"), Toast.LENGTH_SHORT).show(); + } + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_QRCODE"), Toast.LENGTH_SHORT).show(); + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LaborActivity", "SelectLaborOverQRCode(Labor)"); + } + }); + + /** + * Selects labor over QR-Code + */ + public void SelectLaborOverQRCode() + { + try + { + ScanOptions options = new ScanOptions(); + options.setDesiredBarcodeFormats(ScanOptions.QR_CODE); + options.setBeepEnabled(false); + options.setBarcodeImageEnabled(true); + options.setOrientationLocked(true); + barcodeLauncher.launch(options); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LaborActivity", "SelectLaborOverQRCode(Labor)"); + } + } + + /** + * Goes to splash activity + */ + private void GoToSplashScreen() + { + Intent splashActivity = new Intent(this, SplashActivity.class); + splashActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(splashActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + finish(); + } + + @Override + public void onBackPressed() + { + if (Pager.getCurrentItem() == 0) + { + super.onBackPressed(); + } + else + { + Pager.setCurrentItem(Pager.getCurrentItem() - 1); + } + } + + /** Gots asked permission results **/ + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) + { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + + /** got status of camera permission **/ + if (requestCode == CAMERA_PERMISSION) + { + if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) + { + Session.CameraGranted = true; + } + } + } + + /** LaborCard Fragment **/ + public static class LaborFragment extends Fragment + { + /** LaborActivity Context **/ + private LaborActivity LaborActivity; + + /** Labor object **/ + private Labor Labor; + + /** Constructor for labor fragment **/ + public LaborFragment(Labor labor, LaborActivity laborActivity) + { + this.Labor = labor; + this.LaborActivity = laborActivity; + } + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + View view = inflater.inflate(R.layout.fragment_labor, container, false); + ImageView logo = view.findViewById(R.id.fragment_labor_icon); + logo.setImageResource(this.Labor.logo); + TextView name = view.findViewById(R.id.fragment_labor_name); + name.setText(this.Labor.name); + + TextView street = view.findViewById(R.id.fragment_labor_street); + + if(this.Labor.street != null && !this.Labor.street.isEmpty()) + { + street.setText(this.Labor.street); + } + + TextView city = view.findViewById(R.id.fragment_labor_city); + + if(this.Labor.city != null && !this.Labor.city.isEmpty() && this.Labor.zip != null && !this.Labor.zip.isEmpty()) + { + city.setText(this.Labor.zip + " " + this.Labor.city); + } + + TextView tel = view.findViewById(R.id.fragment_labor_tel); + + if(this.Labor.tel != null && !this.Labor.tel.isEmpty()) + { + tel.setText(this.Labor.tel); + } + + TextView web = view.findViewById(R.id.fragment_labor_web); + + if(this.Labor.web != null && !this.Labor.web.isEmpty()) + { + web.setText(this.Labor.web); + } + + Button btnSelect = view.findViewById(R.id.fragment_labor_btnSelect); + btnSelect.setText(Lang.Get("BTN_SELECT")); + btnSelect.setOnClickListener(v -> { this.LaborActivity.SelectLabor(this.Labor); }); + + return view; + } + + /** Creates a new instance of fragment **/ + public static LaborFragment newInstance(Labor labor, LaborActivity laborActivity) + { + return new LaborFragment(labor, laborActivity); + } + } + + /** Fragment to select a labor over qrcode **/ + public static class LaborQRCodeSelectFragment extends Fragment + { + /** LaborActivity Context **/ + private LaborActivity LaborActivity; + + /** Constructor for labor fragment **/ + public LaborQRCodeSelectFragment(LaborActivity laborActivity) + { + this.LaborActivity = laborActivity; + } + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + View view = inflater.inflate(R.layout.fragment_labor_qrcode_select, container, false); + ImageView buttonQRCodeScan = view.findViewById(R.id.fragment_labor_btn_qr_code); + + TextView lblScanQrCode = view.findViewById(R.id.fragment_labor_lbl_scan_qr_code); + lblScanQrCode.setText(Lang.Get("LBL_SCAN_QR_CODE")); + + TextView lblSelectManuel = view.findViewById(R.id.fragment_labor_lbl_select_manuel); + lblSelectManuel.setText(Lang.Get("LBL_SELECT_LABOR_MANUEL")); + + buttonQRCodeScan.setOnClickListener(v -> { this.LaborActivity.SelectLaborOverQRCode(); } ); + return view; + } + + /** Creates a new instance of fragment **/ + public static LaborQRCodeSelectFragment newInstance(LaborActivity laborActivity) + { + return new LaborQRCodeSelectFragment(laborActivity); + } + } + + /** LaborSwitcher Adapter **/ + private class LaborPagerAdapter extends FragmentPagerAdapter + { + /** List of labors**/ + private List Labors = null; + + /** LaborActivity Context **/ + private LaborActivity LaborActivity; + + public LaborPagerAdapter(FragmentManager fragmentManager, List labors, LaborActivity laborActivity) + { + super(fragmentManager); + this.Labors = labors; + this.LaborActivity = laborActivity; + } + + @Override + public int getCount() + { + return 1; + } + + @Override + public Fragment getItem(int position) + { + if(position == 0) + { + return LaborQRCodeSelectFragment.newInstance(this.LaborActivity); + } + else + { + return LaborFragment.newInstance(this.Labors.get(position - 1), this.LaborActivity); + } + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/LoginActivity.java b/app/src/main/java/de/labor_stein/befund/LoginActivity.java new file mode 100644 index 0000000..ff23999 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/LoginActivity.java @@ -0,0 +1,996 @@ +// +// LoginActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 05.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.text.InputType; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.webkit.WebView; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.biometric.BiometricPrompt; +import androidx.constraintlayout.widget.ConstraintLayout; +import androidx.core.content.ContextCompat; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.Executor; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.Results; +import de.labor_stein.befund.Core.Models.Request.ChangeVerificatorHash; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Request.GetPIN; +import de.labor_stein.befund.Core.Models.Response.PIN; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Curve25519; +import de.labor_stein.befund.Core.Security.SHA512; +import de.labor_stein.befund.Core.System; + +public class LoginActivity extends AppCompatActivity +{ + /** LoginActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private ConstraintLayout LoginActivityRootLayout; + + /** Controls **/ + private ImageView loginLaborLogo; + private EditText loginPasswordView_txtPassword; + private ImageView loginPasswordView_txtPasswordViewer; + private Button loginPasswordView_btnLogin; + private Button loginPasswordView_btnPasswordReset; + private Button loginPasswordView_btnSupport; + private TextView loginPasswordStatus; + private TextView LoginActivity_PrivacyPolicy; + + /** BEGIN POPUPS **/ + + /** BEGIN Popup PrivacyPolicy **/ + private PopupWindow PopupPrivacyPolicy; + private TextView PopupPrivacyPolicy_lblHeader; + private Button PopupPrivacyPolicy_btnAcceptPrivacyPolicy; + private WebView PopupPrivacyPolicy_web; + /** END Popup PrivacyPolicy **/ + + /** BEGIN PopupPasswordReset **/ + private PopupWindow PopupPasswordReset; + private View PopupPasswordReset_Overlay; + private LinearLayout PopupPasswordReset_Popup; + private EditText PopupPasswordReset_txtPIN; + private EditText PopupPasswordReset_txtNewPassword; + private ImageView PopupPasswordReset_txtNewPasswordViewer; + private EditText PopupPasswordReset_txtPasswordConfirm; + private ImageView PopupPasswordReset_txtPasswordConfirmViewer; + private EditText PopupPasswordReset_txtNewPIN; + private TextView PopupPasswordReset_Status; + private ProgressBar PopupPasswordReset_Loading; + private Button PopupPasswordReset_BtnChange; + private Button PopupPasswordReset_BtnRequestPIN; + private Button PopupPasswordReset_BtnCancel; + /** END PopupPasswordReset **/ + + /** END POPUPS **/ + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + /** Database Contexts **/ + private de.labor_stein.befund.Core.Database.Results dbResults; + private de.labor_stein.befund.Core.Database.Logs dbLogs; + + private boolean IsPasswordChanging = false; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_login); + + this.Initialize(); + } + + @Override + protected void onResume() + { + super.onResume(); + this.InitializeLanguages(); + } + + /** + * Initialize LoginActivity Activity + */ + private void Initialize() + { + MainContext = this; + this.IsPasswordChanging = false; + + this.dbResults = new de.labor_stein.befund.Core.Database.Results(this); + this.dbLogs = new de.labor_stein.befund.Core.Database.Logs(this); + Log.Initialize(this); + + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + Log.Initialize(this); + + this.InitializeControls(); + this.InitializePopups(); + + this.InitializeLanguages(); + } + + private void InitializePopups() + { + this.InitializePopupPasswordReset(); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + Lang.SetLanguage(this.Settings.lang); + + PopupPasswordReset_txtPIN.setHint(Lang.Get("LBL_PIN")); + PopupPasswordReset_txtNewPassword.setHint(Lang.Get("LBL_NEW_PASSWORD")); + PopupPasswordReset_txtPasswordConfirm.setHint(Lang.Get("LBL_NEW_PASSWORD_CONFIRM")); + PopupPasswordReset_txtNewPIN.setHint(Lang.Get("LBL_NEW_PIN")); + PopupPasswordReset_BtnChange.setText(Lang.Get("BTN_CHANGE")); + PopupPasswordReset_BtnRequestPIN.setText(Lang.Get("BTN_PIN_REQUEST")); + PopupPasswordReset_BtnCancel.setText(Lang.Get("BTN_CANCEL")); + loginPasswordView_txtPassword.setHint(Lang.Get("LBL_PASSWORD")); + loginPasswordView_btnPasswordReset.setText(Lang.Get("BTN_FORGOT")); + loginPasswordView_btnSupport.setText(Lang.Get("BTN_SUPPORT")); + loginPasswordView_btnLogin.setText(Lang.Get("BTN_LOGIN")); + LoginActivity_PrivacyPolicy.setText(Lang.Get("BTN_PRIVACY_POLICY")); + } + + /** + * INitializes Controls + */ + private void InitializeControls() + { + LoginActivityRootLayout = findViewById(R.id.LoginActivityRootLayout); + loginPasswordView_txtPassword = findViewById(R.id.loginPasswordView_txtPassword); + loginPasswordView_txtPasswordViewer = findViewById(R.id.loginPasswordView_txtPasswordViewer); + loginPasswordView_btnPasswordReset = findViewById(R.id.loginPasswordView_btnPasswordReset); + loginPasswordView_btnSupport = findViewById(R.id.loginPasswordView_btnSupport); + loginPasswordView_btnLogin = findViewById(R.id.loginPasswordView_btnLogin); + loginPasswordStatus = findViewById(R.id.loginPasswordStatus); + + loginLaborLogo = findViewById(R.id.loginLaborLogo); + loginLaborLogo.setVisibility(View.VISIBLE); + loginLaborLogo.setImageResource(Settings.labor.logo); + + loginPasswordView_btnLogin.setOnClickListener(v -> { this.loginPasswordView_btnLogin_Click(); }); + + loginPasswordView_txtPassword.setOnKeyListener(new View.OnKeyListener() + { + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) + { + if(keyCode == KeyEvent.KEYCODE_ENTER) + { + loginPasswordView_btnLogin_Click(); + } + + return false; + } + }); + + loginPasswordView_btnSupport.setOnClickListener(v -> { this.GoToSupportActivity(); }); + + /** Password Viewers **/ + loginPasswordView_txtPasswordViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + loginPasswordView_txtPasswordViewer.setAlpha(1.0f); + loginPasswordView_txtPassword.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + loginPasswordView_txtPassword.setSelection(loginPasswordView_txtPassword.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + loginPasswordView_txtPasswordViewer.setAlpha(0.5f); + loginPasswordView_txtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + loginPasswordView_txtPassword.setSelection(loginPasswordView_txtPassword.getText().length()); + } + + return true; + } + }); + + LoginActivity_PrivacyPolicy = LoginActivityRootLayout.findViewById(R.id.LoginActivity_PrivacyPolicy); + LoginActivity_PrivacyPolicy.setVisibility(View.INVISIBLE); + +// LoginActivity_PrivacyPolicy.setOnClickListener(new View.OnClickListener() +// { +// @Override +// public void onClick(View v) { +// ShowPrivacyPolicy(); +// } +// }); + } + + /** Shows privacy policy popup**/ + private void ShowPrivacyPolicy() + { + this.InitializePrivacyPolicyPopup(); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_CLOSE")); + this.LoadPrivacyPolicy(); + } + + /** + * Initializes PrivacyPolicy Popup + */ + private void InitializePrivacyPolicyPopup() + { + Lang.SetLanguage(Lang.GetSystemLang()); + + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + View PopupPrivacyPolicyView = inflater.inflate(R.layout.popup_privacy_policy, null); + + PopupPrivacyPolicy_lblHeader = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_lblHeader); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_btnAccept); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(false); + PopupPrivacyPolicy_lblHeader.setText(Lang.Get("LBL_PRIVACY_POLICY")); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_ACCEPT_PRIVACY_POLICY")); + + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setOnClickListener((v) -> + { + PopupPrivacyPolicy.dismiss(); + }); + + /** Create popup window context **/ + PopupPrivacyPolicy = new PopupWindow( + PopupPrivacyPolicyView, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + + PopupPrivacyPolicy_web = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_web); + + this.LoginActivityRootLayout.post(new Runnable() + { + public void run() + { + LoadPrivacyPolicy(); + PopupPrivacyPolicy.showAtLocation(LoginActivityRootLayout, Gravity.CENTER,0,0); + } + }); + } + + /** + * Load PrivacyPolicy + */ + private void LoadPrivacyPolicy() + { + try + { + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.GetResponseAsync(Settings.GetPrivacyPolicyURL(), + "GET", + (content) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPrivacyPolicy_web.loadUrl(Settings.GetPrivacyPolicyURL()); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + + byte[] local_privacy_policy_data = System.ReadFromAssets("no_connection.html", MainContext); + + if(local_privacy_policy_data != null && local_privacy_policy_data.length > 0) + { + String html = new String(local_privacy_policy_data); + html = html.replace("[NO_CONNECTION]", Lang.Get("ERROR_PRIVACY_POLICY_NEEDS_CONNECTION")); + PopupPrivacyPolicy_web.loadData(html, "text/html", "utf-8"); + } + } + }); + }); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LoginActivity", "LoadPrivacyPolicy"); + } + } + + /** + * Initializes PopupPasswordReset Popup + */ + private void InitializePopupPasswordReset() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + PopupPasswordReset_Overlay = inflater.inflate(R.layout.popup_password_reset, null); + PopupPasswordReset_Popup = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_Popup); + PopupPasswordReset_txtPIN = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_txtPIN); + PopupPasswordReset_txtNewPassword = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_txtNewPassword); + PopupPasswordReset_txtNewPasswordViewer = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_txtNewPasswordViewer); + PopupPasswordReset_txtPasswordConfirm = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_txtPasswordConfirm); + PopupPasswordReset_txtPasswordConfirmViewer = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_txtPasswordConfirmViewer); + PopupPasswordReset_txtNewPIN = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_txtNewPIN); + PopupPasswordReset_BtnChange = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_BtnChange); + PopupPasswordReset_BtnRequestPIN = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_BtnRequestPIN); + PopupPasswordReset_BtnCancel = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_BtnCancel); + + PopupPasswordReset_Status = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_Status); + PopupPasswordReset_Loading = PopupPasswordReset_Overlay.findViewById(R.id.PopupPasswordReset_Loading); + PopupPasswordReset_Loading.setVisibility(View.INVISIBLE); + + PopupPasswordReset_BtnChange.setOnClickListener(v -> { this.ChangePassword(); }); + PopupPasswordReset_BtnRequestPIN.setOnClickListener(v -> { this.RequestPIN(); }); + loginPasswordView_btnPasswordReset.setOnClickListener(v -> { this.PopupPasswordReset_Show(); }); + PopupPasswordReset_BtnCancel.setOnClickListener(v -> { this.PopupPasswordReset_Hide(); }); + + PopupPasswordReset_txtNewPassword.setOnFocusChangeListener((View v, boolean hasFocus) -> { if(hasFocus) { PopupPasswordReset_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); } }); + PopupPasswordReset_txtPIN.setOnFocusChangeListener((View v, boolean hasFocus) -> { if(hasFocus) { PopupPasswordReset_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); } }); + PopupPasswordReset_txtNewPIN.setOnFocusChangeListener((View v, boolean hasFocus) -> { if(hasFocus) { PopupPasswordReset_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); } }); + + /** Create popup window context **/ + PopupPasswordReset = new PopupWindow( + PopupPasswordReset_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + + /** Password Viewers **/ + PopupPasswordReset_txtNewPasswordViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PopupPasswordReset_txtNewPasswordViewer.setAlpha(1.0f); + PopupPasswordReset_txtNewPassword.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PopupPasswordReset_txtNewPassword.setSelection(PopupPasswordReset_txtNewPassword.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PopupPasswordReset_txtNewPasswordViewer.setAlpha(0.5f); + PopupPasswordReset_txtNewPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PopupPasswordReset_txtNewPassword.setSelection(PopupPasswordReset_txtNewPassword.getText().length()); + } + + return true; + } + }); + + PopupPasswordReset_txtPasswordConfirmViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PopupPasswordReset_txtPasswordConfirmViewer.setAlpha(1.0f); + PopupPasswordReset_txtPasswordConfirm.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PopupPasswordReset_txtPasswordConfirm.setSelection(PopupPasswordReset_txtPasswordConfirm.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PopupPasswordReset_txtPasswordConfirmViewer.setAlpha(0.5f); + PopupPasswordReset_txtPasswordConfirm.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PopupPasswordReset_txtPasswordConfirm.setSelection(PopupPasswordReset_txtPasswordConfirm.getText().length()); + } + + return true; + } + }); + } + + + /** + * Show PopupPasswordReset + */ + private void PopupPasswordReset_Show() + { + PopupPasswordReset_txtPIN.setText(""); + PopupPasswordReset_txtNewPassword.setText(""); + PopupPasswordReset_txtPasswordConfirm.setText(""); + PopupPasswordReset_txtNewPIN.setText(""); + PopupPasswordReset_Status.setText(""); + PopupPasswordReset_Loading.setVisibility(View.INVISIBLE); + + PopupPasswordReset_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + PopupPasswordReset_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!PopupPasswordReset.isShowing()) + { + PopupPasswordReset.showAtLocation(LoginActivityRootLayout, Gravity.CENTER,0,0); + } + + if(!BiometricAuthenticationSupported()) + { + PopupPasswordReset_BtnRequestPIN.setVisibility(View.INVISIBLE); + } + } + + /** + * Hide PopupPasswordReset + */ + private void PopupPasswordReset_Hide() + { + PopupPasswordReset_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + PopupPasswordReset_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(PopupPasswordReset.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PopupPasswordReset.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PopupPasswordReset_Popup.startAnimation(anim); + } + } + + /** BEGIN FUNCTIONS **/ + + /** Hide PopupPasswordReset Loading with optional status message **/ + private void PopupPasswordReset_HideLoading(String message) + { + PopupPasswordReset_Loading.setVisibility(View.INVISIBLE); + + if(message != null && !message.isEmpty()) + { + PopupPasswordReset_Status.setText(message); + } + } + + /** + * Changes password with pin + * */ + private void ChangePassword() + { + try + { + PopupPasswordReset_Status.setText(""); + + if(!this.IsPasswordChanging) + { + this.IsPasswordChanging = true; + PopupPasswordReset_Loading.setVisibility(View.VISIBLE); + + if(PopupPasswordReset_txtPIN.getText() == null || PopupPasswordReset_txtPIN.getText().toString().isEmpty()) + { + this.IsPasswordChanging = false; + PopupPasswordReset_HideLoading(Lang.Get("ERROR_ENTER_YOUR_PIN")); + } + else if(PopupPasswordReset_txtPIN.getText().toString().length() != 5) + { + this.IsPasswordChanging = false; + PopupPasswordReset_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); + } + else + { + String pin = PopupPasswordReset_txtPIN.getText().toString(); + String old_password = AES.Decrypt(this.Settings.password_hash, AES.GetKey(this.Settings.password_reset_hash + pin)); + + if(old_password != null) + { + String password_policy = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!+@$%^&<>*~:`-]).{8,}$"; + + if(!PopupPasswordReset_txtNewPassword.getText().toString().matches(password_policy)) + { + this.IsPasswordChanging = false; + PopupPasswordReset_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); + } + else if(!PopupPasswordReset_txtNewPassword.getText().toString().equals(PopupPasswordReset_txtPasswordConfirm.getText().toString())) + { + this.IsPasswordChanging = false; + PopupPasswordReset_HideLoading(Lang.Get("ERROR_CONFIRM_PASSWORD")); + } + else if(PopupPasswordReset_txtNewPIN.getText() == null || PopupPasswordReset_txtNewPIN.getText().toString().isEmpty()) + { + this.IsPasswordChanging = false; + PopupPasswordReset_HideLoading(Lang.Get("ERROR_ENTER_NEW_PIN")); + } + else if(PopupPasswordReset_txtNewPIN.getText().toString().length() != 5) + { + this.IsPasswordChanging = false; + PopupPasswordReset_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); + } + else + { + String new_password = PopupPasswordReset_txtNewPassword.getText().toString(); + String decrypted_private_key = AES.Decrypt(Settings.hashed_private_key, AES.GetKey(old_password)); + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + byte[] key = AES.GetKey(new_password); + + ChangeVerificatorHash changeVerificatorHash = new ChangeVerificatorHash(); + changeVerificatorHash.old_verificator_hash = Settings.verificator_hash; + changeVerificatorHash.new_verificator_hash = SHA512.HMAC(SHA512.VerificatorHashingValue, key); + changeVerificatorHash.udid = Settings.udid; + changeVerificatorHash.pin = PopupPasswordReset_txtNewPIN.getText().toString(); + + PopupPasswordReset_Status.setText(""); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + /** Update verificator_hash & pin on the server **/ + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("ChangeVerificatorHash", changeVerificatorHash, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "update_verificator_hash", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + encryptedResponse.Decrypt(sharedKey); + + if(encryptedResponse.descriptor.toLowerCase().equals("success")) + { + try + { + List results = dbResults.GetResults(); + + /** decrypt & encrypt old results by new password **/ + if(results != null && results.size() > 0) + { + for(int i = 0; i < results.size(); i++) + { + Results res = results.get(i); + + String file = System.GetPathForStorageEncryptedFile(res.pgs, MainContext); + + if(file != null && System.FileExists(file)) + { + byte[] encrypted_content = System.ReadFromEncryptedStorage(res.pgs, MainContext); + + if(encrypted_content != null && encrypted_content.length > 0) + { + String decrypted_content = AES.Decrypt(new String(encrypted_content), AES.GetKey(old_password)); + + if(decrypted_content != null) + { + String local_encrypted = AES.Encrypt(decrypted_content, AES.GetKey(new_password)); + + if(local_encrypted != null) + { + System.WriteToEncryptedStorage(res.pgs, local_encrypted.getBytes(StandardCharsets.UTF_8), MainContext); + } + } + } + } + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "LoginActivity", "Thread change encryption"); + } + + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + /** update settings **/ + byte[] key = AES.GetKey(new_password); + Settings.password_reset_hash = UUID.randomUUID().toString(); + + byte[] passwordHashKey = AES.GetKey(Settings.password_reset_hash + changeVerificatorHash.pin); + Settings.password_hash = AES.Encrypt(new_password, passwordHashKey); + Settings.verificator_hash = SHA512.HMAC(SHA512.VerificatorHashingValue, key); + Settings.hashed_private_key = AES.Encrypt(decrypted_private_key, key); + Settings.save(MainContext); + + Session.DevicePassword = new_password; + + PopupPasswordReset_Hide(); + String msg = Lang.Get("MSG_PASSWORD_HAS_BEEN_CHANGED"); + ShowAlert(msg); + } + }); + } + else + { + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPasswordReset_HideLoading(Lang.Get("ERROR_COULD_NOT_CHANGE_PASSWORD")); + Log.Error("Could not update verificator_hash & pin on the server", "LoginActivity", "RequestPINFromServer"); + } + }); + } + + IsPasswordChanging = false; + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + IsPasswordChanging = false; + PopupPasswordReset_HideLoading(error); + Log.Critical(error, "LoginActivity", "ChangePassword"); + } + }); + + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + IsPasswordChanging = false; + PopupPasswordReset_HideLoading(error); + Log.Critical(error, "LoginActivity", "ChangePassword"); + } + }); + }); + } + }); + + thread.start(); + } + } + else + { + PopupPasswordReset_HideLoading(Lang.Get("ERROR_INVALID_PASSWORD_RESET_PIN")); + IsPasswordChanging = false; + } + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LoginActivity", "ChangePassword"); + IsPasswordChanging = false; + } + } + + /** + * Checks if biometrical authentication is available + * + * @return returns true if available + */ + public boolean BiometricAuthenticationSupported() + { + boolean result = false; + + try + { + androidx.biometric.BiometricManager biometricManager = androidx.biometric.BiometricManager.from(this); + switch(biometricManager.canAuthenticate()) + { + case androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS: + result = true; + break; + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LoginActivity", "BiometricAuthenticationSupported"); + } + + return result; + } + + /** + * Request PIN from the server + * + * User has to authentificate by biometric + */ + private void RequestPIN() + { + try + { + PopupPasswordReset_Status.setText(""); + + Executor executor = ContextCompat.getMainExecutor(this); + + BiometricPrompt biometricPrompt = new BiometricPrompt(LoginActivity.this, executor, new BiometricPrompt.AuthenticationCallback() + { + @Override + public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) + { + super.onAuthenticationError(errorCode, errString); + PopupPasswordReset_HideLoading("" + errString); + } + + @Override + public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) + { + super.onAuthenticationSucceeded(result); + RequestPINFromServer(); + } + + @Override + public void onAuthenticationFailed() + { + super.onAuthenticationFailed(); + PopupPasswordReset_HideLoading(Lang.Get("ERROR_BIOMETRICAL_AUTHENTIFICATION_COULD_NOT_ACTIVATED")); + } + }); + + BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder() + .setTitle(Lang.Get("LBL_BIOMETRICAL_AUTHENTIFICATION")) + .setNegativeButtonText(Lang.Get("BTN_CANCEL")) + .build(); + biometricPrompt.authenticate(promptInfo); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "MainActivity", "RequestPIN"); + } + } + + /** + * Send server request for PIN + */ + private void RequestPINFromServer() + { + try + { + PopupPasswordReset_Loading.setVisibility(View.VISIBLE); + + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + GetPIN getPIN = new GetPIN(); + getPIN.udid = Settings.udid; + getPIN.verificator_hash = Settings.verificator_hash; + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("PIN", getPIN, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "pin", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + Object response = encryptedResponse.Decrypt(sharedKey); + + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if(response != null) + { + try + { + PIN pin = (PIN)response; + + if(pin != null && pin.code != null && !pin.code.isEmpty()) + { + PopupPasswordReset_HideLoading(""); + PopupPasswordReset_txtPIN.setText(pin.code); + } + else + { + PopupPasswordReset_HideLoading(Lang.Get("ERROR_COULD_NOT_GET_PIN")); + Log.Error("Could not get pin from the server", "LoginActivity", "RequestPINFromServer"); + } + } + catch (Exception ex) + { + PopupPasswordReset_HideLoading(Lang.Get("ERROR_COULD_NOT_GET_PIN")); + Log.Error(ex.getMessage(), "LoginActivity", "RequestPINFromServer"); + } + } + else + { + PopupPasswordReset_HideLoading(Lang.Get("ERROR_COULD_NOT_GET_PIN")); + Log.Error("Could not get pin from the server", "LoginActivity", "RequestPINFromServer"); + } + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPasswordReset_HideLoading(error); + Log.Critical(error, "LoginActivity", "RequestPINFromServer"); + } + }); + + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPasswordReset_HideLoading(error); + Log.Critical(error, "LoginActivity", "RequestPINFromServer"); + } + }); + }); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LoginActivity", "RequestPINFromServer"); + } + } + + /** + * Do user login + */ + private void loginPasswordView_btnLogin_Click() + { + try + { + loginPasswordStatus.setText(""); + + if(loginPasswordView_txtPassword.getText() == null || loginPasswordView_txtPassword.getText().toString().isEmpty()) + { + loginPasswordStatus.setText(Lang.Get("ERROR_INVALID_PASSWORD")); + } + else + { + String password = loginPasswordView_txtPassword.getText().toString(); + String tmp_encrypt_key = AES.Decrypt(Settings.hashed_private_key, AES.GetKey(password)); + + if(tmp_encrypt_key == null) + { + loginPasswordStatus.setText(Lang.Get("ERROR_INVALID_PASSWORD")); + } + else + { + Session.DevicePassword = password; + this.GoToMainActivity(); + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "LoginActivity", "loginPasswordView_btnLogin_Click"); + } + } + + /** + * Go Back to MainActivity + */ + private void GoToMainActivity() + { + Intent intent = new Intent(this, MainActivity.class ); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + Bundle parameters = new Bundle(); + parameters.putBoolean("SplashScreenLoaded", true); + intent.putExtras(parameters); + startActivity(intent); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } + + /** + * Goes to SupportActivity + */ + private void GoToSupportActivity() + { + Intent supportActivity = new Intent(this, SupportActivity.class); + startActivity(supportActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + + /** + * Shows message as alert dialog with ok button + * @param msg - message that should be showed in alert dialog + */ + private void ShowAlert(String msg) + { + AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this); + dlgAlert.setMessage(msg); + dlgAlert.setPositiveButton("OK", null); + dlgAlert.setCancelable(true); + dlgAlert.create().show(); + } + + /** END FUNCTIONS **/ +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/MainActivity.java b/app/src/main/java/de/labor_stein/befund/MainActivity.java new file mode 100644 index 0000000..03d0db4 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/MainActivity.java @@ -0,0 +1,2636 @@ +// +// MainActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 29.04.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.DatePickerDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build; +import android.os.Bundle; +import android.text.InputType; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.view.inputmethod.InputMethodManager; +import android.webkit.WebView; +import android.widget.Button; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.activity.result.ActivityResult; +import androidx.activity.result.ActivityResultCallback; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContract; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.recyclerview.widget.ItemTouchHelper; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; + +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.Task; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.firebase.messaging.FirebaseMessaging; +import com.journeyapps.barcodescanner.ScanContract; +import com.journeyapps.barcodescanner.ScanOptions; + +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import de.labor_stein.befund.Adapters.ResultsTableAdapter; +import de.labor_stein.befund.Adapters.ResultsTableAdapterSwipeToDeleteCallback; +import de.labor_stein.befund.Core.Helpers.DateHelper; +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.Results; +import de.labor_stein.befund.Core.Models.Database.Status; +import de.labor_stein.befund.Core.Models.Request.CheckFileChecksum; +import de.labor_stein.befund.Core.Models.Request.DeviceToken; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Request.GetOpened; +import de.labor_stein.befund.Core.Models.Request.Subscribe; +import de.labor_stein.befund.Core.Models.Response.Download; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Models.Settings; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.Security.Curve25519; +import de.labor_stein.befund.Core.Security.SHA512; +import de.labor_stein.befund.Core.System; +import de.labor_stein.befund.Services.PushNotificationService; +import de.labor_stein.befund.databinding.ActivityMainBinding; + +public class MainActivity extends AppCompatActivity +{ + private float x1,x2; + static final int MIN_DISTANCE = 150; + + /** MainActivityContext **/ + private Context MainContext; + private AppCompatActivity CurrentActivity; + private ActivityMainBinding binding; + private ProgressBar MainLoading; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + + /** Controls **/ + private TextView lblMyResults; + private TextView lblNewResults; + private TextView lblNoResults; + private TextView lblResultsNotice; + private FloatingActionButton ButtonNewPGS; + + /** BEGIN POPUPS **/ + + /** BEGIN MessagePopup **/ + private PopupWindow PopupMessage; + private View PopupMessageView_Overlay; + private LinearLayout PopupMessage_Popup; + private TextView PopupMessage_text; + private Button PopupMessage_BtnOk; + /** END MessagePopup **/ + + /** BEGIN PopupNewPGS **/ + private PopupWindow PopupNewPGS; + private View PopupNewPGSView_Overlay; + private LinearLayout PopupNewPGS_Popup; + private LinearLayout PopupNewPGSContent; + private LinearLayout PopupNewPGS_PGS; + private EditText PopupNewPGS_txtZIP; + private EditText PopupNewPGS_txtBirthday; + private DatePickerDialog BirthdayPicker; + private ImageView PopupNewPGS_iconSampleId; + private EditText PopupNewPGS_txtSampleId; + private ImageView PopupNewPGS_btnSampleId; + private TextView PopupNewPGS_Status; + private ProgressBar PopupNewPGS_Loading; + private Button PopupNewPGS_btnCancel; + private Button PopupNewPGS_btnAdd; + + /** PopupNewPGS->MasterPassword **/ + private LinearLayout PopupNewPGS_MasterPassword; + private EditText PopupNewPGS_txtPassword; + private ImageView PopupNewPGS_txtPasswordViewer; + private EditText PopupNewPGS_txtPasswordConfirm; + private ImageView PopupNewPGS_txtPasswordConfirmViewer; + private EditText PopupNewPGS_txtPIN; + + /** END PopupNewPGS **/ + + /** BEGIN Popup PrivacyPolicy **/ + private PopupWindow PopupPrivacyPolicy; + private TextView PopupPrivacyPolicy_lblHeader; + private Button PopupPrivacyPolicy_btnAcceptPrivacyPolicy; + private WebView PopupPrivacyPolicy_web; + /** END Popup PrivacyPolicy **/ + + /** BEGIN PopupMenu **/ + private PopupWindow PopupMenu; + private View PopupMenu_Overlay; + private FrameLayout PopupMenu_Popup; + private TextView PopupMenu_lblMenu; + private TextView PopupMenu_lblNotRegisteredMenu; + private LinearLayout PopupMenu_btnMenuSettings_View; + private Button PopupMenu_btnMenuSettings; + private LinearLayout PopupMenu_btnMenuChangePassword_View; + private Button PopupMenu_btnMenuChangePassword; + private Button PopupMenu_btnMenuSupport; + private Button PopupMenu_btnMenuFAQ; + private Button PopupMenu_btnMenuPrivacyPolicy; + private Button PopupMenu_btnMenuClose; + /** END PopupMenu **/ + + /** BEGIN PopupPushExplain **/ + private PopupWindow PopupPushExplain; + private View PopupPushExplainView_Overlay; + private TextView PopupPushExplain_header; + private TextView PopupPushExplain_text; + private Button PopupPushExplain_BtnOk; + /** END PopupPushExplain **/ + + /** END POPUPS **/ + + /** BEGIN ResultsTable **/ + private RecyclerView ResultsTable; + private ResultsTableAdapter ResultsTable_Adapter; + private SwipeRefreshLayout ResultsTable_Refresher; + private List Results = null; + + /** Settings **/ + private Button bottomMenuOpener; + private Settings Settings; + + /** Database Contexts **/ + private de.labor_stein.befund.Core.Database.Results dbResults; + private de.labor_stein.befund.Core.Database.Logs dbLogs; + + /** PERMISSION FLAGS **/ + private static int PUSH_PERMISSION = 1001; + + private static boolean is_first_subscribe = false; + private static boolean pgs_request_running = false; + + /** PERMISSION FLAGS **/ + private static int CAMERA_PERMISSION = 1000; + private static int POST_NOTIFICATIONS_PERMISSION = 1001; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + binding = ActivityMainBinding.inflate(getLayoutInflater()); + setContentView(binding.getRoot()); + + CurrentActivity = this; + + this.InitializeLayouts(); + + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + if( this.Settings == null || !this.Settings.PrivacyPolicyAccepted) + { + this.InitializePrivacyPolicyPopup(false); + } + else + { + this.SplashScreen(); + } + } + + @Override + protected void onResume() + { + super.onResume(); + + if(de.labor_stein.befund.Core.Models.Session.DevicePassword != null && this.Settings.verificator_hash != null) + { + this.LoadResults(false); + } + } + + /** + * SplashScreen + */ + private void SplashScreen() + { + boolean loadSplashScreen = true; + + Bundle parameters = getIntent().getExtras(); + + if(parameters != null) + { + boolean splashScreenLoaded = parameters.getBoolean("SplashScreenLoaded"); + + if(splashScreenLoaded) + { + loadSplashScreen = false; + } + } + + if(loadSplashScreen) + { + Intent splashScreen = new Intent(this, SplashActivity.class); + startActivity(splashScreen); + finish(); + } + else + { + /** First has to be loaded settings to use system properties **/ + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + Session.Device = System.GetDeviceInfo(this.Settings); + Session.NotificationGranted = false; + Session.CameraGranted = false; + + if(de.labor_stein.befund.Core.Models.Session.DevicePassword == null && this.Settings.verificator_hash != null) + { + Intent loginActivity = new Intent(this, LoginActivity.class); + startActivity(loginActivity); + finish(); + } + else + { + this.Initialize(); + } + } + } + + /** + * Initialize Main Activity + */ + private void Initialize() + { + this.dbResults = new de.labor_stein.befund.Core.Database.Results(this); + this.dbLogs = new de.labor_stein.befund.Core.Database.Logs(this); + Log.Initialize(this); + PushNotificationService.SetMainActivity(this, this.Settings); + + this.dbResults.CreateDBIfNotExists(); + this.dbLogs.CreateDBIfNotExists(); + + this.RequestAuthorizations(); + + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializePopups(); + this.InitializeTable(); + + this.InitializeLanguages(false); + + this.ActivityRootLayout.setVisibility(View.VISIBLE); + + if(!this.Settings.PushNotificationExplained) + { + this.ActivityRootLayout.post(new Runnable() + { + public void run() + { + ShowPushNotificationExplain(); + } + }); + } + } + + /** + * Check necessary permission if already granted + */ + private void RequestAuthorizations() + { + /** Check push notification Permission **/ + this.RequestPushNotificationAuthorization(); + } + + /** + * Require Push Notification Authorize + */ + private void RequestPushNotificationAuthorization() + { + try + { + FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener() + { + @Override + public void onComplete(@NonNull Task task) + { + if (!task.isSuccessful()) + { + Log.Critical("Could not get the Firebase Token", "MainActivity", "RequestPushNotificationAuthorization(ERROR)"); + return; + } + + /** Fire onSessionChanged Event **/ + String token = task.getResult(); + Session.NotificationGranted = true; + + if(token != null) + { + Session.Device.token = token; + UpdateDeviceToken(); + } + } + }); + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "RequestPushNotificationAuthorization"); + } + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + this.MainContext = this; + + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.ActivityRootLayout); + MainLoading = ActivityRootLayout.findViewById(R.id.mainLoading); + MainLoading.setVisibility(View.INVISIBLE); + } + + /** + * Initialize Labels + */ + private void InitializeLabels() + { + lblMyResults = ActivityRootLayout.findViewById(R.id.lblMyResults); + lblNewResults = ActivityRootLayout.findViewById(R.id.lblNewResults); + lblNoResults = ActivityRootLayout.findViewById(R.id.lblNoResults); + lblResultsNotice = ActivityRootLayout.findViewById(R.id.lblResultsNotice); + lblNoResults.setVisibility(View.VISIBLE); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + ButtonNewPGS = findViewById(R.id.ButtonNewPGS); + ButtonNewPGS.setOnClickListener(v -> { this.ButtonNewPGS_Click(); }); + bottomMenuOpener = findViewById(R.id.bottomMenuOpener); + bottomMenuOpener.setOnClickListener(v -> { this.PopupMainMenu_Show(); }); + } + + /** + * Initializes Popups + */ + private void InitializePopups() + { + this.InitializeNewPGSPopup(); + + this.InitializeMenuPopup(); + this.InitializeMessagePopup(); + this.InitializePushExplainPopup(); + } + + /** Initializes Results Table **/ + private void InitializeTable() + { + ResultsTable = ActivityRootLayout.findViewById(R.id.ResultsTable); + ResultsTable.setVisibility(View.INVISIBLE); + ResultsTable_Adapter = new ResultsTableAdapter(this.Results, this, this.ResultsTable); + ResultsTable.setAdapter(ResultsTable_Adapter); + ResultsTable.setLayoutManager(new LinearLayoutManager(this)); + ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ResultsTableAdapterSwipeToDeleteCallback(ResultsTable_Adapter, this)); + itemTouchHelper.attachToRecyclerView(ResultsTable); + ResultsTable_Refresher = ActivityRootLayout.findViewById(R.id.ResultsTableRefresher); + + ResultsTable_Refresher.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() + { + @Override + public void onRefresh() + { + ResultsTable_Refresher.setRefreshing(true); + LoadResults(false); + } + }); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages(boolean reloadSettings) + { + if(reloadSettings) { + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + } + + Lang.SetLanguage(this.Settings.lang); + + lblMyResults.setText(Lang.Get("LBL_MY_RESULTS")); + lblNewResults.setText(Lang.Get("BTN_NEW_RESULTS")); + PopupNewPGS_txtZIP.setHint(Lang.Get("LBL_ZIP")); + PopupNewPGS_txtBirthday.setHint(Lang.Get("LBL_BIRTHDAY")); + PopupNewPGS_txtSampleId.setHint(Lang.Get("LBL_SAMPLEID")); + PopupNewPGS_txtPassword.setHint(Lang.Get("LBL_PASSWORD")); + PopupNewPGS_txtPasswordConfirm.setHint(Lang.Get("LBL_PASSWORD_CONFIRM")); + PopupNewPGS_btnCancel.setText(Lang.Get("BTN_CANCEL")); + PopupNewPGS_btnAdd.setText(Lang.Get("BTN_ADD")); + lblNoResults.setText(Lang.Get("LBL_NO_RESULTS")); + lblResultsNotice.setText(Lang.Get("LBL_RESULTS_NOTICE")); + PopupNewPGS_txtPIN.setHint(Lang.Get("LBL_PIN")); + + PopupMenu_lblMenu.setText(Lang.Get("LBL_MENU")); + PopupMenu_lblNotRegisteredMenu.setText(Lang.Get("MSG_YOU_ARE_NOT_REGISTERED")); + PopupMenu_btnMenuSettings.setText(Lang.Get("BTN_SETTINGS")); + PopupMenu_btnMenuChangePassword.setText(Lang.Get("BTN_CHANGE_PASSWORD")); + PopupMenu_btnMenuSupport.setText(Lang.Get("BTN_SUPPORT")); + PopupMenu_btnMenuFAQ.setText(Lang.Get("BTN_FAQ")); + PopupMenu_btnMenuPrivacyPolicy.setText(Lang.Get("BTN_PRIVACY_POLICY")); + PopupMenu_btnMenuClose.setText(Lang.Get("BTN_CLOSE")); + + if(this.Settings.verificator_hash != null) + { + PopupNewPGS_btnAdd.setText(Lang.Get("BTN_ADD")); + } + else + { + PopupNewPGS_btnAdd.setText(Lang.Get("BTN_NEXT")); + } + + PopupMessage_BtnOk.setText(Lang.Get("BTN_OK")); + + PopupPushExplain_header.setText(Lang.Get("LBL_PUSH_NOTIFICATION_EXPLAIN_HEADER")); + PopupPushExplain_text.setText(Lang.Get("MSG_PUSH_NOTIFICATION_EXPLAIN_TEXT")); + PopupPushExplain_BtnOk.setText(Lang.Get("BTN_OK")); + } + + /** + * Initializes NewPGS Popup + */ + private void InitializeNewPGSPopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + PopupNewPGSView_Overlay = inflater.inflate(R.layout.popup_new_pgs, null); + PopupNewPGS_Popup = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_Popup); + PopupNewPGSContent = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGSContent); + + PopupNewPGS_PGS = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_PGS); + + PopupNewPGS_btnAdd = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_BtnAdd); + PopupNewPGS_btnAdd.setOnClickListener(v -> { this.PopupNewPGS_BtnAdd_Click(); }); + + PopupNewPGS_btnCancel = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_BtnCancel); + PopupNewPGS_btnCancel.setOnClickListener(v -> { this.PopupNewPGS_BtnCancel_Click(); }); + + PopupNewPGS_txtZIP = PopupNewPGSView_Overlay.findViewById(R.id.txtZIP); + PopupNewPGS_txtBirthday = PopupNewPGSView_Overlay.findViewById(R.id.txtBirthday); + PopupNewPGS_iconSampleId = PopupNewPGSView_Overlay.findViewById(R.id.iconSampleIdScan); + PopupNewPGS_txtSampleId = PopupNewPGSView_Overlay.findViewById(R.id.txtSampleId); + PopupNewPGS_btnSampleId = PopupNewPGSView_Overlay.findViewById(R.id.btnSampleIdScan); + PopupNewPGS_txtPassword = PopupNewPGSView_Overlay.findViewById(R.id.txtPassword); + PopupNewPGS_txtPasswordViewer = PopupNewPGSView_Overlay.findViewById(R.id.txtPasswordViewer); + PopupNewPGS_txtPasswordConfirm = PopupNewPGSView_Overlay.findViewById(R.id.txtPasswordConfirm); + PopupNewPGS_txtPasswordConfirmViewer = PopupNewPGSView_Overlay.findViewById(R.id.txtPasswordConfirmViewer); + PopupNewPGS_Status = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_Status); + PopupNewPGS_Loading = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_Loading); + PopupNewPGS_Loading.setVisibility(View.INVISIBLE); + + /** SampleId Scans **/ + PopupNewPGS_iconSampleId.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ScanSampleId(); + } + }); + + PopupNewPGS_btnSampleId.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ScanSampleId(); + } + }); + + /** Password Viewers **/ + PopupNewPGS_txtPasswordViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PopupNewPGS_txtPasswordViewer.setAlpha(1.0f); + PopupNewPGS_txtPassword.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PopupNewPGS_txtPassword.setSelection(PopupNewPGS_txtPassword.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PopupNewPGS_txtPasswordViewer.setAlpha(0.5f); + PopupNewPGS_txtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PopupNewPGS_txtPassword.setSelection(PopupNewPGS_txtPassword.getText().length()); + } + + return true; + } + }); + + PopupNewPGS_txtPasswordConfirmViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PopupNewPGS_txtPasswordConfirmViewer.setAlpha(1.0f); + PopupNewPGS_txtPasswordConfirm.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PopupNewPGS_txtPasswordConfirm.setSelection(PopupNewPGS_txtPasswordConfirm.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PopupNewPGS_txtPasswordConfirmViewer.setAlpha(0.5f); + PopupNewPGS_txtPasswordConfirm.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PopupNewPGS_txtPasswordConfirm.setSelection(PopupNewPGS_txtPasswordConfirm.getText().length()); + } + + return true; + } + }); + + + /** remove suggestions from the keyboard view **/ + PopupNewPGS_txtZIP.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); + PopupNewPGS_txtBirthday.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + ///PopupNewPGS_txtSampleId.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + + /** Run RequestPGS on ENTER KEY (SampleID) **/ + PopupNewPGS_txtSampleId.setOnKeyListener(new View.OnKeyListener() + { + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) + { + if(keyCode == KeyEvent.KEYCODE_ENTER) + { + if(Settings != null) + { + HideKeyboard(v); + RequestPGS(); + } + else + { + PopupNewPGS_ShowPassword(); + } + } + + return false; + } + }); + + /** Run RequestPGS on ENTER KEY (PasswordConfirm) **/ + PopupNewPGS_txtPasswordConfirm.setOnKeyListener(new View.OnKeyListener() + { + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) + { + if(keyCode == KeyEvent.KEYCODE_ENTER) + { + HideKeyboard(v); + RequestPGS(); + } + + return false; + } + }); + + /** Hide Keboard on touch around **/ + PopupNewPGSView_Overlay.setOnTouchListener((View v, MotionEvent event) -> { this.HideKeyboard(v); return true; }); + + /** DatePicker **/ + //BirthdayPicker.setOnDateSetListener( + DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() + { + @Override + public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) + { + Date selectedDate = DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker()); + + if(selectedDate != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); + PopupNewPGS_txtBirthday.setText(dateFormat.format(selectedDate)); + } + } + }; + + BirthdayPicker = new DatePickerDialog(this, R.style.MySpinnerDatePickerStyle, dateListener, 2000,0,1); + BirthdayPicker.getDatePicker().setMaxDate(new Date().getTime()); + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, 1900); + cal.set(Calendar.MONTH, Calendar.JANUARY); + cal.set(Calendar.DAY_OF_MONTH, 1); + BirthdayPicker.getDatePicker().setMinDate(cal.getTimeInMillis()); + + /** Disable directly key insert in the birthday field(it should be set by DatePicker for well formed value) **/ + PopupNewPGS_txtBirthday.setOnKeyListener((View v, int keyCode, KeyEvent event) -> { return true; }); + + /** Show/Hide DatePicker **/ + PopupNewPGS_txtBirthday.setOnFocusChangeListener((View v, boolean hasFocus) -> { if(hasFocus) { BirthdayPicker.show(); } }); + PopupNewPGS_txtBirthday.setOnTouchListener((View v, MotionEvent event) -> { BirthdayPicker.show(); return true; }); + + /** BEGIN MASTER PASSWORD CONTENT **/ + PopupNewPGS_MasterPassword = PopupNewPGSView_Overlay.findViewById(R.id.PopupNewPGS_MasterPassword); + PopupNewPGS_txtPassword = PopupNewPGSView_Overlay.findViewById(R.id.txtPassword); + PopupNewPGS_txtPasswordConfirm = PopupNewPGSView_Overlay.findViewById(R.id.txtPasswordConfirm); + PopupNewPGS_MasterPassword.setVisibility(View.GONE); + PopupNewPGS_txtPIN = PopupNewPGSView_Overlay.findViewById(R.id.txtPIN); + + PopupNewPGS_txtPassword.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); } + else + { PopupNewPGS_Status.setText(""); } + }); + PopupNewPGS_txtPasswordConfirm.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); } + else + { PopupNewPGS_Status.setText(""); } + + }); + PopupNewPGS_txtPIN.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PopupNewPGS_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); } + else + { PopupNewPGS_Status.setText(""); } + }); + + /** Create popup window context **/ + PopupNewPGS = new PopupWindow( + PopupNewPGSView_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + /** Scan SampleId **/ + private void ScanSampleId() + { + try + { + int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); + + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) + { + if (result != PackageManager.PERMISSION_GRANTED) + { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); + alertBuilder.setCancelable(true); + alertBuilder.setTitle(Lang.Get("MSG_CAMERA_PERMISSION_TITLE")); + alertBuilder.setMessage(Lang.Get("MSG_CAMERA_PERMISSION_MSG")); + alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + ActivityCompat.requestPermissions(CurrentActivity, new String[] { Manifest.permission.CAMERA }, CAMERA_PERMISSION); + } + }); + AlertDialog alert = alertBuilder.create(); + alert.show(); + } + else + { + Session.CameraGranted = true; + } + } + else + { + if (result != PackageManager.PERMISSION_GRANTED) + { + AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); + alertBuilder.setCancelable(true); + alertBuilder.setTitle(Lang.Get("MSG_CAMERA_PERMISSION_TITLE")); + alertBuilder.setMessage(Lang.Get("MSG_CAMERA_PERMISSION_MSG")); + alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() + { + @Override + public void onClick(DialogInterface dialog, int which) + { + ActivityCompat.requestPermissions(CurrentActivity, new String[] { Manifest.permission.CAMERA }, CAMERA_PERMISSION); + } + }); + AlertDialog alert = alertBuilder.create(); + alert.show(); + } + else + { + Session.CameraGranted = true; + } + } + + if(Session.CameraGranted) + { + ScanOptions options = new ScanOptions(); + options.setDesiredBarcodeFormats(ScanOptions.ALL_CODE_TYPES); + options.setBeepEnabled(false); + options.setBarcodeImageEnabled(true); + options.setOrientationLocked(false); + barcodeLauncher.launch(options); + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "MainActivity", "ScanSampleId"); + } + } + + /** Launches camera to get qr code **/ + private final ActivityResultLauncher barcodeLauncher = registerForActivityResult(new ScanContract(), + result -> + { + try + { + if(result.getContents() != null) + { + String barcode = result.getContents().toString(); + + if(barcode != null && !barcode.isEmpty()) + { + PopupNewPGS_txtSampleId.setText(barcode); + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_BARCODE"), Toast.LENGTH_SHORT).show(); + } + } + else + { + Toast.makeText(this, Lang.Get("ERROR_COULD_NOT_READ_BARCODE"), Toast.LENGTH_SHORT).show(); + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "MainActivity", "barcodeLauncher"); + } + }); + + /** + * Initializes PrivacyPolicy Popup + */ + private void InitializePrivacyPolicyPopup(boolean openAnyways) + { + if(this.Settings == null) + { + this.Settings = new Settings(); + } + + if(!openAnyways){ + this.Settings.lang = Lang.GetSystemLang(); + } + + Lang.SetLanguage(this.Settings.lang); + + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + View PopupPrivacyPolicyView = inflater.inflate(R.layout.popup_privacy_policy, null); + + PopupPrivacyPolicy_lblHeader = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_lblHeader); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_btnAccept); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(false); + PopupPrivacyPolicy_lblHeader.setText(Lang.Get("LBL_PRIVACY_POLICY")); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_ACCEPT_PRIVACY_POLICY")); + + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setOnClickListener((v) -> + { + if(!this.Settings.PrivacyPolicyAccepted) + { + this.Settings.PrivacyPolicyAccepted = true; + this.Settings.save(this); + this.SplashScreen(); + } + + PopupPrivacyPolicy.dismiss(); + }); + + /** Create popup window context **/ + PopupPrivacyPolicy = new PopupWindow( + PopupPrivacyPolicyView, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + + PopupPrivacyPolicy.setOnDismissListener(new PopupWindow.OnDismissListener() { + @Override + public void onDismiss() { + OpenPrivacyPolicyPopup(false); + } + }); + + View.OnTouchListener corkyListener = new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + boolean retFlag=false; + switch(event.getAction()) { + case MotionEvent.ACTION_DOWN: + x1 = event.getX(); + break; + case MotionEvent.ACTION_UP: + x2 = event.getX(); + float deltaX = x2 - x1; + if (Math.abs(deltaX) > MIN_DISTANCE) + { + retFlag=true; + } + break; + case MotionEvent.ACTION_BUTTON_PRESS: + break; + + } + return retFlag; + } + }; + PopupPrivacyPolicy.setTouchInterceptor(corkyListener); + PopupPrivacyPolicy_web = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_web); + + OpenPrivacyPolicyPopup(openAnyways); + } + + private void OpenPrivacyPolicyPopup(boolean openAnyways) + { + if(openAnyways || this.Settings == null || !this.Settings.PrivacyPolicyAccepted) { + + if(!openAnyways) { + this.ActivityRootLayout.setVisibility(View.INVISIBLE); + } + + this.ActivityRootLayout.post(new Runnable() + { + public void run() + { + LoadPrivacyPolicy(); + PopupPrivacyPolicy.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + }); + } + } + + + /** + * Load PrivacyPolicy + */ + private void LoadPrivacyPolicy() + { + try + { + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.GetResponseAsync(Settings.GetPrivacyPolicyURL(), + "GET", + (content) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPrivacyPolicy_web.loadUrl(Settings.GetPrivacyPolicyURL()); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if(Settings.PrivacyPolicyAccepted) + { + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + } + else + { + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_CLOSE")); + + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setOnClickListener((v) -> + { + finishAndRemoveTask(); + }); + } + + byte[] local_privacy_policy_data = System.ReadFromAssets("no_connection.html", MainContext); + + if(local_privacy_policy_data != null && local_privacy_policy_data.length > 0) + { + String html = new String(local_privacy_policy_data); + html = html.replace("[NO_CONNECTION]", Lang.Get("ERROR_PRIVACY_POLICY_NEEDS_CONNECTION")); + PopupPrivacyPolicy_web.loadData(html, "text/html", "utf-8"); + } + } + }); + }); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "MainActivity", "LoadPrivacyPolicy"); + } + } + + /** + * Initializes MenuPopup + */ + private void InitializeMenuPopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + PopupMenu_Overlay = inflater.inflate(R.layout.popup_menu, null); + PopupMenu_Popup = PopupMenu_Overlay.findViewById(R.id.PopupMainMenu_Popup); + + PopupMenu_lblMenu = PopupMenu_Overlay.findViewById(R.id.lblMenu); + PopupMenu_lblNotRegisteredMenu = PopupMenu_Overlay.findViewById(R.id.lblNotRegisteredMenu); + PopupMenu_lblNotRegisteredMenu.setVisibility(View.GONE); + + PopupMenu_btnMenuSettings_View = PopupMenu_Overlay.findViewById(R.id.btnMenuSettings_View); + PopupMenu_btnMenuSettings = PopupMenu_Overlay.findViewById(R.id.btnMenuSettings); + ImageView PopupMenu_btnMenuSettings_icon = PopupMenu_Overlay.findViewById(R.id.btnMenuSettings_icon); + PopupMenu_btnMenuSettings.setOnClickListener(v -> { this.GoToSettingsActivity(); }); + PopupMenu_btnMenuSettings_icon.setOnClickListener(v -> { this.GoToSettingsActivity(); }); + + PopupMenu_btnMenuChangePassword_View = PopupMenu_Overlay.findViewById(R.id.btnMenuChangePassword_View); + PopupMenu_btnMenuChangePassword = PopupMenu_Overlay.findViewById(R.id.btnMenuChangePassword); + ImageView PopupMenu_btnMenuChangePassword_icon = PopupMenu_Overlay.findViewById(R.id.btnMenuChangePassword_icon); + PopupMenu_btnMenuChangePassword.setOnClickListener(v -> { this.GoToPasswordActivity(); }); + PopupMenu_btnMenuChangePassword_icon.setOnClickListener(v -> { this.GoToPasswordActivity(); }); + + LinearLayout btnMenuSupport_View = PopupMenu_Overlay.findViewById(R.id.btnMenuSupport_View); + PopupMenu_btnMenuSupport = PopupMenu_Overlay.findViewById(R.id.btnMenuSupport); + ImageView PopupMenu_btnMenuSupport_icon = PopupMenu_Overlay.findViewById(R.id.btnMenuSupport_icon); + + PopupMenu_btnMenuSupport.setOnClickListener(v -> { this.GoToSupportActivity(); }); + PopupMenu_btnMenuSupport_icon.setOnClickListener(v -> { this.GoToSupportActivity(); }); + + PopupMenu_btnMenuFAQ = PopupMenu_Overlay.findViewById(R.id.btnMenuFAQ); + ImageView PopupMenu_btnMenuFAQ_icon = PopupMenu_Overlay.findViewById(R.id.btnMenuFAQ_icon); + + PopupMenu_btnMenuFAQ.setOnClickListener(v -> { this.GoToFAQActivity(); }); + PopupMenu_btnMenuFAQ_icon.setOnClickListener(v -> { this.GoToFAQActivity(); }); + + PopupMenu_btnMenuPrivacyPolicy = PopupMenu_Overlay.findViewById(R.id.btnMenuPrivacyPolicy); + ImageView PopupMenu_btnMenuPrivacyPolicy_icon = PopupMenu_Overlay.findViewById(R.id.btnPrivacyPolicy_icon); + + PopupMenu_btnMenuClose = PopupMenu_Overlay.findViewById(R.id.btnMenuClose); + ImageView PopupMenu_PopupMenu_btnMenuClose_icon = PopupMenu_Overlay.findViewById(R.id.btnMenuClose_icon); + + PopupMenu_btnMenuClose.setOnClickListener(v -> { this.PopupMainMenu_Hide(); }); + PopupMenu_PopupMenu_btnMenuClose_icon.setOnClickListener(v -> { this.PopupMainMenu_Hide(); }); + + PopupMenu_btnMenuPrivacyPolicy.setOnClickListener(v -> { this.ShowPrivacyPolicy(); }); + PopupMenu_btnMenuPrivacyPolicy_icon.setOnClickListener(v -> { this.ShowPrivacyPolicy(); }); + + /** Create popup window context **/ + PopupMenu = new PopupWindow( + PopupMenu_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + + PopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() { + @Override + public void onDismiss() { + InitializeLanguages(true); + } + }); + } + + private ActivityResultLauncher settingsResultLauncher = registerForActivityResult( + new ActivityResultContracts.StartActivityForResult(), + new ActivityResultCallback() { + @Override + public void onActivityResult(ActivityResult result) { + //here we will handle the result of our intent + if (result.getResultCode() == Activity.RESULT_OK){ + InitializeLanguages(true); + } + } + } + ); + + /** Shows privacy policy popup**/ + private void ShowPrivacyPolicy() + { + this.InitializePrivacyPolicyPopup(true); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_CLOSE")); + this.LoadPrivacyPolicy(); + } + + /** Initialize MessagePopup **/ + private void InitializeMessagePopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + View MessagePopupView = inflater.inflate(R.layout.fragment_message, null); + + PopupMessageView_Overlay = MessagePopupView.findViewById(R.id.PopupMessage); + PopupMessage_Popup = MessagePopupView.findViewById(R.id.PopupMessage_Popup); + PopupMessage_text = MessagePopupView.findViewById(R.id.PopupMessage_text); + PopupMessage_BtnOk = MessagePopupView.findViewById(R.id.PopupMessage_BtnOk); + + PopupMessage_BtnOk.setOnClickListener((v) -> { this.HideMessagePopup(); }); + + /** Create popup window context **/ + PopupMessage = new PopupWindow( + MessagePopupView, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + /** Shows Message as popup **/ + private void ShowMessagePopup(String message) + { + PopupMessage_text.setText(""); + + if(message != null && !message.isEmpty()) + { + PopupMessage_text.setText(message); + } + + PopupMessageView_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + PopupMessage_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!PopupMessage.isShowing()) + { + PopupMessage.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + } + + /** Hides Message popup **/ + private void HideMessagePopup() + { + PopupMessageView_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + PopupMessage_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(PopupMessage.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PopupMessage.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PopupMessage_Popup.startAnimation(anim); + } + } + + /** Initialize PushNotificationExplain **/ + private void InitializePushExplainPopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + View PushExplainPopupView = inflater.inflate(R.layout.popup_push_explain, null); + + PopupPushExplainView_Overlay = PushExplainPopupView.findViewById(R.id.PopupPushExplain); + PopupPushExplain_header = PushExplainPopupView.findViewById(R.id.PopupPushExplain_header); + PopupPushExplain_text = PushExplainPopupView.findViewById(R.id.PopupPushExplain_text); + PopupPushExplain_BtnOk = PushExplainPopupView.findViewById(R.id.PopupPushExplain_BtnOk); + + PopupPushExplain_BtnOk.setOnClickListener((v) -> { this.HidePushNotificationExplain(); }); + + /** Create popup window context **/ + PopupPushExplain = new PopupWindow( + PushExplainPopupView, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + /** Show Push Notification Explain **/ + private void ShowPushNotificationExplain() + { + PopupPushExplainView_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + + if(!PopupPushExplain.isShowing()) + { + PopupPushExplain.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + } + private void RequestPushNotification() { + if (Build.VERSION.SDK_INT >= 33) { + int result = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS); + + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.POST_NOTIFICATIONS)) { + if (result != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(CurrentActivity, new String[]{Manifest.permission.POST_NOTIFICATIONS}, POST_NOTIFICATIONS_PERMISSION); + } else { + Session.NotificationGranted = true; + } + } + else { + if (result != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(CurrentActivity, new String[]{Manifest.permission.POST_NOTIFICATIONS}, POST_NOTIFICATIONS_PERMISSION); + } else { + Session.NotificationGranted = true; + } + } + } + } + /** Hide Push Notification Explain **/ + + private void HidePushNotificationExplain() + { + this.Settings.PushNotificationExplained = true; + this.Settings.save(this); + + this.RequestPushNotification(); + + if(PopupPushExplain.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PopupPushExplain.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PopupPushExplainView_Overlay.startAnimation(anim); + } + } + + /** Gots asked permission results **/ + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) + { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + + /** got status of push permission **/ + if(requestCode == PUSH_PERMISSION) + { + if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) + { + Session.NotificationGranted = true; + } + } + } + + /** On NewPGS Button clicked **/ + private void ButtonNewPGS_Click() + { + this.PopupNewPGS_Show(); + } + + /** On Cancel button of NewPGSPopup clicked **/ + private void PopupNewPGS_BtnCancel_Click() + { + this.HideKeyboard(PopupNewPGS_txtSampleId); + + if(this.PopupNewPGS_Loading.getVisibility() != View.VISIBLE) + { + if(this.PopupNewPGS_MasterPassword.getVisibility() != View.VISIBLE) + { + this.PopupNewPGS_Hide(); + } + else + { + this.PopupNewPGS_HidePassword(); + } + } + } + + /** On Add button of NewPGSPopup clicked **/ + private void PopupNewPGS_BtnAdd_Click() + { + if(this.Settings.verificator_hash != null) + { + this.RequestPGS(); + } + else + { + PopupNewPGS_Status.setText(""); + + if(PopupNewPGS_txtZIP.getText() == null || PopupNewPGS_txtZIP.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_ZIP")); + } + else if(PopupNewPGS_txtBirthday.getText() == null || PopupNewPGS_txtBirthday.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_BIRTHDAY")); + } + else if(PopupNewPGS_txtSampleId.getText() == null || PopupNewPGS_txtSampleId.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_SAMPLEID")); + } + else if(PopupNewPGS_txtZIP.getText().length() < 4) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_VALID_ZIP")); + } + else if(PopupNewPGS_txtBirthday.getText().length() < 10) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_VALID_BIRTHDAY")); + } + else if(PopupNewPGS_txtSampleId.getText().length() < 8) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_VALID_SAMPLEID")); + } + else + { + this.PopupNewPGS_ShowPassword(); + } + } + } + + /** + * Show PopupNewPGS + */ + private void PopupNewPGS_Show() + { + PopupNewPGS_txtZIP.setText(""); + PopupNewPGS_txtBirthday.setText(""); + PopupNewPGS_txtSampleId.setText(""); + PopupNewPGS_txtPassword.setText(""); + PopupNewPGS_txtPasswordConfirm.setText(""); + PopupNewPGS_txtPIN.setText(""); + PopupNewPGS_Status.setText(""); + PopupNewPGS_Loading.setVisibility(View.INVISIBLE); + PopupNewPGS_MasterPassword.setVisibility(View.GONE); + + /** Sets the default values from the settings **/ + if(this.Settings.verificator_hash != null) + { + this.PopupNewPGS_HidePassword(); + + /** Set the user zip if already defined in from settings **/ + if(this.Settings.zip != null && !this.Settings.zip.isEmpty()) + { + PopupNewPGS_txtZIP.setText(this.Settings.zip); + } + + /** Set the user birthday if already defined in from settings **/ + if(this.Settings.birthday != null && !this.Settings.birthday.isEmpty()) + { + Date birthday = this.Settings.GetBirthday(); + + if(birthday != null) + { + int year = DateHelper.GetFullYearFromDate(birthday); + int month = DateHelper.GetFullMonthFromDate(birthday); + int day = DateHelper.GetFullDayFromDate(birthday); + + BirthdayPicker.updateDate(year, month - 1, day); + PopupNewPGS_txtBirthday.setText(this.Settings.GetFormatedBirthday()); + } + } + + this.PopupNewPGS_MasterPassword.setVisibility(View.GONE); + this.PopupNewPGS_btnAdd.setText(Lang.Get("BTN_ADD")); + } + else + { + this.PopupNewPGS_btnAdd.setText(Lang.Get("BTN_NEXT")); + } + + PopupNewPGSView_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + PopupNewPGS_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!PopupNewPGS.isShowing()) + { + PopupNewPGS.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + + // Show messages directly + //RequestPGS(); + } + } + + /** + * Show Password content from PopupNewPGS + */ + private void PopupNewPGS_ShowPassword() + { + if(PopupNewPGS_MasterPassword.getVisibility() != View.VISIBLE) + { + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(PopupNewPGSContent.getWidth(),LinearLayout.LayoutParams.WRAP_CONTENT); + + PopupNewPGS_MasterPassword.setLayoutParams(layoutParams); + PopupNewPGS_MasterPassword.setTranslationX(PopupNewPGSContent.getWidth()); + PopupNewPGS_MasterPassword.setVisibility(View.VISIBLE); + + PopupNewPGS_PGS.animate().translationX(-(PopupNewPGSContent.getWidth())).setDuration(240); + PopupNewPGS_MasterPassword.animate().translationX(-PopupNewPGSContent.getWidth()).setDuration(240); + + PopupNewPGS_btnCancel.setText(Lang.Get("BTN_BACK")); + PopupNewPGS_btnAdd.setText(Lang.Get("BTN_ADD")); + + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); + } + else + { + RequestPGS(); + } + } + + /** + * Hide PopupNewPGS + */ + private void PopupNewPGS_Hide() + { + PopupNewPGSView_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + PopupNewPGS_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(PopupNewPGS.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PopupNewPGS.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PopupNewPGS_Popup.startAnimation(anim); + } + } + + /** + * Hide Password content from PopupNewPGS + */ + private void PopupNewPGS_HidePassword() + { + PopupNewPGS_Status.setText(""); + + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(PopupNewPGSContent.getWidth(),LinearLayout.LayoutParams.WRAP_CONTENT); + + PopupNewPGS_MasterPassword.setLayoutParams(layoutParams); + PopupNewPGS_MasterPassword.setTranslationX(PopupNewPGSContent.getWidth()); + PopupNewPGS_MasterPassword.setVisibility(View.VISIBLE); + + PopupNewPGS_PGS.animate().translationX(0).setDuration(240); + PopupNewPGS_MasterPassword.animate().translationX(PopupNewPGSContent.getWidth()).setDuration(240); + + PopupNewPGS_btnCancel.setText(Lang.Get("BTN_CANCEL")); + PopupNewPGS_btnAdd.setText(Lang.Get("BTN_NEXT")); + + PopupNewPGS_MasterPassword.setVisibility(View.INVISIBLE); + } + + /** + * Show MainMenu + */ + private void PopupMainMenu_Show() + { + /** + * Hide all user functions if not logged in + */ + if(!Session.IsLoggedIn()) + { + PopupMenu_lblNotRegisteredMenu.setVisibility(View.VISIBLE); + PopupMenu_btnMenuSettings_View.setVisibility(View.GONE); + PopupMenu_btnMenuChangePassword_View.setVisibility(View.GONE); + } + else + { + PopupMenu_lblNotRegisteredMenu.setVisibility(View.GONE); + PopupMenu_btnMenuSettings_View.setVisibility(View.VISIBLE); + PopupMenu_btnMenuChangePassword_View.setVisibility(View.VISIBLE); + } + + if(!PopupMenu.isShowing()) + { + PopupMenu_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.side_in_left)); + PopupMenu.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + } + + /** + * Hide MainMenu + */ + private void PopupMainMenu_Hide() + { + if(PopupMenu.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.side_out_left); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PopupMenu.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PopupMenu_Overlay.startAnimation(anim); + } + } + + /** Hide Keyboard **/ + public void HideKeyboard(View view) + { + InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + } + + /** Hide PopupNewPGS Loading with optional status message **/ + private void PopupNewPGS_HideLoading(String message) + { + PopupNewPGS_Loading.setVisibility(View.INVISIBLE); + + if(message != null && !message.isEmpty()) + { + PopupNewPGS_Status.setText(message); + } + } + + /** + * Goes to SettingsActivity + */ + private void GoToSettingsActivity() + { + Intent settingsActivity = new Intent(this, SettingsActivity.class); + //startActivity(settingsActivity); + settingsResultLauncher.launch(settingsActivity); + + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + + /** + * Goes to PasswordActivity + */ + private void GoToPasswordActivity() + { + Intent passwordActivity = new Intent(this, PasswordActivity.class); + startActivity(passwordActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + + /** + * Goes to SupportActivity + */ + private void GoToSupportActivity() + { + Intent supportActivity = new Intent(this, SupportActivity.class); + startActivity(supportActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + + /** + * Goes to FAQActivity + */ + private void GoToFAQActivity() + { + Intent faqActivity = new Intent(this, FAQActivity.class); + startActivity(faqActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + + /** END EVENTS **/ + + /** BEGIN FUNCTIONS **/ + + /** + * Returns Results from the List by pgs + * + * @param pgs - pgs of results + * @return returns results + */ + private Results GetResultsByPGS(String pgs) + { + de.labor_stein.befund.Core.Models.Database.Results result = null; + + if(Results != null && Results.size() > 0) + { + for(int i = 0; i < Results.size(); i++) + { + de.labor_stein.befund.Core.Models.Database.Results r = Results.get(i); + + if(r.pgs.equals(pgs)) + { + result =r; + break; + } + } + } + + return result; + } + + /** + * Load results from the database and from the outside service(optional) + * @param onlyLocale - if ture it will load only from locale db + */ + public void LoadResults(boolean onlyLocale) + { + try + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + Results = dbResults.GetResults(true); + + if(Results != null && Results.size() > 0) + { + lblNoResults.setVisibility(View.INVISIBLE); + ResultsTable.setVisibility(View.VISIBLE); + } + else + { + lblNoResults.setVisibility(View.VISIBLE); + ResultsTable.setVisibility(View.INVISIBLE); + } + + PushNotificationService.ClearNotificationBadge(MainContext); + + ResultsTable_Adapter.reloadData(Results); + } + }); + + if(!onlyLocale) + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.VISIBLE); + } + }); + + GetOpened getOpened = new GetOpened(); + getOpened.udid = Session.Device.udid; + getOpened.verificator_hash = this.Settings.verificator_hash; + + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + /** Delete old inactive results from local db **/ + dbResults.DeleteOldInactiveResults(); + + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("GetOpened", getOpened, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "opened", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + List statuses = (List)encryptedResponse.Decrypt(sharedKey); + + Results = dbResults.GetResults(false); + + if(statuses != null && statuses.size() > 0) + { + for(int i = 0; i < statuses.size(); i++) + { + Status status = statuses.get(i); + + if(status != null && + status.results_status != null && + !status.results_status.isEmpty() && + !status.results_status.toLowerCase().equals("none")) + { + if(status.results_status.toLowerCase().equals("not_found")) + { + /** Update table on main thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + ShowMessagePopup(Lang.Get("MSG_REQUESTED_RESULTS_NOT_FOUND")); + } + }); + } + else if(status.results_status.toLowerCase().equals("rejected")) + { + /** Update table on main thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + ShowMessagePopup(Lang.Get("MSG_REQUESTED_RESULTS_REJECTED")); + } + }); + } + else + { + de.labor_stein.befund.Core.Models.Database.Results foundResults = GetResultsByPGS(status.pgs); + + if(Results == null || foundResults == null) + { + if(!dbResults.Create(status.ToResults())) + { + Log.Critical("could not create results in db", "MainActivity", "LoadResults"); + } + else + { + /** if available start download automatically **/ + if(status.available && status.ToResults().GetStatus() == de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.COMPLETED) + { + Download(status.ToResults()); + } + } + } + else + { + de.labor_stein.befund.Core.Models.Database.Results serverResult = status.ToResults(); + + if(serverResult != null && foundResults != null && serverResult.pgs.equals(foundResults.pgs)) + { + if(serverResult.available && + serverResult.GetStatus() == de.labor_stein.befund.Core.Models.Database.Results.ResultsStatus.COMPLETED) + { + if(serverResult.file_checksum.equals(foundResults.file_checksum)) + { + serverResult.downloaded = foundResults.downloaded; + serverResult.downloaded_ts = foundResults.downloaded_ts; + serverResult.downloaded_file = foundResults.downloaded_file; + } + + if(!serverResult.picked_up && !serverResult.downloaded) + { + Download(serverResult); + } + + if(!dbResults.Update(serverResult, false)) + { + Log.Critical("could not update results in db", "MainActivity", "LoadResults"); + } + } + else + { + if(!dbResults.Update(serverResult, false)) + { + Log.Critical("could not update results in db", "MainActivity", "LoadResults"); + } + } + } + } + } + } + } + } + + Results = dbResults.GetResults(true); + + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if(Results != null && Results.size() > 0) + { + lblNoResults.setVisibility(View.INVISIBLE); + ResultsTable.setVisibility(View.VISIBLE); + } + else + { + lblNoResults.setVisibility(View.VISIBLE); + ResultsTable.setVisibility(View.INVISIBLE); + } + + MainLoading.setVisibility(View.INVISIBLE); + ResultsTable_Refresher.setRefreshing(false); + ResultsTable_Adapter.reloadData(Results); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + ResultsTable_Refresher.setRefreshing(false); + Log.Critical(error, "MainActivity", "LoadResults"); + } + }); + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if(Session.Maintenance && !Session.MaintenanceNotified) + { + Session.MaintenanceNotified = true; + ShowMessagePopup(Lang.Get("MSG_MAINTENANCE")); + } + + MainLoading.setVisibility(View.INVISIBLE); + ResultsTable_Refresher.setRefreshing(false); + Log.Critical(error, "MainActivity", "LoadResults"); + } + }); + }); + } + }); + + thread.start(); + } + else + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + ResultsTable_Refresher.setRefreshing(false); + } + }); + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "LoadResults(boolean)"); + } + } + + /** + * + * Updates DeviceToken for PUSH in Service + * */ + private void UpdateDeviceToken() + { + try + { + if(Session.Device != null && + Session.Device.udid != null && + this.Settings != null && + this.Settings.verificator_hash != null && + !Session.Device.udid.isEmpty() && + !this.Settings.verificator_hash.isEmpty() && + !Session.Device.udid.isEmpty()) + { + DeviceToken deviceToken = new DeviceToken(); + deviceToken.udid = Session.Device.udid; + deviceToken.verificator_hash = this.Settings.verificator_hash; + deviceToken.device_token = Session.Device.token; + + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("DeviceToken", deviceToken, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "update_token", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + {}, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + Log.Critical(error, "MainActivity", "UpdateDeviceToken"); + } + }); + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + Log.Critical(error, "MainActivity", "UpdateDeviceToken"); + } + }); + }); + } + }); + + thread.start(); + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "UpdateDeviceToken"); + } + } + + /** + * Sends PGS(Subscribe) Request to the server + */ + private void RequestPGS() + { + try + { + if(!pgs_request_running) + { + PopupNewPGS_Status.setText(""); + is_first_subscribe = false; + + if(PopupNewPGS_Loading.getVisibility() != View.VISIBLE) + { + PopupNewPGS_Loading.setVisibility(View.VISIBLE); + + if(PopupNewPGS_txtZIP.getText() == null || PopupNewPGS_txtZIP.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_ZIP")); + } + else if(PopupNewPGS_txtBirthday.getText() == null || PopupNewPGS_txtBirthday.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_BIRTHDAY")); + } + else if(PopupNewPGS_txtSampleId.getText() == null || PopupNewPGS_txtSampleId.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_SAMPLEID")); + } + else if(PopupNewPGS_txtZIP.getText().length() < 4) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_VALID_ZIP")); + } + else if(PopupNewPGS_txtBirthday.getText().length() < 10) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_VALID_BIRTHDAY")); + } + else if(PopupNewPGS_txtSampleId.getText().length() < 8) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_VALID_SAMPLEID")); + } + else + { + /** First Instalation **/ + if(this.Settings.verificator_hash == null) + { + if(PopupNewPGS_txtPassword.getText() == null || PopupNewPGS_txtPassword.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_PASSWORD")); + } + else + { + String password_policy = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!+@$%^&<>*~:`-]).{8,}$"; + + if(!PopupNewPGS_txtPassword.getText().toString().matches(password_policy)) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); + } + else if(!PopupNewPGS_txtPassword.getText().toString().equals(PopupNewPGS_txtPasswordConfirm.getText().toString())) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_CONFIRM_PASSWORD")); + } + else if(PopupNewPGS_txtPIN.getText() == null || PopupNewPGS_txtPIN.getText().toString().isEmpty()) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENTER_PIN")); + } + else if(PopupNewPGS_txtPIN.getText().toString().length() != 5) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); + } + else + { + Curve25519.KeyPair encryptionKeyPair = Curve25519.GenerateKeyPair(); + + if(encryptionKeyPair != null && encryptionKeyPair.PublicKey != null && !encryptionKeyPair.PublicKey.isEmpty()) + { + Session.DevicePassword = PopupNewPGS_txtPassword.getText().toString(); + byte[] key = AES.GetKey(PopupNewPGS_txtPassword.getText().toString()); + this.Settings.public_key = encryptionKeyPair.PublicKey; + this.Settings.password_reset_hash = UUID.randomUUID().toString(); + byte[] passwordHashKey = AES.GetKey(this.Settings.password_reset_hash + PopupNewPGS_txtPIN.getText().toString()); + this.Settings.password_hash = AES.Encrypt(PopupNewPGS_txtPassword.getText().toString(), passwordHashKey); + this.Settings.verificator_hash = SHA512.HMAC(SHA512.VerificatorHashingValue, key); + this.Settings.hashed_private_key = AES.Encrypt(encryptionKeyPair.PrivateKey, key); + this.Settings.zip = PopupNewPGS_txtZIP.getText().toString(); + this.Settings.SetBirthday(DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker())); + is_first_subscribe = true; + } + else + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_ENCRYPTION_NOT_SUPPORTED")); + Log.Critical("Could not create Curve25519 keyPair", "MainActivity", "requestPGS"); + } + } + } + } + else + { + this.Settings.zip = PopupNewPGS_txtZIP.getText().toString(); + this.Settings.SetBirthday(DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker())); + } + + if(this.Settings.verificator_hash != null) + { + String zip = PopupNewPGS_txtZIP.getText().toString(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + String birthday = dateFormat.format(DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker())); + String sampleid = PopupNewPGS_txtSampleId.getText().toString(); + + Subscribe subscribe = new Subscribe(); + subscribe.device_token = Session.Device.token; + subscribe.udid = Session.Device.udid; + subscribe.pgs = SHA512.Encrypt(zip + birthday + sampleid); + subscribe.pgs_hash = AES.Encrypt((zip + "|" + birthday + "|" + sampleid), AES.GetKey(subscribe.udid + AES.PGS_ENCRYPT_PARTIAL_KEY)); + subscribe.client_public_key = this.Settings.public_key; + subscribe.device_type = de.labor_stein.befund.Core.Models.Database.Results.DeviceTypes.ANDROID.ordinal(); + subscribe.verificator_hash = this.Settings.verificator_hash; + subscribe.pin = PopupNewPGS_txtPIN.getText().toString(); + Results dbResult = this.dbResults.GetResults(subscribe.pgs); + + if(dbResult != null) + { + // TODO: Anpassung vom STATUS? Warten auf Artur für iOS + PopupNewPGS_HideLoading(Lang.Get("MSG_PGS_ALREADY_EXISTS")); + } + else + { + HideKeyboard(PopupNewPGS_txtSampleId); + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + pgs_request_running = true; + + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("Subscribe", subscribe, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "subscribe", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + pgs_request_running = false; + Object response = encryptedResponse.Decrypt(sharedKey); + + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + /** Successfully subscripted **/ + if(encryptedResponse.descriptor.toLowerCase().equals("success")) + { + if(dbResults.Create(subscribe.ToResults())) + { + /** new **/ + if(!Settings.save(MainContext)) + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_COULD_NOT_SAVE")); + Log.Critical("Could not save settings to the file", "MainActivity", "requestPGS"); + } + + PopupNewPGS_Loading.setVisibility(View.INVISIBLE); + PopupNewPGS_HideLoading(""); + LoadResults(false); + PopupNewPGS_Hide(); + ShowMessagePopup(Lang.Get("MSG_PGS_SUCCESSFULLY_CREATED")); + } + else + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_COULD_NOT_SAVE")); + Log.Critical("Could not save sresults to the database", "MainActivity", "RequestPGS"); + } + } + /** Got some status on pgs **/ + else if(encryptedResponse.descriptor.toLowerCase().equals("status")) + { + Status status = (Status)response; + + if(status == null || !dbResults.CreateOrUpdate(status.ToResults())) + { + Log.Critical("Could not update status in the database", "MainActivity", "RequestPGS"); + } + + PopupNewPGS_HideLoading(Lang.Get("MSG_PGS_ALREADY_AVAILABLE")); + PopupNewPGS_Loading.setVisibility(View.INVISIBLE); + LoadResults(false); + + new Timer().schedule(new TimerTask() + { + @Override + public void run() + { + PopupNewPGS_Hide(); + } + }, 1000); + } + /** Got some exception response **/ + else + { + if(is_first_subscribe) + { +// Session.DevicePassword = null; +// Settings.verificator_hash = null; + Settings.save(MainContext); + } + + de.labor_stein.befund.Core.Models.Response.Exception responseException = (de.labor_stein.befund.Core.Models.Response.Exception)response; + + if(responseException != null) + { + switch (responseException.error_type) + { + case de.labor_stein.befund.Core.Models.Response.Exception.Types.MaxOpenedRequestLimit: + PopupNewPGS_HideLoading(Lang.Get("ERROR_MAX_OPENED_REQUEST_LIMIT")); + break; + + case de.labor_stein.befund.Core.Models.Response.Exception.Types.AlreadySubscribted: + PopupNewPGS_HideLoading(Lang.Get("ERROR_ALREADY_SUBSCRIBTED")); + break; + + default: + PopupNewPGS_HideLoading(Lang.Get("ERROR_COULD_NOT_REGISTER_PGS")); + break; + } + } + else + { + PopupNewPGS_HideLoading(Lang.Get("ERROR_COULD_NOT_REGISTER_PGS")); + Log.Critical("Could not register", "MainActivity", "RequestPGS"); + } + } + } + }); + }, + (error) -> + { + pgs_request_running = false; + + if(is_first_subscribe) + { +// Session.DevicePassword = null; +// Settings.verificator_hash = null; + Settings.save(MainContext); + } + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupNewPGS_HideLoading(error); + Log.Critical(error, "MainActivity", "RequestPGS"); + } + }); + + }); + }, + (error) -> + { + pgs_request_running = false; + + if(is_first_subscribe) + { +// Session.DevicePassword = null; +// Settings.verificator_hash = null; + Settings.save(MainContext); + } + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupNewPGS_HideLoading(error); + Log.Critical(error, "MainActivity", "RequestPGS"); + } + }); + }); + } + }); + + thread.start(); + } + } + } + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "RequestPGS"); + } + } + + /** + * Deletes results from the server + * @param results - Results that should be deleted on the server + */ + public void DeleteResults(Results results) + { + try + { + if(results != null) + { + if(this.dbResults.Delete(results)) + { + this.LoadResults(true); + + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + Subscribe subscribe = new Subscribe(); + subscribe.udid = Session.Device.udid; + subscribe.device_token = Session.Device.token; + subscribe.pgs = results.pgs; + subscribe.client_public_key = this.Settings.public_key; + subscribe.verificator_hash = this.Settings.verificator_hash; + + /** Delete on server **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("Subscribe", subscribe, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "unsubscribe", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + Log.Critical(error, "MainActivity", "DeleteResults"); + } + }); + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + Log.Critical(error, "MainActivity", "DeleteResults"); + } + }); + }); + } + }); + + this.MainLoading.setVisibility(View.VISIBLE); + thread.start(); + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "DeleteResults(Results)"); + } + } + + /** + * Downloads results from the server + * @param results + */ + public void Download(Results results) + { + try + { + if(!results.downloading) + { + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + Subscribe subscribe = new Subscribe(); + subscribe.udid = Session.Device.udid; + subscribe.device_token = Session.Device.token; + subscribe.pgs = results.pgs; + subscribe.client_public_key = this.Settings.public_key; + subscribe.verificator_hash = this.Settings.verificator_hash; + + /** Download from the server **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("Subscribe", subscribe, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "download", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + Download download = (Download)encryptedResponse.Decrypt(sharedKey, Download.class); + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + + if(download != null && + download.encrypted_content != null && + !download.encrypted_content.isEmpty() && + download.server_public_key != null && + !download.server_public_key.isEmpty()) + { + /** Decrypt hashed private key from the settings **/ + String decryptedPrivateKey = AES.Decrypt(Settings.hashed_private_key, AES.GetKey(Session.DevicePassword)); + + if(decryptedPrivateKey != null) + { + Curve25519.KeyPair keyPair = Curve25519.CreateKeyPair(decryptedPrivateKey, Settings.public_key); + + if(keyPair != null) + { + byte[] sharedKey = keyPair.GetSharedKey(download.server_public_key); + + if(sharedKey != null) + { + String decrypted_content = AES.Decrypt(download.encrypted_content, sharedKey); + + if(decrypted_content != null) + { + String local_encrypted = AES.Encrypt(decrypted_content, AES.GetKey(Session.DevicePassword)); + + if(local_encrypted != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + results.picked_up = true; + results.picked_up_ts = dateFormat.format(new Date()); + results.file_checksum = SHA512.Encrypt(decrypted_content); + + if(System.WriteToEncryptedStorage(results.pgs, local_encrypted.getBytes(StandardCharsets.UTF_8), MainContext) && + dbResults.Update(results, true)) + { + ResultsTable_Adapter.SetStatusForRow(results, results.GetStatusText(), results.GetStatusIcon(MainContext), false, results); + + CheckFileChecksum checksum = new CheckFileChecksum(); + checksum.pgs = results.pgs; + checksum.udid = Session.Device.udid; + checksum.device_token = Session.Device.token; + checksum.client_public_key = Settings.public_key; + checksum.verificator_hash = Settings.verificator_hash; + checksum.file_checksum = results.file_checksum; + + SendPickedUPAsync(checksum); + } + else + { + ResultsTable_Adapter.SetStatusForRow(results, Lang.Get("ERROR_RESULTS_COULD_NOT_DOWNLOADED"), getResources().getDrawable(R.drawable.ic_link_off), false, results); + + Log.Critical("could not store encrypted downloaded results to the encrypted storage", "MainActivity", "EncryptResults(Results)"); + Toast.makeText(MainContext, Lang.Get("ERROR_COULD_NOT_SAVE_ENCRYPTED"), Toast.LENGTH_SHORT).show(); + } + } + else + { + ResultsTable_Adapter.SetStatusForRow(results, Lang.Get("ERROR_RESULTS_COULD_NOT_DOWNLOADED"), getResources().getDrawable(R.drawable.ic_link_off), false, results); + Log.Critical("could not store encrypted downloaded results to the encrypted storage", "MainActivity", "EncryptResults(Results)"); + Toast.makeText(MainContext, Lang.Get("ERROR_COULD_NOT_SAVE_ENCRYPTED"), Toast.LENGTH_SHORT).show(); + } + } + else + { + ResultsTable_Adapter.SetStatusForRow(results, Lang.Get("ERROR_RESULTS_COULD_NOT_DOWNLOADED"), getResources().getDrawable(R.drawable.ic_link_off), false, results); + Log.Critical("could not decrypt downloaded results", "MainActivity", "EncryptResults(Results)"); + Toast.makeText(MainContext, Lang.Get("ERROR_COULD_NOT_DECRYPT"), Toast.LENGTH_SHORT).show(); + } + } + } + } + } + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + ResultsTable_Adapter.SetStatusForRow(results, Lang.Get("ERROR_RESULTS_COULD_NOT_DOWNLOADED"), getResources().getDrawable(R.drawable.ic_link_off), false, results); + Log.Critical(error, "MainActivity", "Download(Results)"); + } + }); + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + ResultsTable_Adapter.SetStatusForRow(results, Lang.Get("ERROR_RESULTS_COULD_NOT_DOWNLOADED"), getResources().getDrawable(R.drawable.ic_link_off), false, results); + Log.Critical(error, "MainActivity", "Download(Results)"); + } + }); + }); + } + }); + + /** set downloading icon on the main thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + ResultsTable_Adapter.SetDownloadingForRow(results); + MainLoading.setVisibility(View.VISIBLE); + } + }); + + thread.start(); + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "Download(Results)"); + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + MainLoading.setVisibility(View.INVISIBLE); + ResultsTable_Adapter.SetStatusForRow(results, Lang.Get("ERROR_RESULTS_COULD_NOT_DOWNLOADED"), getResources().getDrawable(R.drawable.ic_link_off), false, results); + } + }); + } + } + + /** + * Encrypts Results by confirm of password + * + * @param results - results that should be encrypted + */ + public void EncryptResults(Results results) + { + try + { + String filename = System.GetPathForStorageEncryptedFile(results.pgs, this); + + if(filename != null && System.FileExists(filename)) + { + byte[] encrypted_content = System.ReadFromEncryptedStorage(results.pgs, this); + + if(encrypted_content != null) + { + String decrypted_content = AES.Decrypt(new String(encrypted_content), AES.GetKey(Session.DevicePassword)); + + if(decrypted_content != null) + { + if(!results.picked_up) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + results.picked_up = true; + results.picked_up_ts = dateFormat.format(new Date()); + results.file_checksum = SHA512.Encrypt(decrypted_content); + + if(this.dbResults.Update(results, false)) + { + if(!results.picked_up) + { + CheckFileChecksum checksum = new CheckFileChecksum(); + checksum.pgs = results.pgs; + checksum.udid = Session.Device.udid; + checksum.device_token = Session.Device.token; + checksum.client_public_key = this.Settings.public_key; + checksum.verificator_hash = this.Settings.verificator_hash; + checksum.file_checksum = results.file_checksum; + this.SendPickedUPAsync(checksum); + } + } + } + + this.PDFViewer_Show(decrypted_content); + } + } + else + { + Log.Critical("encrypted file not found in storage", "MainActivity", "EncryptResults(Results)"); + Toast.makeText(this, Lang.Get("ERROR_ENCRYPTED_FILE_NOT_FOUND"), Toast.LENGTH_SHORT).show(); + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "MainActivity", "EncryptResults(Results)"); + } + } + + /** + * Call PDF Viewer to render PDF + * + * @param decrypted_content + */ + private void PDFViewer_Show(String decrypted_content) + { + try + { + PDFViewerActivity.PDFCurrentContent = null; + + Intent pdfViewerActivity = new Intent(this, PDFViewerActivity.class); + PDFViewerActivity.PDFCurrentContent = Base64.FromBase64String(decrypted_content); + startActivity(pdfViewerActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "PDFViewer_Show"); + } + } + + /** + * Send PickedUp Flag with file checksum to the server + * + * @param checksum - checksum request + */ + private void SendPickedUPAsync(CheckFileChecksum checksum) + { + try + { + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("CheckFileChecksum", checksum, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "pickedup", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> {}, + (error) -> + { + Log.Critical(error, "MainActivity", "Download(Results)"); + }); + }, + (error) -> + { + Log.Critical(error, "MainActivity", "Download(Results)"); + }); + } + }); + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "MainActivity", "SendPickedUPAsync(CheckFileChecksum)"); + } + } + + /** END FUNCTIONS **/ +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/NewOEGDActivity.java b/app/src/main/java/de/labor_stein/befund/NewOEGDActivity.java new file mode 100644 index 0000000..46da584 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/NewOEGDActivity.java @@ -0,0 +1,354 @@ +// +// NewOEGDActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 02.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.app.DatePickerDialog; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.Spinner; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.gson.Gson; + +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import de.labor_stein.befund.Core.Helpers.DateHelper; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.OEGD; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.System; + +public class NewOEGDActivity extends AppCompatActivity +{ + /** NewOEGDActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + + /** Controls **/ + private TextView lblNewOEGD; + private TextView NewOEGDActivitylblButtonBack; + private EditText NewOEGDActivity_txtTitle; + private EditText NewOEGDActivity_txtFirstname; + private EditText NewOEGDActivity_txtLastname; + private EditText NewOEGDActivity_txtAdditionLastname; + private EditText NewOEGDActivity_txtPrefix; + private Spinner NewOEGDActivity_txtGenders; + private EditText NewOEGDActivity_txtBirthday; + private DatePickerDialog BirthdayPicker; + private EditText NewOEGDActivity_txtStreet; + private EditText NewOEGDActivity_txtZIP; + private EditText NewOEGDActivity_txtCity; + private EditText NewOEGDActivity_txtTelefon; + + private Button NewOEGDActivity_btnCreate; + private TextView NewOEGDActivity_Status; + + /** Buttons **/ + private FloatingActionButton OEGDButtonBack; + + /** List items **/ + private String[] Genders = { Lang.Get("LBL_GENDER"), Lang.Get("LBL_GENDER_M"), Lang.Get("LBL_GENDER_W"), Lang.Get("LBL_GENDER_D"), Lang.Get("LBL_GENDER_X") }; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_new_oegd); + + this.Initialize(); + } + + /** + * Initializes eIDActivity + */ + private void Initialize() + { + MainContext = this; + Log.Initialize(this); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializeControls(); + + this.InitializeLanguages(); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblNewOEGD.setText(Lang.Get("LBL_NEW_OEGD")); + NewOEGDActivitylblButtonBack.setText(Lang.Get("BTN_BACK")); + + NewOEGDActivity_txtTitle.setHint(Lang.Get("LBL_TITLE")); + NewOEGDActivity_txtFirstname.setHint(Lang.Get("LBL_FIRSTNAME")); + NewOEGDActivity_txtLastname.setHint(Lang.Get("LBL_LASTNAME")); + NewOEGDActivity_txtAdditionLastname.setHint(Lang.Get("LBL_ADDITION_NAME")); + NewOEGDActivity_txtPrefix.setHint(Lang.Get("LBL_NAME_PREFIX")); + NewOEGDActivity_txtBirthday.setHint(Lang.Get("LBL_BIRTHDAY")); + NewOEGDActivity_txtStreet.setHint(Lang.Get("LBL_STREET")); + NewOEGDActivity_txtZIP.setHint(Lang.Get("LBL_ZIP")); + NewOEGDActivity_txtCity.setHint(Lang.Get("LBL_CITY")); + NewOEGDActivity_txtTelefon.setHint(Lang.Get("LBL_TELEFON")); + NewOEGDActivity_btnCreate.setText(Lang.Get("BTN_CREATE")); + } + + /** + * Initializes controls + */ + private void InitializeControls() + { + NewOEGDActivity_btnCreate = findViewById(R.id.NewOEGDActivity_btnCreate); + NewOEGDActivity_txtTitle = findViewById(R.id.NewOEGDActivity_txtTitle); + NewOEGDActivity_txtFirstname = findViewById(R.id.NewOEGDActivity_txtFirstname); + NewOEGDActivity_txtLastname = findViewById(R.id.NewOEGDActivity_txtLastname); + NewOEGDActivity_txtAdditionLastname = findViewById(R.id.NewOEGDActivity_txtAdditionLastname); + NewOEGDActivity_txtPrefix = findViewById(R.id.NewOEGDActivity_txtPrefix); + NewOEGDActivity_txtGenders = findViewById(R.id.NewOEGDActivity_txtGenders); + NewOEGDActivity_txtBirthday = findViewById(R.id.NewOEGDActivity_txtBirthday); + NewOEGDActivity_txtStreet = findViewById(R.id.NewOEGDActivity_txtStreet); + NewOEGDActivity_txtZIP = findViewById(R.id.NewOEGDActivity_txtZIP); + NewOEGDActivity_txtCity = findViewById(R.id.NewOEGDActivity_txtCity); + NewOEGDActivity_txtTelefon = findViewById(R.id.NewOEGDActivity_txtTelefon); + NewOEGDActivity_Status = findViewById(R.id.NewOEGDActivity_Status); + + ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, this.Genders); + aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + NewOEGDActivity_txtGenders.setAdapter(aa); + + /** DatePicker **/ + BirthdayPicker = new DatePickerDialog(this, R.style.MySpinnerDatePickerStyle); + BirthdayPicker.getDatePicker().setMaxDate(new Date().getTime()); + BirthdayPicker.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() + { + @Override + public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) + { + Date selectedDate = DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker()); + + if(selectedDate != null) + { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); + NewOEGDActivity_txtBirthday.setText(dateFormat.format(selectedDate)); + } + } + }); + + /** Disable directly key insert in the birthday field(it should be set by DatePicker for well formed value) **/ + NewOEGDActivity_txtBirthday.setOnKeyListener((View v, int keyCode, KeyEvent event) -> { return true; }); + + /** Show/Hide DatePicker **/ + NewOEGDActivity_txtBirthday.setOnFocusChangeListener((View v, boolean hasFocus) -> { if(hasFocus) { BirthdayPicker.show(); } }); + NewOEGDActivity_txtBirthday.setOnTouchListener((View v, MotionEvent event) -> { BirthdayPicker.show(); return true; }); + + NewOEGDActivity_btnCreate.setOnClickListener(v -> { this.NewOEGDActivity_btnCreate_Click(); }); + + //NewOEGDActivity_btnAcceptCWAPolicy.setOnClickListener((v) -> { PopupCWAPolicy.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0);}); + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.NewOEGDActivityRootLayout); + } + + /** + * Initializes Labels + */ + private void InitializeLabels() + { + lblNewOEGD = ActivityRootLayout.findViewById(R.id.lblNewOEGD); + NewOEGDActivitylblButtonBack = ActivityRootLayout.findViewById(R.id.NewOEGDActivitylblButtonBack); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + OEGDButtonBack = ActivityRootLayout.findViewById(R.id.OEGDButtonBack); + OEGDButtonBack.setOnClickListener(v ->{ OEGDButtonBack_Click(); }); + } + + /** + * Go Back to OEGDActivity + */ + private void OEGDButtonBack_Click() + { + Intent intent = new Intent(this, OEGDActivity.class); + startActivity(intent); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } + + /** + * Creates a new OEGD + */ + private void NewOEGDActivity_btnCreate_Click() + { + try + { + NewOEGDActivity_Status.setText(""); + + if(NewOEGDActivity_txtFirstname.getText() == null || NewOEGDActivity_txtFirstname.getText().toString().isEmpty()) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_FIRSTNAME")); + } + else if(NewOEGDActivity_txtLastname.getText() == null || NewOEGDActivity_txtLastname.getText().toString().isEmpty()) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_LASTNAME")); + } + else if(NewOEGDActivity_txtBirthday.getText() == null || NewOEGDActivity_txtBirthday.getText().toString().isEmpty()) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_BIRTHDAY")); + } + else if(NewOEGDActivity_txtGenders.getSelectedItemPosition() <= 0) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_GENDER")); + } + else if(NewOEGDActivity_txtStreet.getText() == null || NewOEGDActivity_txtStreet.getText().toString().isEmpty()) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_STREET")); + } + else if(NewOEGDActivity_txtZIP.getText() == null || NewOEGDActivity_txtZIP.getText().toString().isEmpty()) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_ZIP")); + } + else if(NewOEGDActivity_txtCity.getText() == null || NewOEGDActivity_txtCity.getText().toString().isEmpty()) + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_ENTER_CITY")); + } + else + { + OEGD oegd = new OEGD(); + oegd.first_name = NewOEGDActivity_txtFirstname.getText().toString(); + oegd.last_name = NewOEGDActivity_txtLastname.getText().toString(); + + Date selectedDate = DateHelper.getDateFromDatePicket(BirthdayPicker.getDatePicker()); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + oegd.birthdate = dateFormat.format(selectedDate); + + int genderIndex = (int)NewOEGDActivity_txtGenders.getSelectedItemId(); + String gender_full_name = Genders[genderIndex]; + + if(gender_full_name.equals(Lang.Get("LBL_GENDER_M"))) + { + oegd.gender = "M"; + } + else if(gender_full_name.equals(Lang.Get("LBL_GENDER_W"))) + { + oegd.gender = "W"; + } + else if(gender_full_name.equals(Lang.Get("LBL_GENDER_D"))) + { + oegd.gender = "D"; + } + else + { + oegd.gender = "X"; + } + + if(NewOEGDActivity_txtTitle.getText() != null && !NewOEGDActivity_txtTitle.getText().toString().isEmpty()) + { + oegd.title = NewOEGDActivity_txtTitle.getText().toString(); + } + + if(NewOEGDActivity_txtAdditionLastname.getText() != null && !NewOEGDActivity_txtAdditionLastname.getText().toString().isEmpty()) + { + oegd.name_addition = NewOEGDActivity_txtAdditionLastname.getText().toString(); + } + + if(NewOEGDActivity_txtPrefix.getText() != null && !NewOEGDActivity_txtPrefix.getText().toString().isEmpty()) + { + oegd.prefix = NewOEGDActivity_txtPrefix.getText().toString(); + } + + oegd.address = OEGD.Address.createInstance(); + oegd.address.zip_code = NewOEGDActivity_txtZIP.getText().toString(); + oegd.address.city = NewOEGDActivity_txtCity.getText().toString(); + oegd.address.street_number = NewOEGDActivity_txtStreet.getText().toString(); + oegd.address.country_code = "D"; + + if(NewOEGDActivity_txtTelefon.getText() != null && !NewOEGDActivity_txtTelefon.getText().toString().isEmpty()) + { + oegd.phone = NewOEGDActivity_txtTelefon.getText().toString(); + } + + String json = new Gson().toJson(oegd); + + if(json != null) + { + String encrypted_content = AES.Encrypt(json, AES.GetKey(Session.DevicePassword)); + + if(encrypted_content != null) + { + SimpleDateFormat dF = new SimpleDateFormat("yyyyMMdd_HH_mm_ss"); + String filename = dF.format(new Date()) + "_" + UUID.randomUUID().toString().replace("-", "") + ".oegd"; + + if(System.WriteToStorage(filename, encrypted_content.getBytes(StandardCharsets.UTF_8), this)) + { + GoToOEGDActivity(); + } + else + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_COULD_NOT_SAVE_OEGD")); + } + } + else + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_COULD_NOT_SAVE_OEGD")); + } + } + else + { + NewOEGDActivity_Status.setText(Lang.Get("ERROR_COULD_NOT_SAVE_OEGD")); + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "NewOEGDActivity", "NewOEGDActivity_btnCreate_Click"); + } + } + + /** + * Goes back to OEGDActivity + */ + private void GoToOEGDActivity() + { + Intent OEGDActivity = new Intent(this, OEGDActivity.class); + startActivity(OEGDActivity); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } +} \ No newline at end of file diff --git a/app/src/main/java/de/labor_stein/befund/OEGDActivity.java b/app/src/main/java/de/labor_stein/befund/OEGDActivity.java new file mode 100644 index 0000000..3a05fd2 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/OEGDActivity.java @@ -0,0 +1,717 @@ +// +// OEGDActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 02.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.os.Bundle; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.animation.AlphaAnimation; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.view.animation.LinearInterpolator; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.ProgressBar; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; +import androidx.fragment.app.FragmentStatePagerAdapter; +import androidx.viewpager.widget.PagerAdapter; +import androidx.viewpager.widget.ViewPager; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.gson.Gson; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import de.labor_stein.befund.Core.Helpers.ImageHelper; +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.Status; +import de.labor_stein.befund.Core.Models.Labor; +import de.labor_stein.befund.Core.Models.OEGD; +import de.labor_stein.befund.Core.Models.OEGDFile; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.System; + +public class OEGDActivity extends AppCompatActivity +{ + /** OEGDActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + + /** Controls **/ + private TextView lblOEGD; + private TextView lblOEGDButtonButtonBack; + private TextView lblNoOEGD; + private ProgressBar OEGDMainLoading; + + /** Buttons **/ + private FloatingActionButton OEGDButtonBack; + private Button bottomOEGDButtonMenuOpener; + + /** BEGIN POPUPS **/ + + /** BEGIN OptionsPopup **/ + private PopupWindow OEGDOptionsOptions; + private View OEGDOptionsOptions_Overlay; + private LinearLayout OEGDOptionsOptions_Popup; + private Button OEGDOptionsOptions_BtnAdd; + private LinearLayout OEGDOptionsEditView; + private Button OEGDOptionsOptions_BtnEdit; + private LinearLayout OEGDOptionsDeleteView; + private Button OEGDOptionsOptions_BtnDelete; + private Button OEGDOptionsOptions_BtnCancel; + /** END OptionsPopup **/ + + /** BEGIN ConfirmDeletePopup **/ + private PopupWindow ConfirmDeletePopup; + private View ConfirmDeletePopup_Overlay; + private LinearLayout ConfirmDeletePopup_Popup; + private TextView PopupConfirmDelete_text; + private Button ConfirmDeletePopup_BtnYES; + private Button ConfirmDeletePopup_BtnNO; + /** END ConfirmDeletePopup **/ + + /** END POPUPS **/ + + /** OEGDs **/ + private List OEGDFiles; + private OEGDFile CurrentOEGDFile = null; + + /** ViewPager **/ + private ViewPager Pager; + private PagerAdapter Adapter; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_oegd); + + this.Initialize(); + } + + /** + * Initializes OEGDActivity + */ + private void Initialize() + { + MainContext = this; + Log.Initialize(this); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializeOptionsPopup(); + this.InitializeConfirmDeletePopup(); + this.InitializePager(); + this.InitializeLanguages(); + + this.loadOEGDs(); + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.OEGDActivityRootLayout); + } + + /** + * Initializes Labels + */ + private void InitializeLabels() + { + lblOEGD = ActivityRootLayout.findViewById(R.id.lblOEGD); + lblOEGDButtonButtonBack = ActivityRootLayout.findViewById(R.id.lblOEGDButtonButtonBack); + lblNoOEGD = ActivityRootLayout.findViewById(R.id.lblNoOEGD); + OEGDMainLoading = ActivityRootLayout.findViewById(R.id.OEGDMainLoading); + OEGDMainLoading.setVisibility(View.GONE); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + OEGDButtonBack = ActivityRootLayout.findViewById(R.id.OEGDButtonBack); + OEGDButtonBack.setOnClickListener(v ->{ OEGDButtonBack_Click(); }); + bottomOEGDButtonMenuOpener = ActivityRootLayout.findViewById(R.id.bottomOEGDButtonMenuOpener); + bottomOEGDButtonMenuOpener.setOnClickListener(v -> { this.OEGDOptionsOptions_Show(); }); + } + + /** + * Initializes ConfirmDelete Popup + */ + private void InitializeConfirmDeletePopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + ConfirmDeletePopup_Overlay = inflater.inflate(R.layout.popup_confirm_delete, null); + ConfirmDeletePopup_Popup = ConfirmDeletePopup_Overlay.findViewById(R.id.PopupConfirm_Popup); + PopupConfirmDelete_text = ConfirmDeletePopup_Overlay.findViewById(R.id.PopupConfirmDelete_text); + ConfirmDeletePopup_BtnYES = ConfirmDeletePopup_Overlay.findViewById(R.id.PopupPasswordConfirm_BtnYES); + ConfirmDeletePopup_BtnYES.setOnClickListener(v -> { this.ConfirmDeletePopup_BtnYES_Click(); }); + ConfirmDeletePopup_BtnNO = ConfirmDeletePopup_Overlay.findViewById(R.id.PopupConfirmDelete_BtnNO); + ConfirmDeletePopup_BtnNO.setOnClickListener(v -> { this.OConfirmDeletePopup_Hide(); }); + + /** Create popup window context **/ + ConfirmDeletePopup = new PopupWindow( + ConfirmDeletePopup_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + /** + * Initializes Options Popup + */ + private void InitializeOptionsPopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + OEGDOptionsOptions_Overlay = inflater.inflate(R.layout.popup_oegd_options, null); + OEGDOptionsOptions_Popup = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptions_Popup); + OEGDOptionsOptions_BtnAdd = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptions_BtnAdd); + OEGDOptionsOptions_BtnAdd.setOnClickListener(v -> { this.OEGDOptionsOptions_BtnAdd_Click(); }); + OEGDOptionsEditView = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptionsEditView); + OEGDOptionsOptions_BtnEdit = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptions_BtnEdit); + OEGDOptionsOptions_BtnEdit.setOnClickListener(v -> { this.OEGDOptionsOptions_BtnEdit_Click(); }); + OEGDOptionsDeleteView = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptionsDeleteView); + OEGDOptionsOptions_BtnDelete = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptions_BtnDelete); + OEGDOptionsOptions_BtnDelete.setOnClickListener(v -> { this.OEGDOptionsOptions_BtnDelete_Click(); }); + OEGDOptionsOptions_BtnCancel = OEGDOptionsOptions_Overlay.findViewById(R.id.OEGDOptions_BtnCancel); + OEGDOptionsOptions_BtnCancel.setOnClickListener(v -> { this.OEGDOptionsOptions_BtnCancel_Click(); }); + + /** Create popup window context **/ + OEGDOptionsOptions = new PopupWindow( + OEGDOptionsOptions_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + /** + * Initializes OEGD Pager + */ + private void InitializePager() + { + Pager = (ViewPager) findViewById(R.id.OEGDPager); + Adapter = new OEGDActivity.OEGDPagerAdapter(getSupportFragmentManager(), this.OEGDFiles, this); + Pager.setAdapter(Adapter); + + Pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() + { + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) + { + CurrentOEGDFile = null; + OEGDOptionsEditView.setVisibility(View.GONE); + OEGDOptionsDeleteView.setVisibility(View.GONE); + + if(OEGDFiles != null && OEGDFiles.size() > 0 && position >= 0 && position < OEGDFiles.size()) + { + OEGDOptionsEditView.setVisibility(View.VISIBLE); + OEGDOptionsDeleteView.setVisibility(View.VISIBLE); + CurrentOEGDFile = OEGDFiles.get(position); + } + } + + @Override + public void onPageSelected(int position) {} + + @Override + public void onPageScrollStateChanged(int state) {} + }); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblOEGD.setText(Lang.Get("LBL_OEGD")); + + lblNoOEGD.setText(Lang.Get("LBL_NO_OEGD")); + lblOEGDButtonButtonBack.setText(Lang.Get("BTN_BACK")); + OEGDOptionsOptions_BtnAdd.setText(Lang.Get("BTN_ADD")); + OEGDOptionsOptions_BtnEdit.setText(Lang.Get("BTN_EDIT")); + OEGDOptionsOptions_BtnDelete.setText(Lang.Get("BTN_DELETE")); + OEGDOptionsOptions_BtnCancel.setText(Lang.Get("BTN_CANCEL")); + ConfirmDeletePopup_BtnYES.setText(Lang.Get("BTN_YES")); + ConfirmDeletePopup_BtnNO.setText(Lang.Get("BTN_NO")); + } + + /** BEGIN EVENTS **/ + + /** + * Show ConfirmDeletePopup + */ + private void ConfirmDeletePopup_Show() + { + if(CurrentOEGDFile != null) + { + String text = Lang.Get("MSG_SURE_WANT_DELETE").replace("[ITEM]", (CurrentOEGDFile.OEGD.first_name + " " + CurrentOEGDFile.OEGD.last_name)); + PopupConfirmDelete_text.setText(text); + + ConfirmDeletePopup_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + ConfirmDeletePopup_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!ConfirmDeletePopup.isShowing()) + { + ConfirmDeletePopup.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + } + } + + /** + * Delete confirmed item + */ + private void ConfirmDeletePopup_BtnYES_Click() + { + try + { + if(CurrentOEGDFile != null) + { + String file = System.GetPathForStorageFile(CurrentOEGDFile.filename, MainContext); + + if(file != null) + { + System.DeleteFile(file); + } + + this.OConfirmDeletePopup_Hide(); + + //this.loadOEGDs(); + + finish(); + overridePendingTransition(0, 0); + startActivity(getIntent()); + overridePendingTransition(0, 0); + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "OEGDActivity", "ConfirmDeletePopup_BtnYES_Click"); + } + } + + /** + * Hide ConfirmDeletePopup + */ + private void OConfirmDeletePopup_Hide() + { + ConfirmDeletePopup_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + ConfirmDeletePopup_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(ConfirmDeletePopup.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) {} + + @Override + public void onAnimationEnd(Animation animation) + { + ConfirmDeletePopup.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + ConfirmDeletePopup_Popup.startAnimation(anim); + } + } + + /** + * Show OEGDOptionsOptions + */ + private void OEGDOptionsOptions_Show() + { + OEGDOptionsOptions_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + OEGDOptionsOptions_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!OEGDOptionsOptions.isShowing()) + { + OEGDOptionsOptions.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + } + + /** + * Hide OEGDOptionsOptions + */ + private void OEGDOptionsOptions_Hide() + { + OEGDOptionsOptions_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + OEGDOptionsOptions_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(OEGDOptionsOptions.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + OEGDOptionsOptions.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + OEGDOptionsOptions_Popup.startAnimation(anim); + } + } + + /** + * Go Back to MainActivity + */ + private void OEGDButtonBack_Click() + { + Intent intent = new Intent(this, MainActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + Bundle parameters = new Bundle(); + parameters.putBoolean("SplashScreenLoaded", true); + intent.putExtras(parameters); + startActivity(intent); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } + + /** + * On OptionsPopup Add Button clicked + */ + private void OEGDOptionsOptions_BtnAdd_Click() + { + this.OEGDOptionsOptions_Hide(); + this.NewOEGDActivity(); + } + + /** + * Goes to NewOEGDActivity + */ + private void NewOEGDActivity() + { + Intent newOEGDActivity = new Intent(this, NewOEGDActivity.class); + startActivity(newOEGDActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + + /** + * On OptionsPopup Edit Button clicked + */ + private void OEGDOptionsOptions_BtnEdit_Click() + { + this.OEGDOptionsOptions_Hide(); + + if(CurrentOEGDFile != null) + { + this.GoToEditOEGDActivity(CurrentOEGDFile); + } + } + + /** + * GoTo EditOEGDActivity + * + * @param oegdFile - oegd file that should be edited + */ + private void GoToEditOEGDActivity(OEGDFile oegdFile) + { + try + { + Intent editOEGDActivity = new Intent(this, EditOEGDActivity.class); + Bundle parameters = new Bundle(); + parameters.putString("file", oegdFile.filename); + editOEGDActivity.putExtras(parameters); + startActivity(editOEGDActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "MainActivity", "GoToEditOEGDActivity"); + } + } + + /** + * On OptionsPopup Delete Button clicked + */ + private void OEGDOptionsOptions_BtnDelete_Click() + { + this.OEGDOptionsOptions_Hide(); + this.ConfirmDeletePopup_Show(); + } + + /** + * On OptionsPopup Cancel Button clicked + */ + private void OEGDOptionsOptions_BtnCancel_Click() + { + this.OEGDOptionsOptions_Hide(); + } + + /** END EVENTS **/ + + /** BEGIN FUNCTIONS **/ + + private void loadOEGDs() + { + this.OEGDFiles = null; + + OEGDMainLoading.setVisibility(View.VISIBLE); + + try + { + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + List oegdFiles = System.GetOEGDFiles(MainContext); + + if(oegdFiles != null && oegdFiles.size() > 0) + { + OEGDFiles = new ArrayList<>(); + + for(int i = 0; i < oegdFiles.size(); i++) + { + try + { + File f = oegdFiles.get(i); + + byte[] encrypted_content = System.ReadFromStorage(f.getName(), MainContext); + + if(encrypted_content != null) + { + String json = AES.Decrypt(new String(encrypted_content, StandardCharsets.UTF_8), AES.GetKey(Session.DevicePassword)); + + if(json != null) + { + OEGD obj = (OEGD)new Gson().fromJson(json, OEGD.class); + + if(obj != null) + { + OEGDFile oegdFile = new OEGDFile(); + oegdFile.OEGD = obj; + oegdFile.filename = f.getName(); + OEGDFiles.add(oegdFile); + } + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "eIDActivity", "loadOEGDs"); + } + } + } + + UpdateOEGDCodes(); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "eIDActivity", "loadOEGDs"); + } + } + + /** + * Updates OEGD QR-Codes on main thread + */ + private void UpdateOEGDCodes() + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + OEGDMainLoading.setVisibility(View.GONE); + OEGDOptionsEditView.setVisibility(View.GONE); + OEGDOptionsDeleteView.setVisibility(View.GONE); + + if(OEGDFiles != null && OEGDFiles.size() > 0) + { + OEGDOptionsEditView.setVisibility(View.VISIBLE); + OEGDOptionsDeleteView.setVisibility(View.VISIBLE); + Pager.setVisibility(View.VISIBLE); + lblNoOEGD.setVisibility(View.GONE); + + bottomOEGDButtonMenuOpener.clearAnimation(); + } + else + { + Pager.setVisibility(View.GONE); + lblNoOEGD.setVisibility(View.VISIBLE); + + Animation animation = new AlphaAnimation(1, 0); + animation.setDuration(200); + animation.setInterpolator(new LinearInterpolator()); + animation.setRepeatCount(Animation.INFINITE); + animation.setRepeatMode(Animation.REVERSE); + bottomOEGDButtonMenuOpener.startAnimation(animation); + } + + ((OEGDActivity.OEGDPagerAdapter)Adapter).updateDataset(OEGDFiles); + } + }); + } + + /** END FUNCTIONS **/ + + /** OEGDSwitcher Adapter **/ + private class OEGDPagerAdapter extends FragmentStatePagerAdapter + { + /** List of OEGDFiles **/ + private List OEGDFiles = null; + + /** OEGDActivity Context **/ + private OEGDActivity OEGDActivity; + + public OEGDPagerAdapter(FragmentManager fragmentManager, List oegdFiles, OEGDActivity oegdActivity) + { + super(fragmentManager); + this.OEGDFiles = oegdFiles; + this.OEGDActivity = oegdActivity; + + if(this.OEGDFiles == null) + { + this.OEGDFiles = new ArrayList<>(); + } + } + + /** + * Updates dataset + */ + public void updateDataset(List oegdFiles) + { + this.OEGDFiles = oegdFiles; + + if(this.OEGDFiles == null) + { + this.OEGDFiles = new ArrayList<>(); + } + + this.notifyDataSetChanged(); + } + + @Override + public int getCount() + { + return this.OEGDFiles.size(); + } + + @Override + public Fragment getItem(int position) + { + return de.labor_stein.befund.OEGDActivity.OEGDFragment.newInstance(this.OEGDFiles.get(position), this.OEGDActivity); + } + } + + /** OEGDCard Fragment **/ + public static class OEGDFragment extends Fragment + { + /** OEGDActivity Context **/ + private OEGDActivity OEGDActivity; + + /** OEGDFile object **/ + private OEGDFile OEGDFile; + + /** Constructor for OEGDFragment **/ + public OEGDFragment(OEGDFile oegdFile, OEGDActivity oegdActivity) + { + this.OEGDFile = oegdFile; + this.OEGDActivity = oegdActivity; + } + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + View view = inflater.inflate(R.layout.fragment_oegd_code, container, false); + ImageView qrCode = view.findViewById(R.id.fragment_oegd_qr_code); + + TextView name = view.findViewById(R.id.fragment_oegd_name); + name.setText(this.OEGDFile.OEGD.first_name + " " + this.OEGDFile.OEGD.last_name); + + try + { + String json = new Gson().toJson(this.OEGDFile.OEGD); + + if(json != null && !json.isEmpty()) + { + Bitmap qrCodeImage = ImageHelper.QRCode(json, 350, 350); + + if(qrCodeImage != null) + { + qrCode.setVisibility(View.VISIBLE); + qrCode.setImageBitmap(qrCodeImage); + } + else + { + qrCode.setVisibility(View.INVISIBLE); + } + } + else + { + qrCode.setVisibility(View.INVISIBLE); + } + } + catch (Exception ex) + { + qrCode.setVisibility(View.INVISIBLE); + Log.Error(ex.getMessage(), "OEGDActivity.OEGDFragment", "onCreateView"); + } + + return view; + } + + /** Creates a new instance of fragment **/ + public static de.labor_stein.befund.OEGDActivity.OEGDFragment newInstance(OEGDFile oegdFile, OEGDActivity oegdActivity) + { + return new OEGDActivity.OEGDFragment(oegdFile, oegdActivity); + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/PDFViewerActivity.java b/app/src/main/java/de/labor_stein/befund/PDFViewerActivity.java new file mode 100644 index 0000000..45b3fb1 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/PDFViewerActivity.java @@ -0,0 +1,428 @@ +// +// PDFViewerActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 02.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.app.Activity; +import android.app.DatePickerDialog; +import android.content.Context; +import android.content.Intent; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.pdf.PdfDocument; +import android.net.Uri; +import android.os.Bundle; +import android.os.CancellationSignal; +import android.os.ParcelFileDescriptor; +import android.print.PageRange; +import android.print.PrintAttributes; +import android.print.PrintDocumentAdapter; +import android.print.PrintDocumentInfo; +import android.print.PrintJob; +import android.print.PrintManager; +import android.print.pdf.PrintedPdfDocument; +import android.text.InputType; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.webkit.WebView; +import android.widget.Button; +import android.widget.DatePicker; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.ProgressBar; +import android.widget.TextView; + +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; + +import com.github.barteksc.pdfviewer.PDFView; +import com.github.barteksc.pdfviewer.listener.OnErrorListener; +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Date; + +import de.labor_stein.befund.Core.Helpers.DateHelper; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Security.Base64; +import de.labor_stein.befund.Core.System; + +public class PDFViewerActivity extends AppCompatActivity +{ + /** PDFViewerActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + private FrameLayout PDFViewerLayout; + + /** Controls **/ + private TextView lblMyResult; + private TextView lblPDFViewerButtonBack; + + /** Buttons **/ + private FloatingActionButton PDFViewerButtonBack; + private Button bottomPDFViewerMenuOpener; + + /** PDFViewer **/ + private PDFView PDFViewer; + public static byte[] PDFCurrentContent; + + /** BEGIN POPUPS **/ + + /** BEGIN OptionsPopup **/ + private PopupWindow PDFViewerOptions; + private View PPDFViewerOptions_Overlay; + private LinearLayout PDFViewerOptions_Popup; + private Button PDFViewerOptions_BtnPrint; + private Button PDFViewerOptions_BtnShare; + private Button PDFViewerOptions_BtnCancel; + + private final int SAVE_DOCUMENT_REQUEST_CODE = 0x445; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_pdf_viewer); + this.Initialize(); + } + + /** + * Initialize PDFViewer Activity + */ + private void Initialize() + { + MainContext = this; + Log.Initialize(this); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializePDFViewer(); + this.InitializePopups(); + + this.InitializeLanguages(); + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.PDFActivityRootLayout); + PDFViewerLayout = ActivityRootLayout.findViewById(R.id.PDFViewerLayout); + } + + /** + * Initializes Labels + */ + private void InitializeLabels() + { + lblMyResult = ActivityRootLayout.findViewById(R.id.lblMyResult); + lblPDFViewerButtonBack = ActivityRootLayout.findViewById(R.id.lblPDFViewerButtonBack); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + PDFViewerButtonBack = ActivityRootLayout.findViewById(R.id.PDFViewerButtonBack); + PDFViewerButtonBack.setOnClickListener(v ->{ PDFViewerButtonBack_Click(); }); + + bottomPDFViewerMenuOpener = ActivityRootLayout.findViewById(R.id.bottomPDFViewerMenuOpener); + bottomPDFViewerMenuOpener.setOnClickListener(v -> { PDFViewerOptions_Show(); }); + } + + /** + * Initializes PDFViewer + */ + private void InitializePDFViewer() + { + PDFViewer = ActivityRootLayout.findViewById(R.id.PDFViewer); + + if(PDFCurrentContent != null && PDFCurrentContent.length > 0) + { + PDFViewer.fromBytes(PDFCurrentContent) + .defaultPage(0) + .load(); + } + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblMyResult.setText(Lang.Get("BTN_MY_RESULT")); + lblPDFViewerButtonBack.setText(Lang.Get("BTN_BACK")); + PDFViewerOptions_BtnPrint.setText(Lang.Get("BTN_PRINT")); + PDFViewerOptions_BtnShare.setText(Lang.Get("BTN_FILE_SHARE")); + PDFViewerOptions_BtnCancel.setText(Lang.Get("BTN_CANCEL")); + } + + /** + * Initializes Popups + */ + private void InitializePopups() + { + this.InitializeOptionsPopup(); + } + + /** + * Initializes Options Popup + */ + private void InitializeOptionsPopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + PPDFViewerOptions_Overlay = inflater.inflate(R.layout.popup_pdf_viewer_options, null); + PDFViewerOptions_Popup = PPDFViewerOptions_Overlay.findViewById(R.id.PDFViewerOptions_Popup); + PDFViewerOptions_BtnPrint = PPDFViewerOptions_Overlay.findViewById(R.id.PDFViewerOptions_BtnPrint); + PDFViewerOptions_BtnPrint.setOnClickListener(v -> { this.PDFViewerOptions_BtnPrint_Click(); }); + PDFViewerOptions_BtnShare = PPDFViewerOptions_Overlay.findViewById(R.id.PDFViewerOptions_BtnShare); + PDFViewerOptions_BtnShare.setOnClickListener(v -> { this.PDFViewerOptions_BtnShare_Click(); }); + PDFViewerOptions_BtnCancel = PPDFViewerOptions_Overlay.findViewById(R.id.PDFViewerOptions_BtnCancel); + PDFViewerOptions_BtnCancel.setOnClickListener(v -> { this.PDFViewerOptions_BtnCancel_Click(); }); + + /** Create popup window context **/ + PDFViewerOptions = new PopupWindow( + PPDFViewerOptions_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + /** BEGIN EVENTS **/ + + /** + * Show PDFViewerOptions + */ + private void PDFViewerOptions_Show() + { + PPDFViewerOptions_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + PDFViewerOptions_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!PDFViewerOptions.isShowing()) + { + PDFViewerOptions.showAtLocation(ActivityRootLayout, Gravity.CENTER,0,0); + } + } + + /** + * Hide PDFViewerOptions + */ + private void PDFViewerOptions_Hide() + { + PPDFViewerOptions_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + PDFViewerOptions_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(PDFViewerOptions.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PDFViewerOptions.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PDFViewerOptions_Popup.startAnimation(anim); + } + } + + /** + * Go Back to MainActivity + */ + private void PDFViewerButtonBack_Click() + { + PDFCurrentContent = null; + + Intent intent = new Intent(this, MainActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + Bundle parameters = new Bundle(); + parameters.putBoolean("SplashScreenLoaded", true); + intent.putExtras(parameters); + startActivity(intent); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } + + /** On OptionsPopup Print Button clicked **/ + private void PDFViewerOptions_BtnPrint_Click() + { + try + { + PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE); + + PrintAttributes.Builder builder = new PrintAttributes.Builder(); + builder.setMediaSize(PrintAttributes.MediaSize.NA_LETTER); + + + PrintAttributes attributes = new PrintAttributes.Builder() + .setMediaSize(PrintAttributes.MediaSize.ISO_A4) + .setResolution(new PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 200, 200)) + .setColorMode(PrintAttributes.COLOR_MODE_COLOR) + .setMinMargins(PrintAttributes.Margins.NO_MARGINS) + .build(); + + printManager.print("Befunddruck", new PdfDocumentAdapter(this, PDFCurrentContent), attributes); + + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "PDFViewerActivity", "PDFViewerOptions_BtnPrint_Click"); + } + } + + /** On OptionsPopup Share Button clicked **/ + private void PDFViewerOptions_BtnShare_Click() + { + Intent sendIntent = new Intent(); + sendIntent.setAction(Intent.ACTION_CREATE_DOCUMENT); + sendIntent.addCategory(Intent.CATEGORY_OPENABLE); + sendIntent.setType("application/pdf"); + sendIntent.putExtra(Intent.EXTRA_TITLE, "Befund.pdf"); + Intent shareIntent = Intent.createChooser(sendIntent, null); + startActivityForResult(shareIntent, SAVE_DOCUMENT_REQUEST_CODE); + } + + /** + * On OptionsPopup Cancel Button clicked + */ + private void PDFViewerOptions_BtnCancel_Click() + { + this.PDFViewerOptions_Hide(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) + { + super.onActivityResult(requestCode, resultCode, data); + + if (requestCode == SAVE_DOCUMENT_REQUEST_CODE && resultCode == RESULT_OK) + { + Uri uri = data.getData(); + + try + { + OutputStream output = getContentResolver().openOutputStream(uri); + output.write(PDFCurrentContent); + output.flush(); + output.close(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "PDFViewerActivity", "onActivityResult(Share file)"); + } + } + } + + /** END EVENTS **/ + + /** + * PDFDocumentAdapter + */ + public class PdfDocumentAdapter extends PrintDocumentAdapter + { + Context Context = null; + byte[] Content = null; + + public PdfDocumentAdapter(Context context, byte[] content) + { + this.Context = context; + this.Content = content; + } + + @Override + public void onLayout(PrintAttributes printAttributes, PrintAttributes printAttributes1, CancellationSignal cancellationSignal, LayoutResultCallback layoutResultCallback, Bundle bundle) + { + if (cancellationSignal.isCanceled()) + { + layoutResultCallback.onLayoutCancelled(); + } + else + { + PrintDocumentInfo.Builder builder = new PrintDocumentInfo.Builder("Befund.pdf"); + builder.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).setPageCount(PrintDocumentInfo.PAGE_COUNT_UNKNOWN).build(); + layoutResultCallback.onLayoutFinished(builder.build(), !printAttributes1.equals(printAttributes)); + } + } + + @Override + public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor parcelFileDescriptor, CancellationSignal cancellationSignal, WriteResultCallback writeResultCallback) + { + OutputStream out = null; + InputStream in = null; + + try + { + in = new ByteArrayInputStream(this.Content); + out = new FileOutputStream(parcelFileDescriptor.getFileDescriptor()); + + byte[] buf = new byte[16384]; + int size; + + while ((size = in.read(buf)) >= 0 && !cancellationSignal.isCanceled()) + { + out.write(buf, 0, size); + } + + if (cancellationSignal.isCanceled()) + { + writeResultCallback.onWriteCancelled(); + } + else + { + writeResultCallback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES }); + } + } + catch (Exception e) + { + writeResultCallback.onWriteFailed(e.getMessage()); + } + finally + { + try + { + in.close(); + out.close(); + } + catch (IOException ex) + { + Log.Error(ex.getMessage(), "PDFViewerActivity.PdfDocumentAdapter", "onWrite"); + } + } + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/PasswordActivity.java b/app/src/main/java/de/labor_stein/befund/PasswordActivity.java new file mode 100644 index 0000000..83c0786 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/PasswordActivity.java @@ -0,0 +1,542 @@ +// +// PasswordActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 11.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.text.InputType; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Random; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.Results; +import de.labor_stein.befund.Core.Models.Request.ChangeVerificatorHash; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Curve25519; +import de.labor_stein.befund.Core.Security.SHA512; +import de.labor_stein.befund.Core.System; + +public class PasswordActivity extends AppCompatActivity +{ + /** PasswordActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout PasswordActivityRootLayout; + + /** Buttons **/ + private FloatingActionButton PasswordActivityButtonBack; + private Button PasswordActivity_BtnChange; + + /** Controls **/ + private TextView lblPasswordChange; + private TextView lblPasswordActivityButtonBack; + private EditText PasswordActivity_txtCurrentPassword; + private ImageView PasswordActivity_txtCurrentPasswordViewer; + private EditText PasswordActivity_txtNewPassword; + private ImageView PasswordActivity_txtNewPasswordViewer; + private EditText PasswordActivity_txtPasswordConfirm; + private ImageView PasswordActivity_txtPasswordConfirmViewer; + private EditText PasswordActivity_txtNewPIN; + private TextView PasswordActivity_Status; + private ProgressBar PasswordActivity_Loading; + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + /** Database Contexts **/ + private de.labor_stein.befund.Core.Database.Results dbResults; + private de.labor_stein.befund.Core.Database.Logs dbLogs; + private boolean IsSaving = false; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.password_activity); + + this.Initialize(); + } + + @Override + protected void onResume() + { + super.onResume(); + this.InitializeLanguages(); + } + + /** + * Initialize PasswordActivityContext + */ + private void Initialize() + { + MainContext = this; + this.IsSaving = false; + + this.dbResults = new de.labor_stein.befund.Core.Database.Results(this); + this.dbLogs = new de.labor_stein.befund.Core.Database.Logs(this); + Log.Initialize(this); + + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + + this.InitializeLanguages(); + + //PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_YOUR_CURRENT_PASSWORD")); + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + PasswordActivityRootLayout = (CoordinatorLayout)findViewById(R.id.PasswordActivityRootLayout); + } + + /** + * Initializes Labels + */ + private void InitializeLabels() + { + lblPasswordChange = PasswordActivityRootLayout.findViewById(R.id.lblPasswordChange); + lblPasswordActivityButtonBack = PasswordActivityRootLayout.findViewById(R.id.lblPasswordActivityButtonBack); + + PasswordActivity_txtCurrentPassword = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtCurrentPassword); + PasswordActivity_txtCurrentPasswordViewer = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtCurrentPasswordViewer); + PasswordActivity_txtNewPassword = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtNewPassword); + PasswordActivity_txtNewPIN = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtNewPIN); + PasswordActivity_txtNewPasswordViewer = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtNewPasswordViewer); + PasswordActivity_txtPasswordConfirm = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtPasswordConfirm); + PasswordActivity_txtPasswordConfirmViewer = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_txtPasswordConfirmViewer); + + PasswordActivity_Status = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_Status); + PasswordActivity_Loading = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_Loading); + + PasswordActivity_Loading.setVisibility(View.INVISIBLE); + + PasswordActivity_txtCurrentPassword.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_YOUR_CURRENT_PASSWORD")); } + else + { PasswordActivity_Status.setText(""); } + }); + + PasswordActivity_txtNewPassword.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); } + else + { PasswordActivity_Status.setText(""); } + }); + + PasswordActivity_txtPasswordConfirm.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); } + else + { PasswordActivity_Status.setText(""); } + }); + + PasswordActivity_txtNewPIN.setOnFocusChangeListener((View v, boolean hasFocus) -> + { + if(hasFocus) + { PasswordActivity_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); } + else + { PasswordActivity_Status.setText(""); } + }); + + /** Password Viewers **/ + PasswordActivity_txtCurrentPasswordViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PasswordActivity_txtCurrentPasswordViewer.setAlpha(1.0f); + PasswordActivity_txtCurrentPassword.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PasswordActivity_txtCurrentPassword.setSelection(PasswordActivity_txtCurrentPassword.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PasswordActivity_txtCurrentPasswordViewer.setAlpha(0.5f); + PasswordActivity_txtCurrentPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PasswordActivity_txtCurrentPassword.setSelection(PasswordActivity_txtCurrentPassword.getText().length()); + } + + return true; + } + }); + + PasswordActivity_txtNewPasswordViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PasswordActivity_txtNewPasswordViewer.setAlpha(1.0f); + PasswordActivity_txtNewPassword.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PasswordActivity_txtNewPassword.setSelection(PasswordActivity_txtNewPassword.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PasswordActivity_txtNewPasswordViewer.setAlpha(0.5f); + PasswordActivity_txtNewPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PasswordActivity_txtNewPassword.setSelection(PasswordActivity_txtNewPassword.getText().length()); + } + + return true; + } + }); + + PasswordActivity_txtPasswordConfirmViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PasswordActivity_txtPasswordConfirmViewer.setAlpha(1.0f); + PasswordActivity_txtPasswordConfirm.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PasswordActivity_txtPasswordConfirm.setSelection(PasswordActivity_txtPasswordConfirm.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PasswordActivity_txtPasswordConfirmViewer.setAlpha(0.5f); + PasswordActivity_txtPasswordConfirm.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PasswordActivity_txtPasswordConfirm.setSelection(PasswordActivity_txtPasswordConfirm.getText().length()); + } + + return true; + } + }); + + PasswordActivity_txtPasswordConfirm.setOnKeyListener(new View.OnKeyListener() + { + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) + { + if(keyCode == KeyEvent.KEYCODE_ENTER) + { + PasswordActivity_BtnChange_Click(); + } + + return false; + } + }); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblPasswordChange.setText(Lang.Get("LBL_PASSWORD_CHANGE")); + PasswordActivity_txtCurrentPassword.setHint(Lang.Get("LBL_CURRENT_PASSWORD")); + PasswordActivity_txtNewPassword.setHint(Lang.Get("LBL_NEW_PASSWORD")); + PasswordActivity_txtPasswordConfirm.setHint(Lang.Get("LBL_PASSWORD_CONFIRM")); + PasswordActivity_txtNewPIN.setHint(Lang.Get("LBL_NEW_PIN")); + PasswordActivity_BtnChange.setText(Lang.Get("BTN_CHANGE")); + lblPasswordActivityButtonBack.setText(Lang.Get("BTN_BACK")); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + PasswordActivityButtonBack = PasswordActivityRootLayout.findViewById(R.id.PasswordActivityButtonBack); + PasswordActivityButtonBack.setOnClickListener(v ->{ PasswordActivityButtonBack_Click(); }); + + PasswordActivity_BtnChange = PasswordActivityRootLayout.findViewById(R.id.PasswordActivity_BtnChange); + PasswordActivity_BtnChange.setOnClickListener(v -> { this.PasswordActivity_BtnChange_Click(); }); + } + + /** + * Go Back to MainActivity + */ + private void PasswordActivityButtonBack_Click() + { + this.finish(); + } + + /** + * Change password + */ + private void PasswordActivity_BtnChange_Click() + { + try + { + PasswordActivity_Status.setText(""); + + if(!this.IsSaving) + { + this.IsSaving = true; + PasswordActivity_Loading.setVisibility(View.VISIBLE); + + if(PasswordActivity_txtCurrentPassword.getText() == null || PasswordActivity_txtCurrentPassword.getText().toString().isEmpty()) + { + PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_YOUR_CURRENT_PASSWORD")); + this.IsSaving = false; + } + else + { + String old_password = PasswordActivity_txtCurrentPassword.getText().toString(); + String tmp_encrypt_key = AES.Decrypt(Settings.hashed_private_key, AES.GetKey(old_password)); + + if(tmp_encrypt_key != null) + { + String password_policy = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!+@$%^&<>*~:`-]).{8,}$"; + + if(!PasswordActivity_txtNewPassword.getText().toString().matches(password_policy)) + { + this.IsSaving = false; + PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_STRONG_PASSWORD")); + } + else if(!PasswordActivity_txtNewPassword.getText().toString().equals(PasswordActivity_txtPasswordConfirm.getText().toString())) + { + this.IsSaving = false; + PasswordActivity_HideLoading(Lang.Get("ERROR_CONFIRM_PASSWORD")); + } + else if(PasswordActivity_txtNewPIN.getText() == null || PasswordActivity_txtNewPIN.getText().toString().isEmpty()) + { + this.IsSaving = false; + PasswordActivity_HideLoading(Lang.Get("ERROR_ENTER_NEW_PIN")); + } + else if(PasswordActivity_txtNewPIN.getText().toString().length() != 5) + { + this.IsSaving = false; + PasswordActivity_HideLoading(Lang.Get("ERROR_PIN_LENGTH")); + } + else + { + String new_password = PasswordActivity_txtNewPassword.getText().toString(); + String decrypted_private_key = AES.Decrypt(Settings.hashed_private_key, AES.GetKey(old_password)); + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + byte[] key = AES.GetKey(new_password); + + ChangeVerificatorHash changeVerificatorHash = new ChangeVerificatorHash(); + changeVerificatorHash.old_verificator_hash = Settings.verificator_hash; + changeVerificatorHash.new_verificator_hash = SHA512.HMAC(SHA512.VerificatorHashingValue, key); + changeVerificatorHash.udid = Settings.udid; + changeVerificatorHash.pin = PasswordActivity_txtNewPIN.getText().toString(); + + PasswordActivity_Status.setText(""); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + /** Update verificator_hash & pin on the server **/ + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("ChangeVerificatorHash", changeVerificatorHash, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "update_verificator_hash", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + encryptedResponse.Decrypt(sharedKey); + + /** change encryption to existing files if password has been successfully updated on the server **/ + if(encryptedResponse.descriptor.toLowerCase().equals("success")) + { + try + { + List results = dbResults.GetResults(); + + /** decrypt & encrypt old results by new password **/ + if(results != null && results.size() > 0) + { + for(int i = 0; i < results.size(); i++) + { + Results res = results.get(i); + + String file = System.GetPathForStorageEncryptedFile(res.pgs, MainContext); + + if(file != null && System.FileExists(file)) + { + byte[] encrypted_content = System.ReadFromEncryptedStorage(res.pgs, MainContext); + + if(encrypted_content != null && encrypted_content.length > 0) + { + String decrypted_content = AES.Decrypt(new String(encrypted_content), AES.GetKey(old_password)); + + if(decrypted_content != null) + { + String local_encrypted = AES.Encrypt(decrypted_content, AES.GetKey(new_password)); + + if(local_encrypted != null) + { + System.WriteToEncryptedStorage(res.pgs, local_encrypted.getBytes(StandardCharsets.UTF_8), MainContext); + } + } + } + } + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "PasswordActivity", "Thread change encryption"); + } + + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + /** update settings **/ + byte[] key = AES.GetKey(new_password); + Settings.password_reset_hash = UUID.randomUUID().toString(); + + byte[] passwordHashKey = AES.GetKey(Settings.password_reset_hash + changeVerificatorHash.pin); + Settings.password_hash = AES.Encrypt(new_password, passwordHashKey); + Settings.verificator_hash = SHA512.HMAC(SHA512.VerificatorHashingValue, key); + Settings.hashed_private_key = AES.Encrypt(decrypted_private_key, key); + Settings.save(MainContext); + + Session.DevicePassword = new_password; + String msg = Lang.Get("MSG_PASSWORD_HAS_BEEN_CHANGED"); + + PasswordActivity_HideLoading(msg); + + PasswordActivity_txtCurrentPassword.setText(""); + PasswordActivity_txtNewPassword.setText(""); + PasswordActivity_txtPasswordConfirm.setText(""); + PasswordActivity_txtNewPIN.setText(""); + HideKeyboard(PasswordActivity_txtPasswordConfirm); + } + }); + } + else + { + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PasswordActivity_HideLoading(Lang.Get("ERROR_COULD_NOT_CHANGE_PASSWORD")); + Log.Error("Could not update verificator_hash & pin on the server", "LoginActivity", "RequestPINFromServer"); + } + }); + } + + IsSaving = false; + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + IsSaving = false; + PasswordActivity_HideLoading(error); + Log.Critical(error, "PasswordActivity", "PasswordActivity_BtnChange_Click"); + } + }); + + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + IsSaving = false; + PasswordActivity_HideLoading(error); + Log.Critical(error, "PasswordActivity", "PasswordActivity_BtnChange_Click"); + } + }); + }); + } + }); + + thread.start(); + } + } + else + { + this.IsSaving = false; + PasswordActivity_HideLoading(Lang.Get("ERROR_YOUR_CURRENT_PASSWORD_IS_INVALID")); + } + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "PasswordActivity", "PasswordActivity_BtnChange_Click"); + this.IsSaving = false; + } + } + + /** Hide PasswordActivity Loading with optional status message **/ + private void PasswordActivity_HideLoading(String message) + { + PasswordActivity_Loading.setVisibility(View.INVISIBLE); + + if(message != null && !message.isEmpty()) + { + PasswordActivity_Status.setText(message); + } + } + + /** Hide Keyboard **/ + public void HideKeyboard(View view) + { + InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + } +} diff --git a/app/src/main/java/de/labor_stein/befund/Services/PushNotificationService.java b/app/src/main/java/de/labor_stein/befund/Services/PushNotificationService.java new file mode 100644 index 0000000..704457c --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/Services/PushNotificationService.java @@ -0,0 +1,71 @@ +// +// PushNotificationService.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 29.04.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund.Services; + +import android.app.NotificationManager; +import android.content.Context; + +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; + +import java.util.Map; + +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Settings; +import de.labor_stein.befund.MainActivity; + +public class PushNotificationService extends FirebaseMessagingService +{ + private static MainActivity _MainActivity = null; + private static Settings _Settings = null; + + /** + * Sets the context of mainActivity to the PushNotificationService + * + * @param mainActivity + */ + public static void SetMainActivity(MainActivity mainActivity, Settings settings) + { + _MainActivity = mainActivity; + _Settings = settings; + } + + /** + * Resets budge number of notification + */ + public static void ClearNotificationBadge(Context context) + { + try + { + NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); + + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) + { + if (notificationManager != null) + { + notificationManager.cancelAll(); + } + } + } + catch (Exception ex) + { + Log.Critical(ex.getMessage(), "Services.PushNotificationService", "PushNotificationService"); + } + } + + @Override + public void onMessageReceived(RemoteMessage remoteMessage) + { + super.onMessageReceived(remoteMessage); + + if(_MainActivity != null) + { + _MainActivity.LoadResults(false); + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/SettingsActivity.java b/app/src/main/java/de/labor_stein/befund/SettingsActivity.java new file mode 100644 index 0000000..1345bae --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/SettingsActivity.java @@ -0,0 +1,326 @@ +// +// SettingsActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 08.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.CompoundButton; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.Switch; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; +import androidx.viewpager.widget.ViewPager; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import java.util.List; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Database.Status; +import de.labor_stein.befund.Core.Models.Labor; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Security.Curve25519; + +public class SettingsActivity extends AppCompatActivity +{ + /** SettingsActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout ActivityRootLayout; + + /** Controls **/ + private TextView lblSettings; + private TextView lblSettingsButtonButtonBack; + private TextView SettingsActivity_lblYourLabor; + + /** Labor Controls **/ + private ImageView SettingsActivity_LaborLogo; + private TextView SettingsActivity_LaborName; + private TextView SettingsActivity_LaborStreet; + private TextView SettingsActivity_LaborCity; + private TextView SettingsActivity_LaborTel; + private TextView SettingsActivity_LaborWeb; + private TextView SettingsActivity_LaborStatus; + private TextView SettingsActivity_lblLanguages; + private TextView SettingsActivity_swDE; + private ImageView SettingsActivity_btnDE; + private TextView SettingsActivity_swEN; + private ImageView SettingsActivity_btnEN; + private ProgressBar SettingsActivity_Loading; + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + /** Buttons **/ + private FloatingActionButton SettingsButtonBack; + + /** Connection state **/ + private boolean HostConnected = false; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + + this.Initialize(); + } + + @Override + protected void onResume() + { + super.onResume(); + this.InitializeLanguages(); + } + + /** + * Initialize SettingsActivity + */ + private void Initialize() + { + MainContext = this; + + /** First has to be loaded settings to use system properties **/ + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializeLabor(); + + this.InitializeLanguages(); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + Lang.SetLanguage(this.Settings.lang); + + lblSettings.setText(Lang.Get("LBL_SETTINGS")); + lblSettingsButtonButtonBack.setText(Lang.Get("BTN_BACK")); + SettingsActivity_lblYourLabor.setText(Lang.Get("LBL_YOUR_LABOR")); + SettingsActivity_lblLanguages.setText(Lang.Get("LBL_LANGUAGE")); + + if(Session.Maintenance) + { + SettingsActivity_LaborStatus.setText(Lang.Get("LBL_MAINTENANCE")); + } + else if(HostConnected) + { + SettingsActivity_LaborStatus.setText(Lang.Get("LBL_CONNECTED")); + } + else + { + SettingsActivity_LaborStatus.setText(Lang.Get("LBL_DISCONNECTED")); + } + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + ActivityRootLayout = (CoordinatorLayout)findViewById(R.id.SettingsActivityRootLayout); + SettingsActivity_Loading = ActivityRootLayout.findViewById(R.id.SettingsActivity_Loading); + SettingsActivity_LaborStatus = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborStatus); + + SettingsActivity_Loading.setVisibility(View.GONE); + } + + /** + * Initialize Labels + */ + private void InitializeLabels() + { + lblSettings = ActivityRootLayout.findViewById(R.id.lblSettings); + lblSettingsButtonButtonBack = ActivityRootLayout.findViewById(R.id.lblSettingsButtonButtonBack); + SettingsActivity_lblYourLabor = ActivityRootLayout.findViewById(R.id.SettingsActivity_lblYourLabor); + SettingsActivity_lblLanguages = ActivityRootLayout.findViewById(R.id.SettingsActivity_lblLanguages); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + SettingsButtonBack = ActivityRootLayout.findViewById(R.id.SettingsButtonBack); + SettingsButtonBack.setOnClickListener(v ->{ SettingsButtonBack_Click(); }); + SettingsActivity_swDE = ActivityRootLayout.findViewById(R.id.SettingsActivity_swDE); + SettingsActivity_swEN = ActivityRootLayout.findViewById(R.id.SettingsActivity_swEN); + SettingsActivity_btnDE = ActivityRootLayout.findViewById(R.id.SettingsActivity_btnDE); + SettingsActivity_btnEN = ActivityRootLayout.findViewById(R.id.SettingsActivity_btnEN); + + if(this.Settings.lang == Lang.Languages.EN) + { + SettingsActivity_swDE.setVisibility(View.GONE); + SettingsActivity_swEN.setVisibility(View.VISIBLE); + + } + else + { + SettingsActivity_swDE.setVisibility(View.VISIBLE); + SettingsActivity_swEN.setVisibility(View.GONE); + } + + SettingsActivity_btnEN.setOnClickListener(v -> + { + SettingsActivity_swDE.setVisibility(View.GONE); + SettingsActivity_swEN.setVisibility(View.VISIBLE); + this.ChangeLanguage(Lang.Languages.EN); + }); + + SettingsActivity_btnDE.setOnClickListener(v -> + { + SettingsActivity_swDE.setVisibility(View.VISIBLE); + SettingsActivity_swEN.setVisibility(View.GONE); + this.ChangeLanguage(Lang.Languages.DE); + }); + } + + /** + * Initializes Labor info + */ + private void InitializeLabor() + { + if(this.Settings.labor != null) + { + SettingsActivity_LaborLogo = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborLogo); + SettingsActivity_LaborLogo.setImageResource(this.Settings.labor.logo); + + if(this.Settings.labor.name != null && !this.Settings.labor.name.isEmpty()) + { + SettingsActivity_LaborName = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborName); + SettingsActivity_LaborName.setText(this.Settings.labor.name); + } + + if(this.Settings.labor.street != null && !this.Settings.labor.street.isEmpty()) + { + SettingsActivity_LaborStreet = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborStreet); + SettingsActivity_LaborStreet.setText(this.Settings.labor.street); + } + + if(this.Settings.labor.city != null && !this.Settings.labor.city.isEmpty()) + { + SettingsActivity_LaborCity = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborCity); + SettingsActivity_LaborCity.setText(this.Settings.labor.city); + } + + if(this.Settings.labor.tel != null && !this.Settings.labor.tel.isEmpty()) + { + SettingsActivity_LaborTel = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborTel); + SettingsActivity_LaborTel.setText(this.Settings.labor.tel); + } + + if(this.Settings.labor.web != null && !this.Settings.labor.web.isEmpty()) + { + SettingsActivity_LaborWeb = ActivityRootLayout.findViewById(R.id.SettingsActivity_LaborWeb); + SettingsActivity_LaborWeb.setText(this.Settings.labor.web); + } + + SettingsActivity_swDE = ActivityRootLayout.findViewById(R.id.SettingsActivity_swDE); + SettingsActivity_swEN = ActivityRootLayout.findViewById(R.id.SettingsActivity_swEN); + + if(!Session.Maintenance) + { + this.CheckLaborHost(); + } + } + } + + /** + * Change language + */ + private void ChangeLanguage(Lang.Languages lang) + { + Settings.lang = lang; + Settings.save(MainContext); + InitializeLanguages(); + } + + /** + * Check connection to the selected labor host + */ + private void CheckLaborHost() + { + try + { + HostConnected = false; + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + SettingsActivity_Loading.setVisibility(View.VISIBLE); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + HostConnected = true; + SettingsActivity_Loading.setVisibility(View.GONE); + SettingsActivity_LaborStatus.setText(Lang.Get("LBL_CONNECTED")); + SettingsActivity_LaborStatus.setBackgroundColor(getColor(R.color.color_connected)); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + SettingsActivity_LaborStatus.setText(Lang.Get("LBL_DISCONNECTED")); + SettingsActivity_LaborStatus.setBackgroundColor(getColor(R.color.color_disconnected)); + SettingsActivity_Loading.setVisibility(View.GONE); + Log.Critical(error, "SettingsActivity", "CheckLaborHost"); + } + }); + }); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "SettingsActivity", "CheckLaborHost"); + } + } + + /** BEGIN EVENTS **/ + + /** + * Go Back to MainActivity + */ + private void SettingsButtonBack_Click() + { + setResult(RESULT_OK); + this.finish(); + } + + /** END EVENTS **/ +} diff --git a/app/src/main/java/de/labor_stein/befund/SplashActivity.java b/app/src/main/java/de/labor_stein/befund/SplashActivity.java new file mode 100644 index 0000000..0f3b5af --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/SplashActivity.java @@ -0,0 +1,199 @@ +// +// SplashActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 04.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; +import android.content.Context; +import android.content.Intent; +import android.graphics.Point; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.util.DisplayMetrics; +import android.view.Display; +import android.view.View; +import android.view.WindowManager; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.FrameLayout; +import android.widget.ImageView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.app.AppCompatDelegate; +import androidx.constraintlayout.widget.ConstraintLayout; + +import java.util.Timer; +import java.util.TimerTask; + +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Labor; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Models.Settings; +import de.labor_stein.befund.databinding.ActivityMainBinding; + +public class SplashActivity extends AppCompatActivity +{ + /** SplashActivityContext **/ + private Context MainContext; + private ConstraintLayout ActivityRootLayout; + + /** Limbach Logo **/ + private ImageView LimbachLogo; + + /** Labor Logo **/ + private ImageView LaborLogo; + private static final int LogoWidth = 400; + private static final int LogoHeight = 120; + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_splash); + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + + this.Initialize(); + } + + /** + * Initialize SplashScreen + */ + private void Initialize() + { + MainContext = this; + + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + + if(this.Settings == null || this.Settings.labor == null) + { + Labor labor = GetLaborByStartParameter(getIntent()); + + if(labor != null) + { + if(this.Settings == null) + { + this.Settings = new Settings(); + this.Settings.lang = Lang.GetSystemLang(); + } + + this.Settings.labor = labor; + this.Settings.save(this); + } + } + + ActivityRootLayout = findViewById(R.id.SplashActivityRootLayout); + + LimbachLogo = ActivityRootLayout.findViewById(R.id.logoLimbach); + LaborLogo = ActivityRootLayout.findViewById(R.id.logoLabor); + + this.Animate(); + } + + /** + * Animates Logos on Splash Screen + */ + private void Animate() + { + try + { + if(this.Settings != null && this.Settings.labor != null) + { + Display display = getWindowManager().getDefaultDisplay(); + Point displaySize = new Point(); + display.getSize(displaySize); + int width = displaySize.x; + + LimbachLogo.animate().translationX(width).setStartDelay(1000).setDuration(500).start(); + LaborLogo.setX(-width); + LaborLogo.setVisibility(View.VISIBLE); + LaborLogo.setImageResource(this.Settings.labor.logo); + LaborLogo.animate().translationX(0).setStartDelay(1000).setDuration(500).start(); + } + + final Handler handler = new Handler(); + + handler.postDelayed(new Runnable() + { + @Override + public void run() + { + GoToMainActivity(); + } + }, 2000); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "SplashActivity", "Animate"); + } + } + + /** + * Returns labor by start parameter (data protocol S. Manifest: exp: befund://labor?id=LABOR_MOENCHENGLADBACH) + * + * @param intent - intent that gor query parameter + * @return Returns labor object by Intent incoming query + */ + public static Labor GetLaborByStartParameter(Intent intent) + { + Labor result = null; + + try + { + if(intent != null) + { + Uri query = intent.getData(); + + if(query != null) + { + String id = query.getQueryParameter("id"); + + if(id != null && !id.isEmpty()) + { + result = de.labor_stein.befund.Core.Models.Labor.GetLaborByName(id); + } + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "Core.Models.Session", "GetLabirByStartParameter(Ident)"); + } + + return result; + } + + /** + * Goes ether to main activity or to labor activity to select labor + */ + private void GoToMainActivity() + { + if(this.Settings != null && this.Settings.labor != null) + { + Intent mainActivity = new Intent(this, MainActivity.class); + mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP); + Bundle parameters = new Bundle(); + parameters.putBoolean("SplashScreenLoaded", true); + mainActivity.putExtras(parameters); + startActivity(mainActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + finish(); + } + else + { + Intent laborActivity = new Intent(this, LaborActivity.class); + laborActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(laborActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + finish(); + } + } +} diff --git a/app/src/main/java/de/labor_stein/befund/SupportActivity.java b/app/src/main/java/de/labor_stein/befund/SupportActivity.java new file mode 100644 index 0000000..c711ae8 --- /dev/null +++ b/app/src/main/java/de/labor_stein/befund/SupportActivity.java @@ -0,0 +1,830 @@ +// +// PasswordActivity.java +// Befund +// +// Created by Irakli Abetschkhrischwili on 11.07.22. +// Copyright © 2022 MVZ Dr. Stein und Kollegen. All rights reserved. + +package de.labor_stein.befund; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.text.InputType; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.view.inputmethod.InputMethodManager; +import android.webkit.WebView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.ProgressBar; +import android.widget.Spinner; +import android.widget.TextView; + +import androidx.appcompat.app.AppCompatActivity; +import androidx.coordinatorlayout.widget.CoordinatorLayout; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import java.util.Timer; +import java.util.TimerTask; + +import de.labor_stein.befund.Core.Https.Request; +import de.labor_stein.befund.Core.Lang.Lang; +import de.labor_stein.befund.Core.Log; +import de.labor_stein.befund.Core.Models.Request.EncryptedRequest; +import de.labor_stein.befund.Core.Models.Request.Support; +import de.labor_stein.befund.Core.Models.Session; +import de.labor_stein.befund.Core.Models.Settings; +import de.labor_stein.befund.Core.Security.AES; +import de.labor_stein.befund.Core.Security.Curve25519; +import de.labor_stein.befund.Core.System; + +public class SupportActivity extends AppCompatActivity +{ + /** SupportActivityContext **/ + private Context MainContext; + + /** Layouts **/ + private CoordinatorLayout SupportActivityRootLayout; + + /** Buttons **/ + private FloatingActionButton SupportActivityButtonBack; + private Button SupportActivity_BtnSend; + + /** Controls **/ + private TextView lblSupportActivity; + private TextView lblSupportActivityButtonBack; + private EditText SupportActivity_txtEmail; + private Spinner SupportActivity_Topics; + private EditText SupportActivity_txtTEXT; + private Button SupportActivity_btnSend; + private Button SupportActivity_btnHideKeyboard; + private TextView SupportActivity_PrivacyPolicy; + private TextView SupportActivity_Status; + private ProgressBar SupportActivity_Loading; + private TextView SupportActivity_lblYourLabor; + private boolean IsRunning = false; + + /** List items **/ + private String[] Topics = null; + + /** BEGIN POPUPS **/ + + /** BEGIN PasswordConfirm **/ + private PopupWindow PopupPasswordConfirm; + private View PopupPasswordConfirm_Overlay; + private LinearLayout PopupPasswordConfirm_Popup; + private LinearLayout PopupPasswordConfirmContent; + private EditText PopupPasswordConfirm_txtPassword; + private ImageView PopupPasswordConfirm_txtPasswordViewer; + private ProgressBar PopupPasswordConfirm_Loading; + private TextView PopupPasswordConfirm_Status; + private Button PopupPasswordConfirm_btnCancel; + private Button PopupPasswordConfirm_btnOk; + /** END PasswordConfirm **/ + + /** Settings **/ + private de.labor_stein.befund.Core.Models.Settings Settings; + + /** Labor Controls **/ + private ImageView SupportActivity_LaborLogo; + private TextView SupportActivity_LaborName; + private TextView SupportActivity_LaborStreet; + private TextView SupportActivity_LaborCity; + private TextView SupportActivity_LaborTel; + private TextView SupportActivity_LaborWeb; + + /** BEGIN Popup PrivacyPolicy **/ + private PopupWindow PopupPrivacyPolicy; + private TextView PopupPrivacyPolicy_lblHeader; + private Button PopupPrivacyPolicy_btnAcceptPrivacyPolicy; + private WebView PopupPrivacyPolicy_web; + /** END Popup PrivacyPolicy **/ + + private ImageView btnSupportActivityImpressumCollapse; + private LinearLayout btnSupportActivityImpressum; + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_support); + + this.Initialize(); + } + + @Override + protected void onResume() + { + super.onResume(); + this.InitializeLanguages(); + } + + /** + * Initialize SupportActivityContext + */ + private void Initialize() + { + MainContext = this; + + this.Settings = de.labor_stein.befund.Core.Models.Settings.load(this); + this.InitializeControls(); + + this.InitializeLayouts(); + this.InitializeLabels(); + this.InitializeButtons(); + this.InitializeLabor(); + this.InitializePopup(); + + this.InitializeLanguages(); + } + + /** + * Initializes Languages + */ + private void InitializeLanguages() + { + lblSupportActivity.setText(Lang.Get("LBL_SUPPORT")); + lblSupportActivityButtonBack.setText(Lang.Get("BTN_BACK")); + SupportActivity_txtEmail.setHint(Lang.Get("LBL_EMAIL")); + SupportActivity_btnSend.setText(Lang.Get("BTN_SEND")); + SupportActivity_txtTEXT.setHint(Lang.Get("LBL_TEXT")); + SupportActivity_btnHideKeyboard.setText(Lang.Get("BTN_HIDE_KEYBOARD")); + PopupPasswordConfirm_btnCancel.setText(Lang.Get("BTN_CANCEL")); + PopupPasswordConfirm_btnOk.setText(Lang.Get("BTN_OK")); + PopupPasswordConfirm_txtPassword.setHint(Lang.Get("LBL_PASSWORD")); + SupportActivity_lblYourLabor.setText(Lang.Get("LBL_YOUR_LABOR")); + SupportActivity_PrivacyPolicy.setText(Lang.Get("BTN_PRIVACY_POLICY")); + } + + /** + * Initializes Popup + */ + private void InitializePopup() + { + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + PopupPasswordConfirm_Overlay = inflater.inflate(R.layout.popup_confirm_password, null); + PopupPasswordConfirm_Popup = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_Popup); + PopupPasswordConfirmContent = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirmContent); + + PopupPasswordConfirm_btnCancel = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_BtnCancel); + PopupPasswordConfirm_btnCancel.setOnClickListener(v -> { this.PopupPasswordConfirm_btnCancel_Click(); }); + + PopupPasswordConfirm_btnOk = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_BtnEncrypt); + PopupPasswordConfirm_btnOk.setOnClickListener(v -> { this.PopupPasswordConfirm_btnOk_Click(); }); + + PopupPasswordConfirm_Loading = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_Loading); + PopupPasswordConfirm_Status = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_Status); + PopupPasswordConfirm_txtPassword = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_txtPassword); + PopupPasswordConfirm_txtPasswordViewer = PopupPasswordConfirm_Overlay.findViewById(R.id.PopupPasswordConfirm_txtPasswordViewer); + + PopupPasswordConfirm_txtPasswordViewer.setOnTouchListener(new View.OnTouchListener() + { + @Override + public boolean onTouch(View v, MotionEvent event) + { + if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) + { + PopupPasswordConfirm_txtPasswordViewer.setAlpha(1.0f); + PopupPasswordConfirm_txtPassword.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); + PopupPasswordConfirm_txtPassword.setSelection(PopupPasswordConfirm_txtPassword.getText().length()); + + } + else if (event.getAction() == android.view.MotionEvent.ACTION_UP) + { + PopupPasswordConfirm_txtPasswordViewer.setAlpha(0.5f); + PopupPasswordConfirm_txtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + PopupPasswordConfirm_txtPassword.setSelection(PopupPasswordConfirm_txtPassword.getText().length()); + } + + return true; + } + }); + + PopupPasswordConfirm_txtPassword.setOnKeyListener(new View.OnKeyListener() + { + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) + { + if(keyCode == KeyEvent.KEYCODE_ENTER) + { + PopupPasswordConfirm_btnOk_Click(); + } + + return false; + } + }); + + PopupPasswordConfirm_Loading.setVisibility(View.GONE); + PopupPasswordConfirm_Status.setText(""); + + /** Create popup window context **/ + PopupPasswordConfirm = new PopupWindow( + PopupPasswordConfirm_Overlay, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + } + + private void InitializeControls() + { + if(Session.IsLoggedIn()) + { + this.Topics = new String[] { + Lang.Get("LBL_SUPPORT_TOPIC_INFO"), + Lang.Get("LBL_SUPPORT_TOPIC_TROUBLE"), + Lang.Get("LBL_SUPPORT_TOPIC_ACCOUNT_DELETE") + }; + } + else + { + this.Topics = new String[] { + Lang.Get("LBL_SUPPORT_TOPIC_INFO"), + Lang.Get("LBL_SUPPORT_TOPIC_TROUBLE") + }; + } + } + + /** + * Initializes Labor info + */ + private void InitializeLabor() + { + if(this.Settings.labor != null) + { + SupportActivity_LaborLogo = SupportActivityRootLayout.findViewById(R.id.SupportActivity_LaborLogo); + SupportActivity_LaborLogo.setImageResource(this.Settings.labor.logo); + + if(this.Settings.labor.name != null && !this.Settings.labor.name.isEmpty()) + { + SupportActivity_LaborName = SupportActivityRootLayout.findViewById(R.id.SupportActivity_LaborName); + SupportActivity_LaborName.setText(this.Settings.labor.name); + } + + if(this.Settings.labor.street != null && !this.Settings.labor.street.isEmpty()) + { + SupportActivity_LaborStreet = SupportActivityRootLayout.findViewById(R.id.SupportActivity_LaborStreet); + SupportActivity_LaborStreet.setText(this.Settings.labor.street); + } + + if(this.Settings.labor.city != null && !this.Settings.labor.city.isEmpty()) + { + SupportActivity_LaborCity = SupportActivityRootLayout.findViewById(R.id.SupportActivity_LaborCity); + SupportActivity_LaborCity.setText(this.Settings.labor.city); + } + + if(this.Settings.labor.tel != null && !this.Settings.labor.tel.isEmpty()) + { + SupportActivity_LaborTel = SupportActivityRootLayout.findViewById(R.id.SupportActivity_LaborTel); + SupportActivity_LaborTel.setText(this.Settings.labor.tel); + } + + if(this.Settings.labor.web != null && !this.Settings.labor.web.isEmpty()) + { + SupportActivity_LaborWeb = SupportActivityRootLayout.findViewById(R.id.SupportActivity_LaborWeb); + SupportActivity_LaborWeb.setText(this.Settings.labor.web); + } + + btnSupportActivityImpressumCollapse = SupportActivityRootLayout.findViewById(R.id.btnSupportActivityImpressumCollapse); + btnSupportActivityImpressum = SupportActivityRootLayout.findViewById(R.id.btnSupportActivityImpressum); + + btnSupportActivityImpressumCollapse.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if(btnSupportActivityImpressum.getVisibility() == View.VISIBLE) + { + btnSupportActivityImpressumCollapse.setImageResource(R.drawable.ic_arrow_drop_down_circle); + btnSupportActivityImpressum.setVisibility(View.GONE); + } + else + { + btnSupportActivityImpressumCollapse.setImageResource(R.drawable.ic_arrow_drop_up_circle); + btnSupportActivityImpressum.setVisibility(View.VISIBLE); + } + } + }); + } + } + + /** + * Initialize Layouts + */ + private void InitializeLayouts() + { + SupportActivityRootLayout = (CoordinatorLayout)findViewById(R.id.SupportActivityRootLayout); + } + + /** + * Initializes Labels + */ + private void InitializeLabels() + { + lblSupportActivity = SupportActivityRootLayout.findViewById(R.id.lblSupportActivity); + lblSupportActivityButtonBack = SupportActivityRootLayout.findViewById(R.id.lblSupportActivityButtonBack); + SupportActivity_txtEmail = SupportActivityRootLayout.findViewById(R.id.SupportActivity_txtEmail); + SupportActivity_lblYourLabor = SupportActivityRootLayout.findViewById(R.id.SupportActivity_lblYourLabor); + SupportActivity_txtTEXT = SupportActivityRootLayout.findViewById(R.id.AupportActivity_txtTEXT); + + SupportActivity_Status = SupportActivityRootLayout.findViewById(R.id.SupportActivity_Status); + SupportActivity_Loading = SupportActivityRootLayout.findViewById(R.id.SupportActivity_Loading); + SupportActivity_Loading.setVisibility(View.INVISIBLE); + + /** Run RequestPGS on ENTER KEY (SampleID) **/ + SupportActivity_txtTEXT.setOnFocusChangeListener(new View.OnFocusChangeListener() + { + @Override + public void onFocusChange(View v, boolean hasFocus) + { + if(hasFocus) + { + SupportActivity_btnHideKeyboard.setVisibility(View.VISIBLE); + } + } + }); + + SupportActivity_txtTEXT.setOnClickListener(v -> { SupportActivity_btnHideKeyboard.setVisibility(View.VISIBLE); }); + + SupportActivity_txtTEXT.setOnKeyListener(new View.OnKeyListener() + { + @Override + public boolean onKey(View v, int keyCode, KeyEvent event) + { + SupportActivity_btnHideKeyboard.setVisibility(View.VISIBLE); + return false; + } + }); + + SupportActivity_Topics = SupportActivityRootLayout.findViewById(R.id.AupportActivity_Topics); + ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, this.Topics); + aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + SupportActivity_Topics.setAdapter(aa); + + SupportActivity_txtEmail.setVisibility(View.VISIBLE); + SupportActivity_Topics.setVisibility(View.VISIBLE); + SupportActivity_txtTEXT.setVisibility(View.VISIBLE); + } + + /** + * Initializes Buttons + */ + private void InitializeButtons() + { + SupportActivityButtonBack = SupportActivityRootLayout.findViewById(R.id.SupportActivityButtonBack); + SupportActivityButtonBack.setOnClickListener(v ->{ this.ActivityButtonBack_Click(); }); + //SupportActivityButtonBack.setOnClickListener((v) -> { PopupCWAPolicy.dismiss(); }); + + SupportActivity_btnSend = SupportActivityRootLayout.findViewById(R.id.AupportActivity_btnSend); + SupportActivity_btnHideKeyboard = SupportActivityRootLayout.findViewById(R.id.SupportActivity_btnHideKeyboard); + SupportActivity_btnHideKeyboard.setOnClickListener(v -> { this.HideKeyboard(SupportActivity_txtTEXT); }); + SupportActivity_btnHideKeyboard.setVisibility(View.GONE); + SupportActivity_btnSend.setVisibility(View.VISIBLE); + SupportActivity_btnSend.setOnClickListener(v -> { this.SupportActivity_btnSend_Click(); }); + SupportActivity_PrivacyPolicy = SupportActivityRootLayout.findViewById(R.id.SupportActivity_PrivacyPolicy); + SupportActivity_PrivacyPolicy.setVisibility(View.INVISIBLE); + + //SupportActivity_PrivacyPolicy.setOnClickListener(new View.OnClickListener() + //{ + // @Override + // public void onClick(View v) { + // ShowPrivacyPolicy(); + // } + //}); + } + + /** Shows privacy policy popup**/ + private void ShowPrivacyPolicy() + { + this.InitializePrivacyPolicyPopup(); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_CLOSE")); + this.LoadPrivacyPolicy(); + } + + /** + * Initializes PrivacyPolicy Popup + */ + private void InitializePrivacyPolicyPopup() + { + Lang.SetLanguage(Lang.GetSystemLang()); + + LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); + View PopupPrivacyPolicyView = inflater.inflate(R.layout.popup_privacy_policy, null); + + PopupPrivacyPolicy_lblHeader = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_lblHeader); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_btnAccept); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(false); + PopupPrivacyPolicy_lblHeader.setText(Lang.Get("LBL_PRIVACY_POLICY")); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setText(Lang.Get("BTN_ACCEPT_PRIVACY_POLICY")); + + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setOnClickListener((v) -> + { + PopupPrivacyPolicy.dismiss(); + }); + + /** Create popup window context **/ + PopupPrivacyPolicy = new PopupWindow( + PopupPrivacyPolicyView, + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT, + true + ); + + PopupPrivacyPolicy_web = PopupPrivacyPolicyView.findViewById(R.id.PopupPrivacyPolicy_web); + + this.SupportActivityRootLayout.post(new Runnable() + { + public void run() + { + LoadPrivacyPolicy(); + PopupPrivacyPolicy.showAtLocation(SupportActivityRootLayout, Gravity.CENTER,0,0); + } + }); + } + + /** + * Load PrivacyPolicy + */ + private void LoadPrivacyPolicy() + { + try + { + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + Request.GetResponseAsync(Settings.GetPrivacyPolicyURL(), + "GET", + (content) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPrivacyPolicy_web.loadUrl(Settings.GetPrivacyPolicyURL()); + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + } + }); + }, + (error) -> + { + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPrivacyPolicy_btnAcceptPrivacyPolicy.setEnabled(true); + + byte[] local_privacy_policy_data = System.ReadFromAssets("no_connection.html", MainContext); + + if(local_privacy_policy_data != null && local_privacy_policy_data.length > 0) + { + String html = new String(local_privacy_policy_data); + html = html.replace("[NO_CONNECTION]", Lang.Get("ERROR_PRIVACY_POLICY_NEEDS_CONNECTION")); + PopupPrivacyPolicy_web.loadData(html, "text/html", "utf-8"); + } + } + }); + }); + } + }); + + thread.start(); + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "SupportActivity", "LoadPrivacyPolicy"); + } + } + + /** Hide Keyboard **/ + public void HideKeyboard(View view) + { + InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE); + inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); + + SupportActivity_btnHideKeyboard.setVisibility(View.GONE); + } + + private void ActivityButtonBack_Click() + { + this.finish(); + } + + /** + * Go Back to MainActivity + */ + private void PasswordActivityButtonBack_Click() + { + Intent intent = new Intent(this, MainActivity.class ); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + Bundle parameters = new Bundle(); + parameters.putBoolean("SplashScreenLoaded", true); + intent.putExtras(parameters); + startActivity(intent); + overridePendingTransition(R.anim.side_in_left, R.anim.side_out_right); + } + + /** + * Send support to server + */ + private void SupportActivity_btnSend_Click() + { + try + { + SupportActivity_Status.setText(""); + SupportActivity_Loading.setVisibility(View.GONE); + + + if(SupportActivity_txtEmail.getText() == null || SupportActivity_txtEmail.getText().toString().isEmpty()) + { + this.SupportActivity_HideLoading(Lang.Get("ERROR_ENTER_EMAIL")); + } + else if(SupportActivity_Topics.getSelectedItemPosition() < 0) + { + this.SupportActivity_HideLoading(Lang.Get("ERROR_ENTER_TOPIC")); + } + else if(SupportActivity_txtTEXT.getText() == null || SupportActivity_txtTEXT.getText().toString().isEmpty()) + { + this.SupportActivity_HideLoading(Lang.Get("ERROR_ENTER_TEXT")); + } + else + { + String email = SupportActivity_txtEmail.getText().toString(); + int topicIndex = (int)SupportActivity_Topics.getSelectedItemId(); + String topic = Topics[topicIndex]; + String text = SupportActivity_txtTEXT.getText().toString(); + + if(topic == Lang.Get("LBL_SUPPORT_TOPIC_ACCOUNT_DELETE")) + { + PopupPasswordConfirm_Show(); + } + else + { + this.SendAsync(email, topic, text, false); + } + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "SupportActivity", "AupportActivity_btnSend_Click"); + } + } + + /** + * Send request async + */ + private void SendAsync(String email, String topic, String text, boolean delete_device) + { + try + { + if(!IsRunning) + { + IsRunning = true; + + Curve25519.KeyPair requestKeyPair = Curve25519.GenerateKeyPair(); + Support support = new Support(); + support.email = email; + support.topic = topic; + support.text = text; + support.udid = Session.Device.udid; + support.verificator_hash = this.Settings.verificator_hash; + support.delete_device = delete_device; + + SupportActivity_Loading.setVisibility(View.VISIBLE); + + /** Run request on sub thread **/ + Thread thread = new Thread(new Runnable() + { + @Override + public void run() + { + /** Update verificator_hash & pin on the server **/ + Request.KeyExchangeAsync(Settings.labor.host, + requestKeyPair, + (publicKey) -> + { + byte[] sharedKey = requestKeyPair.GetSharedKey(publicKey.key); + EncryptedRequest request = new EncryptedRequest("Support", support, sharedKey); + + Request.EncryptedRequestAsync(Settings.labor.host, + "results", + "support", + request, + publicKey, + requestKeyPair, + (encryptedResponse) -> + { + IsRunning = false; + encryptedResponse.Decrypt(sharedKey); + + /** Run on main Thread **/ + runOnUiThread(new Runnable() + { + @Override + public void run() + { + if(encryptedResponse.descriptor.toLowerCase().equals("success")) + { + if(delete_device) + { + if(System.DeleteAllFiles(MainContext) && Settings.delete(MainContext)) + { + SupportActivity_HideLoading(Lang.Get("MSG_ACCOUNT_SUCCESSFULLY_DELETED")); + + new Timer().schedule(new TimerTask() + { + @Override + public void run() + { + GoToLaborActivity(); + } + }, 1000); + } + else + { + SupportActivity_HideLoading(Lang.Get("ERROR_ACCOUNT_COULD_NOT_DELETED")); + } + } + else + { + SupportActivity_HideLoading(Lang.Get("MSG_SUPPORT_SUCCESSFULLY_SENT")); + } + } + else + { + SupportActivity_HideLoading(Lang.Get("ERROR_SUPPORT_COULD_NOT_SENT")); + } + + SupportActivity_txtEmail.setText(""); + SupportActivity_txtTEXT.setText(""); + } + }); + }, + (error) -> + { + IsRunning = false; + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPasswordConfirm_Status.setText(""); + PopupPasswordConfirm_Loading.setVisibility(View.GONE); + SupportActivity_HideLoading(error); + Log.Critical(error, "SupportActivity", "SendAsync"); + } + }); + }); + }, + (error) -> + { + IsRunning = false; + + runOnUiThread(new Runnable() + { + @Override + public void run() + { + PopupPasswordConfirm_Status.setText(""); + PopupPasswordConfirm_Loading.setVisibility(View.GONE); + SupportActivity_HideLoading(error); + Log.Critical(error, "SupportActivity", "SendAsync"); + } + }); + }); + } + }); + + thread.start(); + } + } + catch (Exception ex) + { + Log.Error(ex.getMessage(), "SupportActivity", "SendAsync"); + } + } + + /** Hide SupportActivity Loading with optional status message **/ + private void SupportActivity_HideLoading(String message) + { + SupportActivity_Loading.setVisibility(View.INVISIBLE); + + if(message != null && !message.isEmpty()) + { + SupportActivity_Status.setText(message); + } + } + + /** + * Confirm password + */ + private void PopupPasswordConfirm_btnOk_Click() + { + PopupPasswordConfirm_Status.setText(""); + + if(PopupPasswordConfirm_txtPassword.getText() == null || PopupPasswordConfirm_txtPassword.getText().toString().isEmpty()) + { + PopupPasswordConfirm_Status.setText(Lang.Get("ERROR_ENTER_PASSWORD")); + } + else + { + String tmp_decrypted = AES.Decrypt(this.Settings.hashed_private_key, AES.GetKey(PopupPasswordConfirm_txtPassword.getText().toString())); + + if(tmp_decrypted == null) + { + PopupPasswordConfirm_Status.setText(Lang.Get("ERROR_INVALID_PASSWORD")); + } + else + { + String email = SupportActivity_txtEmail.getText().toString(); + int topicIndex = (int)SupportActivity_Topics.getSelectedItemId(); + String topic = Topics[topicIndex]; + String text = SupportActivity_txtTEXT.getText().toString(); + this.SendAsync(email, topic, text, true); + + PopupPasswordConfirm_Hide(); + } + } + } + + /** + * Hides Password confirm popup on cancel button + */ + private void PopupPasswordConfirm_btnCancel_Click() + { + this.PopupPasswordConfirm_Hide(); + } + + /** + * Show Password Confirm Popup + */ + private void PopupPasswordConfirm_Show() + { + PopupPasswordConfirm_txtPassword.setText(""); + + PopupPasswordConfirm_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_in)); + PopupPasswordConfirm_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_in)); + + if(!PopupPasswordConfirm.isShowing()) + { + PopupPasswordConfirm.showAtLocation(SupportActivityRootLayout, Gravity.CENTER,0,0); + } + } + + /** + * Hides Password confirm popup + */ + private void PopupPasswordConfirm_Hide() + { + PopupPasswordConfirm_Overlay.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_overlay_out)); + PopupPasswordConfirm_Popup.setAnimation(AnimationUtils.loadAnimation(this, R.anim.popup_out)); + + if(PopupPasswordConfirm.isShowing()) + { + Animation anim = AnimationUtils.loadAnimation(this, R.anim.popup_out); + anim.setAnimationListener(new Animation.AnimationListener() + { + @Override + public void onAnimationStart(Animation animation) { } + + @Override + public void onAnimationEnd(Animation animation) + { + PopupPasswordConfirm.dismiss(); + } + + @Override + public void onAnimationRepeat(Animation animation) {} + }); + + anim.setFillAfter(true); + PopupPasswordConfirm_Popup.startAnimation(anim); + } + } + + /** + * Goes to Labor activity + */ + private void GoToLaborActivity() + { + Intent laborActivity = new Intent(this, LaborActivity.class); + laborActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(laborActivity); + overridePendingTransition(R.anim.side_in_right, R.anim.side_out_left); + finish(); + } +} diff --git a/app/src/main/res/anim/popup_content_right_in.xml b/app/src/main/res/anim/popup_content_right_in.xml new file mode 100644 index 0000000..06aa907 --- /dev/null +++ b/app/src/main/res/anim/popup_content_right_in.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/popup_in.xml b/app/src/main/res/anim/popup_in.xml new file mode 100644 index 0000000..619b5b5 --- /dev/null +++ b/app/src/main/res/anim/popup_in.xml @@ -0,0 +1,11 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/popup_out.xml b/app/src/main/res/anim/popup_out.xml new file mode 100644 index 0000000..7415a25 --- /dev/null +++ b/app/src/main/res/anim/popup_out.xml @@ -0,0 +1,11 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/popup_overlay_in.xml b/app/src/main/res/anim/popup_overlay_in.xml new file mode 100644 index 0000000..9ad05fb --- /dev/null +++ b/app/src/main/res/anim/popup_overlay_in.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/popup_overlay_out.xml b/app/src/main/res/anim/popup_overlay_out.xml new file mode 100644 index 0000000..cdabfff --- /dev/null +++ b/app/src/main/res/anim/popup_overlay_out.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/side_in_left.xml b/app/src/main/res/anim/side_in_left.xml new file mode 100644 index 0000000..a015111 --- /dev/null +++ b/app/src/main/res/anim/side_in_left.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/anim/side_in_right.xml b/app/src/main/res/anim/side_in_right.xml new file mode 100644 index 0000000..9bf14de --- /dev/null +++ b/app/src/main/res/anim/side_in_right.xml @@ -0,0 +1,8 @@ + + + + diff --git a/app/src/main/res/anim/side_out_left.xml b/app/src/main/res/anim/side_out_left.xml new file mode 100644 index 0000000..0ab1581 --- /dev/null +++ b/app/src/main/res/anim/side_out_left.xml @@ -0,0 +1,8 @@ + + + + diff --git a/app/src/main/res/anim/side_out_right.xml b/app/src/main/res/anim/side_out_right.xml new file mode 100644 index 0000000..6d5a3c5 --- /dev/null +++ b/app/src/main/res/anim/side_out_right.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file 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..90f9580 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/bottom_border.xml b/app/src/main/res/drawable/bottom_border.xml new file mode 100644 index 0000000..c7189c7 --- /dev/null +++ b/app/src/main/res/drawable/bottom_border.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/btn_qrcode.png b/app/src/main/res/drawable/btn_qrcode.png new file mode 100644 index 0000000..9c04bee Binary files /dev/null and b/app/src/main/res/drawable/btn_qrcode.png differ diff --git a/app/src/main/res/drawable/dashed_border.xml b/app/src/main/res/drawable/dashed_border.xml new file mode 100644 index 0000000..ea9f232 --- /dev/null +++ b/app/src/main/res/drawable/dashed_border.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/de.png b/app/src/main/res/drawable/de.png new file mode 100644 index 0000000..2fd433f Binary files /dev/null and b/app/src/main/res/drawable/de.png differ diff --git a/app/src/main/res/drawable/en.png b/app/src/main/res/drawable/en.png new file mode 100644 index 0000000..be8a095 Binary files /dev/null and b/app/src/main/res/drawable/en.png differ diff --git a/app/src/main/res/drawable/ic_add.png b/app/src/main/res/drawable/ic_add.png new file mode 100644 index 0000000..334187b Binary files /dev/null and b/app/src/main/res/drawable/ic_add.png differ diff --git a/app/src/main/res/drawable/ic_add_user.png b/app/src/main/res/drawable/ic_add_user.png new file mode 100644 index 0000000..487fcd6 Binary files /dev/null and b/app/src/main/res/drawable/ic_add_user.png differ diff --git a/app/src/main/res/drawable/ic_alternate_email.png b/app/src/main/res/drawable/ic_alternate_email.png new file mode 100644 index 0000000..cef524e Binary files /dev/null and b/app/src/main/res/drawable/ic_alternate_email.png differ diff --git a/app/src/main/res/drawable/ic_arrow_drop_down_circle.png b/app/src/main/res/drawable/ic_arrow_drop_down_circle.png new file mode 100644 index 0000000..9fa7fa6 Binary files /dev/null and b/app/src/main/res/drawable/ic_arrow_drop_down_circle.png differ diff --git a/app/src/main/res/drawable/ic_arrow_drop_up_circle.png b/app/src/main/res/drawable/ic_arrow_drop_up_circle.png new file mode 100644 index 0000000..2437d09 Binary files /dev/null and b/app/src/main/res/drawable/ic_arrow_drop_up_circle.png differ diff --git a/app/src/main/res/drawable/ic_av_timer.png b/app/src/main/res/drawable/ic_av_timer.png new file mode 100644 index 0000000..1072b6a Binary files /dev/null and b/app/src/main/res/drawable/ic_av_timer.png differ diff --git a/app/src/main/res/drawable/ic_change_key.png b/app/src/main/res/drawable/ic_change_key.png new file mode 100644 index 0000000..7a3f698 Binary files /dev/null and b/app/src/main/res/drawable/ic_change_key.png differ diff --git a/app/src/main/res/drawable/ic_close_menu.png b/app/src/main/res/drawable/ic_close_menu.png new file mode 100644 index 0000000..430a04b Binary files /dev/null and b/app/src/main/res/drawable/ic_close_menu.png differ diff --git a/app/src/main/res/drawable/ic_dehaze.png b/app/src/main/res/drawable/ic_dehaze.png new file mode 100644 index 0000000..1c4200c Binary files /dev/null and b/app/src/main/res/drawable/ic_dehaze.png differ diff --git a/app/src/main/res/drawable/ic_delete_user.png b/app/src/main/res/drawable/ic_delete_user.png new file mode 100644 index 0000000..c162ece Binary files /dev/null and b/app/src/main/res/drawable/ic_delete_user.png differ diff --git a/app/src/main/res/drawable/ic_do_not_disturb_on.png b/app/src/main/res/drawable/ic_do_not_disturb_on.png new file mode 100644 index 0000000..f8282be Binary files /dev/null and b/app/src/main/res/drawable/ic_do_not_disturb_on.png differ diff --git a/app/src/main/res/drawable/ic_downloading.gif b/app/src/main/res/drawable/ic_downloading.gif new file mode 100644 index 0000000..24e97ca Binary files /dev/null and b/app/src/main/res/drawable/ic_downloading.gif differ diff --git a/app/src/main/res/drawable/ic_e_pass.png b/app/src/main/res/drawable/ic_e_pass.png new file mode 100644 index 0000000..1d8ba07 Binary files /dev/null and b/app/src/main/res/drawable/ic_e_pass.png differ diff --git a/app/src/main/res/drawable/ic_edit.png b/app/src/main/res/drawable/ic_edit.png new file mode 100644 index 0000000..20566cf Binary files /dev/null and b/app/src/main/res/drawable/ic_edit.png differ diff --git a/app/src/main/res/drawable/ic_event.png b/app/src/main/res/drawable/ic_event.png new file mode 100644 index 0000000..3b2caee Binary files /dev/null and b/app/src/main/res/drawable/ic_event.png differ diff --git a/app/src/main/res/drawable/ic_file_download.png b/app/src/main/res/drawable/ic_file_download.png new file mode 100644 index 0000000..e9b4478 Binary files /dev/null and b/app/src/main/res/drawable/ic_file_download.png differ diff --git a/app/src/main/res/drawable/ic_help_outline.png b/app/src/main/res/drawable/ic_help_outline.png new file mode 100644 index 0000000..e3d350e Binary files /dev/null and b/app/src/main/res/drawable/ic_help_outline.png differ diff --git a/app/src/main/res/drawable/ic_keyboard_arrow_left.png b/app/src/main/res/drawable/ic_keyboard_arrow_left.png new file mode 100644 index 0000000..af983eb Binary files /dev/null and b/app/src/main/res/drawable/ic_keyboard_arrow_left.png differ 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..00d9241 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_launcher_round.xml b/app/src/main/res/drawable/ic_launcher_round.xml new file mode 100644 index 0000000..90f9580 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_link_off.png b/app/src/main/res/drawable/ic_link_off.png new file mode 100644 index 0000000..08fdc1a Binary files /dev/null and b/app/src/main/res/drawable/ic_link_off.png differ diff --git a/app/src/main/res/drawable/ic_local_printshop.png b/app/src/main/res/drawable/ic_local_printshop.png new file mode 100644 index 0000000..6d0f138 Binary files /dev/null and b/app/src/main/res/drawable/ic_local_printshop.png differ diff --git a/app/src/main/res/drawable/ic_location_on.png b/app/src/main/res/drawable/ic_location_on.png new file mode 100644 index 0000000..6a01fdc Binary files /dev/null and b/app/src/main/res/drawable/ic_location_on.png differ diff --git a/app/src/main/res/drawable/ic_lock.png b/app/src/main/res/drawable/ic_lock.png new file mode 100644 index 0000000..6637623 Binary files /dev/null and b/app/src/main/res/drawable/ic_lock.png differ diff --git a/app/src/main/res/drawable/ic_notifications_active.png b/app/src/main/res/drawable/ic_notifications_active.png new file mode 100644 index 0000000..5fa7ed1 Binary files /dev/null and b/app/src/main/res/drawable/ic_notifications_active.png differ diff --git a/app/src/main/res/drawable/ic_number.png b/app/src/main/res/drawable/ic_number.png new file mode 100644 index 0000000..cf6f7d0 Binary files /dev/null and b/app/src/main/res/drawable/ic_number.png differ diff --git a/app/src/main/res/drawable/ic_opacity.png b/app/src/main/res/drawable/ic_opacity.png new file mode 100644 index 0000000..764552d Binary files /dev/null and b/app/src/main/res/drawable/ic_opacity.png differ diff --git a/app/src/main/res/drawable/ic_photo_camera.png b/app/src/main/res/drawable/ic_photo_camera.png new file mode 100644 index 0000000..5d4dcbc Binary files /dev/null and b/app/src/main/res/drawable/ic_photo_camera.png differ diff --git a/app/src/main/res/drawable/ic_picture_as_pdf.png b/app/src/main/res/drawable/ic_picture_as_pdf.png new file mode 100644 index 0000000..0faa70f Binary files /dev/null and b/app/src/main/res/drawable/ic_picture_as_pdf.png differ diff --git a/app/src/main/res/drawable/ic_pin.png b/app/src/main/res/drawable/ic_pin.png new file mode 100644 index 0000000..7a5c6cc Binary files /dev/null and b/app/src/main/res/drawable/ic_pin.png differ diff --git a/app/src/main/res/drawable/ic_question_answer.png b/app/src/main/res/drawable/ic_question_answer.png new file mode 100644 index 0000000..af06eff Binary files /dev/null and b/app/src/main/res/drawable/ic_question_answer.png differ diff --git a/app/src/main/res/drawable/ic_remove_red_eye.png b/app/src/main/res/drawable/ic_remove_red_eye.png new file mode 100644 index 0000000..d149299 Binary files /dev/null and b/app/src/main/res/drawable/ic_remove_red_eye.png differ diff --git a/app/src/main/res/drawable/ic_security.png b/app/src/main/res/drawable/ic_security.png new file mode 100644 index 0000000..e4b0c38 Binary files /dev/null and b/app/src/main/res/drawable/ic_security.png differ diff --git a/app/src/main/res/drawable/ic_settings.png b/app/src/main/res/drawable/ic_settings.png new file mode 100644 index 0000000..2d36603 Binary files /dev/null and b/app/src/main/res/drawable/ic_settings.png differ diff --git a/app/src/main/res/drawable/ic_share.png b/app/src/main/res/drawable/ic_share.png new file mode 100644 index 0000000..3463f2b Binary files /dev/null and b/app/src/main/res/drawable/ic_share.png differ diff --git a/app/src/main/res/drawable/ic_share_results.png b/app/src/main/res/drawable/ic_share_results.png new file mode 100644 index 0000000..e7c0b3c Binary files /dev/null and b/app/src/main/res/drawable/ic_share_results.png differ diff --git a/app/src/main/res/drawable/ic_support.png b/app/src/main/res/drawable/ic_support.png new file mode 100644 index 0000000..95dfd45 Binary files /dev/null and b/app/src/main/res/drawable/ic_support.png differ diff --git a/app/src/main/res/drawable/labor_aachen.png b/app/src/main/res/drawable/labor_aachen.png new file mode 100644 index 0000000..9f77c74 Binary files /dev/null and b/app/src/main/res/drawable/labor_aachen.png differ diff --git a/app/src/main/res/drawable/labor_berlin.png b/app/src/main/res/drawable/labor_berlin.png new file mode 100644 index 0000000..dddf962 Binary files /dev/null and b/app/src/main/res/drawable/labor_berlin.png differ diff --git a/app/src/main/res/drawable/labor_cottbus.png b/app/src/main/res/drawable/labor_cottbus.png new file mode 100644 index 0000000..a135cac Binary files /dev/null and b/app/src/main/res/drawable/labor_cottbus.png differ diff --git a/app/src/main/res/drawable/labor_dessau.png b/app/src/main/res/drawable/labor_dessau.png new file mode 100644 index 0000000..edfa92c Binary files /dev/null and b/app/src/main/res/drawable/labor_dessau.png differ diff --git a/app/src/main/res/drawable/labor_dortmund.png b/app/src/main/res/drawable/labor_dortmund.png new file mode 100644 index 0000000..e841b3f Binary files /dev/null and b/app/src/main/res/drawable/labor_dortmund.png differ diff --git a/app/src/main/res/drawable/labor_dresden.png b/app/src/main/res/drawable/labor_dresden.png new file mode 100644 index 0000000..f561036 Binary files /dev/null and b/app/src/main/res/drawable/labor_dresden.png differ diff --git a/app/src/main/res/drawable/labor_erfurt.png b/app/src/main/res/drawable/labor_erfurt.png new file mode 100644 index 0000000..f051122 Binary files /dev/null and b/app/src/main/res/drawable/labor_erfurt.png differ diff --git a/app/src/main/res/drawable/labor_essen.png b/app/src/main/res/drawable/labor_essen.png new file mode 100644 index 0000000..20700f0 Binary files /dev/null and b/app/src/main/res/drawable/labor_essen.png differ diff --git a/app/src/main/res/drawable/labor_frankfurt.jpg b/app/src/main/res/drawable/labor_frankfurt.jpg new file mode 100644 index 0000000..d8b0c5e Binary files /dev/null and b/app/src/main/res/drawable/labor_frankfurt.jpg differ diff --git a/app/src/main/res/drawable/labor_freiburg.png b/app/src/main/res/drawable/labor_freiburg.png new file mode 100644 index 0000000..0b4a6d3 Binary files /dev/null and b/app/src/main/res/drawable/labor_freiburg.png differ diff --git a/app/src/main/res/drawable/labor_hannover.png b/app/src/main/res/drawable/labor_hannover.png new file mode 100644 index 0000000..349f42b Binary files /dev/null and b/app/src/main/res/drawable/labor_hannover.png differ diff --git a/app/src/main/res/drawable/labor_hannover_mlh.png b/app/src/main/res/drawable/labor_hannover_mlh.png new file mode 100644 index 0000000..c833511 Binary files /dev/null and b/app/src/main/res/drawable/labor_hannover_mlh.png differ diff --git a/app/src/main/res/drawable/labor_heidelberg.png b/app/src/main/res/drawable/labor_heidelberg.png new file mode 100644 index 0000000..66741bb Binary files /dev/null and b/app/src/main/res/drawable/labor_heidelberg.png differ diff --git a/app/src/main/res/drawable/labor_hofheim.png b/app/src/main/res/drawable/labor_hofheim.png new file mode 100644 index 0000000..331c534 Binary files /dev/null and b/app/src/main/res/drawable/labor_hofheim.png differ diff --git a/app/src/main/res/drawable/labor_karlsruhe.png b/app/src/main/res/drawable/labor_karlsruhe.png new file mode 100644 index 0000000..71a65ad Binary files /dev/null and b/app/src/main/res/drawable/labor_karlsruhe.png differ diff --git a/app/src/main/res/drawable/labor_kassel.png b/app/src/main/res/drawable/labor_kassel.png new file mode 100644 index 0000000..edfa92c Binary files /dev/null and b/app/src/main/res/drawable/labor_kassel.png differ diff --git a/app/src/main/res/drawable/labor_leipzig.png b/app/src/main/res/drawable/labor_leipzig.png new file mode 100644 index 0000000..87f67fa Binary files /dev/null and b/app/src/main/res/drawable/labor_leipzig.png differ diff --git a/app/src/main/res/drawable/labor_ludwigsburg.png b/app/src/main/res/drawable/labor_ludwigsburg.png new file mode 100644 index 0000000..2eb03e2 Binary files /dev/null and b/app/src/main/res/drawable/labor_ludwigsburg.png differ diff --git a/app/src/main/res/drawable/labor_mainz.jpg b/app/src/main/res/drawable/labor_mainz.jpg new file mode 100644 index 0000000..b454b4b Binary files /dev/null and b/app/src/main/res/drawable/labor_mainz.jpg differ diff --git a/app/src/main/res/drawable/labor_moenchengladbach.png b/app/src/main/res/drawable/labor_moenchengladbach.png new file mode 100644 index 0000000..5b05bb2 Binary files /dev/null and b/app/src/main/res/drawable/labor_moenchengladbach.png differ diff --git a/app/src/main/res/drawable/labor_muenchen.png b/app/src/main/res/drawable/labor_muenchen.png new file mode 100644 index 0000000..1000c49 Binary files /dev/null and b/app/src/main/res/drawable/labor_muenchen.png differ diff --git a/app/src/main/res/drawable/labor_muenster.png b/app/src/main/res/drawable/labor_muenster.png new file mode 100644 index 0000000..4910e89 Binary files /dev/null and b/app/src/main/res/drawable/labor_muenster.png differ diff --git a/app/src/main/res/drawable/labor_nuernberg.png b/app/src/main/res/drawable/labor_nuernberg.png new file mode 100644 index 0000000..bc4c055 Binary files /dev/null and b/app/src/main/res/drawable/labor_nuernberg.png differ diff --git a/app/src/main/res/drawable/labor_passau.png b/app/src/main/res/drawable/labor_passau.png new file mode 100644 index 0000000..cd167ff Binary files /dev/null and b/app/src/main/res/drawable/labor_passau.png differ diff --git a/app/src/main/res/drawable/labor_ravensburg.png b/app/src/main/res/drawable/labor_ravensburg.png new file mode 100644 index 0000000..ebbf87c Binary files /dev/null and b/app/src/main/res/drawable/labor_ravensburg.png differ diff --git a/app/src/main/res/drawable/labor_rosenheim.png b/app/src/main/res/drawable/labor_rosenheim.png new file mode 100644 index 0000000..4ceccba Binary files /dev/null and b/app/src/main/res/drawable/labor_rosenheim.png differ diff --git a/app/src/main/res/drawable/labor_schweinfurt.png b/app/src/main/res/drawable/labor_schweinfurt.png new file mode 100644 index 0000000..f052194 Binary files /dev/null and b/app/src/main/res/drawable/labor_schweinfurt.png differ diff --git a/app/src/main/res/drawable/labor_schwerin.png b/app/src/main/res/drawable/labor_schwerin.png new file mode 100644 index 0000000..0cbe864 Binary files /dev/null and b/app/src/main/res/drawable/labor_schwerin.png differ diff --git a/app/src/main/res/drawable/labor_stralsrund.png b/app/src/main/res/drawable/labor_stralsrund.png new file mode 100644 index 0000000..163a05e Binary files /dev/null and b/app/src/main/res/drawable/labor_stralsrund.png differ diff --git a/app/src/main/res/drawable/labor_suhl.png b/app/src/main/res/drawable/labor_suhl.png new file mode 100644 index 0000000..6c95406 Binary files /dev/null and b/app/src/main/res/drawable/labor_suhl.png differ diff --git a/app/src/main/res/drawable/labor_ulm.png b/app/src/main/res/drawable/labor_ulm.png new file mode 100644 index 0000000..707945b Binary files /dev/null and b/app/src/main/res/drawable/labor_ulm.png differ diff --git a/app/src/main/res/drawable/limbach.png b/app/src/main/res/drawable/limbach.png new file mode 100644 index 0000000..1a59a18 Binary files /dev/null and b/app/src/main/res/drawable/limbach.png differ diff --git a/app/src/main/res/drawable/popup_border.xml b/app/src/main/res/drawable/popup_border.xml new file mode 100644 index 0000000..2edb558 --- /dev/null +++ b/app/src/main/res/drawable/popup_border.xml @@ -0,0 +1,11 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_edit_oegd.xml b/app/src/main/res/layout/activity_edit_oegd.xml new file mode 100644 index 0000000..a6dbea8 --- /dev/null +++ b/app/src/main/res/layout/activity_edit_oegd.xml @@ -0,0 +1,387 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_labor_qrcode_select.xml b/app/src/main/res/layout/fragment_labor_qrcode_select.xml new file mode 100644 index 0000000..ebe824b --- /dev/null +++ b/app/src/main/res/layout/fragment_labor_qrcode_select.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_message.xml b/app/src/main/res/layout/fragment_message.xml new file mode 100644 index 0000000..b79d28a --- /dev/null +++ b/app/src/main/res/layout/fragment_message.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/popup_menu.xml b/app/src/main/res/layout/popup_menu.xml new file mode 100644 index 0000000..7d056b9 --- /dev/null +++ b/app/src/main/res/layout/popup_menu.xml @@ -0,0 +1,259 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/popup_new_pgs.xml b/app/src/main/res/layout/popup_new_pgs.xml new file mode 100644 index 0000000..d299284 --- /dev/null +++ b/app/src/main/res/layout/popup_new_pgs.xml @@ -0,0 +1,307 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/popup_push_explain.xml b/app/src/main/res/layout/popup_push_explain.xml new file mode 100644 index 0000000..c153849 --- /dev/null +++ b/app/src/main/res/layout/popup_push_explain.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + +